LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge main into fix/issue-92-xmp-merge
Brandon Thomas577330a08b64
diff --cc crates/engine/src/sidecar.rsindex 7b65a98a6,fb25871c5..69bf8f0f0--- a/crates/engine/src/sidecar.rs+++ b/crates/engine/src/sidecar.rs@@@ -271,112 -258,11 +271,101 @@@ pub fn sidecar_packet(p: &Photo, cat: &lightcraft_meta::write_xmp_lc(&meta, &lc)}-/// Write `data` to `path` atomically (temp file + sync + rename).+/// 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.+pub const OWNED: &[&str] = &[+ "xmp:Rating",+ "xmp:Label",+ "dc:title",+ "dc:description",+ "dc:rights",+ "dc:creator",+ "dc:subject",+ "Iptc4xmpCore:Location",+ "Iptc4xmpCore:AltTextAccessibility",+ "Iptc4xmpCore:ExtDescrAccessibility",+ "photoshop:City",+ "photoshop:State",+ "photoshop:Country",+ "xmpRights:Marked",+ "xmpRights:UsageTerms",+ "xmpRights:WebStatement",+ "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"];++/// 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<()> {- use std::io::Write;- let tmp = path.with_extension(format!("xmp.tmp-{}", std::process::id()));- let r = (|| {- let mut f = std::fs::File::create(&tmp)?;- f.write_all(data)?;- f.sync_all()?;- std::fs::rename(&tmp, path)- })();- if r.is_err() {- let _ = std::fs::remove_file(&tmp);- }- r+ lightcraft_catalog::safe_file::write_atomic(path, data)}+/// Copy `path` to a new `<name>.bak-<stamp>` (`-1`, `-2`… if taken; never overwriting).+fn backup(path: &Path, stamp: &str) -> std::io::Result<PathBuf> {+ use std::io::Write;+ let bytes = std::fs::read(path)?;+ let stamp: String = stamp.chars().filter(char::is_ascii_alphanumeric).collect();+ let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+ for k in 0..1000 {+ let b = path.with_file_name(if k == 0 { format!("{name}.bak-{stamp}") } else { format!("{name}.bak-{stamp}-{k}") });+ match std::fs::OpenOptions::new().write(true).create_new(true).open(&b) {+ Ok(mut f) => {+ f.write_all(&bytes)?;+ f.sync_all()?;+ return Ok(b);+ }+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(e) => return Err(e),+ }+ }+ Err(std::io::Error::other("no free backup name"))+}++/// What [`Session::save_sidecar`] did.+#[derive(Clone, Debug, PartialEq)]+pub struct SidecarSaved {+ pub path: PathBuf,+ /// An existing sidecar was merged into (its other contents kept).+ pub merged: bool,+ /// An existing sidecar that couldn't be read as XMP was copied here before being replaced.+ pub backup: Option<PathBuf>,+}++/// 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<PathBuf>)> {+ let bytes = match std::fs::read(path) {+ Ok(b) => b,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh, 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));+ }+ let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED };+ match std::str::from_utf8(&bytes)+ .map_err(|e| e.to_string())+ .and_then(|old| lightcraft_meta::merge_xmp(old, &fresh, rules).map_err(|e| e.to_string()))+ {+ Ok(merged) => Ok((merged, true, None)),+ Err(why) => {+ 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)))+ }+ }+}++/// Key of the stem sidecar a file maps to (case-insensitive).+fn stem_key(original: &str) -> String {+ sidecar_path(original, SidecarNaming::Stem).to_string_lossy().to_lowercase()+}+fn file_path(p: &Photo) -> Option<&str> {match &p.source {Source::File { path } => Some(path),diff --cc docs/whats-new.mdindex e46584c9d,0a188bd64..53c29a5f2--- a/docs/whats-new.md+++ b/docs/whats-new.md@@@ -10,11 -10,22 +10,27 @@@- 23 new built-in presets: Portrait, Landscape, Urban, Food, Seasons, Vintage and B&W toners.### Reliability+ - Exports and renders never write over a photo's original (issue #93): exporting into the photo's own folder with+ the same name and "Overwrite" (or Export with Previous repeating it), an exact output path from the control+ channel or MCP, a merge preview path or `lightcraft-cli render IMG.jpg -o IMG.jpg` is refused with a clear+ message, and the original is left byte for byte. Ordinary earlier exports are still overwritten when asked.+ Exported files are written to a temp file, synced and then renamed into place, so a full disk or an unplugged+ drive never leaves a truncated file; the XMP sidecar of an "Original" export follows the "If file exists"+ choice too.+ - Convert to DNG, Copy as DNG, Photo Merge and smart previews no longer write straight to the final file (issue+ #106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its+ name (never replacing a file), and only then is the photo relinked or the raw copy removed — a failed write+ leaves no DNG and keeps the raw. Smart previews are written the same way; a damaged one (cut short by a crash or+ a full drive) no longer counts as built and Build Smart Previews replaces it.+ - Import ▸ Copy verifies every copy, like Move (issue #96): each file is written as a new file, synced to disk and+ compared byte for byte with the card. A copy that fails or differs is removed and reported as a failed import —+ so "import complete" means the copies are good before you format the card — and a name that is taken gets -1,+ -2… instead of being replaced.+- Saving metadata to an XMP sidecar another application wrote no longer replaces it (issue #92): LightCraft merges its+ fields in and keeps the rest — e.g. that application's develop settings and edit history — byte for byte. A+ sidecar that isn't valid XMP is copied to `<name>.xmp.bak-<time>` first. With the default stem naming, a raw and a+ JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,+ the JPEG uses `IMG_0001.JPG.xmp`.- Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and othermodels whose sensor starts on a green-blue row) no longer come out magenta (issue #85): the colour-filterlayout is read from each file instead of assumed.