From 6d864f2378a3ad5b96ae7c9a97230537ae97129b Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 03:29:22 -0600 Subject: [PATCH 01/25] LR-LIB-PEOPLE: write face regions and names to XMP sidecars Saving a sidecar now writes the photo's regions as mwg-rs:Regions (MWG 2.0) and the names on its faces as Iptc4xmpExt:PersonInImage, so naming, renaming, clearing, resizing and removing faces reach the file with automatic XMP writing on, or on Save Metadata to File. - Boxes are written on the upright photo with the upright size as AppliedToDimensions and no Rotation, so they read back unchanged. - The detector's unnamed boxes (Detected by ...) stay catalog-only until named; the detector's note is not written. - mwg-rs:Regions is owned (the catalog holds every region read from the sidecar); PersonInImage is owned only when there is a name, since LightCraft doesn't read it. - Exports carry no regions: a crop or resize would misplace them. - Face naming, renaming and box edits no longer skip auto-write; the background scan and Detect Faces still do. --- crates/catalog/src/model.rs | 3 +- crates/engine/src/cmd/face_detect.rs | 4 +- crates/engine/src/cmd/face_recognize.rs | 10 +- crates/engine/src/cmd/library/specs.rs | 2 - crates/engine/src/sidecar.rs | 230 +++++++++++++++++++++++- crates/engine/src/tests/xmp.rs | 55 ++++-- docs/faces.md | 5 +- docs/parity-checklist.md | 2 +- docs/xmp-interop.md | 10 +- 9 files changed, 290 insertions(+), 31 deletions(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 42bf5663594..969e4e222ca 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -219,7 +219,8 @@ pub struct Meta { pub creator: String, pub keywords: Vec, /// Face/pet/focus regions read from XMP (MWG-RS), on the upright (EXIF-oriented) photo. - /// Removing or resizing one edits the catalog only; LightCraft never writes regions to XMP. + /// Written to the photo's sidecar when one is saved (`lightcraft_engine::sidecar`), the detector's unnamed boxes + /// excepted. /// Left out of the catalog JSON when empty (most photos), so older catalogs read unchanged. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub regions: Vec, diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 5f042308454..fcb3273b9ab 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -4,7 +4,7 @@ //! made do not matter), the detector runs on it, and the faces come back as fractions of the photo's width //! and height, the same frame face regions from XMP use. Unless `apply` is false, they are added to the photo as //! unnamed face regions in one undoable step; earlier detections are replaced, and regions that came from XMP (or -//! that you drew or named) are never touched. Like every region edit it is catalog-only: no sidecar is written. +//! that you drew or named) are never touched. Unnamed detected boxes are LightCraft's bookkeeping and are never written to a sidecar. use std::path::PathBuf; use std::sync::{Arc, Mutex, PoisonError}; @@ -291,7 +291,7 @@ fn detect(s: &mut Session, p: &Value) -> Result { let applied = !ops.is_empty(); if applied { s.commit("Detect Faces", Op::Batch { ops })?; - // regions are not written to XMP, so a sidecar must not be rewritten for this + // unnamed detected boxes are not written to XMP, so a sidecar must not be rewritten for this s.skip_auto_write = true; } Ok(json!({"detector": LABEL, "applied": applied, "photos": results, "ms": started.elapsed().as_secs_f64() * 1000.0})) diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index 15519fc7575..110b794fccb 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -4,8 +4,9 @@ //! what teaches the suggestions). `faces.renamePerson` renames every in-library face of one person, or merges two //! people when asked. //! -//! Everything here is a suggestion for the user to confirm; nothing is ever named automatically. All of it is -//! catalog-only (no sidecar is written) and naming is undoable. +//! Everything here is a suggestion for the user to confirm; nothing is ever named automatically. Suggestions stay +//! in the library; a confirmed name reaches the photo's sidecar whenever it is written (`crate::sidecar`), and naming +//! is undoable. use lightcraft_catalog::Op; use serde_json::{Value, json}; @@ -74,7 +75,6 @@ fn name_faces(s: &mut Session, p: &Value) -> Result { } let photos = ops.len(); s.commit(if name.is_some() { "Name Faces" } else { "Clear Face Names" }, Op::Batch { ops })?; - s.skip_auto_write = true; Ok(json!({"named": named, "photos": photos, "name": name})) } @@ -89,7 +89,6 @@ fn set_name(s: &mut Session, p: &Value) -> Result { let region = meta.regions.get_mut(index).ok_or_else(|| bad(C, "no such region"))?; apply_name(region, &name); s.commit(if name.is_some() { "Name Face" } else { "Clear Face Name" }, Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; Ok(json!({"id": id.0, "index": index, "name": name})) } @@ -172,7 +171,6 @@ fn rename_person(s: &mut Session, p: &Value) -> Result { } let photos = ops.len(); s.commit(if other { "Merge People" } else { "Rename Person" }, Op::Batch { ops })?; - s.skip_auto_write = true; if s.filter.person.as_deref().is_some_and(|n| n.trim().to_lowercase() == from_key) { s.filter.person = Some(to.clone()); } @@ -391,7 +389,7 @@ mod imp { meta.regions.push(Region { rect: *rect, kind: RegionKind::Face, name: None, description: Some(format!("{MARK}{LABEL}")) }); } if s.apply_system(Op::SetMeta { id, meta: Box::new(meta) }).is_ok() { - // regions are not written to XMP, so no sidecar may be rewritten for this + // unnamed detected boxes are not written to XMP, so no sidecar may be rewritten for this s.skip_auto_write = true; } } diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b366069fe2e..74ea2bed562 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -737,7 +737,6 @@ pub fn specs() -> Vec { } let gone = meta.regions.remove(index); s.commit("Remove Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; Ok(json!({"removed": gone.name})) } ), @@ -771,7 +770,6 @@ pub fn specs() -> Vec { let region = meta.regions.get_mut(index).ok_or_else(|| bad(C, "no such region"))?; region.rect = lightcraft_geom::Rect { x0, y0, x1, y1 }; s.commit("Resize Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; Ok(json!({"rect": {"x0": x0, "y0": y0, "x1": x1, "y1": y1}})) } ), diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index b46f1a0d04c..3b10f972f60 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -724,7 +724,9 @@ const ORIENTATION_SPAN: u64 = 1 << 20; /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom /// label names included, as other editors do). pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { - sidecar_packet_with(p, cat, false) + // the regions go into the photo's own sidecar only: an export's packet describes the picture as exported, which a + // crop or a resize leaves the boxes no longer fit + with_regions(sidecar_packet_with(p, cat, false), p) } /// [`sidecar_packet`], without any location (GPS, sublocation, city, state, country) when @@ -773,6 +775,109 @@ pub fn sidecar_packet_with(p: &Photo, cat: &lightcraft_catalog::Catalog, remove_ lightcraft_meta::write_xmp_lc(&meta, &lc) } +/// The regions a sidecar carries: every region of the photo except the unnamed faces LightCraft's own detector +/// found (its bookkeeping, marked `Detected by …`), which are not worth a file write until someone names them. +fn file_regions(p: &Photo) -> Vec<&lightcraft_meta::Region> { + let detected = |r: &lightcraft_meta::Region| r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)); + let named = |r: &lightcraft_meta::Region| r.name.as_deref().is_some_and(|n| !n.trim().is_empty()); + p.meta.regions.iter().filter(|r| named(r) || !detected(r)).collect() +} + +/// The people named on a photo's faces, trimmed, each once (case-insensitive), in region order. +fn face_names(p: &Photo) -> Vec { + let mut names: Vec = Vec::new(); + for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { + let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; + if !names.iter().any(|m| m.to_lowercase() == n.to_lowercase()) { + names.push(n.to_string()); + } + } + names +} + +/// Text for an XML element's content. +fn xml_text(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + // characters XML 1.0 can't carry are dropped + '\t' | '\n' | '\r' => o.push(c), + c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {} + c => o.push(c), + } + } + o +} + +/// `packet` with the photo's regions (`mwg-rs:Regions`, MWG Region Guidelines 2.0) and the names on its faces +/// (`Iptc4xmpExt:PersonInImage`) added to its description. The boxes are written on the upright photo, as LightCraft +/// keeps them, with the upright size as `AppliedToDimensions` (the photo's own `width` × `height`), so reading the +/// sidecar back gives the same boxes. Nothing is added for a photo without regions. +fn with_regions(packet: String, p: &Photo) -> String { + let regions = file_regions(p); + if regions.is_empty() { + return packet; + } + let mut x = String::from(" \n"); + if p.width > 0 && p.height > 0 { + x.push_str(&format!( + " \n {}\n {}\n pixel\n \n", + p.width, p.height + )); + } + x.push_str(" \n \n"); + for r in ®ions { + let (x0, y0) = (r.rect.x0.clamp(0.0, 1.0), r.rect.y0.clamp(0.0, 1.0)); + let (x1, y1) = (r.rect.x1.clamp(0.0, 1.0), r.rect.y1.clamp(0.0, 1.0)); + if !(x1 > x0 && y1 > y0) { + continue; + } + x.push_str(" \n"); + // stArea:x/y are the box's centre (MWG Region Guidelines §Area) + x.push_str(&format!( + " \n {:.6}\n {:.6}\n {:.6}\n {:.6}\n normalized\n \n", + (x0 + x1) / 2.0, + (y0 + y1) / 2.0, + x1 - x0, + y1 - y0 + )); + let kind = match &r.kind { + lightcraft_meta::RegionKind::Face => "Face", + lightcraft_meta::RegionKind::Pet => "Pet", + lightcraft_meta::RegionKind::Focus => "Focus", + lightcraft_meta::RegionKind::BarCode => "BarCode", + lightcraft_meta::RegionKind::Other(t) => t.as_str(), + }; + if !kind.trim().is_empty() { + x.push_str(&format!(" {}\n", xml_text(kind))); + } + if let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) { + x.push_str(&format!(" {}\n", xml_text(n))); + } + if let Some(d) = r.description.as_deref().filter(|d| !d.trim().is_empty() && !d.starts_with(crate::cmd::face_detect::MARK)) { + x.push_str(&format!(" {}\n", xml_text(d))); + } + x.push_str(" \n"); + } + x.push_str(" \n \n \n"); + let names = face_names(p); + if !names.is_empty() { + x.push_str(" \n \n"); + for n in &names { + x.push_str(&format!(" {}\n", xml_text(n))); + } + x.push_str(" \n \n"); + } + // into the packet's one description, just before it closes + match packet.rfind(" ") { + Some(at) => format!("{}{x}{}", &packet[..at], &packet[at..]), + None => packet, + } +} + /// The properties LightCraft writes and owns in a sidecar: replaced on every save (removed when /// LightCraft has no value, so clearing a field clears it in the file too). All of them are read /// back on import and by Read Metadata from File. @@ -794,13 +899,19 @@ pub const OWNED: &[&str] = &[ "xmpRights:Marked", "xmpRights:UsageTerms", "xmpRights:WebStatement", + // the photo's face, pet and focus regions: LightCraft reads every region of a sidecar into the catalog, so the + // catalog's list is the file's list as edited here (see `with_regions`) + "mwg-rs:Regions", "lc:*", ]; /// Properties replaced only when LightCraft has a value (capture time; GPS, which LightCraft /// doesn't read from sidecars): otherwise the sidecar's own value stays. Anything else LightCraft /// writes (`xmp:CreatorTool`) goes only into new sidecars. -pub const OWNED_IF_STATED: &[&str] = &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude"]; +/// `Iptc4xmpExt:PersonInImage` (the names on the photo's faces) is one of them: LightCraft doesn't read it, so a list +/// another application wrote is replaced only when LightCraft has names to write. +pub const OWNED_IF_STATED: &[&str] = + &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude", "Iptc4xmpExt:PersonInImage"]; /// Write `data` to `path` atomically: a temp file next to it, synced, then renamed over it. fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { @@ -1802,6 +1913,121 @@ mod tests { assert_eq!(sidecar_path("/a/b/IMG_1.CR3", SidecarNaming::Full), PathBuf::from("/a/b/IMG_1.CR3.xmp")); } + fn region( + x0: f64, + y0: f64, + x1: f64, + y1: f64, + kind: lightcraft_meta::RegionKind, + name: Option<&str>, + description: Option<&str>, + ) -> lightcraft_meta::Region { + lightcraft_meta::Region { + rect: lightcraft_meta::Rect { x0, y0, x1, y1 }, + kind, + name: name.map(str::to_string), + description: description.map(str::to_string), + } + } + + #[test] + fn named_faces_are_written_and_read_back() { + use lightcraft_meta::RegionKind::{Face, Pet}; + let mut p = photo(); + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + p.meta.regions = vec![ + region(0.1, 0.2, 0.3, 0.5, Face, Some("Mimì & "), None), + // a face the detector found and someone named: written, without the detector's note + region(0.5, 0.1, 0.6, 0.3, Face, Some("Anna Netrebko, soprano"), Some(&detected)), + // the detector's unnamed box: LightCraft's bookkeeping, not written + region(0.7, 0.7, 0.8, 0.9, Face, None, Some(&detected)), + region(0.2, 0.6, 0.4, 0.9, Pet, Some("Rex"), Some("the dog")), + // another application's unnamed face: kept + region(0.0, 0.0, 0.1, 0.1, Face, None, None), + ]; + let x = sidecar_packet(&p, &lightcraft_catalog::Catalog::new()); + assert!(x.contains("40") && x.contains("30"), "{x}"); + assert!(!x.contains("Detected by"), "{x}"); + let sc = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap(); + let mut want = p.meta.regions.clone(); + want.remove(2); + want[1].description = None; + let got = sc.regions.clone().expect("regions read back"); + assert_eq!(got.len(), want.len()); + for (g, w) in got.iter().zip(&want) { + assert_eq!((&g.kind, &g.name, &g.description), (&w.kind, &w.name, &w.description)); + for (a, b) in [(g.rect.x0, w.rect.x0), (g.rect.y0, w.rect.y0), (g.rect.x1, w.rect.x1), (g.rect.y1, w.rect.y1)] { + assert!((a - b).abs() < 1e-5, "{g:?} vs {w:?}"); + } + } + let d = lightcraft_meta::parse_xmp(&x).unwrap(); + let people: Vec<&str> = + d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text()).collect()).unwrap_or_default(); + assert_eq!(people, ["Mimì & ", "Anna Netrebko, soprano"]); + } + + #[test] + fn upright_boxes_on_a_turned_photo_come_back_as_written() { + // a portrait shot stored landscape (Exif orientation 6): the catalog's size and boxes are upright + let mut p = Photo::new(PhotoId(3), Source::File { path: "/x/IMG_3.jpg".into() }, "IMG_3.jpg", "JPEG", 30, 40, "2026-01-01T00:00:00"); + p.meta.regions = vec![region(0.1, 0.2, 0.3, 0.4, lightcraft_meta::RegionKind::Face, Some("Ann"), None)]; + let x = sidecar_packet(&p, &lightcraft_catalog::Catalog::new()); + let sc = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap(); + let sc = SidecarData { orientation: Some(lightcraft_meta::Orientation::from_exif(6)), ..sc }; + let mut q = Photo::new(PhotoId(3), p.source.clone(), "IMG_3.jpg", "JPEG", 30, 40, "2026-01-01T00:00:00"); + merge_into(&mut q, &sc, "now"); + let r = q.meta.regions[0].rect; + assert!((r.x0 - 0.1).abs() < 1e-5 && (r.y0 - 0.2).abs() < 1e-5 && (r.x1 - 0.3).abs() < 1e-5 && (r.y1 - 0.4).abs() < 1e-5, "{r:?}"); + } + + #[test] + fn regions_replace_the_sidecars_own_and_keep_its_person_list_when_nobody_is_named() { + let old = r#" + + + + FaceOld Name + Typed In Elsewhere + "#; + let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED }; + let names = |x: &str| -> (Vec, Vec) { + let d = lightcraft_meta::parse_xmp(x).unwrap(); + let sc = parse_sidecar(x, crate::crs::Target::Rendered).unwrap(); + let faces = sc.regions.unwrap_or_default().into_iter().filter_map(|r| r.name).collect(); + let people = d + .values + .get("Iptc4xmpExt:PersonInImage") + .map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect()) + .unwrap_or_default(); + (faces, people) + }; + + // renamed in LightCraft: the file's regions and person list follow, Photo Mechanic's colour class stays + let mut p = photo(); + p.meta.regions = vec![region(0.4, 0.4, 0.6, 0.6, lightcraft_meta::RegionKind::Face, Some("New Name"), None)]; + let merged = lightcraft_meta::merge_xmp(old, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); + assert_eq!(names(&merged), (vec!["New Name".to_string()], vec!["New Name".to_string()])); + assert!(merged.contains("photomechanic:ColorClass=\"1\""), "{merged}"); + + // its last box removed: the regions go, the person list nobody named here stays as it was + p.meta.regions.clear(); + let merged = lightcraft_meta::merge_xmp(old, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); + assert_eq!(names(&merged), (vec![], vec!["Typed In Elsewhere".to_string()])); + // and saving again changes nothing + let again = lightcraft_meta::merge_xmp(&merged, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); + assert_eq!(names(&again), names(&merged)); + } + + #[test] + fn exports_carry_no_regions() { + let mut p = photo(); + p.meta.regions = vec![region(0.1, 0.2, 0.3, 0.5, lightcraft_meta::RegionKind::Face, Some("Ann"), None)]; + let x = sidecar_packet_with(&p, &lightcraft_catalog::Catalog::new(), false); + assert!(!x.contains("mwg-rs:Regions>") && !x.contains("PersonInImage>"), "{x}"); + } + #[test] fn packet_roundtrip_restores_everything() { let p = photo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index c17ec5bc6be..2ffa2139a14 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -817,10 +817,9 @@ fn a_size_only_a_raws_xmp_states_leaves_upright_regions_as_written() { let _ = std::fs::remove_dir_all(&src); } -/// Removing a face box is a catalog-only, undoable edit: it never rewrites the sidecar (Lightroom's -/// regions and everything else in it stay byte for byte), even with auto-write on. +/// Removing a face box is an undoable edit; with auto-write on it reaches the sidecar's regions. #[test] -fn removing_a_region_is_undoable_and_leaves_the_sidecar_alone() { +fn removing_a_region_is_undoable_and_written_to_the_sidecar() { let src = temp_dir("region-remove"); write_png(&src.join("portrait.png"), 9); std::fs::write(src.join("portrait.xmp"), MWG_REGIONS).unwrap(); @@ -836,21 +835,20 @@ fn removing_a_region_is_undoable_and_leaves_the_sidecar_alone() { let r = s.execute("photo.removeRegion", &json!({"index": 0})).unwrap(); assert_eq!(r["removed"], "Jane Doe"); assert_eq!(s.catalog.photo(id).unwrap().meta.regions.len(), n - 1); - assert_eq!(std::fs::read(src.join("portrait.xmp")).unwrap(), before, "the sidecar is untouched"); - // an ordinary edit still auto-writes (the guard is per command) - s.execute("photo.rate", &json!({"rating": 4})).unwrap(); - assert_ne!(std::fs::read(src.join("portrait.xmp")).unwrap(), before, "auto-write still works for other edits"); - // undo brings the region back - s.execute("edit.undo", &json!({})).unwrap(); + let after = std::fs::read_to_string(src.join("portrait.xmp")).unwrap(); + assert_ne!(after.as_bytes(), before.as_slice(), "the sidecar follows"); + assert!(!after.contains("Jane Doe"), "{after}"); + // undo brings the region back, in the file too s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(id).unwrap().meta.regions.len(), n); + assert!(std::fs::read_to_string(src.join("portrait.xmp")).unwrap().contains("Jane Doe")); let _ = std::fs::remove_dir_all(&src); } -/// Resizing a face box is a catalog-only, undoable edit with strict input handling; it leaves the -/// sidecar alone like removal does. +/// Resizing a face box is an undoable edit with strict input handling; with auto-write on the new box reaches the +/// sidecar. #[test] -fn resizing_a_region_validates_clamps_undoes_and_leaves_the_sidecar_alone() { +fn resizing_a_region_validates_clamps_undoes_and_writes_the_sidecar() { let src = temp_dir("region-resize"); write_png(&src.join("portrait.png"), 9); std::fs::write(src.join("portrait.xmp"), MWG_REGIONS).unwrap(); @@ -879,7 +877,10 @@ fn resizing_a_region_validates_clamps_undoes_and_leaves_the_sidecar_alone() { assert_eq!(r["rect"], json!({"x0": 0.0, "y0": 0.2, "x1": 0.6, "y1": 1.0})); let now = s.catalog.photo(id).unwrap().meta.regions[0].rect; assert_eq!((now.x0, now.y0, now.x1, now.y1), (0.0, 0.2, 0.6, 1.0)); - assert_eq!(std::fs::read(src.join("portrait.xmp")).unwrap(), before, "the sidecar is untouched"); + assert_ne!(std::fs::read(src.join("portrait.xmp")).unwrap(), before, "the sidecar follows"); + let read = crate::sidecar::parse_sidecar(&std::fs::read_to_string(src.join("portrait.xmp")).unwrap(), crate::crs::Target::Rendered).unwrap(); + let r = read.regions.unwrap()[0].rect; + assert!([(r.x0, 0.0), (r.y0, 0.2), (r.x1, 0.6), (r.y1, 1.0)].iter().all(|(g, w)| (g - w).abs() < 1e-5), "{r:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(id).unwrap().meta.regions[0].rect, original); let _ = std::fs::remove_dir_all(&src); @@ -2264,3 +2265,31 @@ fn a_failed_auto_write_waits_and_is_written_on_retry() { std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o755)).unwrap(); let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn naming_a_face_writes_it_into_the_sidecar() { + use lightcraft_meta::{Rect, Region, RegionKind}; + let src = temp_dir("face-write"); + write_png(&src.join("a.png"), 4); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + let rect = Rect { x0: 0.25, y0: 0.25, x1: 0.75, y1: 0.75 }; + meta.regions = vec![Region { rect, kind: RegionKind::Face, name: None, description: Some("Detected by YuNet 2023mar".into()) }]; + s.commit("Detect Faces", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("faces.nameFaces", &json!({"faces": [{"photo": id.0, "index": 0}], "name": "Jane Doe"})).unwrap(); + let x = std::fs::read_to_string(src.join("a.xmp")).unwrap(); + assert!(x.contains("Jane Doe") && x.contains("Jane Doe"), "{x}"); + if let Ok(keep) = std::env::var("LC_KEEP_FACE_SIDECAR") { + std::fs::copy(src.join("a.xmp"), keep).unwrap(); + } + // reading the file again gives the same face + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + let r = &s.catalog.photo(id).unwrap().meta.regions; + assert_eq!(r.len(), 1); + assert_eq!(r[0].name.as_deref(), Some("Jane Doe")); + assert!((r[0].rect.x0 - 0.25).abs() < 1e-5 && (r[0].rect.y1 - 0.75).abs() < 1e-5, "{:?}", r[0].rect); + let _ = std::fs::remove_dir_all(&src); +} diff --git a/docs/faces.md b/docs/faces.md index 2e988030ea7..90d74f159be 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -1,7 +1,8 @@ # Faces LightCraft reads the face names other apps (Lightroom, digiKam…) write into your photos, shows them in the loupe -(boxes you can switch off, resize and remove) and groups photos by person in the People view. This page is about the +(boxes you can switch off, resize and remove), groups photos by person in the People view, and writes the boxes and +names into the photo's XMP sidecar when it saves one (see [XMP interop](xmp-interop.md#face-regions-mwg)). This page is about the *models* that find and recognise faces by themselves. ## Nothing is bundled; every model is an opt-in download @@ -314,7 +315,7 @@ at once (`faces.renamePerson`). The name is matched the way the cards are groupe every matching face is stored with the exact new spelling, so a change of capitalization alone updates them all. The dialog says how many faces that is. If the new name is already someone else, it refuses until **Combine with the existing person** is ticked; that makes one person, and Undo separates them again. Cancelling changes nothing. A person filter, -the open person page and the way back to it follow the new name. Nothing is written back to the files. +the open person page and the way back to it follow the new name. With automatic XMP writing on, every renamed photo's sidecar is rewritten. The thumbnail-size slider in the bottom bar sizes the faces here too, with limits of their own. Every face is shown by the same kind of box: the detector's own box once the scan has looked at it (kept beside its embedding), so a loosely drawn box diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index f3d7cfb5c89..c64ef68c6eb 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -110,7 +110,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag`, `crates/ui-egui/src/thumb.rs` | a rejected photo is dimmed on the grids and on the filmstrip, under its marks (the flag keeps its red); P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/thumb.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, the label is a dot in the marks row on every surface (justified grid, square grid, filmstrip) plus translucent colour on the square-grid and filmstrip surrounds; nothing is laid over the photo's pixels (the justified grid's tinted footer band is gone). On the justified grid, which has no surround, the dot is kept before the stars and flag on a narrow photo and stays when Ratings & flags is Never; elsewhere the surround says the label; colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | -| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | +| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, written back to the sidecar, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging; regions and the names on faces are written to the photo's sidecar (`mwg-rs:Regions`, `Iptc4xmpExt:PersonInImage`; see `docs/xmp-interop.md`) | | LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs`, `crates/ui-egui/src/thumb.rs` | grid/filmstrip count badges (the same badge on both, a click expands or collapses the stack, selected or not, one translated tooltip; widgets `stack:`, `film:stack:`), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack | | LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M | | LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) | diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 3886ee6f2e7..a70b003008c 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -119,8 +119,14 @@ LightCraft reads face, pet, focus and barcode regions in the Metadata Working Gr write them, from sidecars and from XMP embedded in the file. Named faces become people in the People view (LR-LIB-PEOPLE in [`parity-checklist.md`](parity-checklist.md)), and every region is drawn as a box in the loupe. -- **Read only.** LightCraft never writes `mwg-rs:Regions`; saving a sidecar keeps another application's regions byte - for byte. Removing or resizing a box in the loupe changes the library only. +- **Written to the photo's sidecar.** Saving a sidecar (Save Metadata to File, or every change with "Automatically + write changes into XMP sidecars" on) writes the photo's regions as `mwg-rs:Regions`, replacing the sidecar's own: + naming, renaming, resizing or removing a box reaches the file. The boxes are written on the upright photo with the + upright size as `mwg-rs:AppliedToDimensions` and no `mwg-rs:Rotation`, so they read back as they were. The unnamed + boxes LightCraft's detector found (its bookkeeping) are left out until someone names them. The names on the faces + also go into `Iptc4xmpExt:PersonInImage`, which is replaced only when there is at least one name (LightCraft doesn't + read it, so a list another application wrote stays when nobody is named here). Exports carry no regions: a crop or + resize would leave the boxes off. - **Areas**: `stArea:x`/`y` are the box's centre, `w`/`h` its size, normalized to the photo (`stArea:unit="pixel"` areas are divided by `mwg-rs:AppliedToDimensions`, and dropped without it). Boxes are clipped to the photo; one that misses it entirely, or has a non-finite, zero or negative size, is skipped (the rest of the list is kept). From 1c3096696c0e290678c1bc215e23db1f723dc429 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 05:22:52 -0600 Subject: [PATCH 02/25] LR-LIB-PEOPLE: fit face names and cleared regions to the sidecar on save Review follow-up: - PersonInImage is now owned and fitted to the sidecar it replaces: the names on the photo's faces, plus names in the file's list that are not the name of one of its face regions (typed elsewhere). Clearing, renaming or removing a face takes its name out of the list. - When the photo has no regions left but the sidecar states a list, an empty list is written, so another reader drops them too; a sidecar that never had one gets none. - Reading a sidecar's regions back keeps the detector's unnamed, catalog-only boxes. - Command help for faces.nameFaces / setName / renamePerson, photo.removeRegion and photo.setRegion, and the docs, say when the sidecar is rewritten. - The end-to-end test re-reads the sidecar into a catalog that lost the face, and checks all four coordinates. --- crates/engine/src/cmd/face_recognize.rs | 6 +- crates/engine/src/cmd/library/specs.rs | 4 +- crates/engine/src/sidecar.rs | 167 +++++++++++++++++++----- crates/engine/src/tests/xmp.rs | 14 +- docs/faces.md | 2 +- docs/parity-checklist.md | 2 +- docs/xmp-interop.md | 20 +-- 7 files changed, 162 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index 110b794fccb..ce7ae891bcd 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -1179,7 +1179,7 @@ pub fn specs() -> Vec { "Name Faces", [], None, - "{faces: [{photo, index}], name} → {named, photos} — name (or, with a null or empty name, clear) many face regions as one undoable step; the sidecar is not touched", + "{faces: [{photo, index}], name} → {named, photos} — name (or, with a null or empty name, clear) many face regions as one undoable step; with auto-write on, the sidecar of each changed original is rewritten (its `mwg-rs:Regions` and `Iptc4xmpExt:PersonInImage`)", super::always, name_faces ), @@ -1197,7 +1197,7 @@ pub fn specs() -> Vec { "Name Face", [], None, - "{id?, index, name} — name a face region (null or empty clears it); undoable; the sidecar is not touched", + "{id?, index, name} — name a face region (null or empty clears it); undoable; with auto-write on, the sidecar of each changed original is rewritten (its `mwg-rs:Regions` and `Iptc4xmpExt:PersonInImage`)", super::always, set_name ), @@ -1206,7 +1206,7 @@ pub fn specs() -> Vec { "Rename Person", [], None, - "{from, to, merge?: bool} → {faces, photos, from, to, merged} — give every in-library face of `from` the name `to` (trimmed, any capitalization), one undo step; refused when `to` is already someone else unless `merge` is true, which combines the two; the sidecar is not touched", + "{from, to, merge?: bool} → {faces, photos, from, to, merged} — give every in-library face of `from` the name `to` (trimmed, any capitalization), one undo step; refused when `to` is already someone else unless `merge` is true, which combines the two; with auto-write on, the sidecar of each changed original is rewritten (its `mwg-rs:Regions` and `Iptc4xmpExt:PersonInImage`)", super::always, rename_person ), diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 74ea2bed562..477b53f22e7 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -721,7 +721,7 @@ pub fn specs() -> Vec { "Remove Face Box", [], None, - "{id?, index} — remove one face / pet region (by its position in the photo's regions) from the photo in the catalog; undoable. The XMP sidecar is never rewritten for this, even with auto-write on, so reading the metadata from the file brings the region back", + "{id?, index} — remove one face / pet region (by its position in the photo's regions) from the photo; undoable. With auto-write on, the sidecar of each changed original is rewritten (its `mwg-rs:Regions` and `Iptc4xmpExt:PersonInImage`)", always, |s, p| { let id = @@ -745,7 +745,7 @@ pub fn specs() -> Vec { "Resize Face Box", [], None, - "{id?, index, rect: {x0, y0, x1, y1}} — set one face / pet region's box (normalized, in the photo's upright frame; clamped to the photo, at least 0.5 % each way) in the catalog; undoable. Like photo.removeRegion it never rewrites the XMP sidecar", + "{id?, index, rect: {x0, y0, x1, y1}} — set one face / pet region's box (normalized, in the photo's upright frame; clamped to the photo, at least 0.5 % each way) ; undoable. With auto-write on, the sidecar of each changed original is rewritten (its `mwg-rs:Regions` and `Iptc4xmpExt:PersonInImage`)", always, |s, p| { const C: &str = "photo.setRegion"; diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 3b10f972f60..24ddfd546f6 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -343,12 +343,23 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { m.keywords = k.clone(); } if let Some(r) = &sc.regions { + // the detector's unnamed boxes are never written to the file (`file_regions`): reading it keeps them + let detected: Vec = m + .regions + .iter() + .filter(|r| { + r.name.as_deref().is_none_or(|n| n.trim().is_empty()) + && r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)) + }) + .cloned() + .collect(); m.regions = r.clone(); // (the photo's size is the upright one) if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) { let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); } + m.regions.extend(detected); } let develop = match &sc.develop { Some(DevelopPatch::Full(s)) => (**s).clone(), @@ -863,21 +874,80 @@ fn with_regions(packet: String, p: &Photo) -> String { x.push_str(" \n"); } x.push_str(" \n \n \n"); - let names = face_names(p); - if !names.is_empty() { - x.push_str(" \n \n"); - for n in &names { - x.push_str(&format!(" {}\n", xml_text(n))); - } - x.push_str(" \n \n"); - } - // into the packet's one description, just before it closes + x.push_str(&people_block(&face_names(p))); + into_description(packet, &x) +} + +/// `xml` added to the packet's one description, just before it closes. +fn into_description(packet: String, xml: &str) -> String { match packet.rfind(" ") { - Some(at) => format!("{}{x}{}", &packet[..at], &packet[at..]), + Some(at) => format!("{}{xml}{}", &packet[..at], &packet[at..]), None => packet, } } +const PEOPLE_OPEN: &str = " \n"; +const PEOPLE_CLOSE: &str = " \n"; + +/// `Iptc4xmpExt:PersonInImage` listing `names`, or nothing for none. +fn people_block(names: &[String]) -> String { + if names.is_empty() { + return String::new(); + } + let mut x = format!("{PEOPLE_OPEN} \n"); + for n in names { + x.push_str(&format!(" {}\n", xml_text(n))); + } + x.push_str(" \n"); + x.push_str(PEOPLE_CLOSE); + x +} + +/// `fresh` (a packet from [`sidecar_packet`]) fitted to the sidecar it replaces, `old`, for the two properties whose +/// right value depends on what the file already says: +/// - `Iptc4xmpExt:PersonInImage`: the names on the photo's faces, plus the names in the file's list that are not the +/// name of a face region in the file (typed in another application). A name that belonged to one of the file's +/// faces goes with it, so clearing a face's name clears it from the list too. +/// - `mwg-rs:Regions`: when the photo has no regions to write but the file states a list, an empty list says they were +/// removed (a missing list says nothing to a reader, so another library that read them would keep them). A file +/// that never had one gets none. +fn fit_to_old(old: &str, fresh: String) -> String { + let old = old.strip_prefix('\u{feff}').unwrap_or(old); + let (Ok(data), Ok(sc)) = (lightcraft_meta::parse_xmp(old), parse_sidecar(old, crate::crs::Target::Rendered)) else { + return fresh; + }; + let lower = |s: &str| s.trim().to_lowercase(); + let face_names: Vec = sc.regions.iter().flatten().filter_map(|r| r.name.as_deref()).map(lower).collect(); + let typed: Vec = data + .values + .get("Iptc4xmpExt:PersonInImage") + .map(|v| v.items().iter().filter_map(|i| i.text()).map(|t| t.trim().to_string()).collect()) + .unwrap_or_default(); + let typed: Vec = typed.into_iter().filter(|t| !t.is_empty() && !face_names.contains(&lower(t))).collect(); + + // the packet's own list, taken out + let mut names: Vec = lightcraft_meta::parse_xmp(&fresh) + .ok() + .and_then(|d| d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect())) + .unwrap_or_default(); + let mut fresh = match (fresh.find(PEOPLE_OPEN), fresh.find(PEOPLE_CLOSE)) { + (Some(a), Some(b)) if b > a => format!("{}{}", &fresh[..a], &fresh[b + PEOPLE_CLOSE.len()..]), + _ => fresh, + }; + for t in typed { + if !names.iter().any(|n| lower(n) == lower(&t)) { + names.push(t); + } + } + if sc.regions.is_some() && !fresh.contains("\n \n \n \n \n", + ); + } + into_description(fresh, &people_block(&names)) +} + /// The properties LightCraft writes and owns in a sidecar: replaced on every save (removed when /// LightCraft has no value, so clearing a field clears it in the file too). All of them are read /// back on import and by Read Metadata from File. @@ -902,16 +972,15 @@ pub const OWNED: &[&str] = &[ // the photo's face, pet and focus regions: LightCraft reads every region of a sidecar into the catalog, so the // catalog's list is the file's list as edited here (see `with_regions`) "mwg-rs:Regions", + // the names on the photo's faces, with any another application listed kept (see `fit_to_old`) + "Iptc4xmpExt:PersonInImage", "lc:*", ]; /// Properties replaced only when LightCraft has a value (capture time; GPS, which LightCraft /// doesn't read from sidecars): otherwise the sidecar's own value stays. Anything else LightCraft /// writes (`xmp:CreatorTool`) goes only into new sidecars. -/// `Iptc4xmpExt:PersonInImage` (the names on the photo's faces) is one of them: LightCraft doesn't read it, so a list -/// another application wrote is replaced only when LightCraft has names to write. -pub const OWNED_IF_STATED: &[&str] = - &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude", "Iptc4xmpExt:PersonInImage"]; +pub const OWNED_IF_STATED: &[&str] = &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude"]; /// Write `data` to `path` atomically: a temp file next to it, synced, then renamed over it. fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { @@ -968,7 +1037,7 @@ fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result< } let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED }; let why = match std::str::from_utf8(&bytes) { - Ok(old) => match lightcraft_meta::merge_xmp(old, &fresh, rules) { + Ok(old) => match lightcraft_meta::merge_xmp(old, &fit_to_old(old, fresh.clone()), rules) { Ok(merged) => return Ok((merged, true, None)), // a readable sidecar whose merge fails (e.g. the merged packet exceeds the XMP limits), or one // that is valid but over the parser's complexity limits: fail the save and keep the file @@ -1981,7 +2050,9 @@ mod tests { } #[test] - fn regions_replace_the_sidecars_own_and_keep_its_person_list_when_nobody_is_named() { + fn saving_fits_regions_and_names_to_the_sidecar_it_replaces() { + use lightcraft_meta::RegionKind::Face; + // Lightroom-style regions, a face name also in PersonInImage, a name typed in elsewhere, and another app's field let old = r#" FaceOld Name - Typed In Elsewhere + Old NameTyped In Elsewhere "#; - let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED }; - let names = |x: &str| -> (Vec, Vec) { - let d = lightcraft_meta::parse_xmp(x).unwrap(); - let sc = parse_sidecar(x, crate::crs::Target::Rendered).unwrap(); - let faces = sc.regions.unwrap_or_default().into_iter().filter_map(|r| r.name).collect(); + let dir = std::env::temp_dir().join(format!("lc-fit-regions-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.xmp"); + std::fs::write(&path, old).unwrap(); + // what a save of `p` leaves in the file: (regions stated?, face names, PersonInImage) + let save = |p: &Photo| -> (bool, Vec, Vec) { + let (x, merged, _) = sidecar_contents(&path, sidecar_packet(p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + assert!(merged); + assert!(x.contains("photomechanic:ColorClass=\"1\""), "{x}"); + std::fs::write(&path, &x).unwrap(); + let d = lightcraft_meta::parse_xmp(&x).unwrap(); + let sc = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap(); let people = d .values .get("Iptc4xmpExt:PersonInImage") .map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect()) .unwrap_or_default(); - (faces, people) + (sc.regions.is_some(), sc.regions.unwrap_or_default().into_iter().filter_map(|r| r.name).collect(), people) }; + let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); - // renamed in LightCraft: the file's regions and person list follow, Photo Mechanic's colour class stays + // renamed here: the regions follow, the old face's name leaves the list, the typed-in name stays let mut p = photo(); - p.meta.regions = vec![region(0.4, 0.4, 0.6, 0.6, lightcraft_meta::RegionKind::Face, Some("New Name"), None)]; - let merged = lightcraft_meta::merge_xmp(old, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); - assert_eq!(names(&merged), (vec!["New Name".to_string()], vec!["New Name".to_string()])); - assert!(merged.contains("photomechanic:ColorClass=\"1\""), "{merged}"); - - // its last box removed: the regions go, the person list nobody named here stays as it was + p.meta.regions = vec![region(0.4, 0.4, 0.6, 0.6, Face, Some("New Name"), None)]; + assert_eq!(save(&p), (true, s(&["New Name"]), s(&["New Name", "Typed In Elsewhere"]))); + // the name cleared: it leaves the list too, the box stays + p.meta.regions[0].name = None; + assert_eq!(save(&p), (true, s(&[]), s(&["Typed In Elsewhere"]))); + // named again, then the box removed: the file says the photo has no regions now + p.meta.regions[0].name = Some("Jane".into()); + assert_eq!(save(&p), (true, s(&["Jane"]), s(&["Jane", "Typed In Elsewhere"]))); p.meta.regions.clear(); - let merged = lightcraft_meta::merge_xmp(old, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); - assert_eq!(names(&merged), (vec![], vec!["Typed In Elsewhere".to_string()])); - // and saving again changes nothing - let again = lightcraft_meta::merge_xmp(&merged, &sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), rules).unwrap(); - assert_eq!(names(&again), names(&merged)); + assert_eq!(save(&p), (true, s(&[]), s(&["Typed In Elsewhere"]))); + // saving again changes nothing + let before = std::fs::read_to_string(&path).unwrap(); + save(&p); + assert_eq!(std::fs::read_to_string(&path).unwrap(), before); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_sidecar_that_never_had_regions_gets_none() { + let dir = std::env::temp_dir().join(format!("lc-no-regions-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.xmp"); + let mut p = photo(); + std::fs::write(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new())).unwrap(); + // only the detector's unnamed box: catalog-only + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + p.meta.regions = vec![region(0.1, 0.1, 0.2, 0.2, lightcraft_meta::RegionKind::Face, None, Some(&detected))]; + let (x, _, _) = sidecar_contents(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + assert!(!x.contains("mwg-rs:Regions") && !x.contains("PersonInImage"), "{x}"); + let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 2ffa2139a14..88b6157f707 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2285,11 +2285,19 @@ fn naming_a_face_writes_it_into_the_sidecar() { if let Ok(keep) = std::env::var("LC_KEEP_FACE_SIDECAR") { std::fs::copy(src.join("a.xmp"), keep).unwrap(); } - // reading the file again gives the same face + // the catalog loses the face (not written: no auto-write outside a command) and the detector finds another box + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + let other = Rect { x0: 0.05, y0: 0.1, x1: 0.15, y1: 0.2 }; + meta.regions = vec![Region { rect: other, kind: RegionKind::Face, name: None, description: Some("Detected by YuNet 2023mar".into()) }]; + s.commit("Detect Faces", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + assert_eq!(std::fs::read_to_string(src.join("a.xmp")).unwrap(), x, "the sidecar is as named"); + // reading the file brings the named face back and keeps the detector's catalog-only box s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); let r = &s.catalog.photo(id).unwrap().meta.regions; - assert_eq!(r.len(), 1); + assert_eq!(r.len(), 2, "{r:?}"); assert_eq!(r[0].name.as_deref(), Some("Jane Doe")); - assert!((r[0].rect.x0 - 0.25).abs() < 1e-5 && (r[0].rect.y1 - 0.75).abs() < 1e-5, "{:?}", r[0].rect); + let close = |a: &Rect, b: &Rect| [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-5); + assert!(close(&r[0].rect, &rect), "{:?}", r[0].rect); + assert_eq!((r[1].name.as_deref(), r[1].rect), (None, other)); let _ = std::fs::remove_dir_all(&src); } diff --git a/docs/faces.md b/docs/faces.md index 90d74f159be..131de0561e6 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -315,7 +315,7 @@ at once (`faces.renamePerson`). The name is matched the way the cards are groupe every matching face is stored with the exact new spelling, so a change of capitalization alone updates them all. The dialog says how many faces that is. If the new name is already someone else, it refuses until **Combine with the existing person** is ticked; that makes one person, and Undo separates them again. Cancelling changes nothing. A person filter, -the open person page and the way back to it follow the new name. With automatic XMP writing on, every renamed photo's sidecar is rewritten. +the open person page and the way back to it follow the new name. With automatic XMP writing on, the sidecar of each renamed file-backed original is rewritten (virtual copies have none). The thumbnail-size slider in the bottom bar sizes the faces here too, with limits of their own. Every face is shown by the same kind of box: the detector's own box once the scan has looked at it (kept beside its embedding), so a loosely drawn box diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index c64ef68c6eb..304fc743256 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -110,7 +110,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag`, `crates/ui-egui/src/thumb.rs` | a rejected photo is dimmed on the grids and on the filmstrip, under its marks (the flag keeps its red); P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/thumb.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, the label is a dot in the marks row on every surface (justified grid, square grid, filmstrip) plus translucent colour on the square-grid and filmstrip surrounds; nothing is laid over the photo's pixels (the justified grid's tinted footer band is gone). On the justified grid, which has no surround, the dot is kept before the stars and flag on a narrow photo and stays when Ratings & flags is Never; elsewhere the surround says the label; colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | -| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, written back to the sidecar, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging; regions and the names on faces are written to the photo's sidecar (`mwg-rs:Regions`, `Iptc4xmpExt:PersonInImage`; see `docs/xmp-interop.md`) | +| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, written back to the sidecar, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (undoable, one undo step per drag; with auto-write on, the original's sidecar follows); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging; regions and the names on faces are written to the photo's sidecar (`mwg-rs:Regions`, `Iptc4xmpExt:PersonInImage`; see `docs/xmp-interop.md`) | | LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs`, `crates/ui-egui/src/thumb.rs` | grid/filmstrip count badges (the same badge on both, a click expands or collapses the stack, selected or not, one translated tooltip; widgets `stack:`, `film:stack:`), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack | | LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M | | LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) | diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index a70b003008c..9acff0b2ba5 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -119,14 +119,18 @@ LightCraft reads face, pet, focus and barcode regions in the Metadata Working Gr write them, from sidecars and from XMP embedded in the file. Named faces become people in the People view (LR-LIB-PEOPLE in [`parity-checklist.md`](parity-checklist.md)), and every region is drawn as a box in the loupe. -- **Written to the photo's sidecar.** Saving a sidecar (Save Metadata to File, or every change with "Automatically - write changes into XMP sidecars" on) writes the photo's regions as `mwg-rs:Regions`, replacing the sidecar's own: - naming, renaming, resizing or removing a box reaches the file. The boxes are written on the upright photo with the - upright size as `mwg-rs:AppliedToDimensions` and no `mwg-rs:Rotation`, so they read back as they were. The unnamed - boxes LightCraft's detector found (its bookkeeping) are left out until someone names them. The names on the faces - also go into `Iptc4xmpExt:PersonInImage`, which is replaced only when there is at least one name (LightCraft doesn't - read it, so a list another application wrote stays when nobody is named here). Exports carry no regions: a crop or - resize would leave the boxes off. +- **Written to the photo's sidecar.** Saving a sidecar (Save Metadata to File, or, with "Automatically write changes + into XMP sidecars" on, each naming, renaming, resizing or removal of a box, and their undo) writes the photo's + regions as `mwg-rs:Regions`, replacing the sidecar's own. Detection alone (Detect Faces, the background scan) does + not rewrite a sidecar: the detector's unnamed boxes are LightCraft's bookkeeping and are left out until someone + names them, and reading the sidecar back keeps them. The boxes are written on the upright photo with the upright + size as `mwg-rs:AppliedToDimensions` and no `mwg-rs:Rotation`, so they read back as they were. When the photo has + no regions left but the sidecar has a list, an empty list is written, so another library reading the file drops + them too; a sidecar that never had one gets none. +- **Names in `Iptc4xmpExt:PersonInImage`.** The names on the photo's faces are listed there too. Names in the + sidecar's list that are not the name of one of its face regions (typed in another application) are kept; a name + that belonged to a face goes when the face is renamed, cleared or removed. LightCraft doesn't read this list. +- Exports carry no regions: a crop or resize would leave the boxes off. - **Areas**: `stArea:x`/`y` are the box's centre, `w`/`h` its size, normalized to the photo (`stArea:unit="pixel"` areas are divided by `mwg-rs:AppliedToDimensions`, and dropped without it). Boxes are clipped to the photo; one that misses it entirely, or has a non-finite, zero or negative size, is skipped (the rest of the list is kept). From a3fce4c10908891f617f1d68fdec0e97c3bb1435 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 06:21:07 -0600 Subject: [PATCH 03/25] LR-LIB-PEOPLE: write boxes on turned files in the stored frame, as Lightroom does The MWG guidelines apply regions to the stored image. For a file whose Exif orientation is 3, 6 or 8, boxes are now written in the stored frame with the turn as mwg-rs:Rotation (pi, -pi/2, +pi/2) and the upright size as AppliedToDimensions, as Lightroom Classic writes them and as parse_xmp already reads them back. Mirrored orientations, which MWG can't describe, stay upright, as the reader takes them. The file's orientation is read only when the photo has regions to write. fit_to_old keeps every name in the sidecar's PersonInImage when its regions can't be read, and slices with get(). --- crates/engine/src/sidecar.rs | 86 +++++++++++++++++++++++++++------- crates/engine/src/tests/xmp.rs | 30 ++++++++++++ docs/xmp-interop.md | 8 +++- 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 24ddfd546f6..d0b6f23cdb3 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -737,7 +737,10 @@ const ORIENTATION_SPAN: u64 = 1 << 20; pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { // the regions go into the photo's own sidecar only: an export's packet describes the picture as exported, which a // crop or a resize leaves the boxes no longer fit - with_regions(sidecar_packet_with(p, cat, false), p) + // the file's own orientation decides how the boxes are written (`with_regions`); a photo with none to write + // doesn't need its file read + let orientation = if file_regions(p).is_empty() { None } else { file_path(p).and_then(file_orientation) }; + with_regions(sidecar_packet_with(p, cat, false), p, orientation) } /// [`sidecar_packet`], without any location (GPS, sublocation, city, state, country) when @@ -824,10 +827,14 @@ fn xml_text(s: &str) -> String { } /// `packet` with the photo's regions (`mwg-rs:Regions`, MWG Region Guidelines 2.0) and the names on its faces -/// (`Iptc4xmpExt:PersonInImage`) added to its description. The boxes are written on the upright photo, as LightCraft -/// keeps them, with the upright size as `AppliedToDimensions` (the photo's own `width` × `height`), so reading the -/// sidecar back gives the same boxes. Nothing is added for a photo without regions. -fn with_regions(packet: String, p: &Photo) -> String { +/// (`Iptc4xmpExt:PersonInImage`) added to its description. Nothing is added for a photo without regions. +/// +/// `AppliedToDimensions` is the photo's upright size (its `width` × `height`). The boxes are written the way +/// Lightroom Classic writes them, which [`lightcraft_meta::parse_xmp`] turns back upright: for a file whose Exif +/// orientation is 3, 6 or 8 (`orientation`), in the frame of the photo as stored, with that turn as `mwg-rs:Rotation` +/// (π, −π/2, +π/2), as the MWG guidelines place regions on the stored image; otherwise on the upright photo. MWG +/// can't say "mirrored", so boxes on mirrored photos (2, 4, 5, 7) are written upright, as the reader takes them. +fn with_regions(packet: String, p: &Photo, orientation: Option) -> String { let regions = file_regions(p); if regions.is_empty() { return packet; @@ -847,14 +854,20 @@ fn with_regions(packet: String, p: &Photo) -> String { continue; } x.push_str(" \n"); - // stArea:x/y are the box's centre (MWG Region Guidelines §Area) + // stArea:x/y are the box's centre (MWG Region Guidelines §Area); (ux, uy, uw, uh) on the upright photo + let (ux, uy, uw, uh) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, x1 - x0, y1 - y0); + let (cx, cy, w, h, rotation) = match orientation { + Some(lightcraft_meta::Orientation::Rotate90) => (uy, 1.0 - ux, uh, uw, Some("-1.57080")), + Some(lightcraft_meta::Orientation::Rotate270) => (1.0 - uy, ux, uh, uw, Some("1.57080")), + Some(lightcraft_meta::Orientation::Rotate180) => (1.0 - ux, 1.0 - uy, uw, uh, Some("3.14159")), + _ => (ux, uy, uw, uh, None), + }; x.push_str(&format!( - " \n {:.6}\n {:.6}\n {:.6}\n {:.6}\n normalized\n \n", - (x0 + x1) / 2.0, - (y0 + y1) / 2.0, - x1 - x0, - y1 - y0 + " \n {cx:.6}\n {cy:.6}\n {w:.6}\n {h:.6}\n normalized\n \n" )); + if let Some(r) = rotation { + x.push_str(&format!(" {r}\n")); + } let kind = match &r.kind { lightcraft_meta::RegionKind::Face => "Face", lightcraft_meta::RegionKind::Pet => "Pet", @@ -881,7 +894,10 @@ fn with_regions(packet: String, p: &Photo) -> String { /// `xml` added to the packet's one description, just before it closes. fn into_description(packet: String, xml: &str) -> String { match packet.rfind(" ") { - Some(at) => format!("{}{xml}{}", &packet[..at], &packet[at..]), + Some(at) => match (packet.get(..at), packet.get(at..)) { + (Some(before), Some(after)) => format!("{before}{xml}{after}"), + _ => packet, + }, None => packet, } } @@ -913,11 +929,14 @@ fn people_block(names: &[String]) -> String { /// that never had one gets none. fn fit_to_old(old: &str, fresh: String) -> String { let old = old.strip_prefix('\u{feff}').unwrap_or(old); - let (Ok(data), Ok(sc)) = (lightcraft_meta::parse_xmp(old), parse_sidecar(old, crate::crs::Target::Rendered)) else { + // (a file that isn't XMP can't be merged either: `sidecar_contents` handles it) + let Ok(data) = lightcraft_meta::parse_xmp(old) else { return fresh; }; + // its regions; if they can't be read, every name in its list is kept as typed in elsewhere + let regions = parse_sidecar(old, crate::crs::Target::Rendered).ok().and_then(|sc| sc.regions); let lower = |s: &str| s.trim().to_lowercase(); - let face_names: Vec = sc.regions.iter().flatten().filter_map(|r| r.name.as_deref()).map(lower).collect(); + let face_names: Vec = regions.iter().flatten().filter_map(|r| r.name.as_deref()).map(lower).collect(); let typed: Vec = data .values .get("Iptc4xmpExt:PersonInImage") @@ -931,7 +950,10 @@ fn fit_to_old(old: &str, fresh: String) -> String { .and_then(|d| d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect())) .unwrap_or_default(); let mut fresh = match (fresh.find(PEOPLE_OPEN), fresh.find(PEOPLE_CLOSE)) { - (Some(a), Some(b)) if b > a => format!("{}{}", &fresh[..a], &fresh[b + PEOPLE_CLOSE.len()..]), + (Some(a), Some(b)) if b > a => match (fresh.get(..a), fresh.get(b.saturating_add(PEOPLE_CLOSE.len())..)) { + (Some(before), Some(after)) => format!("{before}{after}"), + _ => fresh, + }, _ => fresh, }; for t in typed { @@ -939,7 +961,7 @@ fn fit_to_old(old: &str, fresh: String) -> String { names.push(t); } } - if sc.regions.is_some() && !fresh.contains("\n \n \n \n \n", @@ -2117,6 +2139,38 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn boxes_on_a_turned_file_are_written_as_lightroom_writes_them() { + use lightcraft_meta::Orientation::{FlipH, Normal, Rotate90, Rotate180, Rotate270, Transpose}; + let mut p = photo(); + let upright = region(0.1, 0.2, 0.3, 0.6, lightcraft_meta::RegionKind::Face, Some("Ann"), None); + p.meta.regions = vec![upright.clone()]; + for (o, rotation, area) in [ + (Rotate90, Some("-1.57080"), [0.4, 0.8, 0.4, 0.2]), + (Rotate270, Some("1.57080"), [0.6, 0.2, 0.4, 0.2]), + (Rotate180, Some("3.14159"), [0.8, 0.6, 0.2, 0.4]), + (Normal, None, [0.2, 0.4, 0.2, 0.4]), + (FlipH, None, [0.2, 0.4, 0.2, 0.4]), + (Transpose, None, [0.2, 0.4, 0.2, 0.4]), + ] { + let x = with_regions(sidecar_packet_with(&p, &lightcraft_catalog::Catalog::new(), false), &p, Some(o)); + assert_eq!(x.contains(""), rotation.is_some(), "{o:?}: {x}"); + if let Some(r) = rotation { + assert!(x.contains(&format!("{r}")), "{o:?}: {x}"); + } + for (tag, v) in ["x", "y", "w", "h"].iter().zip(area) { + assert!(x.contains(&format!("{v:.6}")), "{o:?} {tag}: {x}"); + } + // read back (the reader turns Lightroom's boxes upright): the same box + let got = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions.unwrap()[0].rect; + let want = upright.rect; + assert!( + [(got.x0, want.x0), (got.y0, want.y0), (got.x1, want.x1), (got.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-5), + "{o:?}: {got:?}" + ); + } + } + #[test] fn exports_carry_no_regions() { let mut p = photo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 88b6157f707..45f9dc998ef 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2301,3 +2301,33 @@ fn naming_a_face_writes_it_into_the_sidecar() { assert_eq!((r[1].name.as_deref(), r[1].rect), (None, other)); let _ = std::fs::remove_dir_all(&src); } + +/// A face named on a photo whose file is stored sideways (Exif orientation 6) is written in the stored frame with +/// Lightroom's `mwg-rs:Rotation`, and reading the sidecar back puts it on the same face of the upright photo. +#[test] +fn a_face_on_a_turned_photo_is_written_in_the_stored_frame_and_read_back_upright() { + use lightcraft_meta::{Rect, Region, RegionKind}; + let src = temp_dir("face-write-turned"); + write_turned_jpeg(&src.join("t.jpg"), None); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + assert_eq!((s.catalog.photo(id).unwrap().width, s.catalog.photo(id).unwrap().height), (24, 32), "upright"); + let rect = Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions = vec![Region { rect, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; + s.commit("Name", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let x = std::fs::read_to_string(src.join("t.xmp")).unwrap(); + assert!(x.contains("-1.57080") && x.contains("24"), "{x}"); + // the catalog forgets the box; reading the sidecar brings it back where it was + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions.clear(); + s.commit("Forget", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + let r = s.catalog.photo(id).unwrap().meta.regions.clone(); + assert_eq!(r.len(), 1); + let g = r[0].rect; + assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); + let _ = std::fs::remove_dir_all(&src); +} diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 9acff0b2ba5..51dd5d87a70 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -123,8 +123,12 @@ write them, from sidecars and from XMP embedded in the file. Named faces become into XMP sidecars" on, each naming, renaming, resizing or removal of a box, and their undo) writes the photo's regions as `mwg-rs:Regions`, replacing the sidecar's own. Detection alone (Detect Faces, the background scan) does not rewrite a sidecar: the detector's unnamed boxes are LightCraft's bookkeeping and are left out until someone - names them, and reading the sidecar back keeps them. The boxes are written on the upright photo with the upright - size as `mwg-rs:AppliedToDimensions` and no `mwg-rs:Rotation`, so they read back as they were. When the photo has + names them, and reading the sidecar back keeps them. `mwg-rs:AppliedToDimensions` is the upright size, and the + boxes are written as Lightroom Classic writes them: for a file whose Exif orientation is 3, 6 or 8, in the frame of + the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`; otherwise, and on + mirrored photos (2, 4, 5, 7), which MWG can't describe, on the upright photo. The file's orientation is read for + this when the photo has regions to write (for a raw, the whole file, as Read Metadata from File does). Either way + they read back as they were. When the photo has no regions left but the sidecar has a list, an empty list is written, so another library reading the file drops them too; a sidecar that never had one gets none. - **Names in `Iptc4xmpExt:PersonInImage`.** The names on the photo's faces are listed there too. Names in the From 708fc1fc707ead751e1662ec153367c38b04f052 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 07:28:27 -0600 Subject: [PATCH 04/25] LR-LIB-PEOPLE: keep a deliberate clear of file regions as an empty list Review of #4512 (CodeRabbit, deliberate clear): - mwg-rs:Regions moves to OWNED_IF_STATED. A save states it when the photo has regions to write, and states an empty list when the file held regions LightCraft read and the photo has none left (or only the detector's unnamed boxes). Otherwise the file's own list stays: no list stays absent, an empty list stays empty (restated, so a save doesn't move it), and a list LightCraft reads nothing from is no longer thrown away by a save. - A catalog box that can't be written (not finite, empty, off the photo) counts as none, so it can't produce an empty list by accident; PersonInImage lists only the names of written faces. - Reading regions back keeps the detector's unnamed boxes, except one on a face the file has a box for (IoU >= 0.5), so a face named in another library isn't doubled. Tests: every branch of the rule, the reader's dedupe, two libraries sharing a sidecar (remove, re-read, undo), and a randomized run of edits (8 x 400 by default; LC_REGION_FUZZ_RUNS=300 passed) checking that the file matches the catalog, re-reading round-trips, typed-in names survive and a second save changes nothing. --- crates/engine/src/sidecar.rs | 335 ++++++++++++++++++++++++++++++--- crates/engine/src/tests/xmp.rs | 44 +++++ docs/xmp-interop.md | 10 +- 3 files changed, 360 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d0b6f23cdb3..4a461892457 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -344,22 +344,25 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { } if let Some(r) = &sc.regions { // the detector's unnamed boxes are never written to the file (`file_regions`): reading it keeps them - let detected: Vec = m - .regions - .iter() - .filter(|r| { - r.name.as_deref().is_none_or(|n| n.trim().is_empty()) - && r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)) - }) - .cloned() - .collect(); + let detected: Vec = + m.regions.iter().filter(|r| r.name.as_deref().is_none_or(|n| n.trim().is_empty()) && is_detected(r)).cloned().collect(); m.regions = r.clone(); // (the photo's size is the upright one) if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) { let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); } - m.regions.extend(detected); + // …except one on a face the file has a box for (named in another library, say): the file's box stands for it + let overlaps = |a: &lightcraft_meta::Rect, b: &lightcraft_meta::Rect| { + let common = a.intersect(b).area(); + let all = a.area() + b.area() - common; + all > 0.0 && common / all >= 0.5 + }; + let kept: Vec = detected + .into_iter() + .filter(|d| !m.regions.iter().any(|f| f.kind == lightcraft_meta::RegionKind::Face && overlaps(&d.rect, &f.rect))) + .collect(); + m.regions.extend(kept); } let develop = match &sc.develop { Some(DevelopPatch::Full(s)) => (**s).clone(), @@ -792,15 +795,29 @@ pub fn sidecar_packet_with(p: &Photo, cat: &lightcraft_catalog::Catalog, remove_ /// The regions a sidecar carries: every region of the photo except the unnamed faces LightCraft's own detector /// found (its bookkeeping, marked `Detected by …`), which are not worth a file write until someone names them. fn file_regions(p: &Photo) -> Vec<&lightcraft_meta::Region> { - let detected = |r: &lightcraft_meta::Region| r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)); let named = |r: &lightcraft_meta::Region| r.name.as_deref().is_some_and(|n| !n.trim().is_empty()); - p.meta.regions.iter().filter(|r| named(r) || !detected(r)).collect() + p.meta.regions.iter().filter(|r| (named(r) || !is_detected(r)) && writable_rect(r.rect).is_some()).collect() +} + +/// One of the detector's boxes (`Detected by …`; see [`crate::cmd::face_detect::MARK`]). +fn is_detected(r: &lightcraft_meta::Region) -> bool { + r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)) +} + +/// A box as it can be written: clamped to the photo, finite and not empty. A catalog box that isn't is never +/// written, and a photo with only such boxes has none to write. +fn writable_rect(r: lightcraft_meta::Rect) -> Option<(f64, f64, f64, f64)> { + let (x0, y0) = (r.x0.clamp(0.0, 1.0), r.y0.clamp(0.0, 1.0)); + let (x1, y1) = (r.x1.clamp(0.0, 1.0), r.y1.clamp(0.0, 1.0)); + // (`clamp` keeps NaN, which fails these comparisons) + (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1)) } -/// The people named on a photo's faces, trimmed, each once (case-insensitive), in region order. +/// The people named on the photo's faces that are written ([`file_regions`]), trimmed, each once (case-insensitive), +/// in region order. fn face_names(p: &Photo) -> Vec { let mut names: Vec = Vec::new(); - for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { + for r in file_regions(p).into_iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; if !names.iter().any(|m| m.to_lowercase() == n.to_lowercase()) { names.push(n.to_string()); @@ -848,11 +865,9 @@ fn with_regions(packet: String, p: &Photo, orientation: Option\n \n"); for r in ®ions { - let (x0, y0) = (r.rect.x0.clamp(0.0, 1.0), r.rect.y0.clamp(0.0, 1.0)); - let (x1, y1) = (r.rect.x1.clamp(0.0, 1.0), r.rect.y1.clamp(0.0, 1.0)); - if !(x1 > x0 && y1 > y0) { + let Some((x0, y0, x1, y1)) = writable_rect(r.rect) else { continue; - } + }; x.push_str(" \n"); // stArea:x/y are the box's centre (MWG Region Guidelines §Area); (ux, uy, uw, uh) on the upright photo let (ux, uy, uw, uh) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, x1 - x0, y1 - y0); @@ -924,9 +939,12 @@ fn people_block(names: &[String]) -> String { /// - `Iptc4xmpExt:PersonInImage`: the names on the photo's faces, plus the names in the file's list that are not the /// name of a face region in the file (typed in another application). A name that belonged to one of the file's /// faces goes with it, so clearing a face's name clears it from the list too. -/// - `mwg-rs:Regions`: when the photo has no regions to write but the file states a list, an empty list says they were -/// removed (a missing list says nothing to a reader, so another library that read them would keep them). A file -/// that never had one gets none. +/// - `mwg-rs:Regions`: when the photo has no regions to write but the file has regions LightCraft can read, they were +/// removed here (every region in the file is read into the catalog), and an empty list says so: a missing list says +/// nothing to a reader, so another library that read them would keep them. The detector's unnamed boxes are never +/// written, so a photo left with only those counts as cleared too; reading the file back keeps them ([`merge_into`]). +/// A file with no list keeps none, one with an empty list keeps it, and one with a list LightCraft reads nothing +/// from keeps it as it is ([`OWNED_IF_STATED`]). fn fit_to_old(old: &str, fresh: String) -> String { let old = old.strip_prefix('\u{feff}').unwrap_or(old); // (a file that isn't XMP can't be merged either: `sidecar_contents` handles it) @@ -961,7 +979,11 @@ fn fit_to_old(old: &str, fresh: String) -> String { names.push(t); } } - if regions.is_some() && !fresh.contains("\n \n \n \n \n", @@ -991,9 +1013,6 @@ pub const OWNED: &[&str] = &[ "xmpRights:Marked", "xmpRights:UsageTerms", "xmpRights:WebStatement", - // the photo's face, pet and focus regions: LightCraft reads every region of a sidecar into the catalog, so the - // catalog's list is the file's list as edited here (see `with_regions`) - "mwg-rs:Regions", // the names on the photo's faces, with any another application listed kept (see `fit_to_old`) "Iptc4xmpExt:PersonInImage", "lc:*", @@ -1002,7 +1021,12 @@ pub const OWNED: &[&str] = &[ /// Properties replaced only when LightCraft has a value (capture time; GPS, which LightCraft /// doesn't read from sidecars): otherwise the sidecar's own value stays. Anything else LightCraft /// writes (`xmp:CreatorTool`) goes only into new sidecars. -pub const OWNED_IF_STATED: &[&str] = &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude"]; +/// +/// `mwg-rs:Regions` is one of them. A packet states it when the photo has regions to write ([`with_regions`]), and +/// states an empty list when the photo's last readable region in the file was removed ([`fit_to_old`]); otherwise +/// the file's list stays as it is: one that never had a list gets none, an empty one stays empty, and a list +/// LightCraft could read nothing from (boxes in pixels with no size, say) is not thrown away by a save. +pub const OWNED_IF_STATED: &[&str] = &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude", "mwg-rs:Regions"]; /// Write `data` to `path` atomically: a temp file next to it, synced, then renamed over it. fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { @@ -2171,6 +2195,265 @@ mod tests { } } + /// A sidecar with Lightroom-style regions (in the order given, upright) and `people` as PersonInImage. + fn sidecar_with(regions: &[(f64, f64, f64, f64, Option<&str>)], people: &[&str]) -> String { + let mut items = String::new(); + for (cx, cy, w, h, name) in regions { + items.push_str(&format!( + "Face{}", + name.map(|n| format!("{n}")).unwrap_or_default() + )); + } + let people: String = people.iter().map(|n| format!("{n}")).collect(); + let people = if people.is_empty() { + String::new() + } else { + format!("{people}") + }; + format!( + r#" + + {items} + {people} + "# + ) + } + + /// A scratch sidecar path, unique to the test. + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-regions-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("a.xmp") + } + + /// Save `p` over `path` as the app does; the new contents. + fn save_over(path: &Path, p: &Photo) -> String { + let (x, _, _) = sidecar_contents(path, sidecar_packet(p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + std::fs::write(path, &x).unwrap(); + x + } + + #[test] + fn a_cleared_photo_states_an_empty_list_only_when_its_file_had_regions() { + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + let det = || region(0.6, 0.6, 0.7, 0.7, lightcraft_meta::RegionKind::Face, None, Some(&detected)); + let stated = |x: &str| parse_sidecar(x, crate::crs::Target::Rendered).unwrap().regions; + + // the file had a readable face; the photo has none left, or only the detector's boxes: an empty list + for left in [vec![], vec![det()]] { + let path = scratch("cleared"); + std::fs::write(&path, sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))], &[])).unwrap(); + let mut p = photo(); + p.meta.regions = left.clone(); + let x = save_over(&path, &p); + assert_eq!(stated(&x), Some(vec![]), "{left:?}: {x}"); + assert!(x.contains("photomechanic:ColorClass=\"1\"")); + // saving again leaves it as it is + assert_eq!(save_over(&path, &p), x); + } + // a file with no list: none, with or without the detector's boxes + for left in [vec![], vec![det()]] { + let path = scratch("never"); + let mut p = photo(); + std::fs::write(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new())).unwrap(); + p.meta.regions = left; + let x = save_over(&path, &p); + assert!(!x.contains("mwg-rs:Regions"), "{x}"); + } + // a file stating an empty list keeps it + let path = scratch("empty"); + std::fs::write(&path, sidecar_with(&[], &[])).unwrap(); + let x = save_over(&path, &photo()); + assert_eq!(stated(&x), Some(vec![]), "{x}"); + // a list LightCraft reads nothing from (pixel areas with no size): a save leaves it alone + let path = scratch("unreadable"); + let old = sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))], &[]).replace("stArea:unit=\"normalized\"", "stArea:unit=\"pixel\""); + std::fs::write(&path, &old).unwrap(); + assert_eq!(stated(&old), Some(vec![]), "the reader can't use pixel areas without a size"); + let x = save_over(&path, &photo()); + assert!(x.contains("stArea:unit=\"pixel\"") && x.contains("Ann"), "kept: {x}"); + // a catalog box that can't be written (not finite, empty, off the photo) counts as none + for bad in [ + region(f64::NAN, 0.1, 0.2, 0.2, lightcraft_meta::RegionKind::Face, Some("Nan"), None), + region(0.3, 0.3, 0.3, 0.5, lightcraft_meta::RegionKind::Face, Some("Flat"), None), + region(1.2, 1.2, 1.5, 1.5, lightcraft_meta::RegionKind::Face, Some("Off"), None), + region(f64::NEG_INFINITY, 0.1, f64::INFINITY, 0.2, lightcraft_meta::RegionKind::Face, Some("Inf"), None), + ] { + let path = scratch("bad"); + let mut p = photo(); + std::fs::write(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new())).unwrap(); + p.meta.regions = vec![bad.clone()]; + let x = save_over(&path, &p); + // (an infinite box clamps to the photo's width: that one is writable) + if bad.name.as_deref() == Some("Inf") { + assert_eq!(stated(&x).map(|r| r.len()), Some(1), "{x}"); + } else { + assert!(!x.contains("mwg-rs:Regions"), "{bad:?}: {x}"); + } + } + } + + #[test] + fn reading_back_keeps_the_detectors_boxes_but_not_on_a_face_the_file_has() { + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + let mut p = photo(); + p.meta.regions = vec![ + // the same face as the file's Ann (named in another library) + region(0.41, 0.41, 0.6, 0.6, lightcraft_meta::RegionKind::Face, None, Some(&detected)), + // a face the file doesn't have + region(0.05, 0.05, 0.15, 0.15, lightcraft_meta::RegionKind::Face, None, Some(&detected)), + // a box another app drew, gone from the file now + region(0.7, 0.7, 0.9, 0.9, lightcraft_meta::RegionKind::Face, None, None), + ]; + let sc = parse_sidecar(&sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))], &[]), crate::crs::Target::Rendered).unwrap(); + merge_into(&mut p, &sc, "now"); + let got: Vec<(Option<&str>, f64)> = p.meta.regions.iter().map(|r| (r.name.as_deref(), r.rect.x0)).collect(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0].0, Some("Ann")); + assert!((got[1].1 - 0.05).abs() < 1e-9, "{got:?}"); + } + + /// A random box: one in ten can't be written as it is (not finite, empty, off the photo, hanging off an edge). + fn box_at(next: &mut impl FnMut(usize) -> usize) -> lightcraft_meta::Rect { + if next(10) == 0 { + match next(4) { + 0 => lightcraft_meta::Rect { x0: f64::NAN, y0: 0.1, x1: 0.2, y1: 0.3 }, + 1 => lightcraft_meta::Rect { x0: 0.5, y0: 0.5, x1: 0.5, y1: 0.9 }, + 2 => lightcraft_meta::Rect { x0: 1.1, y0: 1.1, x1: 1.4, y1: 1.4 }, + _ => lightcraft_meta::Rect { x0: -0.2, y0: 0.9, x1: 0.1, y1: 1.3 }, + } + } else { + let (x, y) = (next(80) as f64 / 100.0, next(80) as f64 / 100.0); + lightcraft_meta::Rect { x0: x, y0: y, x1: x + 0.02 + next(18) as f64 / 100.0, y1: y + 0.02 + next(18) as f64 / 100.0 } + } + } + + /// Hundreds of random edits, each saved over the last sidecar: the file always says exactly what the catalog + /// would write, reading it back gives the catalog's boxes, the names typed elsewhere survive, and a second save + /// changes nothing. Bad boxes, odd names and clears included. + #[test] + fn random_edits_keep_the_sidecar_and_the_catalog_in_step() { + use lightcraft_meta::RegionKind::{Face, Pet}; + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + let names = [ + "Ann", + "ann", + "Mimì", + "A & B \"d\" 'e'", + " Padded ", + "", + " ", + "x,y]z|{w}", + "Ünïcödé 名前", + "a\u{1}b", + "Rodolfo [tenor]", + "Very Long Name Very Long Name Very Long Name Very Long Name Very Long Name Very Long Name", + ]; + // eight runs by default; LC_REGION_FUZZ_RUNS=n for more + let runs: u64 = std::env::var("LC_REGION_FUZZ_RUNS").ok().and_then(|v| v.parse().ok()).unwrap_or(8); + for run in 0..runs { + let mut seed: u64 = 0x5eed_1234_abcd ^ run.wrapping_mul(0x9e37_79b9_7f4a_7c15); + let mut next = move |n: usize| -> usize { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((seed >> 33) as usize) % n.max(1) + }; + let path = scratch(&format!("random-{run}")); + // start from a sidecar another app wrote: a named face and a name typed in elsewhere + std::fs::write(&path, sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Lightroom Face"))], &["Typed Elsewhere", "Lightroom Face"])).unwrap(); + let mut p = photo(); + merge_into(&mut p, &parse_sidecar(&std::fs::read_to_string(&path).unwrap(), crate::crs::Target::Rendered).unwrap(), "now"); + let clean = |n: &str| n.chars().filter(|c| !c.is_control()).collect::().trim().to_string(); + let mut had_regions = true; + for step in 0..400 { + let n = p.meta.regions.len(); + match next(8) { + 0 => { + let rect = box_at(&mut next); + let kind = if next(8) == 0 { Pet } else { Face }; + p.meta.regions.push(lightcraft_meta::Region { rect, kind, name: Some(names[next(names.len())].into()), description: None }); + } + 1 => { + let rect = box_at(&mut next); + p.meta.regions.push(lightcraft_meta::Region { rect, kind: Face, name: None, description: Some(detected.clone()) }); + } + 2 if n > 0 => p.meta.regions[next(n)].name = Some(names[next(names.len())].into()), + 3 if n > 0 => p.meta.regions[next(n)].name = None, + 4 if n > 0 => { + p.meta.regions.remove(next(n)); + } + 5 if n > 0 => { + let from = p.meta.regions[next(n)].name.clone(); + let to = names[next(names.len())]; + for r in &mut p.meta.regions { + if r.name == from { + r.name = Some(to.into()); + } + } + } + 6 => p.meta.regions.clear(), + _ => p.rating = next(6) as u8, // a save that changes no region + } + + let x = save_over(&path, &p); + let sc = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap(); + let want: Vec<&lightcraft_meta::Region> = file_regions(&p); + // the file's list is exactly what the catalog writes (or an empty one once it had regions) + match &sc.regions { + Some(got) => { + assert_eq!(got.len(), want.len(), "run {run} step {step}: {x}"); + for (g, w) in got.iter().zip(&want) { + let wr = w.rect.intersect(&lightcraft_meta::Rect::UNIT); + assert!( + [(g.rect.x0, wr.x0), (g.rect.y0, wr.y0), (g.rect.x1, wr.x1), (g.rect.y1, wr.y1)] + .iter() + .all(|(a, b)| (a - b).abs() < 1e-5), + "run {run} step {step}: {g:?} vs {w:?}" + ); + let wn = w.name.as_deref().map(clean).filter(|n| !n.is_empty()); + assert_eq!(g.name.as_deref().map(str::trim), wn.as_deref(), "run {run} step {step}"); + assert_eq!(g.kind, w.kind, "run {run} step {step}"); + } + } + None => assert!(want.is_empty() && !had_regions, "run {run} step {step}: list missing: {x}"), + } + had_regions |= sc.regions.as_ref().is_some_and(|r| !r.is_empty()); + // the names on the faces, each once, then the one typed elsewhere + let d = lightcraft_meta::parse_xmp(&x).unwrap(); + let people: Vec = d + .values + .get("Iptc4xmpExt:PersonInImage") + .map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect()) + .unwrap_or_default(); + let mut expect: Vec = Vec::new(); + for r in file_regions(&p).into_iter().filter(|r| r.kind == Face) { + let n = clean(r.name.as_deref().unwrap_or("")); + if !n.is_empty() && !expect.iter().any(|e| e.to_lowercase() == n.to_lowercase()) { + expect.push(n); + } + } + if !expect.iter().any(|e| e.to_lowercase() == "typed elsewhere") { + expect.push("Typed Elsewhere".into()); + } + let people: Vec = people.iter().map(|n| clean(n)).collect(); + assert_eq!(people, expect, "run {run} step {step}: {x}"); + // reading the file back gives the catalog's boxes: the written ones, then the detector's not on a written face + let mut q = p.clone(); + merge_into(&mut q, &sc, "now"); + let written = want.len(); + assert!(q.meta.regions.len() >= written, "run {run} step {step}"); + for d in &q.meta.regions[written..] { + assert!(is_detected(d) && d.name.as_deref().is_none_or(|n| n.trim().is_empty()), "run {run} step {step}: {d:?}"); + } + // and a second save changes nothing + assert_eq!(save_over(&path, &p), x, "run {run} step {step}: not stable"); + } + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + } + #[test] fn exports_carry_no_regions() { let mut p = photo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 45f9dc998ef..684a81c765c 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2331,3 +2331,47 @@ fn a_face_on_a_turned_photo_is_written_in_the_stored_frame_and_read_back_upright assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); let _ = std::fs::remove_dir_all(&src); } + +/// Review of #4512: removing the last face writes an empty region list, so a second library that read the face drops +/// it when it reads the file again (keeping its own detector boxes), and undo brings the face back to both. +#[test] +fn a_removed_face_leaves_a_second_library_too_and_undo_brings_it_back() { + use lightcraft_meta::{Rect, Region, RegionKind}; + let src = temp_dir("face-two-libraries"); + write_png(&src.join("a.png"), 4); + let (mut a, mut b) = (Session::new().with_fs(), Session::new().with_fs()); + for s in [&mut a, &mut b] { + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + } + let (ida, idb) = (a.catalog.photos().next().unwrap().id, b.catalog.photos().next().unwrap().id); + let face = Rect { x0: 0.25, y0: 0.25, x1: 0.75, y1: 0.75 }; + let det = |rect| Region { rect, kind: RegionKind::Face, name: None, description: Some("Detected by YuNet 2023mar".into()) }; + for (s, id, extra) in [(&mut a, ida, None), (&mut b, idb, Some(Rect { x0: 0.0, y0: 0.0, x1: 0.1, y1: 0.1 }))] { + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions = std::iter::once(det(face)).chain(extra.map(det)).collect(); + s.commit("Detect Faces", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + } + let names = |s: &Session, id| s.catalog.photo(id).unwrap().meta.regions.iter().map(|r| r.name.clone()).collect::>(); + + // A names the face; B reads it (its own box on that face gives way to the file's, its other box stays) + a.execute("faces.nameFaces", &json!({"faces": [{"photo": ida.0, "index": 0}], "name": "Jane"})).unwrap(); + b.execute("photo.readMetadataFromFile", &json!({"ids": [idb.0]})).unwrap(); + assert_eq!(names(&b, idb), [Some("Jane".to_string()), None]); + + // A removes it: the file says there are no regions, and B drops Jane on reading it + a.execute("photo.removeRegion", &json!({"id": ida.0, "index": 0})).unwrap(); + let x = std::fs::read_to_string(src.join("a.xmp")).unwrap(); + assert!(x.contains("") && !x.contains("Jane"), "{x}"); + let sc = crate::sidecar::parse_sidecar(&x, crate::crs::Target::Rendered).unwrap(); + assert_eq!(sc.regions.map(|r| r.len()), Some(0), "an empty list, not a missing one: {x}"); + b.execute("photo.readMetadataFromFile", &json!({"ids": [idb.0]})).unwrap(); + assert_eq!(names(&b, idb), [None], "B keeps only its own detector box"); + + // undo in A writes Jane back; B gets her again + a.execute("edit.undo", &json!({})).unwrap(); + assert!(std::fs::read_to_string(src.join("a.xmp")).unwrap().contains("Jane")); + b.execute("photo.readMetadataFromFile", &json!({"ids": [idb.0]})).unwrap(); + assert_eq!(names(&b, idb), [Some("Jane".to_string()), None]); + let _ = std::fs::remove_dir_all(&src); +} diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 51dd5d87a70..ed34b24c679 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -129,8 +129,11 @@ write them, from sidecars and from XMP embedded in the file. Named faces become mirrored photos (2, 4, 5, 7), which MWG can't describe, on the upright photo. The file's orientation is read for this when the photo has regions to write (for a raw, the whole file, as Read Metadata from File does). Either way they read back as they were. When the photo has - no regions left but the sidecar has a list, an empty list is written, so another library reading the file drops - them too; a sidecar that never had one gets none. + no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list + is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar + that never had one gets none, an empty one stays empty, and a list LightCraft reads nothing from (pixel areas with + no size, say) is not thrown away by a save. A box that can't be written (not finite, empty or off the photo) counts + as none. - **Names in `Iptc4xmpExt:PersonInImage`.** The names on the photo's faces are listed there too. Names in the sidecar's list that are not the name of one of its face regions (typed in another application) are kept; a name that belonged to a face goes when the face is renamed, cleared or removed. LightCraft doesn't read this list. @@ -150,7 +153,8 @@ write them, from sidecars and from XMP embedded in the file. Named faces become its Exif states decides, and with no such size they are taken as written. A square photo or size looks the same both ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. - **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so - regions removed in another application go away here too. A sidecar without `mwg-rs:Regions` (an application that + regions removed in another application go away here too. The detector's unnamed boxes, which are never written, + are kept, except one on a face the sidecar has a box for (half or more of the two boxes in common). A sidecar without `mwg-rs:Regions` (an application that doesn't do regions) leaves the photo's regions as they are. ## Reading `crs:` develop fields From 25e24390c958de5457d32fa6f762c5e110997241 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 08:26:54 -0600 Subject: [PATCH 05/25] LR-LIB-PEOPLE: keep region entries LightCraft can't read when writing the list Review of #4512 (CodeRabbit, unreadable entries): naming a face on a photo whose sidecar holds an entry LightCraft can't read (a pixel box in a list with no AppliedToDimensions, say) restated mwg-rs:Regions and dropped that entry. - fit_to_old finds the old list's unreadable entries (roxmltree, each entry tried alone through the same reader) and writes them after the photo's own, as their own text with the namespaces they use declared on them. Pixel entries that had no size keep having none. - A clear keeps them too, and a list of unreadable entries only is restated as it was, so a save doesn't move it. - If they can't be singled out (a sidecar with a DTD, say), or the packet built with them doesn't parse as namespaced XML, the file's list is left as it is and a warning is logged. - roxmltree 0.21 (MIT OR Apache-2.0, pure Rust, already in Cargo.lock) becomes a dependency of lightcraft-engine. Tests: a new face beside a pixel entry (both kept, names in order, stable), removal down to the pixel entry, an off-photo entry keeping the list's size, the DTD fallback, and the random-edit run now starts from a sidecar with a pixel entry and checks it survives every save (LC_REGION_FUZZ_RUNS=300 passed). --- Cargo.lock | 1 + crates/engine/Cargo.toml | 2 + crates/engine/src/sidecar.rs | 286 +++++++++++++++++++++++++++++++++-- docs/xmp-interop.md | 7 +- 4 files changed, 283 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2fa44bb74f0..d0446b06300 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4219,6 +4219,7 @@ dependencies = [ "log", "miniz_oxide 0.9.1", "rayon", + "roxmltree", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d9da9711916..9616df95ac0 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -30,6 +30,8 @@ lightcraft-raw = { workspace = true } lightcraft-denoise-core = { workspace = true } lightcraft-denoise = { workspace = true, optional = true } lightcraft-meta = { workspace = true } +# finds the text of the region entries in a sidecar that LightCraft can't read, to keep them on save (sidecar.rs) +roxmltree = "0.21" lightcraft-lensdb = { workspace = true } lightcraft-faces = { workspace = true } miniz_oxide = { workspace = true } diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 4a461892457..70310d0bba3 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -944,7 +944,9 @@ fn people_block(names: &[String]) -> String { /// nothing to a reader, so another library that read them would keep them. The detector's unnamed boxes are never /// written, so a photo left with only those counts as cleared too; reading the file back keeps them ([`merge_into`]). /// A file with no list keeps none, one with an empty list keeps it, and one with a list LightCraft reads nothing -/// from keeps it as it is ([`OWNED_IF_STATED`]). +/// from keeps it as it is ([`OWNED_IF_STATED`]). Entries of the file's list that LightCraft can't read (boxes in +/// pixels with no size, say) are kept whenever the list is written ([`unreadable_regions`]); if they can't be singled +/// out, the file's list is left as it is. fn fit_to_old(old: &str, fresh: String) -> String { let old = old.strip_prefix('\u{feff}').unwrap_or(old); // (a file that isn't XMP can't be merged either: `sidecar_contents` handles it) @@ -979,17 +981,173 @@ fn fit_to_old(old: &str, fresh: String) -> String { names.push(t); } } - // the photo has none left to write and the file held regions LightCraft read: say so. A file stating an empty list - // is given it again, so the save leaves it where it was rather than moving it about (a list LightCraft read - // nothing from is neither: it stays as it is) - let empty_list = data.values.get("mwg-rs:Regions").and_then(|v| v.field("mwg-rs:RegionList")).is_some_and(|l| l.items().is_empty()); - if (empty_list || regions.as_ref().is_some_and(|r| !r.is_empty())) && !fresh.contains("\n \n \n \n \n", + let readable = regions.as_ref().map_or(0, Vec::len); + let carried = unreadable_regions(old, &data, readable); + if fresh.contains(REGIONS_OPEN) { + match carried { + // the file's entries LightCraft can't read go on after the photo's own, as they were + Some(c) => { + if !c.items.is_empty() { + let items: String = c.items.iter().map(|i| format!(" {i}\n")).collect(); + fresh = fresh.replacen(REGION_LIST_CLOSE, &format!("{items}{REGION_LIST_CLOSE}"), 1); + } + // boxes in pixels that had no size to go by keep having none, rather than taking the photo's + if c.pixels_without_size { + fresh = cut(fresh, DIMS_OPEN, DIMS_CLOSE); + } + } + // entries it can't read that it can't single out either: rather than lose them, the file's list stays + None => { + log::warn!("a face region list LightCraft can't fully read was left as it is; its own regions were not written to it"); + fresh = cut(fresh, REGIONS_OPEN, REGIONS_CLOSE); + } + } + } else { + // the photo has none left to write and the file held regions LightCraft read: say so, keeping the entries it + // can't read. A file stating an empty list is given it again, so the save leaves it where it was rather than + // moving it about. A list LightCraft read nothing from is neither: it stays as it is. + let empty_list = data.values.get("mwg-rs:Regions").and_then(|v| v.field("mwg-rs:RegionList")).is_some_and(|l| l.items().is_empty()); + // A list of entries it can't read only is given again too, as it was, for the same reason. + if (empty_list || readable > 0 || carried.as_ref().is_some_and(|c| !c.items.is_empty())) + && let Some(c) = carried + { + let dims = match (&c.dims, c.items.is_empty()) { + (Some((w, h)), false) => format!( + " \n {}\n {}\n pixel\n \n", + xml_text(w), + xml_text(h) + ), + _ => String::new(), + }; + let list = if c.items.is_empty() { + " \n".to_string() + } else { + let items: String = c.items.iter().map(|i| format!(" {i}\n")).collect(); + format!(" \n{items} \n") + }; + fresh = into_description(fresh, &format!("{REGIONS_OPEN}{dims} \n{list} \n{REGIONS_CLOSE}")); + } + } + let fitted = into_description(fresh, &people_block(&names)); + // the file's own entries went in as text: never write a packet that doesn't parse as namespaced XML + let opts = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1 << 20, ..Default::default() }; + if roxmltree::Document::parse_with_options(&fitted, opts).is_err() || lightcraft_meta::parse_xmp(&fitted).is_err() { + log::warn!("a face region list couldn't be written with the file's own entries; the file's list was left as it is"); + return cut(fitted, REGIONS_OPEN, REGIONS_CLOSE); + } + fitted +} + +const REGIONS_OPEN: &str = " \n"; +const REGIONS_CLOSE: &str = " \n"; +const REGION_LIST_CLOSE: &str = " \n \n"; +const DIMS_OPEN: &str = " String { + let Some(a) = text.find(open) else { return text }; + let Some(b) = text.get(a..).and_then(|t| t.find(close)).map(|b| a + b + close.len()) else { return text }; + match (text.get(..a), text.get(b..)) { + (Some(before), Some(after)) => format!("{before}{after}"), + _ => text, + } +} + +/// The entries of a sidecar's region list that LightCraft can't read into the catalog (boxes in pixels with no size +/// to go by, off the photo, without an area…), to be kept when the list is written again. +struct Carried { + /// Each entry's own text from the file, with the namespaces it uses declared on it. + items: Vec, + /// The list's `AppliedToDimensions` (width, height), as written. + dims: Option<(String, String)>, + /// One of them is in pixels and the list has no size. + pixels_without_size: bool, +} + +/// [`Carried`] for the sidecar `old` (parsed as `data`, `readable` regions of it read), or `None` when its list has +/// entries LightCraft can't read but they can't be singled out (a list in an unusual form). +fn unreadable_regions(old: &str, data: &lightcraft_meta::XmpData, readable: usize) -> Option { + let regions = data.values.get("mwg-rs:Regions"); + let n = regions.and_then(|r| r.field("mwg-rs:RegionList")).map_or(0, |l| l.items().len()); + let dims = regions + .and_then(|r| r.field("mwg-rs:AppliedToDimensions")) + .and_then(|d| Some((d.field("stDim:w")?.text()?.to_string(), d.field("stDim:h")?.text()?.to_string()))); + let mut carried = Carried { items: Vec::new(), dims, pixels_without_size: false }; + if n <= readable { + return Some(carried); + } + // (the file was parsed whole already, within the reader's limits; this is a second look at the same text) + let opts = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1 << 20, ..Default::default() }; + let doc = roxmltree::Document::parse_with_options(old, opts).ok()?; + let is = |n: &roxmltree::Node, ns: &str, name: &str| n.is_element() && n.tag_name().namespace() == Some(ns) && n.tag_name().name() == name; + let list = doc.descendants().find(|n| is(n, MWG_RS, "RegionList"))?; + let container = list.children().find(roxmltree::Node::is_element)?; + let mut any_pixels = false; + for li in container.children().filter(|n| is(n, RDF, "li")) { + let item = with_namespaces(old, &li)?; + let dims = carried.dims.as_ref().map_or(String::new(), |(w, h)| { + format!("{}{}pixel", xml_text(w), xml_text(h)) + }); + let alone = format!( + "{dims}{item}" ); + let readable = parse_sidecar(&alone, crate::crs::Target::Rendered).ok().and_then(|sc| sc.regions).is_some_and(|r| !r.is_empty()); + if readable { + continue; + } + any_pixels |= lightcraft_meta::parse_xmp(&alone).ok().is_some_and(|d| { + d.values + .get("mwg-rs:Regions") + .and_then(|r| r.field("mwg-rs:RegionList")) + .and_then(|l| l.items().first().and_then(|i| i.field("mwg-rs:Area")).and_then(|a| a.field("stArea:unit")).and_then(|u| u.text())) + .is_some_and(|u| u.eq_ignore_ascii_case("pixel")) + }); + carried.items.push(item); + } + // every entry accounted for: those read, and those kept as they are + if carried.items.len() != n - readable { + return None; } - into_description(fresh, &people_block(&names)) + carried.pixels_without_size = any_pixels && carried.dims.is_none(); + Some(carried) +} + +/// The text of the element `node` of `doc`, with the namespaces its names use (and it doesn't declare itself) declared +/// on it, so it can stand in another packet. `None` if its text can't be taken out. +fn with_namespaces(doc: &str, node: &roxmltree::Node) -> Option { + let text = doc.get(node.range())?; + let qname_of = |at: usize| doc.get(at..).map(|t| t.split(|c: char| c.is_whitespace() || c == '/' || c == '>').next().unwrap_or("")); + // the element's start tag, where its own declarations are + let tag_end = node.children().next().map_or(node.range().end, |c| c.range().start).min(node.range().end); + let start_tag = doc.get(node.range().start..tag_end)?; + let own_qname = qname_of(node.range().start + 1)?; + let mut used: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for e in node.descendants().filter(roxmltree::Node::is_element) { + let q = qname_of(e.range().start + 1)?; + let prefix = q.split_once(':').map_or("", |(p, _)| p); + if let Some(uri) = e.tag_name().namespace() { + used.insert(prefix.to_string(), uri.to_string()); + } + for a in e.attributes() { + let q = doc.get(a.range_qname())?; + if let (Some((prefix, _)), Some(uri)) = (q.split_once(':'), a.namespace()) { + used.insert(prefix.to_string(), uri.to_string()); + } + } + } + let mut decls = String::new(); + for (prefix, uri) in used.iter().filter(|(p, _)| p.as_str() != "xml" && p.as_str() != "xmlns") { + let attr = if prefix.is_empty() { "xmlns".to_string() } else { format!("xmlns:{prefix}") }; + if start_tag.contains(&format!(" {attr}=")) || start_tag.contains(&format!("\n{attr}=")) || start_tag.contains(&format!("\t{attr}=")) { + continue; + } + decls.push_str(&format!(" {attr}=\"{}\"", uri.replace('&', "&").replace('<', "<").replace('"', """))); + } + let rest = text.get(1 + own_qname.len()..)?; + Some(format!("<{own_qname}{decls}{rest}")) } /// The properties LightCraft writes and owns in a sidecar: replaced on every save (removed when @@ -2296,6 +2454,105 @@ mod tests { } } + /// An entry LightCraft can't read: a box in pixels in a list with no size, named "Pixel Box", with a field of a + /// namespace of its own declared on the description (as another app would write it). + const PIXEL_ENTRY: &str = r#"FacePixel Boxkept as is & untouched"#; + + /// [`sidecar_with`] plus [`PIXEL_ENTRY`] at the end of its list. + fn sidecar_with_pixel_entry(regions: &[(f64, f64, f64, f64, Option<&str>)]) -> String { + sidecar_with(regions, &[]) + .replace("", &format!("{PIXEL_ENTRY}")) + .replace("photomechanic:ColorClass", "xmlns:other=\"http://example.com/other/\" photomechanic:ColorClass") + } + + /// The region entries a sidecar has, readable or not, by name. + fn entry_names(x: &str) -> Vec { + let d = lightcraft_meta::parse_xmp(x).unwrap(); + d.values + .get("mwg-rs:Regions") + .and_then(|r| r.field("mwg-rs:RegionList")) + .map(|l| l.items().iter().map(|i| i.field("mwg-rs:Name").and_then(|n| n.text()).unwrap_or("").to_string()).collect()) + .unwrap_or_default() + } + + #[test] + fn entries_lightcraft_cant_read_are_kept_when_the_list_is_written() { + use lightcraft_meta::RegionKind::Face; + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + let path = scratch("pixel-entry"); + std::fs::write(&path, sidecar_with_pixel_entry(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))])).unwrap(); + // as imported: Ann (the pixel box can't be read), and a face the detector found + let mut p = photo(); + merge_into(&mut p, &parse_sidecar(&std::fs::read_to_string(&path).unwrap(), crate::crs::Target::Rendered).unwrap(), "now"); + assert_eq!(p.meta.regions.len(), 1); + p.meta.regions.push(region(0.05, 0.05, 0.15, 0.15, Face, None, Some(&detected))); + + // naming the detected face writes the list: Ann, the new face, and the pixel box as it was + p.meta.regions[1].name = Some("Bob".into()); + let x = save_over(&path, &p); + assert_eq!(entry_names(&x), ["Ann", "Bob", "Pixel Box"], "{x}"); + assert!(x.contains("stArea:x=\"120\"") && x.contains("stArea:unit=\"pixel\"") && x.contains("kept as is & untouched"), "{x}"); + // its boxes in pixels had no size to go by and still have none (the photo's would give them one) + assert!(!x.contains("AppliedToDimensions"), "{x}"); + // still readable: the catalog's two, nothing else + let read: Vec> = + parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions.unwrap().into_iter().map(|r| r.name).collect(); + assert_eq!(read, [Some("Ann".to_string()), Some("Bob".to_string())]); + // a second save changes nothing + assert_eq!(save_over(&path, &p), x); + + // removing Ann, then Bob: the pixel box stays through both + p.meta.regions.remove(0); + assert_eq!(entry_names(&save_over(&path, &p)), ["Bob", "Pixel Box"]); + p.meta.regions.clear(); + let x = save_over(&path, &p); + assert_eq!(entry_names(&x), ["Pixel Box"], "{x}"); + assert!(x.contains("kept as is & untouched"), "{x}"); + assert_eq!(parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions, Some(vec![])); + assert_eq!(save_over(&path, &p), x, "stable"); + // and a face named again joins it + p.meta.regions.push(region(0.3, 0.3, 0.4, 0.4, Face, Some("Cy"), None)); + assert_eq!(entry_names(&save_over(&path, &p)), ["Cy", "Pixel Box"]); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn a_kept_entry_keeps_its_size_when_the_list_had_one() { + // an entry off the photo in a list with a size: unreadable, kept, and the list keeps its size when cleared + let path = scratch("off-photo"); + let old = sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann")), (5.0, 5.0, 0.1, 0.1, Some("Off"))], &[]).replace( + "", + "", + ); + std::fs::write(&path, &old).unwrap(); + let mut p = photo(); + merge_into(&mut p, &parse_sidecar(&old, crate::crs::Target::Rendered).unwrap(), "now"); + assert_eq!(p.meta.regions.len(), 1, "Off can't be read"); + p.meta.regions.clear(); + let x = save_over(&path, &p); + assert_eq!(entry_names(&x), ["Off"], "{x}"); + assert!(x.contains("300") && x.contains("200"), "{x}"); + assert_eq!(save_over(&path, &p), x, "stable"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn a_list_whose_unreadable_entries_cant_be_singled_out_is_left_as_it_is() { + // LightCraft's reader takes a sidecar roxmltree won't parse (one with a DTD): the unreadable entry can't be + // singled out, so rather than lose it the save leaves the file's list as it is + let path = scratch("odd-list"); + let old = sidecar_with_pixel_entry(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))]); + let odd = format!("\n{old}"); + assert!(lightcraft_meta::parse_xmp(&odd).is_ok(), "LightCraft's reader takes it"); + assert!(unreadable_regions(&odd, &lightcraft_meta::parse_xmp(&odd).unwrap(), 1).is_none(), "roxmltree doesn't"); + std::fs::write(&path, &odd).unwrap(); + let mut p = photo(); + p.meta.regions = vec![region(0.3, 0.3, 0.4, 0.4, lightcraft_meta::RegionKind::Face, Some("New"), None)]; + let (x, _, _) = sidecar_contents(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + assert_eq!(entry_names(&x), ["Ann", "Pixel Box"], "the file's list is left: {x}"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + #[test] fn reading_back_keeps_the_detectors_boxes_but_not_on_a_face_the_file_has() { let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); @@ -2362,7 +2619,10 @@ mod tests { }; let path = scratch(&format!("random-{run}")); // start from a sidecar another app wrote: a named face and a name typed in elsewhere - std::fs::write(&path, sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Lightroom Face"))], &["Typed Elsewhere", "Lightroom Face"])).unwrap(); + let start = sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Lightroom Face"))], &["Typed Elsewhere", "Lightroom Face"]) + .replace("", &format!("{PIXEL_ENTRY}")) + .replace("photomechanic:ColorClass", "xmlns:other=\"http://example.com/other/\" photomechanic:ColorClass"); + std::fs::write(&path, start).unwrap(); let mut p = photo(); merge_into(&mut p, &parse_sidecar(&std::fs::read_to_string(&path).unwrap(), crate::crs::Target::Rendered).unwrap(), "now"); let clean = |n: &str| n.chars().filter(|c| !c.is_control()).collect::().trim().to_string(); @@ -2420,6 +2680,10 @@ mod tests { None => assert!(want.is_empty() && !had_regions, "run {run} step {step}: list missing: {x}"), } had_regions |= sc.regions.as_ref().is_some_and(|r| !r.is_empty()); + // the entry LightCraft can't read is there, last, every time + assert_eq!(entry_names(&x).last().map(String::as_str), Some("Pixel Box"), "run {run} step {step}: {x}"); + assert_eq!(entry_names(&x).len(), want.len() + 1, "run {run} step {step}"); + assert!(x.contains("kept as is & untouched"), "run {run} step {step}"); // the names on the faces, each once, then the one typed elsewhere let d = lightcraft_meta::parse_xmp(&x).unwrap(); let people: Vec = d diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index ed34b24c679..247bfae4de2 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -132,8 +132,11 @@ write them, from sidecars and from XMP embedded in the file. Named faces become no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar that never had one gets none, an empty one stays empty, and a list LightCraft reads nothing from (pixel areas with - no size, say) is not thrown away by a save. A box that can't be written (not finite, empty or off the photo) counts - as none. + no size, say) is not thrown away by a save. Entries of the sidecar's list that LightCraft can't read are kept, as + they were, after the photo's own whenever the list is written (with their namespaces declared on them, and with no + `AppliedToDimensions` given to pixel boxes that had none); if they can't be singled out (a sidecar with a DTD, say), + the sidecar's list is left as it is. A box that can't be written (not finite, empty or off the photo) counts as + none. - **Names in `Iptc4xmpExt:PersonInImage`.** The names on the photo's faces are listed there too. Names in the sidecar's list that are not the name of one of its face regions (typed in another application) are kept; a name that belonged to a face goes when the face is renamed, cleared or removed. LightCraft doesn't read this list. From f8aaf770f35fb738ad62f5c79365f5cc5d14a906 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 08:31:38 -0600 Subject: [PATCH 06/25] LR-LIB-PEOPLE: describe clipping before skipping a box that can't be written Review of #4512 (CodeRabbit, docs): an infinite edge clips to the photo's edge and the box is written; a box is skipped only when no area is left after clipping (empty, entirely off the photo, a coordinate that isn't a number). The doc, writable_rect's comment and the test comments now say so, and the test adds a box infinite on one side (+inf..+inf), which clips to nothing, beside the -inf..+inf one, checked to be written as the photo's full width. --- crates/engine/src/sidecar.rs | 18 +++++++++++++----- docs/xmp-interop.md | 5 +++-- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 70310d0bba3..eab3dec84b5 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -804,7 +804,8 @@ fn is_detected(r: &lightcraft_meta::Region) -> bool { r.description.as_deref().is_some_and(|d| d.starts_with(crate::cmd::face_detect::MARK)) } -/// A box as it can be written: clamped to the photo, finite and not empty. A catalog box that isn't is never +/// A box as it is written: each coordinate clipped to the photo (an infinite one becomes its edge), kept only if it +/// still has an area. One with none left (empty, entirely off the photo, a coordinate that isn't a number) is never /// written, and a photo with only such boxes has none to write. fn writable_rect(r: lightcraft_meta::Rect) -> Option<(f64, f64, f64, f64)> { let (x0, y0) = (r.x0.clamp(0.0, 1.0), r.y0.clamp(0.0, 1.0)); @@ -2433,21 +2434,27 @@ mod tests { assert_eq!(stated(&old), Some(vec![]), "the reader can't use pixel areas without a size"); let x = save_over(&path, &photo()); assert!(x.contains("stArea:unit=\"pixel\"") && x.contains("Ann"), "kept: {x}"); - // a catalog box that can't be written (not finite, empty, off the photo) counts as none + // a catalog box is clipped to the photo; one with no area left (a coordinate that isn't a number, empty, + // entirely off the photo, or infinite on the same side) counts as none, while one an infinite edge clips to + // the photo's edge is written for bad in [ region(f64::NAN, 0.1, 0.2, 0.2, lightcraft_meta::RegionKind::Face, Some("Nan"), None), region(0.3, 0.3, 0.3, 0.5, lightcraft_meta::RegionKind::Face, Some("Flat"), None), region(1.2, 1.2, 1.5, 1.5, lightcraft_meta::RegionKind::Face, Some("Off"), None), region(f64::NEG_INFINITY, 0.1, f64::INFINITY, 0.2, lightcraft_meta::RegionKind::Face, Some("Inf"), None), + region(f64::INFINITY, 0.1, f64::INFINITY, 0.2, lightcraft_meta::RegionKind::Face, Some("BothInf"), None), ] { let path = scratch("bad"); let mut p = photo(); std::fs::write(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new())).unwrap(); p.meta.regions = vec![bad.clone()]; let x = save_over(&path, &p); - // (an infinite box clamps to the photo's width: that one is writable) + // (−∞..+∞ clips to the photo's width and is written: x 0..1, y as given) if bad.name.as_deref() == Some("Inf") { - assert_eq!(stated(&x).map(|r| r.len()), Some(1), "{x}"); + let r = stated(&x).unwrap_or_default(); + assert_eq!(r.len(), 1, "{x}"); + let g = r[0].rect; + assert!([(g.x0, 0.0), (g.y0, 0.1), (g.x1, 1.0), (g.y1, 0.2)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); } else { assert!(!x.contains("mwg-rs:Regions"), "{bad:?}: {x}"); } @@ -2573,7 +2580,8 @@ mod tests { assert!((got[1].1 - 0.05).abs() < 1e-9, "{got:?}"); } - /// A random box: one in ten can't be written as it is (not finite, empty, off the photo, hanging off an edge). + /// A random box: one in ten is odd. It hangs off an edge (written clipped), or has no area left after clipping + /// (a coordinate that isn't a number, empty, entirely off the photo: not written). fn box_at(next: &mut impl FnMut(usize) -> usize) -> lightcraft_meta::Rect { if next(10) == 0 { match next(4) { diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 247bfae4de2..68762ade493 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -135,8 +135,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become no size, say) is not thrown away by a save. Entries of the sidecar's list that LightCraft can't read are kept, as they were, after the photo's own whenever the list is written (with their namespaces declared on them, and with no `AppliedToDimensions` given to pixel boxes that had none); if they can't be singled out (a sidecar with a DTD, say), - the sidecar's list is left as it is. A box that can't be written (not finite, empty or off the photo) counts as - none. + the sidecar's list is left as it is. A catalog box is clipped to the photo before it is written (an infinite edge + becomes the photo's edge); one with no area left after clipping (empty, entirely off the photo, or with a + coordinate that isn't a number) is skipped, and a photo with only such boxes counts as having none. - **Names in `Iptc4xmpExt:PersonInImage`.** The names on the photo's faces are listed there too. Names in the sidecar's list that are not the name of one of its face regions (typed in another application) are kept; a name that belonged to a face goes when the face is renamed, cleared or removed. LightCraft doesn't read this list. From 5ef57ab6a2b97cdb7acdeeb7960ad926c22f73dd Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 08:38:12 -0600 Subject: [PATCH 07/25] LR-LIB-PEOPLE: state the detector-box overlap as intersection over union Review of #4512 (CodeRabbit, docs): the doc now names the measure, intersection over union >= 0.5, with the example of two equal boxes overlapping by 60 % of each (IoU about 0.43, kept). The code comment says the same, and a test pins it: 60 % kept, 70 % and identical dropped, no overlap kept. --- crates/engine/src/sidecar.rs | 18 +++++++++++++++++- docs/xmp-interop.md | 5 ++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index eab3dec84b5..499a09052b7 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -352,7 +352,8 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); } - // …except one on a face the file has a box for (named in another library, say): the file's box stands for it + // …except one on a face the file has a box for (named in another library, say): the file's box stands for it. + // "On" is intersection over union ≥ 0.5: their common area is at least half of the area either covers let overlaps = |a: &lightcraft_meta::Rect, b: &lightcraft_meta::Rect| { let common = a.intersect(b).area(); let all = a.area() + b.area() - common; @@ -2596,6 +2597,21 @@ mod tests { } } + #[test] + fn a_detector_box_gives_way_at_an_intersection_over_union_of_one_half() { + let detected = format!("{}YuNet 2023mar", crate::cmd::face_detect::MARK); + // the file's face: 0.2 × 0.2 at (0.4, 0.4) + let sc = parse_sidecar(&sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))], &[]), crate::crs::Target::Rendered).unwrap(); + // the same size, moved right: 60 % of each box in common is IoU 0.12·0.2 / (2·0.04 − 0.024) ≈ 0.43 (kept); + // 70 % is 0.14·0.2 / (0.08 − 0.028) ≈ 0.54 (dropped) + for (shift, kept) in [(0.08, true), (0.06, false), (0.0, false), (0.2, true)] { + let mut p = photo(); + p.meta.regions = vec![region(0.4 + shift, 0.4, 0.6 + shift, 0.6, lightcraft_meta::RegionKind::Face, None, Some(&detected))]; + merge_into(&mut p, &sc, "now"); + assert_eq!(p.meta.regions.len(), if kept { 2 } else { 1 }, "shift {shift}: {:?}", p.meta.regions); + } + } + /// Hundreds of random edits, each saved over the last sidecar: the file always says exactly what the catalog /// would write, reading it back gives the catalog's boxes, the names typed elsewhere survive, and a second save /// changes nothing. Bad boxes, odd names and clears included. diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 68762ade493..11a4ab0a8fc 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -158,7 +158,10 @@ write them, from sidecars and from XMP embedded in the file. Named faces become ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. - **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so regions removed in another application go away here too. The detector's unnamed boxes, which are never written, - are kept, except one on a face the sidecar has a box for (half or more of the two boxes in common). A sidecar without `mwg-rs:Regions` (an application that + are kept, except one on a face the sidecar has a face box for: one whose intersection with it is at least half of + their union (intersection over union ≥ 0.5). Two boxes of the same size overlapping by 60 % of each have an + intersection over union of about 0.43, so the detector's box is kept. A sidecar without `mwg-rs:Regions` (an + application that doesn't do regions) leaves the photo's regions as they are. ## Reading `crs:` develop fields From 6bcc7dd070899c4cd5e5c9a16bc4fc80aee43c1e Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 09:05:58 -0600 Subject: [PATCH 08/25] LR-LIB-PEOPLE: keep the file's orientation in the catalog; saves never read the file Review of #4512 (CodeRabbit, performance): sidecar_packet read each face-tagged raw in full (file_orientation) on every save, so a bulk edit with auto-write read the whole of every raw in the batch. - catalog::Meta gains file_orientation: the orientation the import's probe read (ProbeInfo::orientation, the one that made width x height upright), so it is consistent with import by construction. Left out of the catalog JSON when unknown; older catalogs read unchanged. - The import keeps it; a Lightroom catalog photo made from a duplicate's bytes takes the duplicate's. - sidecar_packet takes it from the catalog and reads no file. A photo catalogued before it was kept has its boxes written upright (LightCraft reads them back the same) until Read Metadata from File reads it, with or without a packet to read, reading the file at most once. Tests: a save with no file at the path writes the stored frame from the catalog, and a turned file the catalog knows nothing about isn't read; import keeps the orientation; Read Metadata from File fills it in for an older photo, with and without a sidecar. Each fails with its part reverted. --- crates/catalog/src/model.rs | 7 +++ crates/engine/src/files/probe.rs | 2 + crates/engine/src/import/commit.rs | 2 + crates/engine/src/lightroom_catalog.rs | 3 +- crates/engine/src/sidecar.rs | 68 +++++++++++++++++++++++--- crates/engine/src/tests/xmp.rs | 43 ++++++++++++++++ docs/xmp-interop.md | 9 ++-- 7 files changed, 123 insertions(+), 11 deletions(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 969e4e222ca..70eb0dbf000 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -229,6 +229,13 @@ pub struct Meta { /// written to XMP. Left out of the catalog JSON when unknown, so older catalogs read unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] pub focus: Option, + /// The photo file's own orientation, as the import read it (`ProbeInfo::orientation`, the one that made `width` × + /// `height` upright): how its stored pixels turn upright. A sidecar save writes face regions in the stored frame by + /// it (`lightcraft_engine::sidecar`) without reading the file. `None` for a file that states none, and for a photo + /// catalogued before it was kept until Read Metadata from File reads it. Left out of the catalog JSON when unknown, + /// so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_orientation: Option, } impl Meta { diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 4bdf22afa9b..fea22e48ed0 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -38,6 +38,8 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { keywords: lightcraft_catalog::keywords::from_file(&m.keywords, &m.hierarchical_keywords), regions: m.regions.clone(), focus: m.focus.clone(), + // (the import keeps `ProbeInfo::orientation`, which for a raw is the decoder's) + file_orientation: None, }; (meta, m.capture_time.as_ref().map(|d| d.to_iso())) } diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 86827a93ed3..dcda5563b55 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -228,6 +228,8 @@ fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool pub(crate) fn start_from_file(s: &Session, p: &mut Photo, file: FileFacts, now: &str) -> Option { let FileFacts { meta, captured, orientation, sidecar } = file; p.meta = meta; + // how the file turns upright, as the import's probe read it: a sidecar save writes face boxes by it + p.meta.file_orientation = orientation; p.captured = captured; apply_import_defaults(s, p); let sc = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default())?; diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 914c70c7c98..e80b606d8a0 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1355,7 +1355,8 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co focus: m.focus.clone(), ..Default::default() }; - crate::import::FileFacts { meta, ..Default::default() } + // the same bytes turn upright the same way + crate::import::FileFacts { meta, orientation: m.file_orientation, ..Default::default() } }); // as a file import of it: its file's metadata and capture time, the import defaults // (as-shot white balance, embedded lens corrections, the default preset), its XMP diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 499a09052b7..7444471f160 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -165,6 +165,9 @@ pub struct SidecarData { /// [`merge_into`] puts boxes drawn on the photo as stored where the upright photo has them (#2674). pub regions_drawn_on: Option<(f64, f64)>, pub orientation: Option, + /// The photo file's own orientation, read from the file for a photo whose catalog doesn't know it yet (one + /// catalogued before it was kept; see [`Session::read_sidecar_op`]): [`merge_into`] keeps it. + pub file_orientation: Option, /// Capture time (ISO 8601) from `exif:DateTimeOriginal`, `photoshop:DateCreated` or /// `xmp:CreateDate` (first found). Used only when the file itself has no capture time. pub captured: Option, @@ -342,6 +345,9 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { if let Some(k) = &sc.keywords { m.keywords = k.clone(); } + if sc.file_orientation.is_some() { + m.file_orientation = sc.file_orientation; + } if let Some(r) = &sc.regions { // the detector's unnamed boxes are never written to the file (`file_regions`): reading it keeps them let detected: Vec = @@ -741,10 +747,9 @@ const ORIENTATION_SPAN: u64 = 1 << 20; pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { // the regions go into the photo's own sidecar only: an export's packet describes the picture as exported, which a // crop or a resize leaves the boxes no longer fit - // the file's own orientation decides how the boxes are written (`with_regions`); a photo with none to write - // doesn't need its file read - let orientation = if file_regions(p).is_empty() { None } else { file_path(p).and_then(file_orientation) }; - with_regions(sidecar_packet_with(p, cat, false), p, orientation) + // the file's own orientation, as the catalog keeps it, decides how the boxes are written (`with_regions`): a save + // never reads the photo file (for a raw that would be the whole file, for every photo of a batch) + with_regions(sidecar_packet_with(p, cat, false), p, p.meta.file_orientation) } /// [`sidecar_packet`], without any location (GPS, sublocation, city, state, country) when @@ -1641,9 +1646,29 @@ impl Session { pub fn read_sidecar_op_with_warnings(&self, id: PhotoId) -> Result)>> { let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let Some(orig) = file_path(p) else { return Ok(None) }; - let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { return Ok(None) }; + // a photo catalogued before the file's orientation was kept: Read Metadata from File reads it, once, so its + // face boxes are written in the frame the file is stored in from then on (the file is read at most once here) + let mut known: Option> = None; + let mut orientation_of_file = || *known.get_or_insert_with(|| file_orientation(orig)); + let backfill = if p.meta.file_orientation.is_none() { orientation_of_file() } else { None }; + let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { + // no packet to read; the orientation alone is still news + return match backfill { + Some(o) => Ok(Some(( + self.sidecar_op(id, SidecarData { file_orientation: Some(o), ..SidecarData::default() })?, + PathBuf::from(orig), + Vec::new(), + ))), + None => Ok(None), + }; + }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; - let sc = sc.with_file_orientation(orig); + // (as `with_file_orientation`, reusing a read already made) + let sc = match sc.regions_drawn_on { + Some(_) => SidecarData { orientation: orientation_of_file().or(sc.orientation), ..sc }, + None => sc, + }; + let sc = SidecarData { file_orientation: backfill, ..sc }; let mut warnings = sc.warnings.clone(); for warning in &mut warnings { warning.path = orig.to_string(); @@ -2742,6 +2767,37 @@ mod tests { } } + #[test] + fn a_save_takes_the_orientation_from_the_catalog_and_never_reads_the_file() { + let mut p = photo(); + p.meta.regions = vec![region(0.1, 0.2, 0.3, 0.6, lightcraft_meta::RegionKind::Face, Some("Ann"), None)]; + // no file at the photo's path: the catalog's orientation is enough + p.meta.file_orientation = Some(lightcraft_meta::Orientation::Rotate90); + assert!(sidecar_packet(&p, &lightcraft_catalog::Catalog::new()).contains("-1.57080")); + // a turned file the catalog knows nothing about: not read, the boxes are written upright + let dir = std::env::temp_dir().join(format!("lc-no-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("t.jpg"); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [1, 2, 3, 255]); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { + orientation: Some(lightcraft_meta::Orientation::Rotate90), + ..Default::default() + }); + let bytes = lightcraft_codecs::encode_jpeg( + &lightcraft_codecs::EncodeImage::rgba8(&img), + 90, + Default::default(), + &lightcraft_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }, + ) + .unwrap(); + std::fs::write(&file, bytes).unwrap(); + assert_eq!(file_orientation(&file.to_string_lossy()), Some(lightcraft_meta::Orientation::Rotate90)); + p.source = Source::File { path: file.to_string_lossy().into() }; + p.meta.file_orientation = None; + assert!(!sidecar_packet(&p, &lightcraft_catalog::Catalog::new()).contains("mwg-rs:Rotation")); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn exports_carry_no_regions() { let mut p = photo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 684a81c765c..f178ac63dbc 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2313,6 +2313,7 @@ fn a_face_on_a_turned_photo_is_written_in_the_stored_frame_and_read_back_upright s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); let id = s.catalog.photos().next().unwrap().id; assert_eq!((s.catalog.photo(id).unwrap().width, s.catalog.photo(id).unwrap().height), (24, 32), "upright"); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, Some(lightcraft_meta::Orientation::Rotate90), "kept at import"); let rect = Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; let mut meta = s.catalog.photo(id).unwrap().meta.clone(); meta.regions = vec![Region { rect, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; @@ -2375,3 +2376,45 @@ fn a_removed_face_leaves_a_second_library_too_and_undo_brings_it_back() { assert_eq!(names(&b, idb), [Some("Jane".to_string()), None]); let _ = std::fs::remove_dir_all(&src); } + +/// Review of #4512: a save never reads the photo file for its orientation; a photo catalogued before the orientation +/// was kept has its boxes written upright until Read Metadata from File reads it (with or without a packet to read). +#[test] +fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { + use lightcraft_meta::{Orientation, Rect, Region, RegionKind}; + for with_packet in [true, false] { + let src = temp_dir(if with_packet { "face-orientation-packet" } else { "face-orientation-bare" }); + write_turned_jpeg(&src.join("t.jpg"), None); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + // as a photo catalogued before: no orientation kept + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + if with_packet { + meta.regions = vec![Region { + rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, + kind: RegionKind::Face, + name: Some("Ann".into()), + description: None, + }]; + } + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + if with_packet { + // saved upright: the file isn't read for it + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + assert!(!std::fs::read_to_string(src.join("t.xmp")).unwrap().contains("mwg-rs:Rotation")); + } + // Read Metadata from File reads it + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, Some(Orientation::Rotate90), "packet: {with_packet}"); + if with_packet { + // the same box, read back upright, and written in the stored frame from now on + let r = s.catalog.photo(id).unwrap().meta.regions[0].rect; + assert!([(r.x0, 0.1), (r.y0, 0.2), (r.x1, 0.3), (r.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{r:?}"); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + assert!(std::fs::read_to_string(src.join("t.xmp")).unwrap().contains("-1.57080")); + } + let _ = std::fs::remove_dir_all(&src); + } +} diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 11a4ab0a8fc..d5986f390be 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -126,10 +126,11 @@ write them, from sidecars and from XMP embedded in the file. Named faces become names them, and reading the sidecar back keeps them. `mwg-rs:AppliedToDimensions` is the upright size, and the boxes are written as Lightroom Classic writes them: for a file whose Exif orientation is 3, 6 or 8, in the frame of the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`; otherwise, and on - mirrored photos (2, 4, 5, 7), which MWG can't describe, on the upright photo. The file's orientation is read for - this when the photo has regions to write (for a raw, the whole file, as Read Metadata from File does). Either way - they read back as they were. When the photo has - no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list + mirrored photos (2, 4, 5, 7), which MWG can't describe, on the upright photo. The file's orientation is the one + the import read, kept in the catalog: a save never reads the photo file for it. A photo catalogued before LightCraft + kept it has its boxes written upright until Read Metadata from File reads it. Either way they read back as they + were. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions + LightCraft read, an empty list is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar that never had one gets none, an empty one stays empty, and a list LightCraft reads nothing from (pixel areas with no size, say) is not thrown away by a save. Entries of the sidecar's list that LightCraft can't read are kept, as From 4404be9a46765f42b16f00cddd2bf7f2c9b4efeb Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 09:30:38 -0600 Subject: [PATCH 09/25] LR-LIB-PEOPLE: write boxes on turned, mirrored photos (Exif 5, 7) in the stored frame Review of #4512 (CodeRabbit, mirrored orientations): MWG places regions on the stored image. A photo turned a quarter and mirrored (5, 7) that isn't square is now written in the stored frame with the stored size as AppliedToDimensions and no rotation, which MWG readers place correctly and LightCraft's reader already tells from an upright packet by that size and turns back (#2674). Mirrored without a turn (2, 4) and square photos look the same in both frames, so they stay upright, as the reader takes them; documented. Reading a sidecar back (Read Metadata from File, Synchronize Folder) now takes the file's orientation from the catalog when it knows it (with_orientation_known) instead of reading the whole raw whenever a packet states AppliedToDimensions, as every packet LightCraft writes now does. Tests: every orientation written and read back through merge_into, a square 5, and an Exif-5 JPEG end to end; each 5/7 case fails with the change reverted. --- crates/engine/src/sidecar.rs | 70 +++++++++++++++++++++++++--------- crates/engine/src/sync.rs | 21 ++++++---- crates/engine/src/tests/xmp.rs | 37 ++++++++++++++++++ docs/xmp-interop.md | 10 +++-- 4 files changed, 109 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 7444471f160..2e3f741a200 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -476,10 +476,16 @@ impl SidecarData { /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). /// Only then is the file read ([`file_orientation`]). pub fn with_file_orientation(self, original: &str) -> Self { + self.with_orientation_known(None, original) + } + + /// [`SidecarData::with_file_orientation`], taking the orientation the catalog keeps for the photo + /// (`Meta::file_orientation`, the import's) when it has one, so the file isn't read for it. + pub fn with_orientation_known(self, known: Option, original: &str) -> Self { if self.regions_drawn_on.is_none() { return self; } - SidecarData { orientation: file_orientation(original).or(self.orientation), ..self } + SidecarData { orientation: known.or_else(|| file_orientation(original)).or(self.orientation), ..self } } } @@ -856,18 +862,28 @@ fn xml_text(s: &str) -> String { /// `AppliedToDimensions` is the photo's upright size (its `width` × `height`). The boxes are written the way /// Lightroom Classic writes them, which [`lightcraft_meta::parse_xmp`] turns back upright: for a file whose Exif /// orientation is 3, 6 or 8 (`orientation`), in the frame of the photo as stored, with that turn as `mwg-rs:Rotation` -/// (π, −π/2, +π/2), as the MWG guidelines place regions on the stored image; otherwise on the upright photo. MWG -/// can't say "mirrored", so boxes on mirrored photos (2, 4, 5, 7) are written upright, as the reader takes them. +/// (π, −π/2, +π/2), as the MWG guidelines place regions on the stored image. A photo turned a quarter and mirrored +/// (5, 7) and not square is written in the stored frame too, with the stored size as `AppliedToDimensions` and no +/// rotation (MWG has no way to say "mirrored"): the reader tells it from an upright packet by that size and turns +/// it back with the file's orientation (#2674). One mirrored without a turn (2, 4), or a square one, looks the +/// same either way, so it is written on the upright photo, as the reader takes it; MWG readers that apply the +/// mirror place those boxes mirrored. fn with_regions(packet: String, p: &Photo, orientation: Option) -> String { let regions = file_regions(p); if regions.is_empty() { return packet; } let mut x = String::from(" \n"); - if p.width > 0 && p.height > 0 { + // a photo turned a quarter and mirrored (Exif 5, 7) and not square: in the frame of the photo as stored, with the + // stored size, which the reader tells from the upright size and turns back (#2674) + let mirrored_turn = matches!(orientation, Some(lightcraft_meta::Orientation::Transpose | lightcraft_meta::Orientation::Transverse)) + && p.width > 0 + && p.height > 0 + && p.width != p.height; + let (dw, dh) = if mirrored_turn { (p.height, p.width) } else { (p.width, p.height) }; + if dw > 0 && dh > 0 { x.push_str(&format!( - " \n {}\n {}\n pixel\n \n", - p.width, p.height + " \n {dw}\n {dh}\n pixel\n \n" )); } x.push_str(" \n \n"); @@ -882,6 +898,9 @@ fn with_regions(packet: String, p: &Photo, orientation: Option (uy, 1.0 - ux, uh, uw, Some("-1.57080")), Some(lightcraft_meta::Orientation::Rotate270) => (1.0 - uy, ux, uh, uw, Some("1.57080")), Some(lightcraft_meta::Orientation::Rotate180) => (1.0 - ux, 1.0 - uy, uw, uh, Some("3.14159")), + // the stored frame is the upright one mirrored across a diagonal: 5 across the main one, 7 the other + Some(lightcraft_meta::Orientation::Transpose) if mirrored_turn => (uy, ux, uh, uw, None), + Some(lightcraft_meta::Orientation::Transverse) if mirrored_turn => (1.0 - uy, 1.0 - ux, uh, uw, None), _ => (ux, uy, uw, uh, None), }; x.push_str(&format!( @@ -1648,7 +1667,7 @@ impl Session { let Some(orig) = file_path(p) else { return Ok(None) }; // a photo catalogued before the file's orientation was kept: Read Metadata from File reads it, once, so its // face boxes are written in the frame the file is stored in from then on (the file is read at most once here) - let mut known: Option> = None; + let mut known: Option> = p.meta.file_orientation.map(Some); let mut orientation_of_file = || *known.get_or_insert_with(|| file_orientation(orig)); let backfill = if p.meta.file_orientation.is_none() { orientation_of_file() } else { None }; let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { @@ -1663,7 +1682,7 @@ impl Session { }; }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; - // (as `with_file_orientation`, reusing a read already made) + // (as `with_orientation_known`: the catalog's orientation, else the file's, read at most once) let sc = match sc.regions_drawn_on { Some(_) => SidecarData { orientation: orientation_of_file().or(sc.orientation), ..sc }, None => sc, @@ -2350,17 +2369,22 @@ mod tests { #[test] fn boxes_on_a_turned_file_are_written_as_lightroom_writes_them() { - use lightcraft_meta::Orientation::{FlipH, Normal, Rotate90, Rotate180, Rotate270, Transpose}; + use lightcraft_meta::Orientation::{FlipH, FlipV, Normal, Rotate90, Rotate180, Rotate270, Transpose, Transverse}; + // a 40 × 30 photo (upright) let mut p = photo(); let upright = region(0.1, 0.2, 0.3, 0.6, lightcraft_meta::RegionKind::Face, Some("Ann"), None); p.meta.regions = vec![upright.clone()]; - for (o, rotation, area) in [ - (Rotate90, Some("-1.57080"), [0.4, 0.8, 0.4, 0.2]), - (Rotate270, Some("1.57080"), [0.6, 0.2, 0.4, 0.2]), - (Rotate180, Some("3.14159"), [0.8, 0.6, 0.2, 0.4]), - (Normal, None, [0.2, 0.4, 0.2, 0.4]), - (FlipH, None, [0.2, 0.4, 0.2, 0.4]), - (Transpose, None, [0.2, 0.4, 0.2, 0.4]), + for (o, rotation, area, size) in [ + (Rotate90, Some("-1.57080"), [0.4, 0.8, 0.4, 0.2], (40, 30)), + (Rotate270, Some("1.57080"), [0.6, 0.2, 0.4, 0.2], (40, 30)), + (Rotate180, Some("3.14159"), [0.8, 0.6, 0.2, 0.4], (40, 30)), + (Normal, None, [0.2, 0.4, 0.2, 0.4], (40, 30)), + // mirrored without a turn: upright (MWG can't tell it apart) + (FlipH, None, [0.2, 0.4, 0.2, 0.4], (40, 30)), + (FlipV, None, [0.2, 0.4, 0.2, 0.4], (40, 30)), + // mirrored and turned: the stored frame, with the stored size + (Transpose, None, [0.4, 0.2, 0.4, 0.2], (30, 40)), + (Transverse, None, [0.6, 0.8, 0.4, 0.2], (30, 40)), ] { let x = with_regions(sidecar_packet_with(&p, &lightcraft_catalog::Catalog::new(), false), &p, Some(o)); assert_eq!(x.contains(""), rotation.is_some(), "{o:?}: {x}"); @@ -2370,14 +2394,24 @@ mod tests { for (tag, v) in ["x", "y", "w", "h"].iter().zip(area) { assert!(x.contains(&format!("{v:.6}")), "{o:?} {tag}: {x}"); } - // read back (the reader turns Lightroom's boxes upright): the same box - let got = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions.unwrap()[0].rect; + assert!(x.contains(&format!("{}", size.0)) && x.contains(&format!("{}", size.1)), "{o:?}: {x}"); + // read back as LightCraft reads a sidecar (the file's orientation known): the same box, upright + let sc = parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().with_orientation_known(Some(o), "/no/such/file"); + let mut q = photo(); + merge_into(&mut q, &sc, "now"); + let got = q.meta.regions[0].rect; let want = upright.rect; assert!( [(got.x0, want.x0), (got.y0, want.y0), (got.x1, want.x1), (got.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{o:?}: {got:?}" ); } + // a square photo mirrored and turned looks the same either way: upright, as the reader takes it + let mut sq = photo(); + (sq.width, sq.height) = (30, 30); + sq.meta.regions = vec![upright.clone()]; + let x = with_regions(sidecar_packet_with(&sq, &lightcraft_catalog::Catalog::new(), false), &sq, Some(Transpose)); + assert!(x.contains("0.200000") && x.contains("0.400000"), "{x}"); } /// A sidecar with Lightroom-style regions (in the order given, upright) and `people` as PersonInImage. diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 04db8219dc3..7f6ca8da9a2 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -618,7 +618,7 @@ fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarLookup, listing: } let Ok(text) = std::fs::read_to_string(&file) else { return false }; let Ok(sc) = crate::sidecar::parse_sidecar(&text, crate::crs::Target::for_photo(p)) else { return false }; - let sc = sc.with_file_orientation(path).resolve_label(labels); + let sc = sc.with_orientation_known(p.meta.file_orientation, path).resolve_label(labels); let mut q = p.clone(); crate::sidecar::merge_into(&mut q, &sc, ""); (q.rating, q.flag, q.label, &q.meta, &q.captured, &q.develop) != (p.rating, p.flag, p.label, &p.meta, &p.captured, &p.develop) @@ -653,8 +653,8 @@ pub struct SyncWork { import: Option<(crate::import::ImportJob, Vec)>, moved: Vec, missing: Vec, - /// (photo, its file, how its sidecar is named) - sidecars: Vec<(PhotoId, String, SidecarLookup, crate::crs::Target)>, + /// (photo, its file, how its sidecar is named, the orientation the catalog keeps for the file) + sidecars: Vec<(PhotoId, String, SidecarLookup, crate::crs::Target, Option)>, } /// The catalog half of a synchronize (see [`SyncJob`]). @@ -708,7 +708,7 @@ impl SyncJob { .zip(namings) .filter_map(|(m, naming)| { let p = s.catalog.photo(PhotoId(m.id))?; - Some((p.id, m.path, naming, crate::crs::Target::for_photo(p))) + Some((p.id, m.path, naming, crate::crs::Target::for_photo(p), p.meta.file_orientation)) }) .collect() } else { @@ -780,11 +780,11 @@ impl SyncWork { return; } let mut read = Vec::with_capacity(sidecars.len()); - for (id, path, naming, target) in sidecars { + for (id, path, naming, target, known) in sidecars { if cancel.load(Relaxed) { break; } - read.push((id, path.clone(), read_sidecar(&path, naming, target))); + read.push((id, path.clone(), read_sidecar(&path, naming, target, known))); step(1); } if !read.is_empty() { @@ -794,14 +794,19 @@ impl SyncWork { } /// Read and parse photo file `path`'s XMP sidecar file. -fn read_sidecar(path: &str, naming: SidecarLookup, target: crate::crs::Target) -> std::result::Result { +fn read_sidecar( + path: &str, + naming: SidecarLookup, + target: crate::crs::Target, + known: Option, +) -> std::result::Result { let file = naming.find(path).ok_or_else(|| "no XMP sidecar".to_string())?; let len = std::fs::metadata(&file).map_err(|e| format!("{}: {e}", file.display()))?.len(); if len > MAX_SIDECAR_BYTES { return Err(format!("{}: too large for an XMP sidecar", file.display())); } let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; - crate::sidecar::parse_sidecar(&text, target).map(|sc| sc.with_file_orientation(path)).map_err(|e| format!("{}: {e}", file.display())) + crate::sidecar::parse_sidecar(&text, target).map(|sc| sc.with_orientation_known(known, path)).map_err(|e| format!("{}: {e}", file.display())) } impl SyncCommit { diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index f178ac63dbc..190978753e2 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2418,3 +2418,40 @@ fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { let _ = std::fs::remove_dir_all(&src); } } + +/// Review of #4512: a face on a photo stored turned and mirrored (Exif 5) is written in the frame of the photo as +/// stored, with the stored size, and reading the sidecar back puts it on the same face of the upright photo. +#[test] +fn a_face_on_a_turned_mirrored_photo_is_written_in_the_stored_frame() { + use lightcraft_meta::{Orientation, Rect, Region, RegionKind}; + let src = temp_dir("face-write-transpose"); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: Some(Orientation::Transpose), ..Default::default() }); + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; + std::fs::write( + src.join("m.jpg"), + lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(), + ) + .unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let p = s.catalog.photo(id).unwrap(); + assert_eq!(((p.width, p.height), p.meta.file_orientation), ((24, 32), Some(Orientation::Transpose))); + let rect = Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; + let mut meta = p.meta.clone(); + meta.regions = vec![Region { rect, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; + s.commit("Name", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let x = std::fs::read_to_string(src.join("m.xmp")).unwrap(); + // stored frame: x and y swapped, the stored size, no rotation + assert!(x.contains("32") && x.contains("24") && !x.contains("mwg-rs:Rotation"), "{x}"); + assert!(x.contains("0.400000") && x.contains("0.200000"), "{x}"); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions.clear(); + s.commit("Forget", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + let g = s.catalog.photo(id).unwrap().meta.regions[0].rect; + assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); + let _ = std::fs::remove_dir_all(&src); +} diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index d5986f390be..fd931e1171d 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -125,9 +125,13 @@ write them, from sidecars and from XMP embedded in the file. Named faces become not rewrite a sidecar: the detector's unnamed boxes are LightCraft's bookkeeping and are left out until someone names them, and reading the sidecar back keeps them. `mwg-rs:AppliedToDimensions` is the upright size, and the boxes are written as Lightroom Classic writes them: for a file whose Exif orientation is 3, 6 or 8, in the frame of - the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`; otherwise, and on - mirrored photos (2, 4, 5, 7), which MWG can't describe, on the upright photo. The file's orientation is the one - the import read, kept in the catalog: a save never reads the photo file for it. A photo catalogued before LightCraft + the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`. A photo turned a + quarter and mirrored (5, 7) that isn't square is written in the stored frame too, with the stored size as + `AppliedToDimensions` and no rotation; LightCraft tells it from an upright packet by that size, as below. A photo + mirrored without a turn (2, 4) or a square one looks the same either way, so its boxes are written upright, as + LightCraft reads them; MWG readers that apply the mirror place those mirrored. Orientation 1 is written upright. The file's orientation is the one + the import read, kept in the catalog: a save never reads the photo file for it, and neither does reading a sidecar + back (Read Metadata from File, Synchronize Folder) when the catalog knows it. A photo catalogued before LightCraft kept it has its boxes written upright until Read Metadata from File reads it. Either way they read back as they were. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list From 12ce4cb8cb387ba195fb6b701ebe08eb299c8aac Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 14:48:50 -0600 Subject: [PATCH 10/25] LR-LIB-PEOPLE: one orientation for a photo's size and its file_orientation Review of #4512 (CodeRabbit, import orientation): for an image, probe_bytes turns the size upright by the header's Exif orientation (what the decoder shows), but ProbeInfo::orientation comes from lightcraft_meta::extract, which falls back to XMP. A PNG stating 6 only in its XMP kept its stored size while file_orientation said 6, so its face boxes would have been written turned. - ProbeInfo::upright_by: the orientation the size was made upright by (the raw decoder's, or the image header's Exif; None for a raw described from its embedded preview). The import keeps it as Meta::file_orientation and turns a sidecar's boxes by it, so the import, a save and a re-read go by the same one. - Read Metadata from File fills it in for older photos by probing the file the way the import does. Test: a PNG with orientation 6 only in its XMP keeps its size and Normal, its boxes are written and read back unturned (also through Read Metadata from File and a second library's import), and a sidecar another app drew on the turned shape reads the same on import and on re-read. Each part fails with its change reverted. --- crates/catalog/src/model.rs | 4 +- crates/engine/src/files/probe.rs | 5 +- crates/engine/src/import/commit.rs | 14 +-- crates/engine/src/import/job.rs | 4 +- crates/engine/src/import/types.rs | 3 + crates/engine/src/lightroom_catalog.rs | 2 +- crates/engine/src/lightroom_catalog/tests.rs | 1 + crates/engine/src/media/source.rs | 5 + crates/engine/src/sidecar.rs | 17 +++- crates/engine/src/tests/xmp.rs | 100 +++++++++++++++++++ 10 files changed, 140 insertions(+), 15 deletions(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 70eb0dbf000..a292f6d9605 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -229,8 +229,8 @@ pub struct Meta { /// written to XMP. Left out of the catalog JSON when unknown, so older catalogs read unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] pub focus: Option, - /// The photo file's own orientation, as the import read it (`ProbeInfo::orientation`, the one that made `width` × - /// `height` upright): how its stored pixels turn upright. A sidecar save writes face regions in the stored frame by + /// The photo file's own orientation, as the import read it (`ProbeInfo::upright_by`, the one that made `width` × + /// `height` upright and the photo is shown by): how its stored pixels turn upright. A sidecar save writes face regions in the stored frame by /// it (`lightcraft_engine::sidecar`) without reading the file. `None` for a file that states none, and for a photo /// catalogued before it was kept until Read Metadata from File reads it. Left out of the catalog JSON when unknown, /// so older catalogs read unchanged. diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index fea22e48ed0..986bee828d0 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -38,7 +38,7 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { keywords: lightcraft_catalog::keywords::from_file(&m.keywords, &m.hierarchical_keywords), regions: m.regions.clone(), focus: m.focus.clone(), - // (the import keeps `ProbeInfo::orientation`, which for a raw is the decoder's) + // (the import keeps `ProbeInfo::upright_by`) file_orientation: None, }; (meta, m.capture_time.as_ref().map(|d| d.to_iso())) @@ -206,6 +206,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { content_hash, xmp, orientation: Some(raw.orientation), + upright_by: Some(raw.orientation), preview_only: None, }); } @@ -252,6 +253,8 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { embedded_lens: None, xmp, orientation: m.orientation, + // the header's: what the size was turned by, and what the decoder shows + upright_by: Some(o), preview_only: None, }) } diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index dcda5563b55..5332674a115 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -226,16 +226,18 @@ fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool /// capture time, the import defaults, then its XMP sidecar. Returns the sidecar when it said /// anything (labels read through the library's label names). pub(crate) fn start_from_file(s: &Session, p: &mut Photo, file: FileFacts, now: &str) -> Option { - let FileFacts { meta, captured, orientation, sidecar } = file; + let FileFacts { meta, captured, orientation, upright_by, sidecar } = file; p.meta = meta; - // how the file turns upright, as the import's probe read it: a sidecar save writes face boxes by it - p.meta.file_orientation = orientation; + // what the size was made upright by: a sidecar save writes face boxes by it + p.meta.file_orientation = upright_by; p.captured = captured; apply_import_defaults(s, p); let sc = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default())?; // the photo is upright as the file's own orientation turns it, when the file states one - // (after the check above: an orientation alone isn't a sidecar that said something) - let sc = crate::sidecar::SidecarData { orientation: orientation.or(sc.orientation), ..sc }; + // (after the check above: an orientation alone isn't a sidecar that said something); the + // orientation the photo's size was made upright by turns the sidecar's boxes too, so the + // import, a save (`Meta::file_orientation`) and a re-read go by the same one + let sc = crate::sidecar::SidecarData { orientation: upright_by.or(orientation).or(sc.orientation), ..sc }; crate::sidecar::merge_into(p, &sc, now); Some(sc) } @@ -343,7 +345,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.embedded_lens = info.embedded_lens.map(Box::new); p.set_preview_only(info.preview_only.clone()); if let Some(sc) = - start_from_file(s, &mut p, FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar }, &now) + start_from_file(s, &mut p, FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar }, &now) { report.sidecars += 1; report.warnings.extend(sc.warnings.into_iter().map(|mut warning| { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 96781be7a4a..2f051c7b7f2 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -156,7 +156,7 @@ impl Prepared { existing: Some(existing), reason: if existing_path.is_some() { "path" } else { "content" }, hash: info.content_hash, - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), + file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar })), }); } else { items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup }))); @@ -551,7 +551,7 @@ impl ImportJob { existing, reason: "content", hash: Some(hash), - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), + file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar })), })); continue; } diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index b2f017fd802..929dfe8eea9 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -194,6 +194,9 @@ pub struct FileFacts { /// The file's own orientation, when it states one ([`crate::media::ProbeInfo::orientation`]): it turns what its /// sidecar's regions were drawn on, the photo as stored, upright (#2674). pub orientation: Option, + /// The orientation its size was made upright by ([`crate::media::ProbeInfo::upright_by`]): the catalog keeps it + /// (`Meta::file_orientation`) and face boxes are written and read back by it. + pub upright_by: Option, /// Its XMP sidecar (or a raw's embedded XMP), which a file import merges into the record. pub sidecar: Option, } diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index e80b606d8a0..e4658d2784d 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1356,7 +1356,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co ..Default::default() }; // the same bytes turn upright the same way - crate::import::FileFacts { meta, orientation: m.file_orientation, ..Default::default() } + crate::import::FileFacts { meta, upright_by: m.file_orientation, ..Default::default() } }); // as a file import of it: its file's metadata and capture time, the import defaults // (as-shot white balance, embedded lens corrections, the default preset), its XMP diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 3503960858e..48ec53155af 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -215,6 +215,7 @@ fn a_content_duplicate_of_a_trashed_photo_or_virtual_copy_is_a_new_live_photo() meta: lightcraft_catalog::Meta { camera: "Same Camera".into(), ..Default::default() }, captured: None, orientation: None, + upright_by: None, sidecar: None, })), }], diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index e330fe6982e..b4cedba00bb 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -400,6 +400,11 @@ pub struct ProbeInfo { /// The file's Exif orientation, when it states one: how its stored pixels turn upright (`width` and `height` are /// the upright size). pub orientation: Option, + /// The orientation `width` × `height` were turned upright by, the one the photo is shown by: a raw decoder's, or + /// an image header's Exif (an orientation only XMP states turns neither the pixels nor the size). `None` when the + /// size came from something else (a raw described from its embedded preview). The catalog keeps it + /// (`Meta::file_orientation`): face boxes are written and read back by it. + pub upright_by: Option, /// A raw variant that can't be decoded yet: why. The file is described (and will be shown and /// edited) from its embedded preview; see [`lightcraft_catalog::Photo::preview_only`]. pub preview_only: Option, diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 2e3f741a200..1c6160d7029 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -489,7 +489,17 @@ impl SidecarData { } } -/// The orientation the photo file at `path` states, matching what the import stores on [`crate::media::ProbeInfo`]: +/// The orientation the photo file at `path` was (or would be) made upright by on import +/// ([`crate::media::ProbeInfo::upright_by`]), probed the same way: the whole file is read. For a photo catalogued +/// before [`lightcraft_catalog::Meta::file_orientation`] was kept, by Read Metadata from File only. +fn upright_orientation(path: &str) -> Option { + let bytes = std::fs::read(path).ok()?; + let name = Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::files::probe_bytes(&name, &bytes).ok()?.upright_by +} + +/// The orientation the photo file at `path` states, matching what the import stores as +/// [`crate::media::ProbeInfo::orientation`]: /// for a raw, the decoder's (`lightcraft_raw::probe_info`: CIFF for a CRW, the raw IFD for a MEF, …); otherwise Exif, /// else XMP, as [`lightcraft_meta::extract`] reads it. A file shorter than [`ORIENTATION_SPAN`] is read whole. Most /// non-raws state it in the Exif of their first [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later @@ -1667,9 +1677,10 @@ impl Session { let Some(orig) = file_path(p) else { return Ok(None) }; // a photo catalogued before the file's orientation was kept: Read Metadata from File reads it, once, so its // face boxes are written in the frame the file is stored in from then on (the file is read at most once here) - let mut known: Option> = p.meta.file_orientation.map(Some); + // (probed as the import probes it, so it is the one the photo's size was made upright by) + let backfill = if p.meta.file_orientation.is_none() { upright_orientation(orig) } else { None }; + let mut known: Option> = p.meta.file_orientation.or(backfill).map(Some); let mut orientation_of_file = || *known.get_or_insert_with(|| file_orientation(orig)); - let backfill = if p.meta.file_orientation.is_none() { orientation_of_file() } else { None }; let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { // no packet to read; the orientation alone is still news return match backfill { diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 190978753e2..a107a42136f 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2455,3 +2455,103 @@ fn a_face_on_a_turned_mirrored_photo_is_written_in_the_stored_frame() { assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); let _ = std::fs::remove_dir_all(&src); } + +/// Review of #4512: a PNG whose orientation only its XMP states (no Exif) is shown, and sized, as stored. The catalog +/// keeps the orientation the size was made upright by (none), so face boxes are written and read back on the photo +/// as shown, not turned for an orientation the size doesn't have. Read Metadata from File fills it in the same way. +#[test] +fn an_orientation_only_xmp_states_turns_neither_the_size_nor_the_boxes() { + use lightcraft_meta::{Orientation, Rect, Region, RegionKind}; + let src = temp_dir("face-xmp-only-orientation"); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + let xmp = r#""#; + let encoded = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&img), + &lightcraft_codecs::EncodeMeta { xmp: Some(xmp), ..Default::default() }, + ) + .unwrap(); + // the encoder sets the XMP's orientation to 1 (it applies none to the pixels): state 6 in the XMP chunk again, + // with no Exif, as another app could have written it + let crc = |bytes: &[u8]| { + let mut c = 0xffff_ffffu32; + for &b in bytes { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 }; + } + } + !c + }; + let mut png = encoded[..8].to_vec(); + let mut at = 8; + while at + 8 <= encoded.len() { + let len = u32::from_be_bytes(encoded[at..at + 4].try_into().unwrap()) as usize; + let (kind, data) = (&encoded[at + 4..at + 8], &encoded[at + 8..at + 8 + len]); + let data = if kind == b"iTXt" { + String::from_utf8_lossy(data).replace(r#"tiff:Orientation="1""#, r#"tiff:Orientation="6""#).into_bytes() + } else { + data.to_vec() + }; + if kind != b"eXIf" { + png.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + png.extend_from_slice(kind); + png.extend_from_slice(&data); + png.extend_from_slice(&crc(&[kind, data.as_slice()].concat()).to_be_bytes()); + } + at += 12 + len; + } + assert!(!png.windows(4).any(|w| w == b"eXIf")); + assert_eq!(lightcraft_meta::extract(&png).orientation, Some(Orientation::Rotate90), "the XMP states 6"); + assert_eq!(lightcraft_codecs::read_header(&png).unwrap().orientation, 1, "the header (what it's shown by) doesn't"); + std::fs::write(src.join("x.png"), png).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let p = s.catalog.photo(id).unwrap(); + assert_eq!(((p.width, p.height), p.meta.file_orientation), ((32, 24), Some(Orientation::Normal)), "one rule for both"); + + let rect = Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; + let mut meta = p.meta.clone(); + meta.regions = vec![Region { rect, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; + s.commit("Name", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let x = std::fs::read_to_string(src.join("x.xmp")).unwrap(); + assert!(!x.contains("mwg-rs:Rotation") && x.contains("0.200000") && x.contains("32"), "as shown: {x}"); + + // as catalogued before the orientation was kept: Read Metadata from File probes it the way the import does + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + meta.regions.clear(); + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + let p = s.catalog.photo(id).unwrap(); + assert_eq!(p.meta.file_orientation, Some(Orientation::Normal)); + let g = p.meta.regions[0].rect; + assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); + + // and a second library importing the photo with that sidecar reads the box where it is + let mut b = Session::new().with_fs(); + b.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let idb = b.catalog.photos().next().unwrap().id; + let g = b.catalog.photo(idb).unwrap().meta.regions[0].rect; + assert!([(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5), "{g:?}"); + + // another app's sidecar drawn on the turned shape (24 × 32): the import and a re-read go by the same orientation, + // so reading the file again changes nothing (or Synchronize Folder would report it every pass, #2857) + let other = temp_dir("face-xmp-only-orientation-other"); + std::fs::copy(src.join("x.png"), other.join("y.png")).unwrap(); + std::fs::write( + other.join("y.xmp"), + r#"FaceCy"#, + ) + .unwrap(); + let mut c = Session::new().with_fs(); + c.execute("library.import", &json!({"paths": [other.to_string_lossy()]})).unwrap(); + let idc = c.catalog.photos().next().unwrap().id; + let imported = c.catalog.photo(idc).unwrap().meta.regions.clone(); + assert_eq!(imported.len(), 1); + c.execute("photo.readMetadataFromFile", &json!({"ids": [idc.0]})).unwrap(); + assert_eq!(c.catalog.photo(idc).unwrap().meta.regions, imported, "a re-read agrees with the import"); + let _ = std::fs::remove_dir_all(&other); + let _ = std::fs::remove_dir_all(&src); +} From d4c354cfc687bf5a93164055426d94c3cb251b5b Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 15:13:23 -0600 Subject: [PATCH 11/25] LR-LIB-PEOPLE: write 5/7 boxes upright when the list keeps no size Review of #4512 (CodeRabbit): for a photo turned and mirrored (Exif 5, 7), boxes go in the stored frame with no rotation, which only the list's AppliedToDimensions tells. When fit_to_old drops that size because it keeps another app's pixel boxes that had none, a re-read couldn't tell the frame and returned the box transposed. A save now carries the packet with the boxes upright as well (sidecar_packets / Fresh), and fit_to_old picks it after resolving the carried entries whenever the size has to go. With a size, 5/7 stay in the stored frame; 3/6/8 keep Lightroom's rotation either way. Test: Exif 5, 7 and 6 against a sidecar with a sizeless pixel box (upright for 5/7, rotation for 6, read back to the same box, stable) and without one (stored frame with the stored size). It fails with the fallback removed, returning the transposed box. The tests' save helper now goes through the same packets as the app. --- crates/engine/src/sidecar.rs | 107 ++++++++++++++++++++++++++++++----- docs/xmp-interop.md | 3 +- 2 files changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 1c6160d7029..56b37caf276 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -836,6 +836,40 @@ fn writable_rect(r: lightcraft_meta::Rect) -> Option<(f64, f64, f64, f64)> { (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1)) } +/// The packets a save of a photo's sidecar chooses from ([`fit_to_old`]). +#[derive(Clone)] +struct Fresh { + /// The photo's packet ([`sidecar_packet`]). + packet: String, + /// The same with its face boxes on the upright photo, when `packet` has them in the frame the file is stored in + /// with no rotation (Exif 5, 7): only the list's `AppliedToDimensions` tells that frame, so a save that has to + /// leave the size out writes this one. + upright: Option, +} + +impl From for Fresh { + fn from(packet: String) -> Self { + Fresh { packet, upright: None } + } +} + +/// [`Fresh`] for a save of `p`'s sidecar. +fn sidecar_packets(p: &Photo, cat: &lightcraft_catalog::Catalog) -> Fresh { + let upright = unrotated_stored_frame(p, p.meta.file_orientation) + .then(|| with_regions(sidecar_packet_with(p, cat, false), p, None)) + .filter(|_| !file_regions(p).is_empty()); + Fresh { packet: sidecar_packet(p, cat), upright } +} + +/// Whether `p`'s boxes are written in the frame its file is stored in with no rotation: a quarter turn and a mirror +/// (Exif 5, 7) on a photo that isn't square, which the reader tells from an upright packet by the list's size only. +fn unrotated_stored_frame(p: &Photo, orientation: Option) -> bool { + matches!(orientation, Some(lightcraft_meta::Orientation::Transpose | lightcraft_meta::Orientation::Transverse)) + && p.width > 0 + && p.height > 0 + && p.width != p.height +} + /// The people named on the photo's faces that are written ([`file_regions`]), trimmed, each once (case-insensitive), /// in region order. fn face_names(p: &Photo) -> Vec { @@ -886,10 +920,7 @@ fn with_regions(packet: String, p: &Photo, orientation: Option\n"); // a photo turned a quarter and mirrored (Exif 5, 7) and not square: in the frame of the photo as stored, with the // stored size, which the reader tells from the upright size and turns back (#2674) - let mirrored_turn = matches!(orientation, Some(lightcraft_meta::Orientation::Transpose | lightcraft_meta::Orientation::Transverse)) - && p.width > 0 - && p.height > 0 - && p.width != p.height; + let mirrored_turn = unrotated_stored_frame(p, orientation); let (dw, dh) = if mirrored_turn { (p.height, p.width) } else { (p.width, p.height) }; if dw > 0 && dh > 0 { x.push_str(&format!( @@ -970,7 +1001,7 @@ fn people_block(names: &[String]) -> String { x } -/// `fresh` (a packet from [`sidecar_packet`]) fitted to the sidecar it replaces, `old`, for the two properties whose +/// `fresh` (packets from [`sidecar_packets`]) fitted to the sidecar it replaces, `old`, for the two properties whose /// right value depends on what the file already says: /// - `Iptc4xmpExt:PersonInImage`: the names on the photo's faces, plus the names in the file's list that are not the /// name of a face region in the file (typed in another application). A name that belonged to one of the file's @@ -983,14 +1014,21 @@ fn people_block(names: &[String]) -> String { /// from keeps it as it is ([`OWNED_IF_STATED`]). Entries of the file's list that LightCraft can't read (boxes in /// pixels with no size, say) are kept whenever the list is written ([`unreadable_regions`]); if they can't be singled /// out, the file's list is left as it is. -fn fit_to_old(old: &str, fresh: String) -> String { +fn fit_to_old(old: &str, fresh: Fresh) -> String { let old = old.strip_prefix('\u{feff}').unwrap_or(old); // (a file that isn't XMP can't be merged either: `sidecar_contents` handles it) let Ok(data) = lightcraft_meta::parse_xmp(old) else { - return fresh; + return fresh.packet; }; // its regions; if they can't be read, every name in its list is kept as typed in elsewhere let regions = parse_sidecar(old, crate::crs::Target::Rendered).ok().and_then(|sc| sc.regions); + let readable = regions.as_ref().map_or(0, Vec::len); + let carried = unreadable_regions(old, &data, readable); + // the list's size goes when kept pixel boxes had none (below); boxes only that size tells the frame of go upright + let fresh = match fresh.upright { + Some(upright) if carried.as_ref().is_some_and(|c| c.pixels_without_size) => upright, + _ => fresh.packet, + }; let lower = |s: &str| s.trim().to_lowercase(); let face_names: Vec = regions.iter().flatten().filter_map(|r| r.name.as_deref()).map(lower).collect(); let typed: Vec = data @@ -1017,8 +1055,6 @@ fn fit_to_old(old: &str, fresh: String) -> String { names.push(t); } } - let readable = regions.as_ref().map_or(0, Vec::len); - let carried = unreadable_regions(old, &data, readable); if fresh.contains(REGIONS_OPEN) { match carried { // the file's entries LightCraft can't read go on after the photo's own, as they were @@ -1265,15 +1301,16 @@ pub struct SidecarSaved { /// The new contents for the sidecar at `path`: `fresh` merged into the existing file, if any. /// Returns (contents, merged, backup). -fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result<(String, bool, Option)> { +fn sidecar_contents(path: &Path, fresh: impl Into, stamp: &str) -> std::io::Result<(String, bool, Option)> { + let fresh: Fresh = fresh.into(); let bytes = match crate::read_file::read_regular(path, SIDECAR_READ_MAX) { Ok(b) => b, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh, false, None)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh.packet, false, None)), // can't see what is there: never overwrite it blindly Err(e) => return Err(e), }; if bytes.iter().all(u8::is_ascii_whitespace) { - return Ok((fresh, false, None)); + return Ok((fresh.packet, false, None)); } let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED }; let why = match std::str::from_utf8(&bytes) { @@ -1297,7 +1334,7 @@ fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result< }; let b = backup(path, stamp)?; log::warn!("{}: not readable as XMP ({why}); kept a copy as {} before replacing it", path.display(), b.display()); - Ok((fresh, false, Some(b))) + Ok((fresh.packet, false, Some(b))) } /// Key of the stem sidecar a file maps to (case-insensitive). @@ -1660,7 +1697,7 @@ impl Session { self.validate_sidecar_packets_for_paths(std::slice::from_ref(&path), &crate::rename::RealFs)?; let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let err = |e: std::io::Error| EngineError::Other(format!("{}: {e}", path.display())); - let (data, merged, backup) = sidecar_contents(&path, sidecar_packet(p, &self.catalog), &(self.clock)()).map_err(err)?; + let (data, merged, backup) = sidecar_contents(&path, sidecar_packets(p, &self.catalog), &(self.clock)()).map_err(err)?; write_atomic(&path, data.as_bytes()).map_err(err)?; self.note_sidecar_write(&path, data.as_bytes()); Ok(SidecarSaved { path, merged, backup }) @@ -2461,7 +2498,7 @@ mod tests { /// Save `p` over `path` as the app does; the new contents. fn save_over(path: &Path, p: &Photo) -> String { - let (x, _, _) = sidecar_contents(path, sidecar_packet(p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + let (x, _, _) = sidecar_contents(path, sidecar_packets(p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); std::fs::write(path, &x).unwrap(); x } @@ -2594,6 +2631,46 @@ mod tests { let _ = std::fs::remove_dir_all(path.parent().unwrap()); } + #[test] + fn boxes_go_upright_when_a_kept_pixel_entry_takes_the_lists_size_away() { + use lightcraft_meta::Orientation::{Rotate90, Transpose, Transverse}; + let upright = lightcraft_meta::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; + let read_back = |x: &str, o| { + let sc = parse_sidecar(x, crate::crs::Target::Rendered).unwrap().with_orientation_known(Some(o), "/no/such/file"); + let mut q = photo(); + merge_into(&mut q, &sc, "now"); + q.meta.regions.iter().find(|r| r.name.as_deref() == Some("Ann")).map(|r| r.rect).unwrap() + }; + let near = |g: lightcraft_meta::Rect| [(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5); + for o in [Transpose, Transverse, Rotate90] { + let mut p = photo(); + p.meta.file_orientation = Some(o); + p.meta.regions = + vec![lightcraft_meta::Region { rect: upright, kind: lightcraft_meta::RegionKind::Face, name: Some("Ann".into()), description: None }]; + + // a sidecar with a pixel box and no size: the list keeps having no size, so the boxes can't be in a frame + // only the size tells (5, 7) and go upright; a rotation still says Lightroom's frame (6) + let path = scratch("upright-fallback"); + std::fs::write(&path, sidecar_with_pixel_entry(&[])).unwrap(); + let x = save_over(&path, &p); + assert!(!x.contains("AppliedToDimensions") && x.contains("stArea:unit=\"pixel\""), "{o:?}: {x}"); + assert!(near(read_back(&x, o)), "{o:?}: {:?} {x}", read_back(&x, o)); + assert_eq!(x.contains("mwg-rs:Rotation"), o == Rotate90, "{o:?}"); + assert_eq!(save_over(&path, &p), x, "{o:?}: stable"); + + // with no pixel box to keep, the list has its size and 5, 7 are in the stored frame + let path = scratch("stored-frame"); + std::fs::write(&path, sidecar_with(&[], &[])).unwrap(); + let x = save_over(&path, &p); + assert!(x.contains("AppliedToDimensions"), "{o:?}: {x}"); + if o != Rotate90 { + assert!(x.contains("30"), "{o:?}: stored size: {x}"); + } + assert!(near(read_back(&x, o)), "{o:?}: {:?}", read_back(&x, o)); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + } + #[test] fn a_kept_entry_keeps_its_size_when_the_list_had_one() { // an entry off the photo in a list with a size: unreadable, kept, and the list keeps its size when cleared diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index fd931e1171d..1eea9c1824d 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -127,7 +127,8 @@ write them, from sidecars and from XMP embedded in the file. Named faces become boxes are written as Lightroom Classic writes them: for a file whose Exif orientation is 3, 6 or 8, in the frame of the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`. A photo turned a quarter and mirrored (5, 7) that isn't square is written in the stored frame too, with the stored size as - `AppliedToDimensions` and no rotation; LightCraft tells it from an upright packet by that size, as below. A photo + `AppliedToDimensions` and no rotation; LightCraft tells it from an upright packet by that size, as below. When + the list can't have a size (it keeps pixel boxes that had none, see below), those boxes are written upright. A photo mirrored without a turn (2, 4) or a square one looks the same either way, so its boxes are written upright, as LightCraft reads them; MWG readers that apply the mirror place those mirrored. Orientation 1 is written upright. The file's orientation is the one the import read, kept in the catalog: a save never reads the photo file for it, and neither does reading a sidecar From 45ba2fc2c9672a0ad9e0ec90dbb47dfe2d91ddac Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 15:28:58 -0600 Subject: [PATCH 12/25] LR-LIB-PEOPLE: an unreadable sidecar fails Read Metadata even when the orientation is news Review of #4512 (CodeRabbit): read_packet returns None both for a photo with no packet and for a discovered sidecar that can't be read (or isn't UTF-8). With the orientation backfill, the second was reported as read for the orientation alone and its contents never applied. find_packet now tells the three apart (found, there but unreadable, none). Read Metadata from File fails an unreadable one, naming the file and why, and reports the orientation alone as read only when there is no sidecar and no XMP LightCraft finds in the photo file. read_packet keeps its signature. Test: a photo without a kept orientation and a non-UTF-8 sidecar fails the read naming t.xmp and changes nothing; with the sidecar gone the orientation is read. It fails with the unreadable case folded back into "none". --- crates/engine/src/sidecar.rs | 73 +++++++++++++++++++++++++--------- crates/engine/src/tests/xmp.rs | 29 ++++++++++++++ 2 files changed, 84 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 56b37caf276..9e9e1d0fe0a 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -1378,21 +1378,53 @@ fn file_path(p: &Photo) -> Option<&str> { /// The XMP packet that describes a photo on disk: its sidecar, else embedded raw/DNG or JPEG XMP. pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Option<(String, PathBuf)> { + match find_packet(original, kind, lookup) { + Packet::Found(packet, from) => Some((packet, from)), + Packet::Unreadable(..) | Packet::None => None, + } +} + +/// What [`find_packet`] finds. +enum Packet { + /// The packet, and the file it was read from. + Found(String, PathBuf), + /// A sidecar, or the photo file holding the packet, that is there but can't be read (or isn't UTF-8), and why. + Unreadable(PathBuf, String), + /// No sidecar, and no XMP in the photo file that LightCraft finds there. + None, +} + +/// [`read_packet`], telling a packet that can't be read from none. +fn find_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Packet { if let Some(sc) = lookup.find(original) { // A discovered sidecar keeps precedence even when reading it fails. - return crate::read_file::read_regular(&sc, SIDECAR_READ_MAX).ok().and_then(|b| String::from_utf8(b).ok()).map(|s| (s, sc)); + return match crate::read_file::read_regular(&sc, SIDECAR_READ_MAX) { + Ok(b) => match String::from_utf8(b) { + Ok(text) => Packet::Found(text, sc), + Err(_) => Packet::Unreadable(sc, "it isn't UTF-8 text".into()), + }, + Err(e) => Packet::Unreadable(sc, e.to_string()), + }; } if kind == MediaKind::Raw { - let bytes = crate::read_file::read_regular(original, crate::read_file::MAX_MEDIA_BYTES).ok()?; - let x = lightcraft_meta::embedded(&bytes).xmp?; - return Some((x, PathBuf::from(original))); + return match crate::read_file::read_regular(original, crate::read_file::MAX_MEDIA_BYTES) { + Ok(bytes) => match lightcraft_meta::embedded(&bytes).xmp { + Some(x) => Packet::Found(x, PathBuf::from(original)), + None => Packet::None, + }, + Err(e) => Packet::Unreadable(PathBuf::from(original), e.to_string()), + }; } if kind == MediaKind::Image { - let mut file = std::fs::File::open(original).ok()?; - let x = read_jpeg_xmp(&mut file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS)?; - return Some((x, PathBuf::from(original))); + return match std::fs::File::open(original) { + Ok(mut file) => match read_jpeg_xmp(&mut file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS) { + Some(x) => Packet::Found(x, PathBuf::from(original)), + None => Packet::None, + }, + Err(e) => Packet::Unreadable(PathBuf::from(original), e.to_string()), + }; } - None + Packet::None } /// Most bytes of a sidecar read whole (the opened file must be a regular file). @@ -1718,16 +1750,21 @@ impl Session { let backfill = if p.meta.file_orientation.is_none() { upright_orientation(orig) } else { None }; let mut known: Option> = p.meta.file_orientation.or(backfill).map(Some); let mut orientation_of_file = || *known.get_or_insert_with(|| file_orientation(orig)); - let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { - // no packet to read; the orientation alone is still news - return match backfill { - Some(o) => Ok(Some(( - self.sidecar_op(id, SidecarData { file_orientation: Some(o), ..SidecarData::default() })?, - PathBuf::from(orig), - Vec::new(), - ))), - None => Ok(None), - }; + let (packet, from) = match find_packet(orig, p.kind, self.sidecar_lookup(id)) { + Packet::Found(packet, from) => (packet, from), + // one that is there but can't be read fails the read, as before: nothing is reported read from it + Packet::Unreadable(from, why) => return Err(EngineError::Other(format!("{} can't be read: {why}", from.display()))), + // no packet at all: the orientation alone is still news + Packet::None => { + return match backfill { + Some(o) => Ok(Some(( + self.sidecar_op(id, SidecarData { file_orientation: Some(o), ..SidecarData::default() })?, + PathBuf::from(orig), + Vec::new(), + ))), + None => Ok(None), + }; + } }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; // (as `with_orientation_known`: the catalog's orientation, else the file's, read at most once) diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index a107a42136f..d90fff119a5 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2555,3 +2555,32 @@ fn an_orientation_only_xmp_states_turns_neither_the_size_nor_the_boxes() { let _ = std::fs::remove_dir_all(&other); let _ = std::fs::remove_dir_all(&src); } + +/// Review of #4512: on a photo whose catalog doesn't know its file's orientation yet, a sidecar that is there but +/// can't be read (not UTF-8) still fails Read Metadata from File, naming the file, rather than being reported read +/// for the orientation alone; nothing changes. With no sidecar at all, the orientation alone is read. +#[test] +fn an_unreadable_sidecar_fails_the_read_even_when_the_orientation_is_news() { + let src = temp_dir("unreadable-sidecar-orientation"); + write_turned_jpeg(&src.join("t.jpg"), None); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + + std::fs::write(src.join("t.xmp"), [0xff, 0xfe, 0x00, 0x3c]).unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["read"], json!([]), "{read}"); + assert_eq!(read["failed"][0]["id"], id.0, "{read}"); + let why = read["failed"][0]["error"].as_str().unwrap(); + assert!(why.contains("t.xmp") && why.contains("can't be read"), "{why}"); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, None, "nothing applied"); + + std::fs::remove_file(src.join("t.xmp")).unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{read}"); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, Some(lightcraft_meta::Orientation::Rotate90)); + let _ = std::fs::remove_dir_all(&src); +} From 7098018d9e0bfc60e24f586f7d0f56022c7b0430 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 17:31:25 -0600 Subject: [PATCH 13/25] LR-LIB-PEOPLE: bound the orientation backfill and probe only for it Read Metadata from File gets a missing file orientation by the import's rule (files::upright_by: the raw decoder's, else the image header's), without the full import probe or hashing. It reads the file only for a photo with face boxes to write, at most once, within MAX_MEDIA_BYTES, and a raw's embedded XMP comes from the same bytes. The unbounded file_orientation fallback is no longer used on that path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/engine/src/files.rs | 2 +- crates/engine/src/files/probe.rs | 14 +++ crates/engine/src/sidecar.rs | 85 ++++++++++--- crates/engine/src/tests/xmp.rs | 207 ++++++++++++++++++++++++------- docs/xmp-interop.md | 3 +- 5 files changed, 243 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index a327d0c111c..210246579ba 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -32,7 +32,7 @@ pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_v use preview::PLAN_PREFIX; pub(crate) use preview::decode_raw_preview; pub use preview::{PreviewRead, embedded_preview_srgb, fs_preview_loader, load_embedded_preview, preview_window}; -pub use probe::{embedded_lens, probe_bytes}; +pub use probe::{embedded_lens, probe_bytes, upright_by}; #[cfg(test)] use probe::{meta_of, preview_reason}; diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 986bee828d0..1312dc86a94 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -144,6 +144,20 @@ fn ext_upper(name: &str) -> String { std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default() } +/// The orientation a file's size is made upright by on import ([`ProbeInfo::upright_by`]) and nothing else: a raw's +/// from its decoder, an image's from its header's Exif (what [`probe_bytes`] turns them by). `None` where the import +/// has none: a raw described from its embedded preview, or a file it can't read. No hashing, no metadata. +pub fn upright_by(bytes: &[u8]) -> Option { + if lightcraft_raw::probe(bytes).is_some() { + return lightcraft_raw::probe_info(bytes).ok().map(|raw| raw.orientation); + } + let fmt = lightcraft_codecs::sniff(bytes)?; + if fmt.not_decodable().is_some() { + return None; + } + lightcraft_codecs::read_header(bytes).ok().map(|h| Orientation::from_exif(h.orientation)) +} + /// Probe a file's bytes: kind, dimensions (oriented), metadata. No pixel data is decompressed: /// raws are described from their headers ([`lightcraft_raw::probe_info`]), other images too /// ([`lightcraft_codecs::read_header`], which refuses truncated files but can't see damage inside diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 9e9e1d0fe0a..3a6740acb0a 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -490,12 +490,11 @@ impl SidecarData { } /// The orientation the photo file at `path` was (or would be) made upright by on import -/// ([`crate::media::ProbeInfo::upright_by`]), probed the same way: the whole file is read. For a photo catalogued -/// before [`lightcraft_catalog::Meta::file_orientation`] was kept, by Read Metadata from File only. -fn upright_orientation(path: &str) -> Option { - let bytes = std::fs::read(path).ok()?; - let name = Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - crate::files::probe_bytes(&name, &bytes).ok()?.upright_by +/// ([`crate::media::ProbeInfo::upright_by`], by [`crate::files::upright_by`]'s rule): the file is read, up to `max` +/// bytes (none past that), and nothing but its orientation is worked out. For a photo catalogued before +/// [`lightcraft_catalog::Meta::file_orientation`] was kept, by Read Metadata from File only. +fn upright_orientation(path: &str, max: u64) -> Option { + crate::files::upright_by(&crate::read_file::read_regular(path, max).ok()?) } /// The orientation the photo file at `path` states, matching what the import stores as @@ -1378,7 +1377,7 @@ fn file_path(p: &Photo) -> Option<&str> { /// The XMP packet that describes a photo on disk: its sidecar, else embedded raw/DNG or JPEG XMP. pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Option<(String, PathBuf)> { - match find_packet(original, kind, lookup) { + match find_packet(original, kind, lookup, None) { Packet::Found(packet, from) => Some((packet, from)), Packet::Unreadable(..) | Packet::None => None, } @@ -1394,8 +1393,8 @@ enum Packet { None, } -/// [`read_packet`], telling a packet that can't be read from none. -fn find_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Packet { +/// [`read_packet`], telling a packet that can't be read from none. `raw` is a raw's bytes already read, if they were. +fn find_packet(original: &str, kind: MediaKind, lookup: SidecarLookup, raw: Option<&[u8]>) -> Packet { if let Some(sc) = lookup.find(original) { // A discovered sidecar keeps precedence even when reading it fails. return match crate::read_file::read_regular(&sc, SIDECAR_READ_MAX) { @@ -1407,7 +1406,11 @@ fn find_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Packet }; } if kind == MediaKind::Raw { - return match crate::read_file::read_regular(original, crate::read_file::MAX_MEDIA_BYTES) { + let bytes = match raw { + Some(b) => Ok(std::borrow::Cow::Borrowed(b)), + None => crate::read_file::read_regular(original, crate::read_file::MAX_MEDIA_BYTES).map(std::borrow::Cow::Owned), + }; + return match bytes { Ok(bytes) => match lightcraft_meta::embedded(&bytes).xmp { Some(x) => Packet::Found(x, PathBuf::from(original)), None => Packet::None, @@ -1744,18 +1747,29 @@ impl Session { pub fn read_sidecar_op_with_warnings(&self, id: PhotoId) -> Result)>> { let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let Some(orig) = file_path(p) else { return Ok(None) }; - // a photo catalogued before the file's orientation was kept: Read Metadata from File reads it, once, so its - // face boxes are written in the frame the file is stored in from then on (the file is read at most once here) - // (probed as the import probes it, so it is the one the photo's size was made upright by) - let backfill = if p.meta.file_orientation.is_none() { upright_orientation(orig) } else { None }; - let mut known: Option> = p.meta.file_orientation.or(backfill).map(Some); - let mut orientation_of_file = || *known.get_or_insert_with(|| file_orientation(orig)); - let (packet, from) = match find_packet(orig, p.kind, self.sidecar_lookup(id)) { + // A photo catalogued before the file's orientation was kept gets it here, so its face boxes are written in the + // frame the file is stored in from then on. Only a photo with boxes to write needs it: the file isn't read for + // one without. It is probed by the import's rule, from the file read at most once, within the media limit. + let lookup = self.sidecar_lookup(id); + let unknown = p.meta.file_orientation.is_none(); + // a raw with no sidecar is read whole for its embedded XMP anyway: the orientation comes from the same bytes + let raw_bytes = (unknown && p.kind == MediaKind::Raw && lookup.find(orig).is_none()) + .then(|| crate::read_file::read_regular(orig, crate::read_file::MAX_MEDIA_BYTES).ok()) + .flatten(); + let mut probed: Option> = None; + let backfill_now = |probed: &mut Option>| { + *probed.get_or_insert_with(|| match &raw_bytes { + Some(bytes) => crate::files::upright_by(bytes), + None => upright_orientation(orig, crate::read_file::MAX_MEDIA_BYTES), + }) + }; + let (packet, from) = match find_packet(orig, p.kind, lookup, raw_bytes.as_deref()) { Packet::Found(packet, from) => (packet, from), // one that is there but can't be read fails the read, as before: nothing is reported read from it Packet::Unreadable(from, why) => return Err(EngineError::Other(format!("{} can't be read: {why}", from.display()))), - // no packet at all: the orientation alone is still news + // no packet at all: the orientation alone is news for a photo with boxes to write Packet::None => { + let backfill = if unknown && !file_regions(p).is_empty() { backfill_now(&mut probed) } else { None }; return match backfill { Some(o) => Ok(Some(( self.sidecar_op(id, SidecarData { file_orientation: Some(o), ..SidecarData::default() })?, @@ -1767,9 +1781,15 @@ impl Session { } }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; - // (as `with_orientation_known`: the catalog's orientation, else the file's, read at most once) + // the photo has boxes to write once this is read: its own, or the packet's + let backfill = if unknown && (!file_regions(p).is_empty() || sc.regions.as_ref().is_some_and(|r| !r.is_empty())) { + backfill_now(&mut probed) + } else { + None + }; + // The catalog's orientation, else the bounded probe's. Not `file_orientation`: it reads a raw whole, with no limit. let sc = match sc.regions_drawn_on { - Some(_) => SidecarData { orientation: orientation_of_file().or(sc.orientation), ..sc }, + Some(_) => SidecarData { orientation: p.meta.file_orientation.or(backfill).or(sc.orientation), ..sc }, None => sc, }; let sc = SidecarData { file_orientation: backfill, ..sc }; @@ -2957,6 +2977,31 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn the_orientation_backfill_reads_no_more_than_its_limit() { + let dir = std::env::temp_dir().join(format!("lc-upright-limit-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("t.jpg"); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [1, 2, 3, 255]); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { + orientation: Some(lightcraft_meta::Orientation::Rotate90), + ..Default::default() + }); + let bytes = lightcraft_codecs::encode_jpeg( + &lightcraft_codecs::EncodeImage::rgba8(&img), + 90, + Default::default(), + &lightcraft_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }, + ) + .unwrap(); + std::fs::write(&file, &bytes).unwrap(); + let path = file.to_string_lossy(); + assert_eq!(upright_orientation(&path, crate::read_file::MAX_MEDIA_BYTES), Some(lightcraft_meta::Orientation::Rotate90)); + // a file past the limit isn't read (nor held in memory) at all + assert_eq!(upright_orientation(&path, bytes.len() as u64 - 1), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn exports_carry_no_regions() { let mut p = photo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index d90fff119a5..8185e408d24 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2391,14 +2391,9 @@ fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { // as a photo catalogued before: no orientation kept let mut meta = s.catalog.photo(id).unwrap().meta.clone(); meta.file_orientation = None; - if with_packet { - meta.regions = vec![Region { - rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, - kind: RegionKind::Face, - name: Some("Ann".into()), - description: None, - }]; - } + // (a face: the orientation is needed, and read, only for a photo with boxes to write) + meta.regions = + vec![Region { rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); if with_packet { // saved upright: the file isn't read for it @@ -2463,44 +2458,7 @@ fn a_face_on_a_turned_mirrored_photo_is_written_in_the_stored_frame() { fn an_orientation_only_xmp_states_turns_neither_the_size_nor_the_boxes() { use lightcraft_meta::{Orientation, Rect, Region, RegionKind}; let src = temp_dir("face-xmp-only-orientation"); - let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); - let xmp = r#""#; - let encoded = lightcraft_codecs::encode_png( - &lightcraft_codecs::EncodeImage::rgba8(&img), - &lightcraft_codecs::EncodeMeta { xmp: Some(xmp), ..Default::default() }, - ) - .unwrap(); - // the encoder sets the XMP's orientation to 1 (it applies none to the pixels): state 6 in the XMP chunk again, - // with no Exif, as another app could have written it - let crc = |bytes: &[u8]| { - let mut c = 0xffff_ffffu32; - for &b in bytes { - c ^= u32::from(b); - for _ in 0..8 { - c = if c & 1 == 1 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 }; - } - } - !c - }; - let mut png = encoded[..8].to_vec(); - let mut at = 8; - while at + 8 <= encoded.len() { - let len = u32::from_be_bytes(encoded[at..at + 4].try_into().unwrap()) as usize; - let (kind, data) = (&encoded[at + 4..at + 8], &encoded[at + 8..at + 8 + len]); - let data = if kind == b"iTXt" { - String::from_utf8_lossy(data).replace(r#"tiff:Orientation="1""#, r#"tiff:Orientation="6""#).into_bytes() - } else { - data.to_vec() - }; - if kind != b"eXIf" { - png.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); - png.extend_from_slice(kind); - png.extend_from_slice(&data); - png.extend_from_slice(&crc(&[kind, data.as_slice()].concat()).to_be_bytes()); - } - at += 12 + len; - } - assert!(!png.windows(4).any(|w| w == b"eXIf")); + let png = png_orientation_only_in_xmp(); assert_eq!(lightcraft_meta::extract(&png).orientation, Some(Orientation::Rotate90), "the XMP states 6"); assert_eq!(lightcraft_codecs::read_header(&png).unwrap().orientation, 1, "the header (what it's shown by) doesn't"); std::fs::write(src.join("x.png"), png).unwrap(); @@ -2568,6 +2526,12 @@ fn an_unreadable_sidecar_fails_the_read_even_when_the_orientation_is_news() { let id = s.catalog.photos().next().unwrap().id; let mut meta = s.catalog.photo(id).unwrap().meta.clone(); meta.file_orientation = None; + meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_meta::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Ann".into()), + description: None, + }]; s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); std::fs::write(src.join("t.xmp"), [0xff, 0xfe, 0x00, 0x3c]).unwrap(); @@ -2584,3 +2548,154 @@ fn an_unreadable_sidecar_fails_the_read_even_when_the_orientation_is_news() { assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, Some(lightcraft_meta::Orientation::Rotate90)); let _ = std::fs::remove_dir_all(&src); } + +/// A 32 × 24 PNG whose orientation (6) only its XMP states: no Exif. +fn png_orientation_only_in_xmp() -> Vec { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + let xmp = r#""#; + let encoded = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&img), + &lightcraft_codecs::EncodeMeta { xmp: Some(xmp), ..Default::default() }, + ) + .unwrap(); + // the encoder sets the XMP's orientation to 1 (it applies none to the pixels): state 6 in the XMP chunk again, + // with no Exif, as another app could have written it + let crc = |bytes: &[u8]| { + let mut c = 0xffff_ffffu32; + for &b in bytes { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 }; + } + } + !c + }; + let mut png = encoded[..8].to_vec(); + let mut at = 8; + while at + 8 <= encoded.len() { + let len = u32::from_be_bytes(encoded[at..at + 4].try_into().unwrap()) as usize; + let (kind, data) = (&encoded[at + 4..at + 8], &encoded[at + 8..at + 8 + len]); + let data = if kind == b"iTXt" { + String::from_utf8_lossy(data).replace(r#"tiff:Orientation="1""#, r#"tiff:Orientation="6""#).into_bytes() + } else { + data.to_vec() + }; + if kind != b"eXIf" { + png.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + png.extend_from_slice(kind); + png.extend_from_slice(&data); + png.extend_from_slice(&crc(&[kind, data.as_slice()].concat()).to_be_bytes()); + } + at += 12 + len; + } + assert!(!png.windows(4).any(|w| w == b"eXIf")); + png +} + +/// Review of #4512: `files::upright_by` (what Read Metadata from File fills a missing orientation in with) gives what +/// the import probe keeps, for raws and images alike, without the rest of the probe. +#[test] +fn upright_by_is_the_import_probes_orientation() { + use lightcraft_meta::{Metadata, Orientation}; + let jpeg = |o: Option| { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [9, 9, 9, 255]); + let exif = o.map(|o| lightcraft_meta::write_exif(&Metadata { orientation: Some(o), ..Default::default() })); + let meta = lightcraft_codecs::EncodeMeta { exif: exif.as_deref(), ..Default::default() }; + lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap() + }; + let dng = |o| turned_dng(o, None); + let files: Vec<(&str, Vec, Option)> = vec![ + ("a.jpg", jpeg(None), Some(Orientation::Normal)), + ("b.jpg", jpeg(Some(Orientation::Rotate90)), Some(Orientation::Rotate90)), + ("c.jpg", jpeg(Some(Orientation::Transpose)), Some(Orientation::Transpose)), + ("d.png", png_orientation_only_in_xmp(), Some(Orientation::Normal)), + ("e.dng", dng(Orientation::Rotate90), Some(Orientation::Rotate90)), + ("f.dng", dng(Orientation::Rotate270), Some(Orientation::Rotate270)), + ("g.dng", dng(Orientation::Normal), Some(Orientation::Normal)), + ("h.txt", b"not a photo".to_vec(), None), + ]; + for (name, bytes, want) in files { + assert_eq!(crate::files::upright_by(&bytes), want, "{name}"); + if want.is_some() { + assert_eq!(crate::files::probe_bytes(name, &bytes).unwrap().upright_by, want, "{name}: the import's"); + } + } +} + +/// Review of #4512: Read Metadata from File reads a photo file for its orientation only when the photo has face +/// boxes to write: a rating-only refresh of an older photo leaves the original alone, and with no XMP at all it fails +/// as before. A face (in the catalog or the packet) makes it probe the file, and a raw read for its embedded XMP +/// gives the orientation from the same bytes. +#[test] +fn the_orientation_is_read_only_for_a_photo_with_faces() { + use lightcraft_meta::{Metadata, Orientation, Rect, Region, RegionKind}; + let src = temp_dir("orientation-only-with-faces"); + let plain = { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [9, 9, 9, 255]); + lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &Default::default()).unwrap() + }; + std::fs::write(src.join("a.jpg"), &plain).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let forget = |s: &mut Session, regions: Vec| { + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + meta.regions = regions; + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + }; + forget(&mut s, vec![]); + // the original now says something else: probing it would be seen + let turned = { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [9, 9, 9, 255]); + let exif = lightcraft_meta::write_exif(&Metadata { orientation: Some(Orientation::Rotate90), ..Default::default() }); + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; + lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap() + }; + std::fs::write(src.join("a.jpg"), &turned).unwrap(); + + // no faces, a rating-only sidecar: read, the original isn't probed + std::fs::write( + src.join("a.xmp"), + r#""#, + ) + .unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{read}"); + assert_eq!((s.catalog.photo(id).unwrap().rating, s.catalog.photo(id).unwrap().meta.file_orientation), (3, None)); + // no faces and no XMP at all: a failed read, as before the orientation was kept + std::fs::remove_file(src.join("a.xmp")).unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"].as_array().map(Vec::len), Some(1), "{read}"); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, None); + // a face in the catalog: probed + let face = Region { rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }; + forget(&mut s, vec![face.clone()]); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, Some(Orientation::Rotate90)); + let _ = std::fs::remove_dir_all(&src); + + // a raw with a face only in its embedded XMP and no sidecar: probed, from the bytes read for that XMP + let src = temp_dir("orientation-only-with-faces-raw"); + let xmp = r#"FaceBo"#; + std::fs::write(src.join("r.dng"), turned_dng(Orientation::Rotate270, Some(xmp))).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + meta.regions.clear(); + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{read}"); + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.meta.file_orientation, p.meta.regions.len()), (Some(Orientation::Rotate270), 1)); + let _ = std::fs::remove_dir_all(&src); +} + +/// A synthetic DNG stored turned by `o` (its own Orientation tag, what the raw decoder reads), with `xmp` embedded. +fn turned_dng(o: lightcraft_meta::Orientation, xmp: Option<&str>) -> Vec { + let mut raw = lightcraft_raw::decode(&synthetic_dng_with(None, Default::default())).unwrap(); + raw.orientation = o; + lightcraft_raw::write_dng(&raw, &lightcraft_raw::DngWriteOptions { xmp: xmp.map(str::to_string), ..Default::default() }).unwrap() +} diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 1eea9c1824d..c01f1d31b5f 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -133,7 +133,8 @@ write them, from sidecars and from XMP embedded in the file. Named faces become LightCraft reads them; MWG readers that apply the mirror place those mirrored. Orientation 1 is written upright. The file's orientation is the one the import read, kept in the catalog: a save never reads the photo file for it, and neither does reading a sidecar back (Read Metadata from File, Synchronize Folder) when the catalog knows it. A photo catalogued before LightCraft - kept it has its boxes written upright until Read Metadata from File reads it. Either way they read back as they + kept it has its boxes written upright until Read Metadata from File reads it: by the import's rule, only for a photo + with face boxes, from the file read at most once and within the media size limit. Either way they read back as they were. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar From 305f513240652704399f9762614d27c511996e47 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 17:55:49 -0600 Subject: [PATCH 14/25] LR-LIB-PEOPLE: a JPEG XMP read that fails is unreadable, not a missing packet read_jpeg_app1 returns io::Result>: Ok(None) when the scan finds nothing (not a JPEG, a short or malformed header, the span or steps used up), Err for an I/O error that stopped it. find_packet reports the error as Packet::Unreadable, so Read Metadata from File fails instead of reporting an orientation-only update as the photo read. read_packet and the orientation scan keep treating a failure as nothing found. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/engine/src/sidecar.rs | 111 ++++++++++++++++++++++++----------- 1 file changed, 77 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 3a6740acb0a..af51f417e94 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -569,7 +569,9 @@ fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option tiff_orientation(file, 0, len), @@ -1420,9 +1422,11 @@ fn find_packet(original: &str, kind: MediaKind, lookup: SidecarLookup, raw: Opti } if kind == MediaKind::Image { return match std::fs::File::open(original) { + // a scan that ends without a packet allows the orientation-only update; a read that fails doesn't Ok(mut file) => match read_jpeg_xmp(&mut file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS) { - Some(x) => Packet::Found(x, PathBuf::from(original)), - None => Packet::None, + Ok(Some(x)) => Packet::Found(x, PathBuf::from(original)), + Ok(None) => Packet::None, + Err(e) => Packet::Unreadable(PathBuf::from(original), e.to_string()), }, Err(e) => Packet::Unreadable(PathBuf::from(original), e.to_string()), }; @@ -1440,57 +1444,79 @@ const JPEG_XMP_HEADER_STEPS: usize = 4096; /// The span includes SOI, segment headers and skipped payloads; each marker/fill step after SOI /// consumes one iteration. Only a complete APP1 payload (at most 65533 bytes) reaches the shared /// parser, in a single SOI+APP1 wrapper (at most 65539 bytes). This does not validate the whole JPEG. -fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize) -> Option { +fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize) -> std::io::Result> { read_jpeg_app1(reader, header_span, marker_steps, |segment| lightcraft_meta::jpeg_segments(segment).xmp) } /// Like [`read_jpeg_xmp`], stopping at the first APP1 segment (in its SOI+APP1 wrapper) that `pick` finds something in. -fn read_jpeg_app1(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, mut pick: impl FnMut(&[u8]) -> Option) -> Option { +/// +/// `Ok(None)` when the scan finds nothing: not a JPEG, a malformed or short header, or the span or steps used up. `Err` +/// only for an I/O error that stopped the scan, so a caller can't take a failed read for a file with no packet. +fn read_jpeg_app1( + reader: &mut (impl Read + Seek), + header_span: u64, + marker_steps: usize, + mut pick: impl FnMut(&[u8]) -> Option, +) -> std::io::Result> { let mut header = reader.take(header_span); let mut soi = [0; 2]; - header.read_exact(&mut soi).ok()?; - if soi != [0xff, 0xd8] { - return None; + if !read_or_end(&mut header, &mut soi)? || soi != [0xff, 0xd8] { + return Ok(None); } let mut filled = false; for _ in 0..marker_steps { if !filled { let mut prefix = [0]; - header.read_exact(&mut prefix).ok()?; - if prefix != [0xff] { - return None; + if !read_or_end(&mut header, &mut prefix)? || prefix != [0xff] { + return Ok(None); } } let mut code = [0]; - header.read_exact(&mut code).ok()?; + if !read_or_end(&mut header, &mut code)? { + return Ok(None); + } let [marker] = code; filled = marker == 0xff; match marker { 0xff | 0xd8 | 0xd0..=0xd7 | 0x01 => continue, - 0xd9 | 0xda => return None, + 0xd9 | 0xda => return Ok(None), _ => {} } let mut length = [0; 2]; - header.read_exact(&mut length).ok()?; - let payload_len = u16::from_be_bytes(length).checked_sub(2)?; - let remaining = header.limit().checked_sub(u64::from(payload_len))?; + if !read_or_end(&mut header, &mut length)? { + return Ok(None); + } + let Some(payload_len) = u16::from_be_bytes(length).checked_sub(2) else { return Ok(None) }; + let Some(remaining) = header.limit().checked_sub(u64::from(payload_len)) else { return Ok(None) }; if marker != 0xe1 { // Seeking must spend the same span budget as reading, before the seek is attempted. header.set_limit(remaining); - header.get_mut().seek(SeekFrom::Current(i64::from(payload_len))).ok()?; + header.get_mut().seek(SeekFrom::Current(i64::from(payload_len)))?; continue; } - let segment_len = 6usize.checked_add(usize::from(payload_len))?; + let Some(segment_len) = 6usize.checked_add(usize::from(payload_len)) else { return Ok(None) }; let [hi, lo] = length; let mut segment = Vec::with_capacity(segment_len); segment.extend_from_slice(&[0xff, 0xd8, 0xff, 0xe1, hi, lo]); segment.resize(segment_len, 0); - header.read_exact(segment.get_mut(6..)?).ok()?; + let Some(payload) = segment.get_mut(6..) else { return Ok(None) }; + if !read_or_end(&mut header, payload)? { + return Ok(None); + } if let Some(found) = pick(&segment) { - return Some(found); + return Ok(Some(found)); } } - None + Ok(None) +} + +/// Fills `buf`: `Ok(false)` when the file or the span ends first (a short header, no packet), `Err` for any other error. +fn read_or_end(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result { + match reader.read_exact(buf) { + Ok(()) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(false), + Err(e) => Err(e), + } } /// Photo ids touched by an op (for auto-write). @@ -2977,6 +3003,23 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn an_image_that_fails_to_read_is_unreadable_not_a_missing_packet() { + // an image that opens but can't be read: unreadable, so no orientation-only update reports it read + let dir = std::env::temp_dir().join(format!("lc-jpeg-unreadable-{}", std::process::id())); + let fake = dir.join("a.jpg"); + std::fs::create_dir_all(&fake).unwrap(); + let lookup = SidecarLookup { naming: SidecarNaming::Stem, owns_stem: true }; + let got = find_packet(&fake.to_string_lossy(), MediaKind::Image, lookup, None); + assert!(matches!(got, Packet::Unreadable(..)), "a directory opened as a JPEG"); + // a clean scan without a packet stays a missing packet + let plain = dir.join("b.jpg"); + std::fs::write(&plain, [0xff, 0xd8, 0xff, 0xd9]).unwrap(); + let lookup = SidecarLookup { naming: SidecarNaming::Stem, owns_stem: true }; + assert!(matches!(find_packet(&plain.to_string_lossy(), MediaKind::Image, lookup, None), Packet::None)); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn the_orientation_backfill_reads_no_more_than_its_limit() { let dir = std::env::temp_dir().join(format!("lc-upright-limit-{}", std::process::id())); @@ -3163,7 +3206,7 @@ mod jpeg_header_tests { bytes.extend_from_slice(&[3; 128]); let mut reader = CountedReader::new(bytes); reader.read_error_at = Some(end as u64); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), Some(first)); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).unwrap(), Some(first)); assert_eq!(reader.cursor.position(), end as u64, "later packets and image bytes are not read"); assert_eq!(reader.bytes_read, end - 17, "APP0 payload is skipped, not buffered"); assert_eq!(reader.seeks, 1); @@ -3177,7 +3220,7 @@ mod jpeg_header_tests { bytes.extend(xmp_segment(&packet(3))); let mut reader = CountedReader::new(bytes); reader.read_error_at = Some(4); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert_eq!((reader.bytes_read, reader.cursor.position(), reader.seeks), (4, 4, 0)); } } @@ -3193,7 +3236,7 @@ mod jpeg_header_tests { assert_eq!(super::parse_sidecar(&partial, crate::crs::Target::Rendered).unwrap().rating, Some(4)); let len = bytes.len(); let mut reader = CountedReader::new(bytes); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert_eq!(reader.bytes_read, len); } @@ -3205,11 +3248,11 @@ mod jpeg_header_tests { bytes.extend(xmp_segment(&expected)); let end = bytes.len(); let mut exact = CountedReader::new(bytes.clone()); - assert_eq!(read_jpeg_xmp(&mut exact, end as u64, JPEG_XMP_HEADER_STEPS), Some(expected)); + assert_eq!(read_jpeg_xmp(&mut exact, end as u64, JPEG_XMP_HEADER_STEPS).unwrap(), Some(expected)); assert_eq!(exact.cursor.position(), end as u64, "a complete early APP1 does not require EOI"); assert_eq!(exact.bytes_read, end - 23); let mut short = CountedReader::new(bytes); - assert_eq!(read_jpeg_xmp(&mut short, (end - 1) as u64, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut short, (end - 1) as u64, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert_eq!((short.bytes_read, short.cursor.position(), short.seeks), (10, 33, 1), "reject before APP1 payload read"); assert_eq!(short.largest_read, 2); } @@ -3220,7 +3263,7 @@ mod jpeg_header_tests { bytes.extend(segment(0xe0, &[8; 18])); bytes.extend(xmp_segment(&packet(1))); let mut reader = CountedReader::new(bytes); - assert_eq!(read_jpeg_xmp(&mut reader, 6, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut reader, 6, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert_eq!((reader.bytes_read, reader.cursor.position(), reader.seeks), (6, 6, 0)); } @@ -3232,11 +3275,11 @@ mod jpeg_header_tests { bytes.extend(xmp_segment(&expected)); for (steps, end) in [(0, 2), (5, 10)] { let mut reader = CountedReader::new(bytes.clone()); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, steps), None); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, steps).unwrap(), None); assert_eq!((reader.bytes_read, reader.cursor.position()), (end, end as u64)); } let mut reader = CountedReader::new(bytes); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, 6), Some(expected)); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, 6).unwrap(), Some(expected)); } #[test] @@ -3253,7 +3296,7 @@ mod jpeg_header_tests { ] { let len = bytes.len(); let mut reader = CountedReader::new(bytes); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert!(reader.bytes_read <= len); } } @@ -3263,7 +3306,7 @@ mod jpeg_header_tests { for at in [0, 6] { let mut reader = CountedReader::new(jpeg(&packet(4))); reader.read_error_at = Some(at); - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), None); + assert!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).is_err(), "a read failure at {at}"); assert_eq!(reader.bytes_read as u64, at); } let mut bytes = vec![0xff, 0xd8]; @@ -3271,7 +3314,7 @@ mod jpeg_header_tests { bytes.extend(xmp_segment(&packet(4))); let mut reader = CountedReader::new(bytes); reader.seek_error = true; - assert_eq!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS), None); + assert!(read_jpeg_xmp(&mut reader, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS).is_err(), "a seek failure"); assert_eq!((reader.bytes_read, reader.seeks), (6, 1)); } @@ -3282,12 +3325,12 @@ mod jpeg_header_tests { let end = bytes.len(); let mut exact = CountedReader::new(bytes.clone()); exact.chunk = 1; - assert_eq!(read_jpeg_xmp(&mut exact, end as u64, JPEG_XMP_HEADER_STEPS), Some(expected)); + assert_eq!(read_jpeg_xmp(&mut exact, end as u64, JPEG_XMP_HEADER_STEPS).unwrap(), Some(expected)); assert_eq!(exact.bytes_read, end); for (span, read) in [(0, 0), (1, 1), (end - 1, 6)] { let mut reader = CountedReader::new(bytes.clone()); reader.chunk = 1; - assert_eq!(read_jpeg_xmp(&mut reader, span as u64, JPEG_XMP_HEADER_STEPS), None); + assert_eq!(read_jpeg_xmp(&mut reader, span as u64, JPEG_XMP_HEADER_STEPS).unwrap(), None); assert_eq!(reader.bytes_read, read); assert!(reader.cursor.position() <= span as u64); } From ce3ceeeadcd62fcacde94eebd1af7199df108317 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 18:43:17 -0600 Subject: [PATCH 15/25] LR-LIB-PEOPLE: read a preview-only raw's boxes by its stated orientation files::orientations gives what the catalog keeps (kept, = upright_by) and what the import reads face boxes by (read_by: kept, else, for a raw described from its embedded preview, the orientation its metadata states). Read Metadata from File reads the boxes by read_by, from the same bounded read, and stores only kept, so a preview-only raw's stored-frame sidecar boxes land where the import put them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/engine/src/files.rs | 2 +- crates/engine/src/files/probe.rs | 28 +++++++++++++++++++++---- crates/engine/src/sidecar.rs | 36 +++++++++++++++++--------------- crates/engine/src/tests/xmp.rs | 26 +++++++++++++++++++++++ 4 files changed, 70 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 210246579ba..49723e0a513 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -32,7 +32,7 @@ pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_v use preview::PLAN_PREFIX; pub(crate) use preview::decode_raw_preview; pub use preview::{PreviewRead, embedded_preview_srgb, fs_preview_loader, load_embedded_preview, preview_window}; -pub use probe::{embedded_lens, probe_bytes, upright_by}; +pub use probe::{Orientations, embedded_lens, orientations, probe_bytes, upright_by}; #[cfg(test)] use probe::{meta_of, preview_reason}; diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 1312dc86a94..ec03302ad8c 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -148,14 +148,34 @@ fn ext_upper(name: &str) -> String { /// from its decoder, an image's from its header's Exif (what [`probe_bytes`] turns them by). `None` where the import /// has none: a raw described from its embedded preview, or a file it can't read. No hashing, no metadata. pub fn upright_by(bytes: &[u8]) -> Option { + orientations(bytes).kept +} + +/// A file's orientations, from its bytes, by the import's rules. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Orientations { + /// What the catalog keeps as the file's orientation: [`upright_by`]. + pub kept: Option, + /// What the import reads the file's face boxes by: `kept`, else (a raw described from its embedded preview) the + /// orientation its metadata states ([`ProbeInfo::orientation`]). Not kept: it isn't what the size was turned by. + pub read_by: Option, +} + +/// [`Orientations`] of a file's bytes. Like [`upright_by`], no hashing; the metadata is read only for a raw the decoder +/// can't describe. +pub fn orientations(bytes: &[u8]) -> Orientations { if lightcraft_raw::probe(bytes).is_some() { - return lightcraft_raw::probe_info(bytes).ok().map(|raw| raw.orientation); + return match lightcraft_raw::probe_info(bytes) { + Ok(raw) => Orientations { kept: Some(raw.orientation), read_by: Some(raw.orientation) }, + Err(_) => Orientations { kept: None, read_by: lightcraft_meta::extract(bytes).orientation }, + }; } - let fmt = lightcraft_codecs::sniff(bytes)?; + let Some(fmt) = lightcraft_codecs::sniff(bytes) else { return Orientations::default() }; if fmt.not_decodable().is_some() { - return None; + return Orientations::default(); } - lightcraft_codecs::read_header(bytes).ok().map(|h| Orientation::from_exif(h.orientation)) + let kept = lightcraft_codecs::read_header(bytes).ok().map(|h| Orientation::from_exif(h.orientation)); + Orientations { kept, read_by: kept } } /// Probe a file's bytes: kind, dimensions (oriented), metadata. No pixel data is decompressed: diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index af51f417e94..6ba35cc68e9 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -489,12 +489,11 @@ impl SidecarData { } } -/// The orientation the photo file at `path` was (or would be) made upright by on import -/// ([`crate::media::ProbeInfo::upright_by`], by [`crate::files::upright_by`]'s rule): the file is read, up to `max` -/// bytes (none past that), and nothing but its orientation is worked out. For a photo catalogued before -/// [`lightcraft_catalog::Meta::file_orientation`] was kept, by Read Metadata from File only. -fn upright_orientation(path: &str, max: u64) -> Option { - crate::files::upright_by(&crate::read_file::read_regular(path, max).ok()?) +/// The orientations of the photo file at `path` by the import's rules ([`crate::files::orientations`]): the file is +/// read, up to `max` bytes (none past that, and then none are known), and nothing but its orientation is worked out. +/// For a photo whose [`lightcraft_catalog::Meta::file_orientation`] isn't known, by Read Metadata from File only. +fn upright_orientation(path: &str, max: u64) -> crate::files::Orientations { + crate::read_file::read_regular(path, max).map(|bytes| crate::files::orientations(&bytes)).unwrap_or_default() } /// The orientation the photo file at `path` states, matching what the import stores as @@ -1782,10 +1781,10 @@ impl Session { let raw_bytes = (unknown && p.kind == MediaKind::Raw && lookup.find(orig).is_none()) .then(|| crate::read_file::read_regular(orig, crate::read_file::MAX_MEDIA_BYTES).ok()) .flatten(); - let mut probed: Option> = None; - let backfill_now = |probed: &mut Option>| { + let mut probed: Option = None; + let backfill_now = |probed: &mut Option| { *probed.get_or_insert_with(|| match &raw_bytes { - Some(bytes) => crate::files::upright_by(bytes), + Some(bytes) => crate::files::orientations(bytes), None => upright_orientation(orig, crate::read_file::MAX_MEDIA_BYTES), }) }; @@ -1795,7 +1794,7 @@ impl Session { Packet::Unreadable(from, why) => return Err(EngineError::Other(format!("{} can't be read: {why}", from.display()))), // no packet at all: the orientation alone is news for a photo with boxes to write Packet::None => { - let backfill = if unknown && !file_regions(p).is_empty() { backfill_now(&mut probed) } else { None }; + let backfill = if unknown && !file_regions(p).is_empty() { backfill_now(&mut probed).kept } else { None }; return match backfill { Some(o) => Ok(Some(( self.sidecar_op(id, SidecarData { file_orientation: Some(o), ..SidecarData::default() })?, @@ -1808,17 +1807,19 @@ impl Session { }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; // the photo has boxes to write once this is read: its own, or the packet's - let backfill = if unknown && (!file_regions(p).is_empty() || sc.regions.as_ref().is_some_and(|r| !r.is_empty())) { + let probe = if unknown && (!file_regions(p).is_empty() || sc.regions.as_ref().is_some_and(|r| !r.is_empty())) { backfill_now(&mut probed) } else { - None + crate::files::Orientations::default() }; - // The catalog's orientation, else the bounded probe's. Not `file_orientation`: it reads a raw whole, with no limit. + // The boxes are read by the catalog's orientation, else the bounded probe's, as the import reads them: for a raw + // described from its preview, the orientation its metadata states. Not `file_orientation`: it reads a raw + // whole, with no limit. Only the import's kept orientation is stored. let sc = match sc.regions_drawn_on { - Some(_) => SidecarData { orientation: p.meta.file_orientation.or(backfill).or(sc.orientation), ..sc }, + Some(_) => SidecarData { orientation: p.meta.file_orientation.or(probe.read_by).or(sc.orientation), ..sc }, None => sc, }; - let sc = SidecarData { file_orientation: backfill, ..sc }; + let sc = SidecarData { file_orientation: probe.kept, ..sc }; let mut warnings = sc.warnings.clone(); for warning in &mut warnings { warning.path = orig.to_string(); @@ -3039,9 +3040,10 @@ mod tests { .unwrap(); std::fs::write(&file, &bytes).unwrap(); let path = file.to_string_lossy(); - assert_eq!(upright_orientation(&path, crate::read_file::MAX_MEDIA_BYTES), Some(lightcraft_meta::Orientation::Rotate90)); + let turned = Some(lightcraft_meta::Orientation::Rotate90); + assert_eq!(upright_orientation(&path, crate::read_file::MAX_MEDIA_BYTES), crate::files::Orientations { kept: turned, read_by: turned }); // a file past the limit isn't read (nor held in memory) at all - assert_eq!(upright_orientation(&path, bytes.len() as u64 - 1), None); + assert_eq!(upright_orientation(&path, bytes.len() as u64 - 1), crate::files::Orientations::default()); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 8185e408d24..65412c238dc 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2699,3 +2699,29 @@ fn turned_dng(o: lightcraft_meta::Orientation, xmp: Option<&str>) -> Vec { raw.orientation = o; lightcraft_raw::write_dng(&raw, &lightcraft_raw::DngWriteOptions { xmp: xmp.map(str::to_string), ..Default::default() }).unwrap() } + +/// Review of #4512: a raw described from its embedded preview keeps no orientation in the catalog, so Read Metadata +/// from File reads its face boxes the way the import does: by the orientation the raw's metadata states, not left as +/// drawn on the stored image. That orientation isn't stored. +#[test] +fn read_metadata_turns_a_preview_only_raws_boxes_as_the_import_does() { + let src = temp_dir("preview-only-read-by"); + let file = src.join("p.iiq"); + let empty = r#""#; + std::fs::write(&file, turned_preview_only_raw(empty)).unwrap(); + std::fs::write(src.join("p.xmp"), STORED_FRAME_REGIONS).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = only(&s); + let rects = |s: &Session| s.catalog.photo(id).unwrap().meta.regions.iter().map(|r| r.rect).collect::>(); + let imported = rects(&s); + let p = s.catalog.photo(id).unwrap(); + assert!(p.preview_only.is_some() && p.meta.file_orientation.is_none(), "{:?} {:?}", p.preview_only, p.meta.file_orientation); + let r = imported.first().copied().expect("the sidecar's box"); + let as_drawn = [0.2, 0.325, 0.3, 0.475]; + assert!([r.x0, r.y0, r.x1, r.y1].iter().zip(as_drawn).any(|(g, w)| (g - w).abs() > 1e-6), "the import turned it: {r:?}"); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(rects(&s), imported, "read back where the import put it"); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, None, "the metadata's orientation isn't kept"); + let _ = std::fs::remove_dir_all(&src); +} From 8c63fc5aa85c5ae2b091290c5625cd45243f496f Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 19:32:51 -0600 Subject: [PATCH 16/25] LR-LIB-PEOPLE: Synchronize Folder reads face boxes by the import's orientation with_orientation_known, for a photo whose orientation the catalog doesn't keep, now takes the bounded import-rule probe (upright_orientation's read_by) instead of file_orientation, which also read XMP. Synchronize Folder and Read Metadata from File now turn the same sidecar's boxes the same way, and the way the import does. file_orientation and the helpers only it used (head-span, late Exif, WebP, PNG, PSD, TIFF readers) are no longer called and are removed with their two tests. Sync reads a photo file only for a sidecar with news (newer than the catalog's view) whose boxes were drawn on a stated size, and only when the catalog has no orientation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/engine/src/sidecar.rs | 562 +-------------------------------- crates/engine/src/tests/xmp.rs | 23 ++ 2 files changed, 30 insertions(+), 555 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 6ba35cc68e9..3f4c760c54a 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -474,7 +474,7 @@ impl SidecarData { /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). - /// Only then is the file read ([`file_orientation`]). + /// Only then is the file read, by the import's rule ([`upright_orientation`]). pub fn with_file_orientation(self, original: &str) -> Self { self.with_orientation_known(None, original) } @@ -485,279 +485,20 @@ impl SidecarData { if self.regions_drawn_on.is_none() { return self; } - SidecarData { orientation: known.or_else(|| file_orientation(original)).or(self.orientation), ..self } + // the import's rule, as Read Metadata from File reads it: the same boxes land in the same place either way + let read_by = || upright_orientation(original, crate::read_file::MAX_MEDIA_BYTES).read_by; + SidecarData { orientation: known.or_else(read_by).or(self.orientation), ..self } } } /// The orientations of the photo file at `path` by the import's rules ([`crate::files::orientations`]): the file is /// read, up to `max` bytes (none past that, and then none are known), and nothing but its orientation is worked out. -/// For a photo whose [`lightcraft_catalog::Meta::file_orientation`] isn't known, by Read Metadata from File only. +/// For a photo whose [`lightcraft_catalog::Meta::file_orientation`] isn't known: by Read Metadata from File and +/// Synchronize Folder. fn upright_orientation(path: &str, max: u64) -> crate::files::Orientations { crate::read_file::read_regular(path, max).map(|bytes| crate::files::orientations(&bytes)).unwrap_or_default() } -/// The orientation the photo file at `path` states, matching what the import stores as -/// [`crate::media::ProbeInfo::orientation`]: -/// for a raw, the decoder's (`lightcraft_raw::probe_info`: CIFF for a CRW, the raw IFD for a MEF, …); otherwise Exif, -/// else XMP, as [`lightcraft_meta::extract`] reads it. A file shorter than [`ORIENTATION_SPAN`] is read whole. Most -/// non-raws state it in the Exif of their first [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later -/// ([`late_orientation`]). A WebP's or PNG's chunks are always walked, since the last Exif chunk is the one that counts -/// ([`webp_orientation`], [`png_orientation`]). -fn file_orientation(path: &str) -> Option { - let mut file = std::fs::File::open(path).ok()?; - let mut head = Vec::new(); - (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?; - // Import takes a raw's orientation from the decoder, not from Exif IFD0 / XMP alone. Re-read and sync must do the - // same, or face boxes turned at import are put back and Synchronize Folder reports changes every pass (#2857). - if lightcraft_raw::probe(&head).is_some() { - let bytes = if (head.len() as u64) < ORIENTATION_SPAN { - head - } else { - file.rewind().ok()?; - let mut all = Vec::new(); - file.read_to_end(&mut all).ok()?; - all - }; - return match lightcraft_raw::probe_info(&bytes) { - Ok(raw) => Some(raw.orientation), - // unsupported / preview-only: same fallback the import uses (`ProbeInfo::orientation` from meta) - Err(_) => lightcraft_meta::extract(&bytes).orientation, - }; - } - if (head.len() as u64) < ORIENTATION_SPAN { - return lightcraft_meta::extract(&head).orientation; - } - if head.get(..4) == Some(b"RIFF") && head.get(8..12) == Some(b"WEBP") { - return webp_orientation(&mut file); - } - if head.starts_with(b"\x89PNG\r\n\x1a\n") { - return png_orientation(&mut file); - } - if let Some(o) = exif_orientation(&head) { - return Some(o); - } - late_orientation(&mut file, &head).or_else(|| lightcraft_meta::extract(&head).orientation) -} - -/// The orientation the Exif in `bytes` (a file, or the start of one) states, leaving out a separate XMP packet (the -/// one the Exif holds in tag 700 counts, as in [`lightcraft_meta::read_exif`]). -fn exif_orientation(bytes: &[u8]) -> Option { - lightcraft_meta::embedded(bytes).exif.as_deref().map(lightcraft_meta::read_exif).and_then(|m| m.orientation) -} - -/// The orientation of a JPEG, TIFF or PSD whose `head` has no Exif stating it, found by the file's structure without -/// reading its image data (a JPEG's Exif can follow other long segments, many TIFF writers put the first IFD after the -/// strips, and a PSD's image resources can outgrow `head`). As the import does, a JPEG takes its first Exif segment, -/// else its first XMP segment. -fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { - let len = file.seek(SeekFrom::End(0)).ok()?; - file.rewind().ok()?; - match head.get(..4)? { - [0xff, 0xd8, ..] => { - let (mut exif_seen, mut xmp) = (false, None); - let exif = read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |segment| { - let embedded = lightcraft_meta::embedded(segment); - if let Some(exif) = embedded.exif - && !exif_seen - { - // the first Exif segment ends the walk if it states one; later ones don't count - exif_seen = true; - return lightcraft_meta::read_exif(&exif).orientation; - } - if xmp.is_none() { - xmp = embedded.xmp.map(|x| lightcraft_meta::parse_xmp(&x).ok().and_then(|x| x.metadata.orientation)); - } - None - }) - .ok() - .flatten(); - exif.or(xmp.flatten()) - } - b"II*\0" | b"MM\0*" => tiff_orientation(file, 0, len), - b"8BPS" => psd_orientation(file), - _ => None, - } -} - -/// A WebP's orientation as the import takes it: from its last `EXIF` chunk, else its last `XMP ` chunk, in whichever -/// order they come. The chunk headers are walked from the start of `file` (at most [`WEBP_CHUNK_STEPS`], ending at a -/// chunk that runs past the end of the file); then only the first IFD of the EXIF chunk is read, whatever its size -/// ([`tiff_orientation`]), and the XMP chunk if it is at most [`ORIENTATION_SPAN`]. -fn webp_orientation(file: &mut (impl Read + Seek)) -> Option { - let len = file.seek(SeekFrom::End(0)).ok()?; - let (mut exif, mut xmp) = (None, None); - let mut at = 12u64; - for _ in 0..WEBP_CHUNK_STEPS { - let mut header = [0; 8]; - if file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { - break; - } - let [a, b, c, d, s0, s1, s2, s3] = header; - let size = u64::from(u32::from_le_bytes([s0, s1, s2, s3])); - let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; - match &[a, b, c, d] { - b"EXIF" => exif = Some((at + 8, end)), - b"XMP " => xmp = Some((at + 8, size)), - _ => {} - } - // chunks are padded to an even size - at = end + (size & 1); - } - if let Some(o) = exif.and_then(|(start, end)| exif_chunk_orientation(file, start, end)) { - return Some(o); - } - let (start, size) = xmp?; - xmp_orientation(file, start, size) -} - -/// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame). -const WEBP_CHUNK_STEPS: usize = 4096; - -/// The orientation the Exif chunk from `start` to `end` in `file` states: its TIFF stream comes after an `Exif\0\0` if -/// the chunk starts with one (as `strip_exif_header` takes it). -fn exif_chunk_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Option { - let mut prefix = [0; 5]; - file.seek(SeekFrom::Start(start)).ok()?; - let prefixed = start + 6 <= end && file.read_exact(&mut prefix).is_ok() && &prefix == b"Exif\0"; - tiff_orientation(file, if prefixed { start + 6 } else { start }, end) -} - -/// A PNG's orientation as the import takes it: from its last `eXIf` chunk, else its last uncompressed XMP `iTXt` chunk, -/// wherever they come (a writer may put them after the image data). The chunk headers are walked from the start of -/// `file` to `IEND` (at most [`png_chunk_steps`], ending at a chunk that runs past the end of the file); then only the -/// first IFD of the `eXIf` chunk is read, whatever its size ([`tiff_orientation`]), and the `iTXt` chunk if it is at -/// most [`ORIENTATION_SPAN`]. -fn png_orientation(file: &mut (impl Read + Seek)) -> Option { - let len = file.seek(SeekFrom::End(0)).ok()?; - let (mut exif, mut xmp) = (None, None); - let mut at = 8u64; - for _ in 0..png_chunk_steps(len) { - let (mut header, mut key) = ([0; 8], [0; 19]); - if at + 12 > len || file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { - break; - } - let [s0, s1, s2, s3, a, b, c, d] = header; - let size = u64::from(u32::from_be_bytes([s0, s1, s2, s3])); - let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; - match &[a, b, c, d] { - b"eXIf" => exif = Some((at + 8, end)), - // the keyword, then compression flag 0 - b"iTXt" if size >= 20 && file.read_exact(&mut key).is_ok() && &key == b"XML:com.adobe.xmp\0\0" => xmp = Some((at + 8, size)), - b"IEND" => break, - _ => {} - } - // past the chunk's CRC - at = end + 4; - } - if let Some(o) = exif.and_then(|(start, end)| exif_chunk_orientation(file, start, end)) { - return Some(o); - } - let (start, size) = xmp?; - let chunk = read_within_span(file, start, size)?; - // keyword\0 compression-flag compression-method language\0 translated\0 text - let text = chunk.get(20..)?.splitn(3, |&c| c == 0).nth(2)?; - lightcraft_meta::parse_xmp(&String::from_utf8_lossy(text)).ok()?.metadata.orientation -} - -/// How many chunks [`png_orientation`] passes over in a file of `len` bytes: 4096 and one per KiB of the file, at most -/// 2^20. Image data is often split into many `IDAT` chunks (libpng writes 8 KiB ones by default), so the limit grows -/// with the file; each chunk costs two system calls, so a short file of empty chunks can't hold a worker for seconds. -fn png_chunk_steps(len: u64) -> u64 { - (4096 + len / 1024).min(1 << 20) -} - -/// A PSD's or PSB's orientation as the import takes it, from its image resources: the file's start up to their end is -/// read if it is at most [`PSD_RESOURCES_SPAN`]. They come before the layers and the image data, after the 26-byte -/// header and the colour-mode data; each of those two sections starts with its length. -fn psd_orientation(file: &mut (impl Read + Seek)) -> Option { - let mut length = [0; 4]; - file.seek(SeekFrom::Start(26)).ok()?; - file.read_exact(&mut length).ok()?; - let resources = 30 + u64::from(u32::from_be_bytes(length)); - file.seek(SeekFrom::Start(resources)).ok()?; - file.read_exact(&mut length).ok()?; - let end = resources + 4 + u64::from(u32::from_be_bytes(length)); - if end > PSD_RESOURCES_SPAN { - return None; - } - file.rewind().ok()?; - let mut bytes = Vec::new(); - (&mut *file).take(end).read_to_end(&mut bytes).ok()?; - lightcraft_meta::extract(&bytes).orientation -} - -/// How far into a PSD or PSB [`psd_orientation`] reads. -const PSD_RESOURCES_SPAN: u64 = 16 * 1024 * 1024; - -/// The orientation the TIFF stream from `start` to `end` in `file` states in its first IFD (a TIFF file, or the Exif -/// block of a WebP's EXIF chunk; its offsets count from `start`, and nothing past `end` is read). Only the IFD's 12-byte -/// entries are read (at most 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] -/// does) the XMP packet its tag 700 holds, read if it is at most [`ORIENTATION_SPAN`]. -fn tiff_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Option { - // where the `len` bytes at `offset` in the stream are in the file, when all of them are in the stream - let within = |offset: u32, len: u64| { - let at = start.checked_add(u64::from(offset))?; - (at.checked_add(len)? <= end).then_some(at) - }; - file.seek(SeekFrom::Start(within(0, 8)?)).ok()?; - let mut header = [0; 8]; - file.read_exact(&mut header).ok()?; - let [b0, b1, b2, b3, i0, i1, i2, i3] = header; - let le = match &[b0, b1, b2, b3] { - b"II*\0" => true, - b"MM\0*" => false, - _ => return None, - }; - let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; - let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; - let ifd = u32_of([i0, i1, i2, i3]); - file.seek(SeekFrom::Start(within(ifd, 2)?)).ok()?; - let mut count = [0; 2]; - file.read_exact(&mut count).ok()?; - let count = u16_of(count); - within(ifd, 2 + 12 * u64::from(count))?; - let mut entries = vec![0; usize::from(count) * 12]; - file.read_exact(&mut entries).ok()?; - let mut xmp = None; - for &[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] in entries.as_chunks::<12>().0 { - let (tag, kind, count) = (u16_of([t0, t1]), u16_of([y0, y1]), u32_of([c0, c1, c2, c3])); - match (tag, kind) { - // exactly one SHORT (with more, the field also holds a second value, or an offset to them all) - (274, 3) if count == 1 => { - let v = u16_of([v0, v1]); - if (1..=8).contains(&v) { - return Some(lightcraft_meta::Orientation::from_exif(v)); - } - } - // BYTE or UNDEFINED, at an offset (a packet longer than the field's four bytes) - (700, 1 | 7) if count > 4 => xmp = Some((u32_of([v0, v1, v2, v3]), u64::from(count))), - _ => {} - } - } - let (offset, len) = xmp?; - xmp_orientation(file, within(offset, len)?, len) -} - -/// The orientation the XMP packet of `len` bytes at `at` in `file` states, read if it is at most [`ORIENTATION_SPAN`]. -fn xmp_orientation(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option { - let packet = read_within_span(file, at, len)?; - lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation -} - -/// The `len` bytes at `at` in `file`, read if they are at most [`ORIENTATION_SPAN`]. -fn read_within_span(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option> { - if len > ORIENTATION_SPAN { - return None; - } - file.seek(SeekFrom::Start(at)).ok()?; - let mut bytes = Vec::new(); - (&mut *file).take(len).read_to_end(&mut bytes).ok()?; - Some(bytes) -} - -/// How much of a photo file [`file_orientation`] reads first. -const ORIENTATION_SPAN: u64 = 1 << 20; - /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom /// label names included, as other editors do). pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { @@ -1931,295 +1672,6 @@ impl Session { #[cfg(test)] mod tests { - /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, a TIFF's first IFD can follow its strips - /// and a JPEG's Exif other long segments, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of - /// the file. Every file gives what the import gives reading it whole: Exif over XMP wherever each is, a WebP's last - /// EXIF chunk and a JPEG's first Exif segment, and none for a file that states none. - #[test] - fn the_file_orientation_is_found_after_the_image_data() { - let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { - orientation: Some(lightcraft_meta::Orientation::Rotate90), - ..Default::default() - }); - let span = super::ORIENTATION_SPAN as usize; - let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); - // a WebP: VP8X, then `chunks` - let webp = |chunks: &[(&[u8], Vec)]| { - let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); - for (id, data) in [(&b"VP8X"[..], vec![0; 10])].iter().chain(chunks) { - w.extend_from_slice(id); - w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(data); - if data.len() % 2 == 1 { - w.push(0); - } - } - let size = u32::try_from(w.len() - 8).unwrap(); - w[4..8].copy_from_slice(&size.to_le_bytes()); - w - }; - let image = |len: usize| (&b"VP8L"[..], vec![0; len]); - let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); - // an EXIF chunk over the span (orientation 6 too), one stating no orientation, and an XMP packet stating 8 - let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); - let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); - let plain_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &plain].concat()); - let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); - let xmp_chunk = (&b"XMP "[..], packet.clone().into_bytes()); - // the XMP packet padded with whitespace to `len` bytes - let padded_xmp = |len: usize| { - let mut p = packet.clone().into_bytes(); - p.resize(len, b' '); - (&b"XMP "[..], p) - }; - // an EXIF chunk holding only a TIFF header, whose IFD offset (16) points past the chunk's end into the next - // chunk's data, where an IFD stating orientation 6 sits - let stray_exif = (&b"EXIF"[..], b"II*\0\x10\0\0\0".to_vec()); - let stray_ifd = (&b"JUNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); - // a TIFF whose first IFD follows more than the first MiB of image data: an orientation tag of `values` values - // whose field starts with `value` (with more than two, it is an offset), a tag pointing elsewhere, and an XMP - // packet (tag 700) stored after the IFD - let tiff = |le: bool, orientation: Option<(u32, u16)>, xmp: Option<&str>| { - let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) = - if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) }; - let strips = span + 64; - let mut entries = Vec::new(); - if let Some((values, value)) = orientation { - entries.push((274u16, 3u16, values, [u16_of(value), [0, 0]].concat())); - } - entries.push((305, 2, 64, u32_of(4).to_vec())); - let packet_at = 8 + strips + 2 + 12 * (entries.len() + usize::from(xmp.is_some())) + 4; - if let Some(x) = xmp { - entries.push((700, 7, x.len() as u32, u32_of(packet_at as u32).to_vec())); - } - let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; - t.extend_from_slice(&u32_of(8 + strips as u32)); - t.resize(8 + strips, 0); - t.extend_from_slice(&u16_of(entries.len() as u16)); - for (tag, kind, count, value) in entries { - t.extend_from_slice(&u16_of(tag)); - t.extend_from_slice(&u16_of(kind)); - t.extend_from_slice(&u32_of(count)); - t.extend_from_slice(&value); - } - t.extend_from_slice(&[0; 4]); - t.extend_from_slice(xmp.unwrap_or_default().as_bytes()); - t - }; - // a JPEG: the APP1 payloads `early`, more than the first MiB of other segments, `late`, the image data - let jpeg = |early: &[Vec], late: &[Vec]| { - let app1 = |j: &mut Vec, payload: &Vec| { - j.extend_from_slice(&[0xff, 0xe1]); - j.extend_from_slice(&(payload.len() as u16 + 2).to_be_bytes()); - j.extend_from_slice(payload); - }; - let mut j = vec![0xff, 0xd8]; - early.iter().for_each(|p| app1(&mut j, p)); - for _ in 0..17 { - j.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]); - j.resize(j.len() + 0xfffd, 0); - } - late.iter().for_each(|p| app1(&mut j, p)); - j.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); - j - }; - let exif_app1 = [&b"Exif\0\0"[..], &exif].concat(); - let plain_app1 = [&b"Exif\0\0"[..], &plain].concat(); - let xmp_app1 = [&b"http://ns.adobe.com/xap/1.0/\0"[..], packet.as_bytes()].concat(); - for (name, bytes, want) in [ - ("small.webp", webp(&[image(64), exif_chunk.clone()]), o6), - ("large.webp", webp(&[image(span + 64), exif_chunk.clone(), xmp_chunk.clone()]), o6), - // EXIF wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search - ("reversed.webp", webp(&[image(span + 64), xmp_chunk.clone(), exif_chunk.clone()]), o6), - ("xmp-first.webp", webp(&[xmp_chunk.clone(), image(span + 64), exif_chunk.clone()]), o6), - ("none.webp", webp(&[image(span + 64), exif_chunk.clone()])[..span + 100].to_vec(), None), - ("xmp.webp", webp(&[image(span + 64), xmp_chunk.clone()]), o8), - // an EXIF chunk of any size is read by its IFD: one over the span, one (without `Exif\0\0`, big-endian) - // whose IFD is more than the span into it - ("huge.webp", webp(&[image(span + 64), huge_exif, xmp_chunk.clone()]), o6), - ("late-ifd.webp", webp(&[image(span + 64), (&b"EXIF"[..], tiff(false, Some((1, 6)), None)), xmp_chunk.clone()]), o6), - // nothing outside the EXIF chunk is read for its IFD - ("outside.webp", webp(&[image(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), - // the last EXIF chunk counts, here a late one stating no orientation after one in the first MiB - ("last-exif.webp", webp(&[exif_chunk, image(span + 64), plain_chunk, xmp_chunk]), o8), - // an XMP chunk of the span is read - ("span-xmp.webp", webp(&[image(64), padded_xmp(span)]), o8), - ("le.tif", tiff(true, Some((1, 8)), None), o8), - ("be.tif", tiff(false, Some((1, 8)), None), o8), - ("offset.tif", tiff(true, Some((3, 8)), None), None), - // the tag wins over the IFD's XMP; XMP fills in for no tag or an invalid one - ("both.tif", tiff(true, Some((1, 6)), Some(&packet)), o6), - ("xmp.tif", tiff(false, None, Some(&packet)), o8), - ("invalid.tif", tiff(true, Some((1, 0)), Some(&packet)), o8), - ("none.jpg", jpeg(&[], &[]), None), - ("xmp-first.jpg", jpeg(std::slice::from_ref(&xmp_app1), std::slice::from_ref(&exif_app1)), o6), - ("xmp-only.jpg", jpeg(&[], std::slice::from_ref(&xmp_app1)), o8), - // the first Exif segment counts, though it states no orientation - ("two-exif.jpg", jpeg(&[plain_app1], &[exif_app1, xmp_app1]), o8), - ] { - assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); - let path = dir.join(name); - std::fs::write(&path, bytes).unwrap(); - assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); - } - // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation - let over = webp(&[image(64), padded_xmp(span + 1)]); - assert_eq!(lightcraft_meta::extract(&over).orientation, o8); - std::fs::write(dir.join("over-xmp.webp"), over).unwrap(); - assert_eq!(super::file_orientation(&dir.join("over-xmp.webp").to_string_lossy()), None); - assert_eq!(super::file_orientation(&dir.join("missing.webp").to_string_lossy()), None); - std::fs::remove_dir_all(dir).unwrap(); - } - - /// Issue #2674: the same for a PNG, whose `eXIf` and XMP `iTXt` chunks can follow the image data, and a PSD, whose - /// image resources can outgrow the first [`super::ORIENTATION_SPAN`]. - #[test] - fn a_png_or_psd_gives_the_orientation_the_import_gives() { - let dir = std::env::temp_dir().join(format!("lightcraft-png-psd-orientation-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let span = super::ORIENTATION_SPAN as usize; - let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); - let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: o6, ..Default::default() }); - let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); - let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); - // a PNG: its IHDR, then `chunks`, each with a CRC (nothing checks it) - let png = |chunks: &[(&[u8], Vec)]| { - let mut p = b"\x89PNG\r\n\x1a\n".to_vec(); - for (id, data) in [(&b"IHDR"[..], vec![0; 13])].iter().chain(chunks) { - p.extend_from_slice(&(data.len() as u32).to_be_bytes()); - p.extend_from_slice(id); - p.extend_from_slice(data); - p.extend_from_slice(&[0; 4]); - } - p - }; - let idat = |len: usize| (&b"IDAT"[..], vec![0; len]); - let iend = (&b"IEND"[..], Vec::new()); - let exif_chunk = (&b"eXIf"[..], exif.clone()); - let plain_chunk = (&b"eXIf"[..], plain.clone()); - // an `iTXt` chunk: the keyword, compression flag `flag`, method, no language, no translated keyword, the text - let itxt = |keyword: &[u8], flag: u8, text: &[u8]| (&b"iTXt"[..], [keyword, &[0, flag, 0, 0, 0], text].concat()); - let xmp_key = &b"XML:com.adobe.xmp"[..]; - let xmp_chunk = itxt(xmp_key, 0, packet.as_bytes()); - // the XMP packet padded with whitespace, in a chunk of `len` bytes - let padded_xmp = |len: usize| { - let mut p = packet.clone().into_bytes(); - p.resize(len - 22, b' '); - itxt(xmp_key, 0, &p) - }; - // a big-endian TIFF stream whose IFD, stating orientation 6, is more than the span into it - let ifd = [0u8, 1, 1, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0]; - let late_ifd = [&b"MM\0*"[..], &(8 + span as u32).to_be_bytes(), &vec![0; span], &ifd].concat(); - // an `eXIf` holding only a TIFF header, whose IFD offset (20) points past the chunk's end into the next chunk's - // data, where an IFD stating orientation 6 sits - let stray_exif = (&b"eXIf"[..], b"II*\0\x14\0\0\0".to_vec()); - let stray_ifd = (&b"juNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); - // a PSD: its header, `colour` bytes of colour-mode data, the image resources (id, data), `pixels` other bytes - let psd = |colour: usize, resources: &[(u16, &[u8])], pixels: usize| { - let mut section = Vec::new(); - for (id, data) in resources { - section.extend_from_slice(b"8BIM"); - section.extend_from_slice(&id.to_be_bytes()); - section.extend_from_slice(&[0, 0]); - section.extend_from_slice(&(data.len() as u32).to_be_bytes()); - section.extend_from_slice(data); - if data.len() % 2 == 1 { - section.push(0); - } - } - // a valid header: one RGB pixel, 8 bits - let mut p = b"8BPS\0\x01".to_vec(); - p.resize(12, 0); - p.extend_from_slice(&[0, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 8, 0, 3]); - p.extend_from_slice(&(colour as u32).to_be_bytes()); - p.resize(p.len() + colour, 0); - p.extend_from_slice(&(section.len() as u32).to_be_bytes()); - p.extend_from_slice(§ion); - p.resize(p.len() + pixels, 0); - p - }; - let long = vec![0; span + 64]; - let (exif_res, plain_res, xmp_res, long_res) = ((1058, &exif[..]), (1058, &plain[..]), (1060, packet.as_bytes()), (1039, &long[..])); - let late_png = png(&[idat(span + 64), exif_chunk.clone()]); - let late_psd = psd(0, &[long_res, exif_res], 0); - for (name, bytes, want) in [ - ("early.png", png(&[exif_chunk.clone(), idat(span + 64), iend.clone()]), o6), - ("late.png", png(&[idat(span + 64), exif_chunk.clone(), xmp_chunk.clone(), iend.clone()]), o6), - // the `eXIf` wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search - ("reversed.png", png(&[idat(span + 64), xmp_chunk.clone(), exif_chunk.clone(), iend.clone()]), o6), - ("xmp-first.png", png(&[xmp_chunk.clone(), idat(span + 64), exif_chunk.clone(), iend.clone()]), o6), - ("xmp.png", png(&[idat(span + 64), xmp_chunk.clone(), iend.clone()]), o8), - ("none.png", png(&[idat(span + 64), iend.clone()]), None), - // the `eXIf` is cut short, or comes after the end of the image - ("cut.png", late_png[..late_png.len() - 6].to_vec(), None), - ("after-iend.png", png(&[idat(span + 64), iend.clone(), exif_chunk.clone()]), None), - // an `eXIf` of any size is read by its IFD: with `Exif\0\0`, over the span, and with its IFD past the span - ("prefixed.png", png(&[idat(span + 64), (&b"eXIf"[..], [&b"Exif\0\0"[..], &exif].concat())]), o6), - ("huge.png", png(&[idat(64), (&b"eXIf"[..], [&exif[..], &vec![0; span]].concat()), xmp_chunk.clone()]), o6), - ("late-ifd.png", png(&[idat(span + 64), (&b"eXIf"[..], late_ifd), xmp_chunk.clone()]), o6), - // nothing outside the `eXIf` is read for its IFD - ("outside.png", png(&[idat(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), - // the last `eXIf` counts, here a late one stating no orientation after one in the first MiB - ("last-exif.png", png(&[exif_chunk.clone(), idat(span + 64), plain_chunk, xmp_chunk.clone()]), o8), - // a compressed packet or another keyword isn't the XMP; a chunk of the span is read - ("compressed.png", png(&[idat(span + 64), xmp_chunk.clone(), itxt(xmp_key, 1, packet.as_bytes())]), o8), - ("only-compressed.png", png(&[idat(span + 64), itxt(xmp_key, 1, packet.as_bytes())]), None), - ("other-text.png", png(&[idat(span + 64), itxt(b"Comment", 0, packet.as_bytes())]), None), - ("short-text.png", png(&[idat(span + 64), xmp_chunk.clone(), (&b"iTXt"[..], b"XML:com.adobe.xmp\0\0".to_vec())]), o8), - ("span-xmp.png", png(&[idat(64), padded_xmp(span)]), o8), - ("late.psd", late_psd.clone(), o6), - ("early.psd", psd(0, &[exif_res], span + 64), o6), - // Exif wins in whichever order the resources come; XMP fills in for none, or none stating an orientation - ("both.psd", psd(0, &[xmp_res, long_res, exif_res], 0), o6), - ("xmp.psd", psd(768, &[long_res, xmp_res], 0), o8), - ("plain.psd", psd(0, &[long_res, plain_res, xmp_res], 0), o8), - ("none.psd", psd(0, &[long_res], span), None), - // as at import, nothing is taken from resources that are cut short or state their Exif twice - ("cut.psd", late_psd[..late_psd.len() - 1].to_vec(), None), - ("two-exif.psd", psd(0, &[long_res, exif_res, exif_res], 0), None), - ] { - assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); - let path = dir.join(name); - std::fs::write(&path, bytes).unwrap(); - assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); - } - // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation - let over = png(&[idat(64), padded_xmp(span + 1)]); - assert_eq!(lightcraft_meta::extract(&over).orientation, o8); - std::fs::write(dir.join("over-xmp.png"), over).unwrap(); - assert_eq!(super::file_orientation(&dir.join("over-xmp.png").to_string_lossy()), None); - std::fs::remove_dir_all(dir).unwrap(); - - // the `eXIf` as the last chunk walked, and as the first one not: IHDR, `chunks` of empty `IDAT`, the `eXIf` - let steps = super::png_chunk_steps; - let split = |chunks: usize| png(&[vec![idat(0); chunks], vec![exif_chunk.clone()]].concat()); - let len = |chunks: usize| (8 + 25 + 12 * chunks + 12 + exif.len()) as u64; - let walked = (0..).find(|&n| n as u64 + 2 == steps(len(n)) && n as u64 + 3 > steps(len(n + 1))).unwrap(); - let (last, past) = (split(walked), split(walked + 1)); - assert_eq!(last.len() as u64, len(walked)); - assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&last)), o6); - assert_eq!(lightcraft_meta::extract(&past).orientation, o6); - assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&past)), None); - // image data split into chunks of a KiB is walked whatever its length, up to the limit - let kib_chunks = png(&[vec![idat(1012); 6000], vec![exif_chunk.clone()]].concat()); - assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&kib_chunks)), o6); - assert_eq!(steps(u64::MAX), 1 << 20); - - // image resources that end exactly at the limit, and a byte past it - let limit = super::PSD_RESOURCES_SPAN as usize; - let padding = vec![0; limit - 58 - exif.len().next_multiple_of(2)]; - let within = psd(0, &[(1039, &padding[..]), exif_res], 0); - assert_eq!(within.len(), limit); - assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&within)), o6); - let past = psd(1, &[(1039, &padding[..]), exif_res], 0); - assert_eq!(lightcraft_meta::extract(&past).orientation, o6); - assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&past)), None); - } - #[test] fn sidecars_are_written_only_beside_an_existing_original() { let dir = std::env::temp_dir().join(format!("lightcraft-sidecar-local-{}", std::process::id())); @@ -2997,7 +2449,7 @@ mod tests { ) .unwrap(); std::fs::write(&file, bytes).unwrap(); - assert_eq!(file_orientation(&file.to_string_lossy()), Some(lightcraft_meta::Orientation::Rotate90)); + assert_eq!(upright_orientation(&file.to_string_lossy(), u64::MAX).kept, Some(lightcraft_meta::Orientation::Rotate90)); p.source = Source::File { path: file.to_string_lossy().into() }; p.meta.file_orientation = None; assert!(!sidecar_packet(&p, &lightcraft_catalog::Catalog::new()).contains("mwg-rs:Rotation")); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 65412c238dc..ea9884ec4ff 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2725,3 +2725,26 @@ fn read_metadata_turns_a_preview_only_raws_boxes_as_the_import_does() { assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, None, "the metadata's orientation isn't kept"); let _ = std::fs::remove_dir_all(&src); } + +/// Review of #4512: Synchronize Folder, for a photo whose orientation the catalog doesn't keep, reads its sidecar's +/// boxes by the import's rule, as Read Metadata from File does: a PNG whose only orientation is in its XMP is shown, +/// and its boxes read, as stored (no Exif to turn it), not by the XMP's 6. +#[test] +fn synchronize_reads_boxes_by_the_imports_orientation_as_read_metadata_does() { + use lightcraft_meta::Orientation; + let src = temp_dir("sync-read-by"); + let png = src.join("x.png"); + let bytes = png_orientation_only_in_xmp(); + std::fs::write(&png, &bytes).unwrap(); + assert_eq!(lightcraft_meta::extract(&bytes).orientation, Some(Orientation::Rotate90), "the XMP says 6"); + let want = crate::files::orientations(&bytes).read_by; + assert_eq!(want, Some(Orientation::Normal), "the import's rule: the header's"); + let sc = crate::sidecar::parse_sidecar(STORED_FRAME_REGIONS, crate::crs::Target::Rendered).unwrap(); + assert!(sc.regions_drawn_on.is_some(), "the boxes were drawn on a stated size"); + // the fallback Synchronize Folder takes when the catalog has no orientation (`sync::read_sidecar`, `sidecar_has_news`) + let path = png.to_string_lossy(); + assert_eq!(sc.clone().with_orientation_known(None, &path).orientation, want); + // and the catalog's own wins without the file being read + assert_eq!(sc.with_orientation_known(Some(Orientation::Rotate180), "/no/such/file").orientation, Some(Orientation::Rotate180)); + let _ = std::fs::remove_dir_all(&src); +} From 528c700d672f320570408622cf585378643e795e Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 22:27:27 -0600 Subject: [PATCH 17/25] LR-LIB-PEOPLE: read a non-raw's orientation from its header, not the whole file lightcraft_codecs::orientation::header_orientation finds the orientation read_header gives a JPEG, PNG, WebP, TIFF or PSD by seeking to the bytes that hold it (the first Exif APP1 before the first scan, the first eXIf or EXIF chunk, IFD0's tag 274, the last Exif image resource), parsed as the header readers parse them, and says Ok(None) where it can't follow them (BigTIFF, an unusual tag type, a block over 64 MiB). files::orientations_of_file reads the first MiB: a file that fits, and a raw, keep the bounded whole-file probe; any other image uses the header probe, and falls back to the whole file only where it can't tell. Read Metadata from File and Synchronize Folder both use it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/codecs/src/lib.rs | 1 + crates/codecs/src/orientation.rs | 488 +++++++++++++++++++++++++++++++ crates/engine/src/files.rs | 2 +- crates/engine/src/files/probe.rs | 48 +++ crates/engine/src/sidecar.rs | 7 +- crates/engine/src/tests/xmp.rs | 55 ++++ 6 files changed, 597 insertions(+), 4 deletions(-) create mode 100644 crates/codecs/src/orientation.rs diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index c2846db258a..f789b2e550c 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -30,6 +30,7 @@ mod jpeg; #[cfg(feature = "jxl")] mod jxl; mod jxl_encode; +pub mod orientation; mod other; mod png_codec; pub mod print; diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs new file mode 100644 index 00000000000..143c92ba12a --- /dev/null +++ b/crates/codecs/src/orientation.rs @@ -0,0 +1,488 @@ +//! The orientation [`crate::read_header`] gives a file, found by seeking to the bytes that hold it rather than reading +//! the file: the first `Exif` APP1 segment before a JPEG's first scan, a PNG's first `eXIf` chunk, a WebP's first +//! `EXIF` chunk, a TIFF's first directory, a PSD's last Exif image resource. Each is parsed as the header reader parses +//! it. A many-gigabyte TIFF or PSD costs a few reads of its first kilobytes. +//! +//! The file is taken as one that has been read before: what the header reader also checks (the pixel data, its size +//! and layout) is not checked again. Where this can't follow the reader (BigTIFF, an orientation stored in an unusual +//! TIFF type, a structure the reader would reject, a block over [`MAX_BLOCK`]), it says so with `Ok(None)` and the +//! caller reads the file whole. + +use std::io::{self, BufReader, Read, Seek}; + +use crate::Format; + +/// The most bytes read for one block (an Exif segment or chunk, a TIFF directory, a PSD's head). A larger one is +/// `Ok(None)`: read the file whole instead. +pub const MAX_BLOCK: u64 = 64 << 20; + +/// The most structures (JPEG markers, PNG or WebP chunks) walked before giving up with `Ok(None)`. +const MAX_STEPS: u32 = 1 << 22; + +/// The Exif orientation (1–8) [`crate::read_header`] would give the file `reader` holds, `len` bytes long, of +/// `format`; 1 where it states none. `Ok(None)`: not found this way (another format, or see the module notes). +/// `Err`: the file couldn't be read. +pub fn header_orientation(reader: &mut R, len: u64, format: Format) -> io::Result> { + let mut at = At { r: BufReader::new(reader), pos: 0, len }; + at.r.rewind()?; + match format { + Format::Jpeg => jpeg(&mut at), + Format::Png => png(&mut at), + Format::WebP => webp(&mut at), + Format::Tiff => tiff(&mut at), + Format::Psd => psd(&mut at), + _ => Ok(None), + } +} + +/// Positioned reads within a file of `len` bytes, through a buffer that short forward skips don't empty. +struct At { + r: BufReader, + pos: u64, + len: u64, +} + +impl At { + /// Fills `buf` from `at`: `Ok(false)` when that runs past the end of the file. + fn fill(&mut self, at: u64, buf: &mut [u8]) -> io::Result { + let Some(end) = at.checked_add(buf.len() as u64) else { return Ok(false) }; + if end > self.len { + return Ok(false); + } + let (Ok(to), Ok(from)) = (i64::try_from(at), i64::try_from(self.pos)) else { return Ok(false) }; + self.r.seek_relative(to.saturating_sub(from))?; + self.r.read_exact(buf)?; + self.pos = end; + Ok(true) + } + + /// The `n` bytes at `at`: `None` past the end of the file or over [`MAX_BLOCK`]. + fn block(&mut self, at: u64, n: u64) -> io::Result>> { + if n > MAX_BLOCK { + return Ok(None); + } + let Ok(n) = usize::try_from(n) else { return Ok(None) }; + let mut v = vec![0; n]; + Ok(self.fill(at, &mut v)?.then_some(v)) + } +} + +/// As [`crate::jpeg`]'s marker walk (`parse_markers`): garbage between segments is skipped to the next 0xFF, the walk +/// ends at the first scan or EOI, and the first APP1 that starts `Exif\0\0` counts, cut at the end of the file. +fn jpeg(f: &mut At) -> io::Result> { + let mut soi = [0; 2]; + if !f.fill(0, &mut soi)? || soi != [0xff, 0xd8] { + return Ok(None); + } + let mut p: u64 = 2; + for _ in 0..MAX_STEPS { + let mut h = [0; 4]; + if !f.fill(p, &mut h)? { + return Ok(Some(1)); + } + let [b0, marker, l0, l1] = h; + if b0 != 0xff || marker == 0xff { + p = p.saturating_add(1); + continue; + } + match marker { + 0xd8 | 0xd0..=0xd7 | 0x01 => { + p = p.saturating_add(2); + continue; + } + 0xd9 | 0xda => return Ok(Some(1)), + _ => {} + } + let seg_len = u64::from(u16::from_be_bytes([l0, l1])); + if seg_len < 2 { + return Ok(None); + } + let start = p.saturating_add(4); + let declared_end = p.saturating_add(2).saturating_add(seg_len); + if marker == 0xe1 { + let end = declared_end.min(f.len); + let Some(seg) = f.block(start, end.saturating_sub(start))? else { return Ok(None) }; + if let Some(exif) = seg.strip_prefix(b"Exif\0\0") { + return Ok(Some(crate::exif::summarize(exif).orientation.unwrap_or(1))); + } + } + p = declared_end; + } + Ok(None) +} + +/// As `craft_image_codecs::png_probe::header`: the first `eXIf` chunk anywhere, the walk ending at IEND or at a damaged +/// chunk after the image data. +fn png(f: &mut At) -> io::Result> { + let mut sig = [0; 16]; + if !f.fill(0, &mut sig)? || &sig[..8] != b"\x89PNG\r\n\x1a\n" || sig[8..12] != 13u32.to_be_bytes() || &sig[12..] != b"IHDR" { + return Ok(None); + } + let (mut p, mut idat, mut after_idat, mut exif) = (8u64, false, false, None); + for _ in 0..MAX_STEPS { + let mut h = [0; 8]; + if !f.fill(p, &mut h)? { + // too short for a chunk header here: the reader's walk ends too + return finish_png(f, idat, after_idat, exif); + } + let [l0, l1, l2, l3, k0, k1, k2, k3] = h; + let (n, kind) = (u32::from_be_bytes([l0, l1, l2, l3]), [k0, k1, k2, k3]); + if idat && &kind != b"IDAT" { + after_idat = true; + } + if &kind == b"IEND" { + return finish_png(f, idat, after_idat, exif); + } + let start = p.saturating_add(8); + let end = start.saturating_add(u64::from(n)); + if n > i32::MAX as u32 || end > f.len { + if after_idat { + return finish_png(f, idat, after_idat, exif); + } + return Ok(None); + } + match &kind { + b"IDAT" if !after_idat => idat = true, + b"eXIf" if exif.is_none() => exif = Some((start, u64::from(n))), + _ => {} + } + p = end.saturating_add(4); + } + Ok(None) +} + +fn finish_png(f: &mut At, idat: bool, after_idat: bool, exif: Option<(u64, u64)>) -> io::Result> { + if !idat || !after_idat { + return Ok(None); + } + let Some((at, n)) = exif else { return Ok(Some(1)) }; + let Some(data) = f.block(at, n)? else { return Ok(None) }; + Ok(Some(craft_metadata::compat_orientation::orientation(data.strip_prefix(b"Exif\0\0").unwrap_or(&data)))) +} + +/// As [`crate::webp`]'s header: the first `EXIF` chunk that fits in the file. +fn webp(f: &mut At) -> io::Result> { + let (mut p, mut has_image, mut exif) = (12u64, false, None); + for _ in 0..MAX_STEPS { + let mut h = [0; 8]; + if !f.fill(p, &mut h)? { + if !has_image { + return Ok(None); + } + let Some((at, n)) = exif else { return Ok(Some(1)) }; + let Some(e) = f.block(at, n)? else { return Ok(None) }; + return Ok(Some(crate::exif::summarize(e.strip_prefix(b"Exif\0\0").unwrap_or(&e)).orientation.unwrap_or(1))); + } + let [i0, i1, i2, i3, s0, s1, s2, s3] = h; + let (id, size) = ([i0, i1, i2, i3], u64::from(u32::from_le_bytes([s0, s1, s2, s3]))); + let end = p.saturating_add(8).saturating_add(size); + if matches!(&id, b"VP8 " | b"VP8L" | b"ANMF") { + if end > f.len { + return Ok(None); + } + has_image = true; + } else if &id == b"EXIF" && end <= f.len && exif.is_none() { + exif = Some((p.saturating_add(8), size)); + } + p = end.saturating_add(size & 1); + } + Ok(None) +} + +/// As `craft_image_codecs::tiff_probe::header`: the first directory's Orientation tag, 1 when it has none or it +/// isn't 1–8. Classic TIFF only, the tag stored as one BYTE, SHORT or LONG. +fn tiff(f: &mut At) -> io::Result> { + let mut h = [0; 8]; + if !f.fill(0, &mut h)? { + return Ok(None); + } + let le = match &h[..2] { + b"II" => true, + b"MM" => false, + _ => return Ok(None), + }; + let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; + let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; + let [_, _, m0, m1, o0, o1, o2, o3] = h; + if u16_of([m0, m1]) != 42 { + return Ok(None); + } + let ifd = u64::from(u32_of([o0, o1, o2, o3])); + let mut count = [0; 2]; + if ifd < 8 || !f.fill(ifd, &mut count)? { + return Ok(None); + } + let Some(entries) = f.block(ifd.saturating_add(2), 12 * u64::from(u16_of(count)))? else { return Ok(None) }; + let mut found = None; + for e in entries.chunks_exact(12) { + let [t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] = <[u8; 12]>::try_from(e).unwrap_or_default(); + if u16_of([t0, t1]) != 274 { + continue; + } + if found.is_some() || u32_of([c0, c1, c2, c3]) != 1 { + return Ok(None); + } + found = Some(match u16_of([y0, y1]) { + 1 => u32::from(v0), + 3 => u32::from(u16_of([v0, v1])), + 4 => u32_of([v0, v1, v2, v3]), + _ => return Ok(None), + }); + } + Ok(Some(found.and_then(|v| u16::try_from(v).ok()).filter(|o| (1..=8).contains(o)).unwrap_or(1))) +} + +/// As [`crate::psd`]'s header: the head (header, colour mode data, image resources) parsed by `craft_psd`, the last +/// Exif resource (1058) counting. +fn psd(f: &mut At) -> io::Result> { + let mut h = [0; 30]; + if !f.fill(0, &mut h)? { + return Ok(None); + } + let [.., c0, c1, c2, c3] = h; + let res_len_at = 30u64.saturating_add(u64::from(u32::from_be_bytes([c0, c1, c2, c3]))); + let mut r = [0; 4]; + if !f.fill(res_len_at, &mut r)? { + return Ok(None); + } + let head_len = res_len_at.saturating_add(4).saturating_add(u64::from(u32::from_be_bytes(r))); + let Some(head) = f.block(0, head_len)? else { return Ok(None) }; + let resources = craft_psd::Head::from_bytes(&head).map(|head| head.resources).unwrap_or_default(); + let exif = resources.iter().rev().find(|r| r.id == 1058).map(|r| r.data.as_slice()); + Ok(Some(exif.map(|d| crate::exif::summarize(d.strip_prefix(b"Exif\0\0").unwrap_or(d))).unwrap_or_default().orientation.unwrap_or(1))) +} + +#[cfg(test)] +mod tests { + use std::io::{Cursor, Read, Seek, SeekFrom}; + + use super::header_orientation; + use crate::{EncodeImage, EncodeMeta, Format, TiffCompression, read_header}; + + /// Counts the bytes read from the file, so a test can see how little of it was. + struct Counting { + inner: Cursor>, + read: u64, + } + impl Read for Counting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n as u64; + Ok(n) + } + } + impl Seek for Counting { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } + } + + /// The seek probe's answer and the bytes it read; `None` when it can't tell. + fn probe(bytes: &[u8]) -> (Option, u64) { + let format = crate::sniff(bytes).unwrap(); + let mut c = Counting { inner: Cursor::new(bytes.to_vec()), read: 0 }; + (header_orientation(&mut c, bytes.len() as u64, format).unwrap(), c.read) + } + + /// The probe gives what `read_header` gives the whole file, and finds it by seeking. + #[track_caller] + fn same(name: &str, bytes: &[u8]) -> u16 { + let whole = read_header(bytes).unwrap_or_else(|e| panic!("{name}: {e}")).orientation; + assert_eq!(probe(bytes).0, Some(whole), "{name}"); + whole + } + + fn encode(format: Format, w: usize, h: usize, exif: Option<&[u8]>, xmp: Option<&str>) -> Vec { + let img = lightcraft_raster::Rgba8::from_fn(w, h, |x, y| { + // noise: a large file stays large in every format + let n = (x as u32).wrapping_mul(2_654_435_761) ^ (y as u32).wrapping_mul(40_503).rotate_left(13); + let [a, b, c, _] = n.wrapping_mul(2_246_822_519).to_le_bytes(); + [a, b, c, 255] + }); + let img = EncodeImage::rgba8(&img); + let meta = EncodeMeta { exif, xmp, ..Default::default() }; + match format { + Format::Jpeg => crate::encode_jpeg(&img, 90, Default::default(), &meta), + Format::Png => crate::encode_png(&img, &meta), + Format::Tiff => crate::encode_tiff(&img, TiffCompression::None, &meta), + Format::Psd => crate::encode_psd(&img, &meta), + Format::WebP => crate::encode_webp_lossless(&img, &meta), + other => panic!("no encoder here for {other:?}"), + } + .unwrap() + } + + const FORMATS: [Format; 5] = [Format::Jpeg, Format::Png, Format::Tiff, Format::Psd, Format::WebP]; + + #[test] + fn every_orientation_of_every_format_is_the_headers() { + for format in FORMATS { + let mut seen = Vec::new(); + for o in 1..=8u16 { + let exif = crate::exif::minimal_exif(o); + seen.push(same(&format!("{format:?} {o}"), &encode(format, 16, 12, Some(&exif), None))); + } + assert_eq!(same(&format!("{format:?} none"), &encode(format, 16, 12, None, None)), 1); + // an orientation only XMP states is not the header's + let xmp = r#""#; + assert_eq!(same(&format!("{format:?} xmp"), &encode(format, 16, 12, None, Some(xmp))), 1); + // the TIFF encoder writes no Orientation tag: `tiff_with_orientation` covers TIFF's eight + let want: Vec = if format == Format::Tiff { vec![1; 8] } else { (1..=8).collect() }; + assert_eq!(seen, want, "{format:?}: the fixtures carry their orientation"); + } + } + + #[test] + fn a_large_file_is_read_only_where_its_orientation_is() { + let exif = crate::exif::minimal_exif(6); + for format in FORMATS { + let bytes = encode(format, 1024, 1024, Some(&exif), None); + assert!(bytes.len() > 1 << 20, "{format:?}: {}", bytes.len()); + same(&format!("{format:?} large"), &bytes); + let (_, read) = probe(&bytes); + assert!(read <= 64 << 10, "{format:?}: read {read} of {} bytes", bytes.len()); + } + } + + /// JPEG segments the walk must step over, or stop at, as the header reader does. + #[test] + fn jpeg_segments_are_walked_as_the_header_reader_walks_them() { + let six = [&b"Exif\0\0"[..], &crate::exif::minimal_exif(6)].concat(); + let plain = [&b"Exif\0\0"[..], &crate::exif::minimal_exif(1)].concat(); + let base = encode(Format::Jpeg, 16, 12, None, None); + // `extra` inserted right after SOI + let with = |extra: &[u8]| [&base[..2], extra, &base[2..]].concat(); + let seg = |marker: u8, payload: &[u8]| [&[0xff, marker][..], &(payload.len() as u16 + 2).to_be_bytes(), payload].concat(); + let big: Vec = (0..17).flat_map(|_| seg(0xef, &vec![0; 0xfffd])).collect(); + let xmp = [&b"http://ns.adobe.com/xap/1.0/\0"[..], b""].concat(); + for (name, bytes, want) in [ + ("past the first MiB", with(&[big.clone(), seg(0xe1, &six)].concat()), 6), + ("garbage and fill bytes", with(&[&seg(0xee, b"x")[..], &[0x00, 0x12, 0xff, 0xff], &seg(0xe1, &six)].concat()), 6), + ("XMP first", with(&[seg(0xe1, &xmp), seg(0xe1, &six)].concat()), 6), + ("the first Exif counts", with(&[seg(0xe1, &plain), seg(0xe1, &six)].concat()), 1), + // the walk ends at the first scan: an Exif segment after the image isn't the header's + ("after the image", [&base[..], &seg(0xe1, &six)].concat(), 1), + ] { + assert_eq!(same(name, &bytes), want, "{name}"); + } + // nor one after the first scan header (the header reader stops there, before any EOI) + let after_sos = [&[0xff, 0xd8][..], &seg(0xda, &[1, 1, 0, 0, 0, 0]), &seg(0xe1, &six)].concat(); + assert_eq!(probe(&after_sos).0, Some(1), "after SOS"); + // reading the Exif past the first MiB costs a buffer per segment header, not the segments + let far = with(&[big, seg(0xe1, &six)].concat()); + let (_, read) = probe(&far); + assert!(read < far.len() as u64 / 4, "read {read} of {}", far.len()); + } + + /// PNG and WebP keep chunks after the image data; the first Exif chunk counts. + #[test] + fn late_and_repeated_exif_chunks_are_the_header_readers() { + let six = crate::exif::minimal_exif(6); + let three = crate::exif::minimal_exif(3); + // a PNG with `chunks` (kind, data) put before IEND; the CRC isn't checked by either reader + let png = |chunks: &[(&[u8; 4], &[u8])]| { + let base = encode(Format::Png, 16, 12, None, None); + let iend = base.len() - 12; + let mut out = base[..iend].to_vec(); + for (kind, data) in chunks { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(*kind); + out.extend_from_slice(data); + out.extend_from_slice(&[0; 4]); + } + out.extend_from_slice(&base[iend..]); + out + }; + assert_eq!(same("png late", &png(&[(b"eXIf", &six)])), 6); + assert_eq!(same("png two", &png(&[(b"eXIf", &three), (b"eXIf", &six)])), 3); + // after an early eXIf (the encoder's), a late one doesn't count + let early = encode(Format::Png, 16, 12, Some(&three), None); + let iend = early.len() - 12; + let mut both = early[..iend].to_vec(); + both.extend_from_slice(&(six.len() as u32).to_be_bytes()); + both.extend_from_slice(b"eXIf"); + both.extend_from_slice(&six); + both.extend_from_slice(&[0; 4]); + both.extend_from_slice(&early[iend..]); + assert_eq!(same("png early and late", &both), 3); + + // a WebP with a second EXIF chunk after the encoder's + let webp = encode(Format::WebP, 16, 12, Some(&three), None); + let chunk = [&b"EXIF"[..], &(six.len() as u32).to_le_bytes(), &six, &vec![0; six.len() % 2]].concat(); + let mut two = [&webp[..], &chunk].concat(); + let riff = (two.len() - 8) as u32; + two[4..8].copy_from_slice(&riff.to_le_bytes()); + assert_eq!(same("webp two", &two), 3); + } + + /// Where the probe can't follow the header reader it says so, rather than guessing. + #[test] + fn what_the_probe_cant_follow_is_none() { + let tiff = encode(Format::Tiff, 16, 12, None, None); + let mut big = tiff.clone(); + big[2] = 43; // BigTIFF magic (little-endian) + assert_eq!(probe(&big).0, None, "BigTIFF"); + let mut c = Cursor::new(vec![0xff]); + assert_eq!(header_orientation(&mut c, 1, Format::Jpeg).unwrap(), None, "too short for SOI"); + let mut c = Cursor::new(Vec::new()); + assert_eq!(header_orientation(&mut c, 0, Format::Gif).unwrap(), None, "another format"); + let _ = tiff; + } + + /// `tiff` (little-endian, as the encoder writes it) with its first directory copied to the end of the file and + /// `added` (tag, type, count, 4 value bytes) entries put in it, tag order kept. + fn tiff_with(tiff: &[u8], added: &[(u16, u16, u32, [u8; 4])]) -> Vec { + assert_eq!(&tiff[..4], b"II*\0"); + let le16 = |at: usize| u16::from_le_bytes([tiff[at], tiff[at + 1]]); + let ifd = u32::from_le_bytes(tiff[4..8].try_into().unwrap()) as usize; + let n = usize::from(le16(ifd)); + let mut entries: Vec<[u8; 12]> = (0..n).map(|i| tiff[ifd + 2 + 12 * i..ifd + 14 + 12 * i].try_into().unwrap()).collect(); + for (tag, typ, count, value) in added { + let mut e = [0; 12]; + e[..2].copy_from_slice(&tag.to_le_bytes()); + e[2..4].copy_from_slice(&typ.to_le_bytes()); + e[4..8].copy_from_slice(&count.to_le_bytes()); + e[8..].copy_from_slice(value); + entries.push(e); + } + entries.sort_by_key(|e| u16::from_le_bytes([e[0], e[1]])); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let at = out.len() as u32; + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + entries.iter().for_each(|e| out.extend_from_slice(e)); + out.extend_from_slice(&[0; 4]); + out[4..8].copy_from_slice(&at.to_le_bytes()); + out + } + + #[test] + fn a_tiffs_orientation_tag_is_the_headers() { + let base = encode(Format::Tiff, 16, 12, None, None); + let short = |v: u16| [v.to_le_bytes()[0], v.to_le_bytes()[1], 0, 0]; + for o in 1..=8u16 { + assert_eq!(same(&format!("SHORT {o}"), &tiff_with(&base, &[(274, 3, 1, short(o))])), o); + assert_eq!(same(&format!("LONG {o}"), &tiff_with(&base, &[(274, 4, 1, u32::from(o).to_le_bytes())])), o); + assert_eq!(same(&format!("BYTE {o}"), &tiff_with(&base, &[(274, 1, 1, [o as u8, 0, 0, 0])])), o); + } + // out of range: 1, as the header reader takes it + for v in [0, 9, 0xffff] { + assert_eq!(same(&format!("SHORT {v}"), &tiff_with(&base, &[(274, 3, 1, short(v))])), 1); + } + assert_eq!(same("LONG past u16", &tiff_with(&base, &[(274, 4, 1, 0x1_0006u32.to_le_bytes())])), 1); + // the large-file test's TIFF, with its orientation tag: still a few reads + let big = tiff_with(&encode(Format::Tiff, 1024, 1024, None, None), &[(274, 3, 1, short(6))]); + assert_eq!(same("large", &big), 6); + assert!(probe(&big).1 <= 64 << 10); + // what the probe doesn't follow: a signed type, two tags, a count of two + for (name, added) in [ + ("SSHORT", vec![(274, 8, 1, short(6))]), + ("two tags", vec![(274, 3, 1, short(6)), (274, 3, 1, short(3))]), + ("two values", vec![(274, 3, 2, [6, 0, 3, 0])]), + ] { + assert_eq!(probe(&tiff_with(&base, &added)).0, None, "{name}"); + } + } +} diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 49723e0a513..44e1f10236c 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -32,7 +32,7 @@ pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_v use preview::PLAN_PREFIX; pub(crate) use preview::decode_raw_preview; pub use preview::{PreviewRead, embedded_preview_srgb, fs_preview_loader, load_embedded_preview, preview_window}; -pub use probe::{Orientations, embedded_lens, orientations, probe_bytes, upright_by}; +pub use probe::{ORIENTATION_HEAD, Orientations, embedded_lens, orientations, orientations_of_file, probe_bytes, upright_by}; #[cfg(test)] use probe::{meta_of, preview_reason}; diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index ec03302ad8c..2b1628a5d09 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -178,6 +178,54 @@ pub fn orientations(bytes: &[u8]) -> Orientations { Orientations { kept, read_by: kept } } +/// [`Orientations`] of the file at `path` (none when it can't be read or is over `max` bytes), reading no more of it +/// than its orientation needs. A raw, and a file of at most [`ORIENTATION_HEAD`] bytes, is read whole (within `max`) +/// and given [`orientations`]. Any other image is read where its header reader finds the orientation +/// ([`lightcraft_codecs::orientation::header_orientation`]: a few reads, however large the file), and whole only where +/// that can't tell. +pub fn orientations_of_file(path: &str, max: u64) -> Orientations { + orientations_read(path, max).unwrap_or_default() +} + +/// How much of a file [`orientations_of_file`] reads first: enough to tell a raw (as upstream's sync did) and to +/// take a small file whole. +pub const ORIENTATION_HEAD: u64 = 1 << 20; + +fn orientations_read(path: &str, max: u64) -> Option { + use std::io::{Read, Seek}; + let mut file = crate::read_file::open_for_read(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() || meta.len() > max { + return None; + } + let len = meta.len(); + let mut head = Vec::new(); + (&mut file).take(ORIENTATION_HEAD.min(len)).read_to_end(&mut head).ok()?; + if head.len() as u64 >= len { + return Some(orientations(&head)); + } + let whole = |mut file: std::fs::File| -> Option { + file.rewind().ok()?; + crate::read_file::read_open(file, max).ok().map(|bytes| orientations(&bytes)) + }; + // a raw's orientation is its decoder's, which needs the file + if lightcraft_raw::probe(&head).is_some() { + return whole(file); + } + let format = lightcraft_codecs::sniff(&head)?; + if format.not_decodable().is_some() { + return None; + } + match lightcraft_codecs::orientation::header_orientation(&mut file, len, format) { + Ok(Some(o)) => { + let o = Some(Orientation::from_exif(o)); + Some(Orientations { kept: o, read_by: o }) + } + Ok(None) => whole(file), + Err(_) => None, + } +} + /// Probe a file's bytes: kind, dimensions (oriented), metadata. No pixel data is decompressed: /// raws are described from their headers ([`lightcraft_raw::probe_info`]), other images too /// ([`lightcraft_codecs::read_header`], which refuses truncated files but can't see damage inside diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 3f4c760c54a..36563ff7b94 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -491,12 +491,13 @@ impl SidecarData { } } -/// The orientations of the photo file at `path` by the import's rules ([`crate::files::orientations`]): the file is -/// read, up to `max` bytes (none past that, and then none are known), and nothing but its orientation is worked out. +/// The orientations of the photo file at `path` by the import's rules ([`crate::files::orientations_of_file`]): a raw +/// is read whole, up to `max` bytes (none past that, and then none are known); another image only where its +/// orientation is. Nothing but its orientation is worked out. /// For a photo whose [`lightcraft_catalog::Meta::file_orientation`] isn't known: by Read Metadata from File and /// Synchronize Folder. fn upright_orientation(path: &str, max: u64) -> crate::files::Orientations { - crate::read_file::read_regular(path, max).map(|bytes| crate::files::orientations(&bytes)).unwrap_or_default() + crate::files::orientations_of_file(path, max) } /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index ea9884ec4ff..d33d9bc8b22 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2748,3 +2748,58 @@ fn synchronize_reads_boxes_by_the_imports_orientation_as_read_metadata_does() { assert_eq!(sc.with_orientation_known(Some(Orientation::Rotate180), "/no/such/file").orientation, Some(Orientation::Rotate180)); let _ = std::fs::remove_dir_all(&src); } + +/// A 1024 × 1024 8-bit grey TIFF, padded past [`crate::files::ORIENTATION_HEAD`], stating orientation 6 as `typ` +/// (3 SHORT, 8 SSHORT), its strip at `strip_at`. +fn grey_tiff(typ: u16, strip_at: u32) -> Vec { + let entries: [(u16, u16, u32); 10] = [ + (256, 3, 1024), + (257, 3, 1024), + (258, 3, 8), + (259, 3, 1), + (262, 3, 1), + (273, 4, strip_at), + (274, typ, 6), + (277, 3, 1), + (278, 3, 1024), + (279, 4, 1 << 20), + ]; + let mut t = b"II*\0\x08\0\0\0".to_vec(); + t.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, kind, value) in entries { + t.extend_from_slice(&tag.to_le_bytes()); + t.extend_from_slice(&kind.to_le_bytes()); + t.extend_from_slice(&1u32.to_le_bytes()); + t.extend_from_slice(&if kind == 4 { value.to_le_bytes() } else { [value as u8, (value >> 8) as u8, 0, 0] }); + } + t.extend_from_slice(&[0; 4]); + t.resize(256 + (1 << 20), 0x80); + t +} + +/// Review of #4512: an image past the first MiB is read only where its header reader finds the orientation, not whole; +/// and whole, within the limit, where the header probe can't tell. +#[test] +fn a_large_images_orientation_is_read_from_its_header() { + use lightcraft_meta::Orientation; + let dir = temp_dir("header-orientation"); + // its strip runs past the end of the file: read whole, the header reader refuses it, so only a header read gives 6 + let cut = grey_tiff(3, 1 << 30); + assert!(cut.len() as u64 > crate::files::ORIENTATION_HEAD); + assert_eq!(crate::files::orientations(&cut), crate::files::Orientations::default(), "the whole file gives none"); + let path = dir.join("cut.tif"); + std::fs::write(&path, &cut).unwrap(); + let six = Some(Orientation::Rotate90); + let read = crate::files::orientations_of_file(&path.to_string_lossy(), crate::read_file::MAX_MEDIA_BYTES); + assert_eq!(read, crate::files::Orientations { kept: six, read_by: six }, "read from its header"); + // a SSHORT orientation the header probe doesn't follow: the file is read whole, and gives the header reader's 6 + let signed = grey_tiff(8, 256); + assert_eq!(crate::files::orientations(&signed).kept, six, "the header reader takes a SSHORT"); + let path = dir.join("signed.tif"); + std::fs::write(&path, &signed).unwrap(); + let file = path.to_string_lossy(); + assert_eq!(crate::files::orientations_of_file(&file, crate::read_file::MAX_MEDIA_BYTES).kept, six, "read whole"); + // over the limit: not read at all + assert_eq!(crate::files::orientations_of_file(&file, signed.len() as u64 - 1), crate::files::Orientations::default()); + let _ = std::fs::remove_dir_all(&dir); +} From 47cfa3736beabe32f7df98cb029fb7790376d9fb Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 23:43:48 -0600 Subject: [PATCH 18/25] LR-LIB-PEOPLE: write boxes upright when a kept entry has a rotation A kept entry LightCraft can't read but that has mwg-rs:Rotation makes regions_drawn_on take the whole list as marked by rotation, ignoring its AppliedToDimensions. Boxes on an Exif 5 or 7 photo, which only that size puts in the stored frame, came back transposed. Carried records such an entry (the same field test regions_drawn_on makes), and the save then writes the upright packet, as it does for kept pixel boxes with no size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/engine/src/sidecar.rs | 81 +++++++++++++++++++++++++++++++----- docs/xmp-interop.md | 4 +- 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 36563ff7b94..02abc61b18f 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -585,7 +585,7 @@ struct Fresh { packet: String, /// The same with its face boxes on the upright photo, when `packet` has them in the frame the file is stored in /// with no rotation (Exif 5, 7): only the list's `AppliedToDimensions` tells that frame, so a save that has to - /// leave the size out writes this one. + /// leave the size out, or keeps an entry whose `mwg-rs:Rotation` makes readers ignore the size, writes this one. upright: Option, } @@ -766,9 +766,10 @@ fn fit_to_old(old: &str, fresh: Fresh) -> String { let regions = parse_sidecar(old, crate::crs::Target::Rendered).ok().and_then(|sc| sc.regions); let readable = regions.as_ref().map_or(0, Vec::len); let carried = unreadable_regions(old, &data, readable); - // the list's size goes when kept pixel boxes had none (below); boxes only that size tells the frame of go upright + // the list's size goes when kept pixel boxes had none (below), and says nothing when a kept entry has a rotation: + // boxes only that size tells the frame of go upright let fresh = match fresh.upright { - Some(upright) if carried.as_ref().is_some_and(|c| c.pixels_without_size) => upright, + Some(upright) if carried.as_ref().is_some_and(Carried::size_untold) => upright, _ => fresh.packet, }; let lower = |s: &str| s.trim().to_lowercase(); @@ -879,6 +880,17 @@ struct Carried { dims: Option<(String, String)>, /// One of them is in pixels and the list has no size. pixels_without_size: bool, + /// One of them has a `mwg-rs:Rotation`: a reader then takes the whole list as marked by rotation, not by its size + /// ([`lightcraft_meta::XmpData::regions_drawn_on`]), even though it can't read that entry. + rotation: bool, +} + +impl Carried { + /// The list, written with these entries, can't tell its frame by its size: boxes only that size tells the frame of + /// (Exif 5, 7) must go upright. + fn size_untold(&self) -> bool { + self.pixels_without_size || self.rotation + } } /// [`Carried`] for the sidecar `old` (parsed as `data`, `readable` regions of it read), or `None` when its list has @@ -889,7 +901,7 @@ fn unreadable_regions(old: &str, data: &lightcraft_meta::XmpData, readable: usiz let dims = regions .and_then(|r| r.field("mwg-rs:AppliedToDimensions")) .and_then(|d| Some((d.field("stDim:w")?.text()?.to_string(), d.field("stDim:h")?.text()?.to_string()))); - let mut carried = Carried { items: Vec::new(), dims, pixels_without_size: false }; + let mut carried = Carried { items: Vec::new(), dims, pixels_without_size: false, rotation: false }; if n <= readable { return Some(carried); } @@ -912,13 +924,16 @@ fn unreadable_regions(old: &str, data: &lightcraft_meta::XmpData, readable: usiz if readable { continue; } - any_pixels |= lightcraft_meta::parse_xmp(&alone).ok().is_some_and(|d| { - d.values - .get("mwg-rs:Regions") - .and_then(|r| r.field("mwg-rs:RegionList")) - .and_then(|l| l.items().first().and_then(|i| i.field("mwg-rs:Area")).and_then(|a| a.field("stArea:unit")).and_then(|u| u.text())) - .is_some_and(|u| u.eq_ignore_ascii_case("pixel")) - }); + let parsed = lightcraft_meta::parse_xmp(&alone).ok(); + let entry = + parsed.as_ref().and_then(|d| d.values.get("mwg-rs:Regions")).and_then(|r| r.field("mwg-rs:RegionList")).and_then(|l| l.items().first()); + any_pixels |= entry + .and_then(|i| i.field("mwg-rs:Area")) + .and_then(|a| a.field("stArea:unit")) + .and_then(|u| u.text()) + .is_some_and(|u| u.eq_ignore_ascii_case("pixel")); + // the test `regions_drawn_on` makes of every entry, this one included + carried.rotation |= entry.is_some_and(|i| i.field("mwg-rs:Rotation").is_some()); carried.items.push(item); } // every entry accounted for: those read, and those kept as they are @@ -2208,6 +2223,50 @@ mod tests { } } + /// Review of #4512: a kept entry LightCraft can't read but that has a `mwg-rs:Rotation` makes readers take the + /// whole list as marked by rotation, its size ignored. Boxes on an Exif 5 or 7 photo, which only that size would + /// put in the stored frame, are written upright then. + #[test] + fn boxes_go_upright_when_a_kept_entry_has_a_rotation() { + use lightcraft_meta::Orientation::{Transpose, Transverse}; + let upright = lightcraft_meta::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }; + let ann = |x: &str, o| { + let sc = parse_sidecar(x, crate::crs::Target::Rendered).unwrap().with_orientation_known(Some(o), "/no/such/file"); + let mut q = photo(); + merge_into(&mut q, &sc, "now"); + q.meta.regions.iter().find(|r| r.name.as_deref() == Some("Ann")).map(|r| r.rect).unwrap() + }; + let near = |g: lightcraft_meta::Rect| [(g.x0, 0.1), (g.y0, 0.2), (g.x1, 0.3), (g.y1, 0.6)].iter().all(|(a, b)| (a - b).abs() < 1e-5); + // a zero-width box (unreadable, so kept as it is), with or without a rotation of 0 + let with_entry = |rotation: bool| { + let x = sidecar_with(&[(0.5, 0.5, 0.0, 0.2, None)], &[]); + let end = "Face"; + if rotation { x.replacen(end, "Face0", 1) } else { x } + }; + for o in [Transpose, Transverse] { + let mut p = photo(); + p.meta.file_orientation = Some(o); + p.meta.regions = + vec![lightcraft_meta::Region { rect: upright, kind: lightcraft_meta::RegionKind::Face, name: Some("Ann".into()), description: None }]; + + let path = scratch("kept-rotation"); + std::fs::write(&path, with_entry(true)).unwrap(); + let x = save_over(&path, &p); + assert!(x.contains("stArea:w=\"0\"") && x.contains("0"), "{o:?}: kept: {x}"); + assert_eq!(parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions_drawn_on, None, "{o:?}: readers ignore the size"); + assert!(near(ann(&x, o)), "{o:?}: {:?} {x}", ann(&x, o)); + assert_eq!(save_over(&path, &p), x, "{o:?}: stable"); + + // without the rotation the list's size tells the stored frame, which the boxes are written in + let path = scratch("kept-no-rotation"); + std::fs::write(&path, with_entry(false)).unwrap(); + let x = save_over(&path, &p); + assert!(x.contains("stArea:w=\"0\"") && x.contains("30"), "{o:?}: stored frame: {x}"); + assert!(near(ann(&x, o)), "{o:?}: {:?}", ann(&x, o)); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + } + #[test] fn a_kept_entry_keeps_its_size_when_the_list_had_one() { // an entry off the photo in a list with a size: unreadable, kept, and the list keeps its size when cleared diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index c01f1d31b5f..f77a3de1964 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -128,7 +128,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become the photo as stored (where the MWG guidelines place regions) with that turn as `mwg-rs:Rotation`. A photo turned a quarter and mirrored (5, 7) that isn't square is written in the stored frame too, with the stored size as `AppliedToDimensions` and no rotation; LightCraft tells it from an upright packet by that size, as below. When - the list can't have a size (it keeps pixel boxes that had none, see below), those boxes are written upright. A photo + the list can't have a size (it keeps pixel boxes that had none, see below), or its size says nothing (it keeps an + entry with a `mwg-rs:Rotation`, which makes readers take the whole list as marked by rotation), those boxes are + written upright. A photo mirrored without a turn (2, 4) or a square one looks the same either way, so its boxes are written upright, as LightCraft reads them; MWG readers that apply the mirror place those mirrored. Orientation 1 is written upright. The file's orientation is the one the import read, kept in the catalog: a save never reads the photo file for it, and neither does reading a sidecar From bc7d71d69c338329b4537d30e8bf81b2ceff8e40 Mon Sep 17 00:00:00 2001 From: edcasati Date: Wed, 18 Nov 2026 23:57:52 -0600 Subject: [PATCH 19/25] LR-LIB-PEOPLE: no orientation for a PSD whose fixed header is invalid The PSD header probe turned any Head::from_bytes error into an empty resource list and answered 1. It now checks the fixed header first (craft_psd::Header::from_bytes, as the header reader does) and answers Ok(None) when that fails, so the engine reads the file whole and gets the import's answer. A valid header with a resource section that doesn't parse still counts as no Exif, as the header reader takes it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014DPtyLJY3u2bgbfoZh5MA2 --- crates/codecs/src/orientation.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs index 143c92ba12a..591596e8ea7 100644 --- a/crates/codecs/src/orientation.rs +++ b/crates/codecs/src/orientation.rs @@ -232,8 +232,9 @@ fn tiff(f: &mut At) -> io::Result> { Ok(Some(found.and_then(|v| u16::try_from(v).ok()).filter(|o| (1..=8).contains(o)).unwrap_or(1))) } -/// As [`crate::psd`]'s header: the head (header, colour mode data, image resources) parsed by `craft_psd`, the last -/// Exif resource (1058) counting. +/// As [`crate::psd`]'s header: a fixed header `craft_psd` rejects is `Ok(None)` (the header reader rejects the file); +/// past it, the head (colour mode data, image resources) parsed by `craft_psd`, a resource section that doesn't parse +/// counting as none (as the header reader takes it), and the last Exif resource (1058) counting. fn psd(f: &mut At) -> io::Result> { let mut h = [0; 30]; if !f.fill(0, &mut h)? { @@ -247,6 +248,9 @@ fn psd(f: &mut At) -> io::Result> { } let head_len = res_len_at.saturating_add(4).saturating_add(u64::from(u32::from_be_bytes(r))); let Some(head) = f.block(0, head_len)? else { return Ok(None) }; + if craft_psd::Header::from_bytes(&head).is_err() { + return Ok(None); + } let resources = craft_psd::Head::from_bytes(&head).map(|head| head.resources).unwrap_or_default(); let exif = resources.iter().rev().find(|r| r.id == 1058).map(|r| r.data.as_slice()); Ok(Some(exif.map(|d| crate::exif::summarize(d.strip_prefix(b"Exif\0\0").unwrap_or(d))).unwrap_or_default().orientation.unwrap_or(1))) @@ -485,4 +489,25 @@ mod tests { assert_eq!(probe(&tiff_with(&base, &added)).0, None, "{name}"); } } + + /// A PSD whose fixed header the reader rejects is not given an orientation; one whose resources don't parse is + /// given 1, as the reader gives it. + #[test] + fn a_psd_with_a_bad_fixed_header_is_none_and_bad_resources_are_none_found() { + let six = crate::exif::minimal_exif(6); + let good = encode(Format::Psd, 16, 12, Some(&six), None); + assert_eq!(same("good", &good), 6); + // no channels: the fixed header's own check + let mut no_channels = good.clone(); + no_channels[12..14].copy_from_slice(&0u16.to_be_bytes()); + assert!(read_header(&no_channels).is_err(), "the reader rejects it"); + assert_eq!(probe(&no_channels).0, None, "no channels"); + // the first resource's signature spoiled, the section's length kept: no metadata, as the reader takes it + let cm = u32::from_be_bytes(good[26..30].try_into().unwrap()) as usize; + let first = 30 + cm + 4; + assert_eq!(&good[first..first + 4], b"8BIM"); + let mut bad_resources = good.clone(); + bad_resources[first..first + 4].copy_from_slice(b"JUNK"); + assert_eq!(same("bad resources", &bad_resources), 1); + } } From cbf00111bf4d0b2c159a3787666cbec5110034d3 Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:52:11 +1100 Subject: [PATCH 20/25] LR-LIB-PEOPLE: a sidecar's face boxes keep the size they were drawn on when a file's own XMP is read too Since #4512 was written, the import reads a file's embedded XMP and its sidecar together (SidecarData::override_with), the sidecar winning field by field. The sidecar's regions replaced the embedded ones, but regions_drawn_on stayed the embedded packet's, so boxes a sidecar gave on the photo as stored (a turned raw, Exif 5 or 7 written by LightCraft) were left as drawn instead of being turned upright. The size now travels with the list. Guarded by read_metadata_turns_a_preview_only_raws_boxes_as_the_import_does, which fails without it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/sidecar.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 02abc61b18f..eb4f60ada40 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -460,6 +460,9 @@ impl SidecarData { } if other.regions.is_some() { self.regions = other.regions; + // the size the boxes were drawn on belongs to the list they came from: the embedded packet's, if any, would + // turn the sidecar's boxes by a frame they weren't drawn on, or leave them as drawn on the stored photo + self.regions_drawn_on = other.regions_drawn_on; } if other.captured.is_some() { self.captured = other.captured; From f25a843c6efe37ae933821cf97955ff29e59b3c7 Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:00:15 +1100 Subject: [PATCH 21/25] LR-LIB-PEOPLE: faces.renamePerson's doc says the sidecar follows with auto-write Its command description already says so (#4512); the function's doc comment still said the sidecar is not touched. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/face_recognize.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index ce7ae891bcd..eafed38cc00 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -94,7 +94,8 @@ fn set_name(s: &mut Session, p: &Value) -> Result { /// `faces.renamePerson {from, to, merge?}`: give every in-library face of `from` the exact name `to`, as one undo /// step. Names match the People view (trimmed, case-insensitive). A `to` that is already someone else is refused -/// unless `merge` is set, and then the two people become one. The sidecar is not touched, and a refusal changes nothing. +/// unless `merge` is set, and then the two people become one. With auto-write on, each changed original's sidecar is +/// rewritten; a refusal changes nothing. fn rename_person(s: &mut Session, p: &Value) -> Result { const C: &str = "faces.renamePerson"; let from = match p.get("from") { From 44ddffd272b490cfd0b8edf23bfc6131ea25732f Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:01:02 +1100 Subject: [PATCH 22/25] LR-LIB-PEOPLE: format the import's FileFacts after adding upright_by Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/import/commit.rs | 9 ++++++--- crates/engine/src/import/job.rs | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 5332674a115..2ae0f5d5497 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -344,9 +344,12 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.content_hash = info.content_hash; p.embedded_lens = info.embedded_lens.map(Box::new); p.set_preview_only(info.preview_only.clone()); - if let Some(sc) = - start_from_file(s, &mut p, FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar }, &now) - { + if let Some(sc) = start_from_file( + s, + &mut p, + FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar }, + &now, + ) { report.sidecars += 1; report.warnings.extend(sc.warnings.into_iter().map(|mut warning| { warning.path = path.clone(); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 2f051c7b7f2..9cfa3758d02 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -156,7 +156,13 @@ impl Prepared { existing: Some(existing), reason: if existing_path.is_some() { "path" } else { "content" }, hash: info.content_hash, - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar })), + file: Some(Box::new(FileFacts { + meta: info.meta, + captured: info.captured, + orientation: info.orientation, + upright_by: info.upright_by, + sidecar, + })), }); } else { items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup }))); @@ -551,7 +557,13 @@ impl ImportJob { existing, reason: "content", hash: Some(hash), - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, upright_by: info.upright_by, sidecar })), + file: Some(Box::new(FileFacts { + meta: info.meta, + captured: info.captured, + orientation: info.orientation, + upright_by: info.upright_by, + sidecar, + })), })); continue; } From 43f2fe75118d6f98ef8674580f712ec01edf23ed Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:03:31 +1100 Subject: [PATCH 23/25] LR-LIB-PEOPLE: read TIFF entries with as_chunks (clippy::chunks_exact_to_as_chunks) The lint is newer than #4512. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/orientation.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs index 591596e8ea7..41f5903b2d8 100644 --- a/crates/codecs/src/orientation.rs +++ b/crates/codecs/src/orientation.rs @@ -214,8 +214,7 @@ fn tiff(f: &mut At) -> io::Result> { } let Some(entries) = f.block(ifd.saturating_add(2), 12 * u64::from(u16_of(count)))? else { return Ok(None) }; let mut found = None; - for e in entries.chunks_exact(12) { - let [t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] = <[u8; 12]>::try_from(e).unwrap_or_default(); + for &[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] in entries.as_chunks::<12>().0 { if u16_of([t0, t1]) != 274 { continue; } From 383be5e93cadfd67da826df6038f3a23bf1aeedd Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:34:13 +1100 Subject: [PATCH 24/25] LR-LIB-PEOPLE: answer the review of the face region writer - A save with face boxes to write for a photo catalogued before its orientation was kept reads the orientation from the file, so the boxes go in the stored frame; when it can't be read, the sidecar's region list and PersonInImage are left as they are. Convert to DNG does the same. - A box too small for the six decimals it is written with isn't written, nor is its name. - Only Face regions' names are taken as names that went with a face: a person typed in elsewhere stays when a pet has the same name. - When the file's region list is left as it is, its PersonInImage is too; a list carrying pixel boxes of another size is now left as it is. - Entries carried from the file keep the namespace bindings in scope where they start. - Read Metadata from File keeps the first read of a raw's bytes. - docs/faces.md says the detector's unnamed boxes aren't written. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/convert.rs | 7 +- crates/engine/src/sidecar.rs | 222 ++++++++++++++++++++++++++----- crates/engine/src/tests/xmp.rs | 43 +++++- docs/faces.md | 4 +- docs/xmp-interop.md | 11 +- 5 files changed, 243 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index cf0991f4e3d..3c12aaba4de 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -82,7 +82,12 @@ fn convert(s: &mut Session, p: &Value) -> Result { ])); continue; } - let packet = crate::sidecar::sidecar_packet(&ph, &s.catalog); + // face boxes go in by the raw's orientation, read from it for a photo catalogued before it was kept; none go in + // when it can't be told + let packet = match crate::sidecar::with_writing_orientation(&ph, path) { + Some(q) => crate::sidecar::sidecar_packet(&q, &s.catalog), + None => crate::sidecar::sidecar_packet_with(&ph, &s.catalog, false), + }; match write_dng_for(s, path, packet) { Ok(out) => { let file_name = Path::new(&out).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index eb4f60ada40..ba63fe2726e 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -508,8 +508,9 @@ fn upright_orientation(path: &str, max: u64) -> crate::files::Orientations { pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { // the regions go into the photo's own sidecar only: an export's packet describes the picture as exported, which a // crop or a resize leaves the boxes no longer fit - // the file's own orientation, as the catalog keeps it, decides how the boxes are written (`with_regions`): a save - // never reads the photo file (for a raw that would be the whole file, for every photo of a batch) + // the file's own orientation, as the catalog keeps it, decides how the boxes are written (`with_regions`); this never + // reads the photo file (for a raw that would be the whole file). A save reads it only for a photo catalogued before + // the orientation was kept ([`with_writing_orientation`]) with_regions(sidecar_packet_with(p, cat, false), p, p.meta.file_orientation) } @@ -572,15 +573,20 @@ fn is_detected(r: &lightcraft_meta::Region) -> bool { } /// A box as it is written: each coordinate clipped to the photo (an infinite one becomes its edge), kept only if it -/// still has an area. One with none left (empty, entirely off the photo, a coordinate that isn't a number) is never -/// written, and a photo with only such boxes has none to write. +/// still has an area as written. One with none left (empty, entirely off the photo, narrower than the six decimals +/// it is written with, a coordinate that isn't a number) is never written, nor is its name, and a photo with only such +/// boxes has none to write. fn writable_rect(r: lightcraft_meta::Rect) -> Option<(f64, f64, f64, f64)> { let (x0, y0) = (r.x0.clamp(0.0, 1.0), r.y0.clamp(0.0, 1.0)); let (x1, y1) = (r.x1.clamp(0.0, 1.0), r.y1.clamp(0.0, 1.0)); // (`clamp` keeps NaN, which fails these comparisons) - (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1)) + (x1 - x0 >= SMALLEST_WRITTEN && y1 - y0 >= SMALLEST_WRITTEN).then_some((x0, y0, x1, y1)) } +/// The smallest width or height a box is written with: `stArea:w`/`h` have six decimals, and a smaller size would be +/// written as 0, which a reader drops. +const SMALLEST_WRITTEN: f64 = 1e-6; + /// The packets a save of a photo's sidecar chooses from ([`fit_to_old`]). #[derive(Clone)] struct Fresh { @@ -590,11 +596,14 @@ struct Fresh { /// with no rotation (Exif 5, 7): only the list's `AppliedToDimensions` tells that frame, so a save that has to /// leave the size out, or keeps an entry whose `mwg-rs:Rotation` makes readers ignore the size, writes this one. upright: Option, + /// `packet` leaves the photo's face boxes and names out because the frame to write them in can't be told: the + /// file's region list and `Iptc4xmpExt:PersonInImage` stay as they are. + keep_faces: bool, } impl From for Fresh { fn from(packet: String) -> Self { - Fresh { packet, upright: None } + Fresh { packet, upright: None, keep_faces: false } } } @@ -603,7 +612,35 @@ fn sidecar_packets(p: &Photo, cat: &lightcraft_catalog::Catalog) -> Fresh { let upright = unrotated_stored_frame(p, p.meta.file_orientation) .then(|| with_regions(sidecar_packet_with(p, cat, false), p, None)) .filter(|_| !file_regions(p).is_empty()); - Fresh { packet: sidecar_packet(p, cat), upright } + Fresh { packet: sidecar_packet(p, cat), upright, keep_faces: false } +} + +/// `p` with the orientation its face boxes are written by ([`with_regions`]): the catalog's +/// ([`lightcraft_catalog::Meta::file_orientation`]), else, for a photo catalogued before it was kept that has boxes to +/// write, its file's at `original`, as Read Metadata from File reads them back (the import's rule: a raw is read whole, +/// within the media limit; another image only where its orientation is). `None` when it has boxes to write and the +/// orientation can't be told: an upright box would land elsewhere in an application that places boxes on the photo as +/// stored, so none is written. +pub(crate) fn with_writing_orientation<'a>(p: &'a Photo, original: &str) -> Option> { + if p.meta.file_orientation.is_some() || file_regions(p).is_empty() { + return Some(std::borrow::Cow::Borrowed(p)); + } + let probe = upright_orientation(original, crate::read_file::MAX_MEDIA_BYTES); + let o = probe.kept.or(probe.read_by)?; + let mut q = p.clone(); + q.meta.file_orientation = Some(o); + Some(std::borrow::Cow::Owned(q)) +} + +/// [`Fresh`] for a save of `p`'s sidecar next to its file at `original` ([`with_writing_orientation`]). +fn packets_for_save(p: &Photo, cat: &lightcraft_catalog::Catalog, original: &str) -> Fresh { + match with_writing_orientation(p, original) { + Some(q) => sidecar_packets(&q, cat), + None => { + log::warn!("{original}: its orientation can't be read, so its face regions were not written; the sidecar's are left as they are"); + Fresh { packet: sidecar_packet_with(p, cat, false), upright: None, keep_faces: true } + } + } } /// Whether `p`'s boxes are written in the frame its file is stored in with no rotation: a quarter turn and a mirror @@ -765,6 +802,16 @@ fn fit_to_old(old: &str, fresh: Fresh) -> String { let Ok(data) = lightcraft_meta::parse_xmp(old) else { return fresh.packet; }; + // the file's list as it is: kept whole when the file's region list is (below), so the two still name the same people + let listed: Vec = data + .values + .get("Iptc4xmpExt:PersonInImage") + .map(|v| v.items().iter().filter_map(|i| i.text()).map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).collect()) + .unwrap_or_default(); + // the photo's faces can't be written: the file's stay as they are, and the names with them + if fresh.keep_faces { + return into_description(fresh.packet, &people_block(&listed)); + } // its regions; if they can't be read, every name in its list is kept as typed in elsewhere let regions = parse_sidecar(old, crate::crs::Target::Rendered).ok().and_then(|sc| sc.regions); let readable = regions.as_ref().map_or(0, Vec::len); @@ -776,13 +823,12 @@ fn fit_to_old(old: &str, fresh: Fresh) -> String { _ => fresh.packet, }; let lower = |s: &str| s.trim().to_lowercase(); - let face_names: Vec = regions.iter().flatten().filter_map(|r| r.name.as_deref()).map(lower).collect(); - let typed: Vec = data - .values - .get("Iptc4xmpExt:PersonInImage") - .map(|v| v.items().iter().filter_map(|i| i.text()).map(|t| t.trim().to_string()).collect()) - .unwrap_or_default(); - let typed: Vec = typed.into_iter().filter(|t| !t.is_empty() && !face_names.contains(&lower(t))).collect(); + // only faces' names: a pet called Rex says nothing about a person called Rex typed in elsewhere + let face_names: Vec = + regions.iter().flatten().filter(|r| r.kind == lightcraft_meta::RegionKind::Face).filter_map(|r| r.name.as_deref()).map(lower).collect(); + let typed: Vec = listed.iter().filter(|t| !face_names.contains(&lower(t))).cloned().collect(); + // entries LightCraft can't read that it can't single out: the file's region list stays as it is, written or cleared + let mut keep_old = carried.is_none(); // the packet's own list, taken out let mut names: Vec = lightcraft_meta::parse_xmp(&fresh) @@ -802,7 +848,15 @@ fn fit_to_old(old: &str, fresh: Fresh) -> String { } } if fresh.contains(REGIONS_OPEN) { + // boxes in pixels are placed by the list's size: under another size they would mean other places (one off the + // photo could land on it), so the file's list stays as it is + let resized = carried.as_ref().is_some_and(|c| c.pixels && c.dims.is_some() && c.dims.as_ref().and_then(dims_of) != stated_dims(&fresh)); match carried { + Some(_) if resized => { + log::warn!("a face region list with boxes in pixels of another size was left as it is; its own regions were not written to it"); + fresh = cut(fresh, REGIONS_OPEN, REGIONS_CLOSE); + keep_old = true; + } // the file's entries LightCraft can't read go on after the photo's own, as they were Some(c) => { if !c.items.is_empty() { @@ -846,16 +900,28 @@ fn fit_to_old(old: &str, fresh: Fresh) -> String { fresh = into_description(fresh, &format!("{REGIONS_OPEN}{dims} \n{list} \n{REGIONS_CLOSE}")); } } - let fitted = into_description(fresh, &people_block(&names)); + let fitted = into_description(fresh.clone(), &people_block(if keep_old { &listed } else { &names })); // the file's own entries went in as text: never write a packet that doesn't parse as namespaced XML let opts = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1 << 20, ..Default::default() }; if roxmltree::Document::parse_with_options(&fitted, opts).is_err() || lightcraft_meta::parse_xmp(&fitted).is_err() { log::warn!("a face region list couldn't be written with the file's own entries; the file's list was left as it is"); - return cut(fitted, REGIONS_OPEN, REGIONS_CLOSE); + return into_description(cut(fresh, REGIONS_OPEN, REGIONS_CLOSE), &people_block(&listed)); } fitted } +/// A list's `AppliedToDimensions` as numbers, `None` when either isn't one. +fn dims_of((w, h): &(String, String)) -> Option<(f64, f64)> { + Some((w.trim().parse().ok()?, h.trim().parse().ok()?)) +} + +/// The `AppliedToDimensions` of the region list in `packet`, as numbers. +fn stated_dims(packet: &str) -> Option<(f64, f64)> { + let data = lightcraft_meta::parse_xmp(packet).ok()?; + let d = data.values.get("mwg-rs:Regions")?.field("mwg-rs:AppliedToDimensions")?; + dims_of(&(d.field("stDim:w")?.text()?.to_string(), d.field("stDim:h")?.text()?.to_string())) +} + const REGIONS_OPEN: &str = " \n"; const REGIONS_CLOSE: &str = " \n"; const REGION_LIST_CLOSE: &str = " \n \n"; @@ -881,6 +947,8 @@ struct Carried { items: Vec, /// The list's `AppliedToDimensions` (width, height), as written. dims: Option<(String, String)>, + /// One of them is in pixels. + pixels: bool, /// One of them is in pixels and the list has no size. pixels_without_size: bool, /// One of them has a `mwg-rs:Rotation`: a reader then takes the whole list as marked by rotation, not by its size @@ -904,7 +972,7 @@ fn unreadable_regions(old: &str, data: &lightcraft_meta::XmpData, readable: usiz let dims = regions .and_then(|r| r.field("mwg-rs:AppliedToDimensions")) .and_then(|d| Some((d.field("stDim:w")?.text()?.to_string(), d.field("stDim:h")?.text()?.to_string()))); - let mut carried = Carried { items: Vec::new(), dims, pixels_without_size: false, rotation: false }; + let mut carried = Carried { items: Vec::new(), dims, pixels: false, pixels_without_size: false, rotation: false }; if n <= readable { return Some(carried); } @@ -943,6 +1011,7 @@ fn unreadable_regions(old: &str, data: &lightcraft_meta::XmpData, readable: usiz if carried.items.len() != n - readable { return None; } + carried.pixels = any_pixels; carried.pixels_without_size = any_pixels && carried.dims.is_none(); Some(carried) } @@ -956,17 +1025,20 @@ fn with_namespaces(doc: &str, node: &roxmltree::Node) -> Option { let tag_end = node.children().next().map_or(node.range().end, |c| c.range().start).min(node.range().end); let start_tag = doc.get(node.range().start..tag_end)?; let own_qname = qname_of(node.range().start + 1)?; + // each prefix used in it, bound as it is where the element starts: one that an element inside binds again keeps + // that binding in its own start tag, and one bound only inside needs nothing here let mut used: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for e in node.descendants().filter(roxmltree::Node::is_element) { - let q = qname_of(e.range().start + 1)?; - let prefix = q.split_once(':').map_or("", |(p, _)| p); - if let Some(uri) = e.tag_name().namespace() { + let mut note = |prefix: &str| { + if let Some(uri) = node.lookup_namespace_uri((!prefix.is_empty()).then_some(prefix)) { used.insert(prefix.to_string(), uri.to_string()); } + }; + for e in node.descendants().filter(roxmltree::Node::is_element) { + let q = qname_of(e.range().start + 1)?; + note(q.split_once(':').map_or("", |(p, _)| p)); for a in e.attributes() { - let q = doc.get(a.range_qname())?; - if let (Some((prefix, _)), Some(uri)) = (q.split_once(':'), a.namespace()) { - used.insert(prefix.to_string(), uri.to_string()); + if let Some((prefix, _)) = doc.get(a.range_qname())?.split_once(':') { + note(prefix); } } } @@ -1517,7 +1589,8 @@ impl Session { self.validate_sidecar_packets_for_paths(std::slice::from_ref(&path), &crate::rename::RealFs)?; let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let err = |e: std::io::Error| EngineError::Other(format!("{}: {e}", path.display())); - let (data, merged, backup) = sidecar_contents(&path, sidecar_packets(p, &self.catalog), &(self.clock)()).map_err(err)?; + let fresh = packets_for_save(p, &self.catalog, file_path(p).unwrap_or_default()); + let (data, merged, backup) = sidecar_contents(&path, fresh, &(self.clock)()).map_err(err)?; write_atomic(&path, data.as_bytes()).map_err(err)?; self.note_sidecar_write(&path, data.as_bytes()); Ok(SidecarSaved { path, merged, backup }) @@ -1538,9 +1611,14 @@ impl Session { let lookup = self.sidecar_lookup(id); let unknown = p.meta.file_orientation.is_none(); // a raw with no sidecar is read whole for its embedded XMP anyway: the orientation comes from the same bytes - let raw_bytes = (unknown && p.kind == MediaKind::Raw && lookup.find(orig).is_none()) - .then(|| crate::read_file::read_regular(orig, crate::read_file::MAX_MEDIA_BYTES).ok()) - .flatten(); + // (one that fails fails the read, as `find_packet` would: the file isn't read again for the packet) + let raw_bytes = match (unknown && p.kind == MediaKind::Raw && lookup.find(orig).is_none()) + .then(|| crate::read_file::read_regular(orig, crate::read_file::MAX_MEDIA_BYTES)) + { + Some(Ok(bytes)) => Some(bytes), + Some(Err(e)) => return Err(EngineError::Other(format!("{orig} can't be read: {e}"))), + None => None, + }; let mut probed: Option = None; let backfill_now = |probed: &mut Option| { *probed.get_or_insert_with(|| match &raw_bytes { @@ -2295,15 +2373,93 @@ mod tests { // LightCraft's reader takes a sidecar roxmltree won't parse (one with a DTD): the unreadable entry can't be // singled out, so rather than lose it the save leaves the file's list as it is let path = scratch("odd-list"); - let old = sidecar_with_pixel_entry(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))]); + let old = sidecar_with_pixel_entry(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))]).replace( + "", + "Ann", + ); let odd = format!("\n{old}"); assert!(lightcraft_meta::parse_xmp(&odd).is_ok(), "LightCraft's reader takes it"); assert!(unreadable_regions(&odd, &lightcraft_meta::parse_xmp(&odd).unwrap(), 1).is_none(), "roxmltree doesn't"); - std::fs::write(&path, &odd).unwrap(); let mut p = photo(); - p.meta.regions = vec![region(0.3, 0.3, 0.4, 0.4, lightcraft_meta::RegionKind::Face, Some("New"), None)]; - let (x, _, _) = sidecar_contents(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); - assert_eq!(entry_names(&x), ["Ann", "Pixel Box"], "the file's list is left: {x}"); + // Ann renamed, or her box removed: either way the list and the names the file has stay together + for regions in [vec![region(0.4, 0.4, 0.6, 0.6, lightcraft_meta::RegionKind::Face, Some("New"), None)], vec![]] { + std::fs::write(&path, &odd).unwrap(); + p.meta.regions = regions; + let (x, _, _) = sidecar_contents(&path, sidecar_packet(&p, &lightcraft_catalog::Catalog::new()), "now").unwrap(); + assert_eq!(entry_names(&x), ["Ann", "Pixel Box"], "the file's list is left: {x}"); + assert_eq!(people_in(&x), ["Ann"], "and the names that go with it: {x}"); + } + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + /// The `Iptc4xmpExt:PersonInImage` names a packet lists. + fn people_in(x: &str) -> Vec { + let d = lightcraft_meta::parse_xmp(x).unwrap(); + d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text().map(str::to_string)).collect()).unwrap_or_default() + } + + #[test] + fn a_box_too_small_to_write_takes_its_name_with_it() { + use lightcraft_meta::RegionKind::Face; + let mut p = photo(); + // narrower than the six decimals a box is written with: it would be written as 0 wide, and dropped on reading + p.meta.regions = vec![region(0.25, 0.2, 0.2500004, 0.4, Face, Some("Tiny"), None), region(0.5, 0.5, 0.6, 0.6, Face, Some("Ann"), None)]; + let x = sidecar_packet(&p, &lightcraft_catalog::Catalog::new()); + assert_eq!((entry_names(&x), people_in(&x)), (vec!["Ann".to_string()], vec!["Ann".to_string()]), "{x}"); + } + + #[test] + fn a_person_typed_in_elsewhere_stays_when_a_pet_has_the_same_name() { + let path = scratch("pet-name"); + let old = + sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Rex"))], &["Rex"]).replace("Face", "Pet"); + std::fs::write(&path, &old).unwrap(); + let mut p = photo(); + merge_into(&mut p, &parse_sidecar(&old, crate::crs::Target::Rendered).unwrap(), "now"); + assert_eq!(p.meta.regions[0].kind, lightcraft_meta::RegionKind::Pet); + assert_eq!(people_in(&save_over(&path, &p)), ["Rex"]); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn boxes_in_pixels_of_another_size_keep_the_files_list() { + // a box in pixels off a 300 × 200 photo: unreadable, and on the photo if the list took a 600 × 400 size + let path = scratch("pixels-resized"); + let off = r#"FaceOff"#; + let old = sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann"))], &["Ann"]) + .replace("", &format!("{off}")) + .replace( + "", + "", + ); + std::fs::write(&path, &old).unwrap(); + let mut p = photo(); + (p.width, p.height) = (600, 400); + p.meta.regions = vec![region(0.1, 0.1, 0.2, 0.2, lightcraft_meta::RegionKind::Face, Some("New"), None)]; + let x = save_over(&path, &p); + assert_eq!((entry_names(&x), people_in(&x)), (vec!["Ann".to_string(), "Off".to_string()], vec!["Ann".to_string()]), "{x}"); + let read: Vec = + parse_sidecar(&x, crate::crs::Target::Rendered).unwrap().regions.unwrap_or_default().into_iter().filter_map(|r| r.name).collect(); + assert_eq!(read, ["Ann"], "Off stays off the photo"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn a_kept_entry_keeps_the_namespaces_its_fields_had() { + // an entry off the photo (kept as written) with a field in `p` as the description binds it, then a field + // binding `p` again for itself + let path = scratch("rebound-prefix"); + let old = sidecar_with(&[(0.5, 0.5, 0.2, 0.2, Some("Ann")), (5.0, 5.0, 0.1, 0.1, Some("Off"))], &[]) + .replace("Off", "Offouterinner") + .replace("photomechanic:ColorClass", "xmlns:p=\"urn:outer\" photomechanic:ColorClass"); + std::fs::write(&path, &old).unwrap(); + let mut p = photo(); + p.meta.regions = vec![region(0.1, 0.1, 0.2, 0.2, lightcraft_meta::RegionKind::Face, Some("New"), None)]; + let x = save_over(&path, &p); + assert_eq!(entry_names(&x), ["New", "Off"], "{x}"); + let doc = roxmltree::Document::parse(&x).unwrap(); + let ns = |text: &str| doc.descendants().find(|n| n.is_element() && n.text() == Some(text)).and_then(|n| n.tag_name().namespace()); + assert_eq!((ns("outer"), ns("inner")), (Some("urn:outer"), Some("urn:inner")), "{x}"); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index d33d9bc8b22..2ab12ceaa7a 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2377,8 +2377,9 @@ fn a_removed_face_leaves_a_second_library_too_and_undo_brings_it_back() { let _ = std::fs::remove_dir_all(&src); } -/// Review of #4512: a save never reads the photo file for its orientation; a photo catalogued before the orientation -/// was kept has its boxes written upright until Read Metadata from File reads it (with or without a packet to read). +/// Review of #4512 and #4973: a save takes the orientation from the catalog; for a photo catalogued before it was kept, +/// the save reads it from the file, so the boxes are written in the stored frame without the catalog changing, and +/// Read Metadata from File keeps it (with or without a packet to read). #[test] fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { use lightcraft_meta::{Orientation, Rect, Region, RegionKind}; @@ -2396,9 +2397,10 @@ fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { vec![Region { rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); if with_packet { - // saved upright: the file isn't read for it + // saved in the stored frame, as Lightroom places it: the file is read for it; a save changes no catalog s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); - assert!(!std::fs::read_to_string(src.join("t.xmp")).unwrap().contains("mwg-rs:Rotation")); + assert!(std::fs::read_to_string(src.join("t.xmp")).unwrap().contains("-1.57080")); + assert_eq!(s.catalog.photo(id).unwrap().meta.file_orientation, None); } // Read Metadata from File reads it s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); @@ -2414,6 +2416,39 @@ fn the_orientation_comes_from_the_catalog_and_read_metadata_fills_it_in() { } } +/// Review of #4973: a photo catalogued before its orientation was kept, whose file's orientation can't be read, has no +/// frame to write its face boxes in: a save leaves the sidecar's boxes and names as they are, and writes the rest. +#[test] +fn a_save_leaves_the_sidecars_faces_when_the_orientation_cant_be_told() { + use lightcraft_meta::{Rect, Region, RegionKind}; + let src = temp_dir("face-orientation-untold"); + write_turned_jpeg(&src.join("t.jpg"), None); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.file_orientation = None; + meta.regions = + vec![Region { rect: Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.6 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }]; + s.commit("Old", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let before = std::fs::read_to_string(src.join("t.xmp")).unwrap(); + assert!(before.contains("Ann"), "{before}"); + // the original can't be read for its orientation now; Ann is renamed and the photo rated + std::fs::write(src.join("t.jpg"), b"not a photo any more").unwrap(); + s.execute("faces.setName", &json!({"id": id.0, "index": 0, "name": "Bea"})).unwrap(); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": 4})).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let x = std::fs::read_to_string(src.join("t.xmp")).unwrap(); + let d = lightcraft_meta::parse_xmp(&x).unwrap(); + assert_eq!(d.values.get("xmp:Rating").and_then(|v| v.text()), Some("4"), "the rest is written: {x}"); + assert!(x.contains("Ann") && !x.contains("Bea"), "the boxes are left: {x}"); + let people: Vec<&str> = + d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text()).collect()).unwrap_or_default(); + assert_eq!(people, ["Ann"], "and the names with them: {x}"); + let _ = std::fs::remove_dir_all(&src); +} + /// Review of #4512: a face on a photo stored turned and mirrored (Exif 5) is written in the frame of the photo as /// stored, with the stored size, and reading the sidecar back puts it on the same face of the upright photo. #[test] diff --git a/docs/faces.md b/docs/faces.md index 131de0561e6..23d19af6824 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -2,7 +2,9 @@ LightCraft reads the face names other apps (Lightroom, digiKam…) write into your photos, shows them in the loupe (boxes you can switch off, resize and remove), groups photos by person in the People view, and writes the boxes and -names into the photo's XMP sidecar when it saves one (see [XMP interop](xmp-interop.md#face-regions-mwg)). This page is about the +names into the photo's XMP sidecar when it saves one (see [XMP interop](xmp-interop.md#face-regions-mwg)). A box +LightCraft's own detector finds is written once you name it; until then it is kept in the library only, so a backup +of your sidecars doesn't keep it. This page is about the *models* that find and recognise faces by themselves. ## Nothing is bundled; every model is an opt-in download diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index f77a3de1964..5f80ee23980 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -133,11 +133,12 @@ write them, from sidecars and from XMP embedded in the file. Named faces become written upright. A photo mirrored without a turn (2, 4) or a square one looks the same either way, so its boxes are written upright, as LightCraft reads them; MWG readers that apply the mirror place those mirrored. Orientation 1 is written upright. The file's orientation is the one - the import read, kept in the catalog: a save never reads the photo file for it, and neither does reading a sidecar - back (Read Metadata from File, Synchronize Folder) when the catalog knows it. A photo catalogued before LightCraft - kept it has its boxes written upright until Read Metadata from File reads it: by the import's rule, only for a photo - with face boxes, from the file read at most once and within the media size limit. Either way they read back as they - were. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions + the import read, kept in the catalog: a save doesn't read the photo file for it, and neither does reading a sidecar + back (Read Metadata from File, Synchronize Folder) when the catalog knows it. For a photo catalogued before LightCraft + kept it, a save with face boxes to write reads it from the file, by the import's rule (a raw is read whole, within + the media size limit; another image only where its orientation is), and Read Metadata from File keeps it so later + saves don't read it again. When it can't be read, the save leaves the sidecar's region list and + `Iptc4xmpExt:PersonInImage` as they are, and writes everything else. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar that never had one gets none, an empty one stays empty, and a list LightCraft reads nothing from (pixel areas with From b66c27ce0b54730e0d7c3ec97bd5f221d736f6d4 Mon Sep 17 00:00:00 2001 From: SamLovick <39815276+SamLovick@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:12:27 +1100 Subject: [PATCH 25/25] LR-LIB-PEOPLE: a save that leaves the faces out says so, and names are listed as written From CodeRabbit's second review of #4973: - When a photo's orientation can't be read, Save Metadata to File lists it under facesNotWritten, and an automatic write keeps it waiting with the failed writes until its faces can be written. - PersonInImage lists each name once as it is written: characters XML can't carry are dropped before the duplicate check, and a name left empty isn't written. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/xmp.rs | 8 +++-- crates/engine/src/lib.rs | 5 +-- crates/engine/src/sidecar.rs | 62 ++++++++++++++++++++++++++-------- crates/engine/src/tests/xmp.rs | 14 +++++++- docs/xmp-interop.md | 4 ++- 5 files changed, 73 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/xmp.rs b/crates/engine/src/cmd/xmp.rs index 49922ce992a..be048874abf 100644 --- a/crates/engine/src/cmd/xmp.rs +++ b/crates/engine/src/cmd/xmp.rs @@ -12,6 +12,7 @@ fn save(s: &mut Session, p: &Value) -> Result { let mut merged = Vec::new(); let mut backups = Vec::new(); let mut failed = Vec::new(); + let mut faces_not_written = Vec::new(); let ids = s.targets(p)?; let owners = crate::sidecar::StemOwners::among(&s.catalog, &ids); for id in ids { @@ -21,6 +22,9 @@ fn save(s: &mut Session, p: &Value) -> Result { if r.merged { merged.push(path.clone()); } + if r.faces_left { + faces_not_written.push(json!({"id": id.0, "path": path, "error": "the file's orientation can't be read, so its face regions and names were not written; the sidecar's are left as they are"})); + } if let Some(b) = r.backup { backups.push(json!({"path": path, "backup": b.display().to_string()})); } @@ -29,7 +33,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Err(e) => failed.push(json!({"id": id.0, "error": e.to_string()})), } } - Ok(json!({"written": written, "merged": merged, "backups": backups, "failed": failed})) + Ok(json!({"written": written, "merged": merged, "backups": backups, "failed": failed, "facesNotWritten": faces_not_written})) } fn read(s: &mut Session, p: &Value) -> Result { @@ -86,7 +90,7 @@ pub fn specs() -> Vec { "Save Metadata to File", ["Photo", "Metadata"], Some("Cmd+S"), - "{ids?} — writes each photo's XMP sidecar (metadata + develop settings) next to the original, merged into an existing one (other apps' data kept; an unreadable one is backed up first) → {written: [path], merged: [path], backups: [{path, backup}], failed}", + "{ids?} — writes each photo's XMP sidecar (metadata + develop settings) next to the original, merged into an existing one (other apps' data kept; an unreadable one is backed up first) → {written: [path], merged: [path], backups: [{path, backup}], failed, facesNotWritten: [{id, path, error}] (written without the photo's face regions and names, its file's orientation unreadable; the sidecar's are kept)}", has_selection, save ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6042b51c8e8..9e1fb5ae17e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -289,8 +289,9 @@ pub struct Session { pub(crate) skip_auto_write: bool, /// The order of Reload from Disk runs, so an older one finishing late is dropped ([`cmd::reload`]). pub(crate) reload_tickets: cmd::reload::Tickets, - /// Photos whose automatic XMP sidecar write failed (their folder offline, read-only or full), written again by - /// [`Session::retry_unsaved_sidecars`] once their file is reachable. + /// Photos whose automatic XMP sidecar write failed (their folder offline, read-only or full), or left out their + /// face regions ([`sidecar::SidecarSaved::faces_left`]), written again by [`Session::retry_unsaved_sidecars`] once + /// their file is reachable. pub(crate) unsaved_sidecars: std::collections::BTreeSet, /// AI denoise: the model in use, the photos that have their picture and the work in progress. pub(crate) denoise: denoise::State, diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index ba63fe2726e..2643a6c4381 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -652,30 +652,40 @@ fn unrotated_stored_frame(p: &Photo, orientation: Option Vec { let mut names: Vec = Vec::new(); for r in file_regions(p).into_iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { - let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; + let Some(n) = r.name.as_deref().and_then(written_name) else { continue }; if !names.iter().any(|m| m.to_lowercase() == n.to_lowercase()) { - names.push(n.to_string()); + names.push(n); } } names } -/// Text for an XML element's content. +/// A region's name as the sidecar carries it: without the characters XML 1.0 can't ([`xml_char`]), trimmed; `None` +/// when nothing is left. +fn written_name(n: &str) -> Option { + let n: String = n.chars().filter(|c| xml_char(*c)).collect(); + let n = n.trim(); + (!n.is_empty()).then(|| n.to_string()) +} + +/// Whether XML 1.0 can carry `c` in an element's content. +fn xml_char(c: char) -> bool { + matches!(c, '\t' | '\n' | '\r') || !((c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}') +} + +/// Text for an XML element's content; the characters XML 1.0 can't carry are dropped ([`xml_char`]). fn xml_text(s: &str) -> String { let mut o = String::with_capacity(s.len()); - for c in s.chars() { + for c in s.chars().filter(|c| xml_char(*c)) { match c { '&' => o.push_str("&"), '<' => o.push_str("<"), '>' => o.push_str(">"), - // characters XML 1.0 can't carry are dropped - '\t' | '\n' | '\r' => o.push(c), - c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {} c => o.push(c), } } @@ -742,8 +752,8 @@ fn with_regions(packet: String, p: &Photo, orientation: Option{}\n", xml_text(kind))); } - if let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) { - x.push_str(&format!(" {}\n", xml_text(n))); + if let Some(n) = r.name.as_deref().and_then(written_name) { + x.push_str(&format!(" {}\n", xml_text(&n))); } if let Some(d) = r.description.as_deref().filter(|d| !d.trim().is_empty() && !d.starts_with(crate::cmd::face_detect::MARK)) { x.push_str(&format!(" {}\n", xml_text(d))); @@ -1129,6 +1139,9 @@ pub struct SidecarSaved { pub merged: bool, /// An existing sidecar that couldn't be read as XMP was copied here before being replaced. pub backup: Option, + /// The photo's face regions and names weren't written, because its file's orientation can't be read (a photo + /// catalogued before it was kept: [`with_writing_orientation`]); the sidecar's are left as they are. + pub faces_left: bool, } /// The new contents for the sidecar at `path`: `fresh` merged into the existing file, if any. @@ -1590,10 +1603,11 @@ impl Session { let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let err = |e: std::io::Error| EngineError::Other(format!("{}: {e}", path.display())); let fresh = packets_for_save(p, &self.catalog, file_path(p).unwrap_or_default()); + let faces_left = fresh.keep_faces; let (data, merged, backup) = sidecar_contents(&path, fresh, &(self.clock)()).map_err(err)?; write_atomic(&path, data.as_bytes()).map_err(err)?; self.note_sidecar_write(&path, data.as_bytes()); - Ok(SidecarSaved { path, merged, backup }) + Ok(SidecarSaved { path, merged, backup, faces_left }) } /// The op that applies a photo's sidecar (or embedded XMP) to the catalog, if there is one. @@ -1712,9 +1726,13 @@ impl Session { for id in ids { if self.catalog.photo(id).is_some_and(|p| file_path(p).is_some() && p.copy_of.is_none()) { match self.save_sidecar_with(id, &owners) { - Ok(_) => { + Ok(r) if !r.faces_left => { self.unsaved_sidecars.remove(&id); } + // the rest was written; the faces wait for the file's orientation, as a write that failed does + Ok(_) => { + self.unsaved_sidecars.insert(id); + } Err(e) => { // kept for a retry once the file is reachable: a network share that dropped out mustn't leave // the sidecar silently behind the edit @@ -1756,10 +1774,11 @@ impl Session { let mut written = 0; for id in ready { match self.save_sidecar_with(id, &owners) { - Ok(_) => { + Ok(r) if !r.faces_left => { self.unsaved_sidecars.remove(&id); written += 1; } + Ok(_) => {} Err(e) => log::debug!("retry XMP: {e}"), } } @@ -2408,6 +2427,21 @@ mod tests { assert_eq!((entry_names(&x), people_in(&x)), (vec!["Ann".to_string()], vec!["Ann".to_string()]), "{x}"); } + #[test] + fn names_are_listed_once_as_written() { + use lightcraft_meta::RegionKind::Face; + let mut p = photo(); + // a control character XML can't carry is dropped: "a\u{1}b" is written "ab", and a name of nothing else isn't one + p.meta.regions = vec![ + region(0.1, 0.1, 0.2, 0.2, Face, Some("a\u{1}b"), None), + region(0.3, 0.3, 0.4, 0.4, Face, Some("ab"), None), + region(0.5, 0.5, 0.6, 0.6, Face, Some("\u{2}"), None), + ]; + let x = sidecar_packet(&p, &lightcraft_catalog::Catalog::new()); + assert_eq!(people_in(&x), ["ab"], "{x}"); + assert_eq!(entry_names(&x), ["ab", "ab", ""], "{x}"); + } + #[test] fn a_person_typed_in_elsewhere_stays_when_a_pet_has_the_same_name() { let path = scratch("pet-name"); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 2ab12ceaa7a..2b9dbd4108d 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -2438,7 +2438,8 @@ fn a_save_leaves_the_sidecars_faces_when_the_orientation_cant_be_told() { std::fs::write(src.join("t.jpg"), b"not a photo any more").unwrap(); s.execute("faces.setName", &json!({"id": id.0, "index": 0, "name": "Bea"})).unwrap(); s.execute("photo.rate", &json!({"ids": [id.0], "rating": 4})).unwrap(); - s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(r["facesNotWritten"].as_array().map(Vec::len), Some(1), "the save says so: {r}"); let x = std::fs::read_to_string(src.join("t.xmp")).unwrap(); let d = lightcraft_meta::parse_xmp(&x).unwrap(); assert_eq!(d.values.get("xmp:Rating").and_then(|v| v.text()), Some("4"), "the rest is written: {x}"); @@ -2446,6 +2447,17 @@ fn a_save_leaves_the_sidecars_faces_when_the_orientation_cant_be_told() { let people: Vec<&str> = d.values.get("Iptc4xmpExt:PersonInImage").map(|v| v.items().iter().filter_map(|i| i.text()).collect()).unwrap_or_default(); assert_eq!(people, ["Ann"], "and the names with them: {x}"); + // written automatically, the photo waits until its orientation can be read, and its faces are written then + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + s.execute("faces.setName", &json!({"id": id.0, "index": 0, "name": "Cy"})).unwrap(); + assert_eq!(s.unsaved_sidecars(), 1, "the faces wait"); + let r = s.execute("library.retrySidecars", &json!({})).unwrap(); + assert_eq!(r["waiting"], 1, "still unreadable: {r}"); + write_turned_jpeg(&src.join("t.jpg"), None); + let r = s.execute("library.retrySidecars", &json!({})).unwrap(); + assert_eq!(r["waiting"], 0, "{r}"); + let x = std::fs::read_to_string(src.join("t.xmp")).unwrap(); + assert!(x.contains("Cy") && !x.contains(">Ann<"), "{x}"); let _ = std::fs::remove_dir_all(&src); } diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 5f80ee23980..ff00591c60c 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -138,7 +138,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become kept it, a save with face boxes to write reads it from the file, by the import's rule (a raw is read whole, within the media size limit; another image only where its orientation is), and Read Metadata from File keeps it so later saves don't read it again. When it can't be read, the save leaves the sidecar's region list and - `Iptc4xmpExt:PersonInImage` as they are, and writes everything else. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions + `Iptc4xmpExt:PersonInImage` as they are, and writes everything else; Save Metadata to File lists the photo under + `facesNotWritten`, and with automatic writing on the photo waits with the sidecar writes that failed, to be written + again once its orientation can be read. When the photo has no regions left to write (none, or only the detector's) but the sidecar has regions LightCraft read, an empty list is written, so another library reading the file drops them too. Otherwise the sidecar's own list stays: a sidecar that never had one gets none, an empty one stays empty, and a list LightCraft reads nothing from (pixel areas with