LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Lightroom import: follow catalog paths only on this computer or the catalog's share
aiongg346681561ade
diff --git a/Cargo.lock b/Cargo.lockindex 4b6d54289..c70a2adba 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1072,6 +1072,10 @@ dependencies = ["libc",]+[[package]]+name = "craft-docpath"+version = "0.1.0"+[[package]]name = "craft-ui"version = "0.1.0"@@ -3217,6 +3221,7 @@ name = "lightcraft-engine"version = "0.8.0"dependencies = ["ab_glyph",+ "craft-docpath","harfrust","jxl-oxide","libc",diff --git a/Cargo.toml b/Cargo.tomlindex ac8cbeca1..8f08431b2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,6 +11,7 @@ repository = "https://github.com/storytold/lightcraft"[workspace.dependencies]craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }+craft-docpath = { path = "../secfix-craft-libs/crates/docpath" }# internallightcraft-denoise-core = { path = "crates/denoise-core" }lightcraft-denoise = { path = "crates/denoise", default-features = false }diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex ed20cd605..091efe066 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -9,6 +9,8 @@ description = "LightCraft engine: session, command registry, history, render jobworkspace = true[dependencies]+# Paths stored in a Lightroom catalog are followed only to local files or the catalog's share.+craft-docpath = { workspace = true }lightcraft-geom = { workspace = true }lightcraft-color = { workspace = true }lightcraft-raster = { workspace = true }diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex 7b0e1e562..860cf089f 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -1488,7 +1488,7 @@ pub fn specs() -> Vec<CommandSpec> {always, |_, p| {let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?;let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?;- Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !std::path::Path::new(&p.path).is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings}))+ Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings}))}),cmd!("library.importLightroom",diff --git a/crates/engine/src/doc_path.rs b/crates/engine/src/doc_path.rsnew file mode 100644index 000000000..c2b0e9f69--- /dev/null+++ b/crates/engine/src/doc_path.rs@@ -0,0 +1,63 @@+//! Paths stored in a file LightCraft reads but the user did not choose path by path, such as the+//! originals a Lightroom catalog lists.+//!+//! Such a path reaches the file system only through [`resolve`]: a relative path is taken from the+//! document's folder, and only local files, or files on the network share the document itself is+//! on, are looked at (see `craft_docpath`). A path that is not followed is handled like a missing+//! file.++use std::fmt;+use std::path::{Path, PathBuf};++pub use craft_docpath::Refused;++/// Why a stored path is not followed.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NotFollowed {+ /// The path is on another computer (other than the document's share), names a device, is a+ /// URL, or is not a usable path.+ Refused(Refused),+ /// The path is not an absolute path on this computer, such as a Windows drive path read on+ /// macOS or Linux.+ NotHere,+}++impl fmt::Display for NotFollowed {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Refused(r) => r.fmt(f),+ Self::NotHere => f.write_str("the path is not a path on this computer"),+ }+ }+}++impl std::error::Error for NotFollowed {}++/// The file to look at for `stored`, a path or `file:` URL stored in the document at `document`,+/// or why it is not followed. A relative `document` is taken from the working directory, where it+/// was opened from.+pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, NotFollowed> {+ let document = document.map(|d| if d.is_relative() { std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf()) } else { d.to_path_buf() });+ let path = craft_docpath::resolve(stored, document.as_deref()).map_err(NotFollowed::Refused)?;+ // A path that is still relative would be taken from the working directory, which the+ // document does not choose.+ if path.is_relative() {+ return Err(NotFollowed::NotHere);+ }+ Ok(path)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn relative_paths_are_taken_from_the_document_folder_and_other_computers_are_refused() {+ let doc = std::env::temp_dir().join("lrcat").join("catalog.lrcat");+ assert_eq!(resolve("Photos/a.jpg", Some(&doc)), Ok(std::env::temp_dir().join("lrcat").join("Photos").join("a.jpg")));+ assert_eq!(resolve("a.jpg", None), Err(NotFollowed::NotHere));+ assert_eq!(resolve(r"\\192.0.2.1\share\x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network)));+ assert_eq!(resolve("file://192.0.2.1/s/x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network)));+ assert_eq!(resolve(r"\\.\COM1", Some(&doc)), Err(NotFollowed::Refused(Refused::Device)));+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 8a282ce3e..1e9c18d99 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -29,6 +29,7 @@ pub mod demo;pub mod denoise;pub mod devices;pub mod display;+pub mod doc_path;mod errors;pub mod export;pub mod face_download;diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rsindex 0dceb421d..5133fc80c 100644--- a/crates/engine/src/lightroom_archive.rs+++ b/crates/engine/src/lightroom_archive.rs@@ -538,6 +538,7 @@ mod tests {keywords: vec!["Trips|Goa".into()],history: vec![BTreeMap::from([("text".into(), serde_json::json!("step")), ("curve".into(), serde_json::json!([0, 128, 255]))])],snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("before"))])],+ original: crate::lightroom_catalog::Original::Local,};CatalogImport {source: "source.lrcat".into(),@@ -621,6 +622,7 @@ mod tests {keywords: Vec::new(),history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])],snapshots: Vec::new(),+ original: crate::lightroom_catalog::Original::Local,}).collect();assert_eq!(store_best_effort(&path, &input).unwrap(), None);diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rsindex 777206bcb..d60d60582 100644--- a/crates/engine/src/lightroom_catalog.rs+++ b/crates/engine/src/lightroom_catalog.rs@@ -2,7 +2,7 @@//! Lightroom, Python and a C SQLite runtime are not needed. Original paths stay in place.//! Raw settings are archived before mutation; mapped edits are approximations, not Adobe renders.use std::collections::{BTreeMap, HashMap, HashSet};-use std::path::{Component, Path, PathBuf};+use std::path::{Path, PathBuf};use std::sync::{Arc,atomic::{AtomicBool, AtomicUsize, Ordering},@@ -146,6 +146,31 @@ pub struct CatalogPhoto {pub keywords: Vec<String>,pub history: Vec<Row>,pub snapshots: Vec<Row>,+ /// Whether `path` may be looked at (derived when the catalog is read; not archived).+ #[serde(skip)]+ pub original: Original,+}++/// Whether the original a catalog lists may be looked at. Its path is resolved with the catalog+/// as the document ([`crate::doc_path::resolve`]).+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub enum Original {+ /// `path` is a local file path, or one on the network share the catalog is on.+ Local,+ /// `path` is not a path on this computer (a catalog made on another system): the photo is+ /// kept as an offline record for later relinking, and the path is not looked at.+ #[default]+ NotHere,+ /// `path` is refused (why): it is on another computer or a device, or its folder or file name+ /// is an absolute path. The photo is reported missing and not added to the library.+ Refused(String),+}++impl CatalogPhoto {+ /// Whether the original is a file here; only a [`Original::Local`] path is looked at.+ pub fn original_is_file(&self) -> bool {+ self.original == Original::Local && Path::new(&self.path).is_file()+ }}#[derive(Clone, Debug, Serialize, Deserialize)]@@ -343,25 +368,36 @@ fn committed_wal_len(main: &[u8], wal: &[u8]) -> Result<usize, String> {/// Where a root folder is when its `absolutePath` isn't a folder here (the catalog came from/// another computer): `relativePathFromCatalog`, which Lightroom records for roots on the-/// catalog's volume, resolved against the catalog's folder, if that is a folder.+/// catalog's volume, resolved against the catalog's folder, if that is a folder. Both paths are+/// looked at only when [`crate::doc_path::resolve`] follows them.fn relocated_root(absolute: &str, relative: &str, catalog: &Path) -> Option<PathBuf> {- if relative.is_empty() || !Path::new(relative).is_relative() || Path::new(absolute).is_dir() {+ if relative.is_empty() || !Path::new(relative).is_relative() || crate::doc_path::resolve(absolute, Some(catalog)).is_ok_and(|p| p.is_dir()) {return None;}- let dir = std::path::absolute(catalog).ok()?.parent()?.join(relative);- let mut out = PathBuf::new();- for part in dir.components() {- match part {- Component::ParentDir => {- if !out.pop() {- return None;- }- }- Component::CurDir => {}- part => out.push(part),- }+ crate::doc_path::resolve(relative, Some(catalog)).ok().filter(|dir| dir.is_dir())+}++/// Whether a folder path or file name from the catalog is absolute: `Path::join` would put it in+/// place of the root folder.+fn is_absolute_part(part: &str) -> bool {+ let bytes = part.as_bytes();+ part.starts_with(['/', '\\'])+ || (bytes.first().is_some_and(u8::is_ascii_alphabetic) && bytes.get(1) == Some(&b':'))+ || Path::new(part).is_absolute()+}++/// The path of an original under `root` and whether it may be looked at, resolved with the+/// catalog at `catalog` as the document.+fn original_path(root: &str, folder: &str, name: &str, catalog: &Path) -> (String, Original) {+ let stored = Path::new(root).join(folder).join(name).to_string_lossy().to_string();+ if is_absolute_part(folder) || is_absolute_part(name) {+ return (stored, Original::Refused("its folder or file name is an absolute path".into()));+ }+ match crate::doc_path::resolve(&stored, Some(catalog)) {+ Ok(found) => (found.to_string_lossy().to_string(), Original::Local),+ Err(crate::doc_path::NotFollowed::NotHere) => (stored, Original::NotHere),+ Err(crate::doc_path::NotFollowed::Refused(why)) => (stored, Original::Refused(why.to_string())),}- out.is_dir().then_some(out)}/// Inspect `.lrcat` plus committed WAL pages without modifying either source file.@@ -457,6 +493,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,out};let mut root_paths = HashMap::new();+ let mut refused_roots = HashSet::new();let mut root_ids: Vec<_> = roots.keys().copied().collect();root_ids.sort_unstable();for (id, root) in root_ids.iter().filter_map(|id| Some((*id, roots.get(id)?))) {@@ -469,6 +506,11 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,}None => absolute.to_string(),};+ if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(path)) {+ warnings+ .push(format!("root folder {}: {resolved} is not opened: {why}; its photos are listed as missing and not added", text(root, "name")));+ refused_roots.insert(id);+ }root_paths.insert(id, resolved);}let mut history = group(optional_table("Adobe_libraryImageDevelopHistoryStep", &mut warnings)?);@@ -487,13 +529,19 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,let file = files.get(&number(&image, "rootFile")).ok_or_else(|| format!("image {id}: missing file record"))?;let folder = folders.get(&number(file, "folder")).ok_or_else(|| format!("image {id}: missing folder record"))?;let root = roots.get(&number(folder, "rootFolder")).ok_or_else(|| format!("image {id}: missing root record"))?;- let root_path = root_paths.get(&number(root, "id_local")).map_or("", String::as_str);+ let root_id = number(root, "id_local");+ let root_path = root_paths.get(&root_id).map_or("", String::as_str);let folder_path = text(folder, "pathFromRoot");let name = text(file, "idx_filename");if root_path.is_empty() || name.is_empty() {return Err(format!("image {id}: incomplete original path"));}- let path = Path::new(root_path).join(folder_path).join(name).to_string_lossy().to_string();+ let (photo_path, original) = original_path(root_path, folder_path, name, path);+ if let Original::Refused(why) = &original+ && !refused_roots.contains(&root_id)+ {+ out.warnings.push(format!("image {id}: {photo_path} is not opened: {why}; listed as missing and not added"));+ }let packet = match xmp(metadata.get(&id).and_then(|r| r.get("xmp"))) {Ok(s) => s,Err(e) => {@@ -504,13 +552,14 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,out.photos.push(CatalogPhoto {source_id: id,uuid: text(&image, "id_global").into(),- path,+ path: photo_path,image,settings: develops.get(&id).cloned().unwrap_or_default(),xmp: packet,keywords: keywords.remove(&id).unwrap_or_default(),history: history.remove(&id).unwrap_or_default(),snapshots: snapshots.remove(&id).unwrap_or_default(),+ original,});}ensure_read_active(cancel)?;@@ -665,11 +714,11 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) ->let paths: Vec<_> = data.photos.iter()- .filter(|p| number(&p.image, "masterImage") == 0 && !existing.contains_key(&key(&p.path)) && Path::new(&p.path).is_file())+ .filter(|p| number(&p.image, "masterImage") == 0 && !existing.contains_key(&key(&p.path)) && p.original_is_file()).map(|p| p.path.clone()).collect();let missing_sources: HashSet<String> =- data.photos.iter().filter(|p| number(&p.image, "masterImage") == 0).filter(|p| !Path::new(&p.path).is_file()).map(|p| key(&p.path)).collect();+ data.photos.iter().filter(|p| number(&p.image, "masterImage") == 0).filter(|p| !p.original_is_file()).map(|p| key(&p.path)).collect();let files = crate::import::import(s, &paths, crate::import::ImportMode::Add)?;let applied =apply_prepared(s, data, ApplyPrepared { update_existing, files, index: &mut index, archive_path, missing_sources: &missing_sources, undo0 })?;@@ -713,12 +762,18 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, data: CatalogImport, contexlet mut photos: Vec<_> = data.photos.iter().collect();photos.sort_by_key(|p| number(&p.image, "masterImage") != 0);let copy_masters: HashSet<_> = data.photos.iter().map(|p| number(&p.image, "masterImage")).filter(|id| *id != 0).collect();+ let refused: HashSet<_> = data.photos.iter().filter(|p| matches!(p.original, Original::Refused(_))).map(|p| p.source_id).collect();let mut planned: HashMap<PhotoId, Photo> = HashMap::new();for src in photos {let master = number(&src.image, "masterImage");if master == 0 && missing_sources.contains(&key(&src.path)) {missing.push(src.path.clone());}+ // A refused path must not become a library record the app would look at later; its+ // virtual copies go with it.+ if refused.contains(&src.source_id) || refused.contains(&master) {+ continue;+ }let indexed = index.photos.get(&identity(&data, src))@@ -940,6 +995,7 @@ mod tests {keywords: vec!["Travel|Goa".into()],history: vec![row(json!({"text":"s = { Exposure2012 = 0.5 }"}))],snapshots: Vec::new(),+ original: Original::Local,};let mut copy = photo.clone();copy.source_id = 2;@@ -1508,11 +1564,57 @@ mod tests {// a relative path that leads nowhere keeps the recorded onestd::fs::write(&path, native_catalog(&photo_tables(("C:/Users/me/Project/RAW/", "../Elsewhere/")))).unwrap();let catalog = read(&path).unwrap();- assert!(catalog.photos[0].path.starts_with("C:/Users/me/Project/RAW/"), "{}", catalog.photos[0].path);+ assert!(Path::new(&catalog.photos[0].path).starts_with("C:/Users/me/Project/RAW/"), "{}", catalog.photos[0].path);assert!(catalog.warnings.is_empty(), "{:?}", catalog.warnings);std::fs::remove_dir_all(dir).unwrap();}+ #[test]+ fn originals_on_other_computers_are_never_looked_at_or_added() {+ let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-remote-roots-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("Photos")).unwrap();+ std::fs::write(dir.join("Photos/test.ARW"), b"original").unwrap();+ let source = dir.join("source.lrcat");+ let mut roots = vec![r"\\192.0.2.1\share\".to_string(), "file://192.0.2.1/s/".to_string()];+ if cfg!(unix) {+ // `//<local folder>/` is a local folder to Linux, but a network path to the resolver.+ roots.push(format!("/{}/", dir.display()));+ }+ for root in &roots {+ std::fs::write(&source, native_catalog(&photo_tables((root, "")))).unwrap();+ let catalog = read(&source).unwrap();+ assert!(matches!(catalog.photos[0].original, Original::Refused(_)), "{root}: {:?}", catalog.photos[0]);+ assert!(catalog.warnings.iter().any(|w| w.contains("not opened")), "{root}: {:?}", catalog.warnings);+ let mut s = crate::Session::new();+ let probes = Arc::new(AtomicUsize::new(0));+ let calls = probes.clone();+ s.media.file_probe = Some(Arc::new(move |_| {+ calls.fetch_add(1, Ordering::Relaxed);+ Err("a refused original must not be probed".into())+ }));+ let report = import(&mut s, &source, false).unwrap();+ assert_eq!(probes.load(Ordering::Relaxed), 0, "{root}");+ assert_eq!(report["missing"].as_array().map(Vec::len), Some(1), "{root}: {report}");+ assert!(s.catalog.is_empty(), "{root}");+ }+ // An absolute folder path would replace the root.+ let mut tables = photo_tables((dir.to_str().unwrap(), ""));+ tables[1].2[2] = SqlValue::Text(format!("{}/Photos/", dir.display()));+ std::fs::write(&source, native_catalog(&tables)).unwrap();+ assert!(matches!(read(&source).unwrap().photos[0].original, Original::Refused(_)));+ // A root beside the catalog is followed.+ std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap();+ let catalog = read(&source).unwrap();+ assert_eq!(catalog.photos[0].original, Original::Local);+ assert!(catalog.photos[0].original_is_file());+ // A root that moved is found through its path relative to the catalog.+ std::fs::write(&source, native_catalog(&photo_tables((r"\\192.0.2.1\share\", "./")))).unwrap();+ let catalog = read(&source).unwrap();+ assert!(catalog.photos[0].original_is_file(), "{:?}", catalog.photos[0]);+ std::fs::remove_dir_all(dir).unwrap();+ }+#[test]fn oversized_optional_table_warns_and_is_skipped() {let mut main = vec![0u8; 2 * 512];diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rsindex 8de1cc806..52a51b30f 100644--- a/crates/engine/src/lightroom_job.rs+++ b/crates/engine/src/lightroom_job.rs@@ -329,7 +329,7 @@ fn original_paths(data: &CatalogImport, cancel: &AtomicBool) -> crate::Result<(Vif !seen.insert(key.clone()) {continue;}- if Path::new(&photo.path).is_file() {+ if photo.original_is_file() {paths.push(photo.path.clone());} else {missing.insert(key);@@ -393,6 +393,7 @@ mod tests {keywords: Vec::new(),history: Vec::new(),snapshots: Vec::new(),+ original: lightroom_catalog::Original::Local,}],collections: Vec::new(),members: Vec::new(),@@ -531,6 +532,7 @@ mod tests {serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))),)])],snapshots: Vec::new(),+ original: lightroom_catalog::Original::Local,}}).collect();diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rsindex d7ea85122..241a23d6b 100644--- a/crates/ui-egui/src/lightroom_import.rs+++ b/crates/ui-egui/src/lightroom_import.rs@@ -233,7 +233,7 @@ fn inspect_report(data: lightcraft_engine::lightroom_catalog::CatalogImport) ->json!({"photos": data.photos.len(),"collections": data.collections.iter().filter(|r| r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0) == 0.0).count(),- "missing": data.photos.iter().filter(|p| !std::path::Path::new(&p.path).is_file()).map(|p| &p.path).collect::<Vec<_>>(),+ "missing": data.photos.iter().filter(|p| !p.original_is_file()).map(|p| &p.path).collect::<Vec<_>>(),"warnings": data.warnings,})}diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.mdindex 5ad4383fd..b6c0014f0 100644--- a/docs/lightroom-catalog-import.md+++ b/docs/lightroom-catalog-import.md@@ -97,3 +97,12 @@ the path relative to the catalog that Lightroom records for root folders on the(`relativePathFromCatalog`), when that is a folder, and reports the remapping as a warning. Copyinga project folder with its catalog inside it therefore keeps its originals linked. Other movedoriginals stay missing; use LightCraft's missing-photo relinking tools to update their paths.++Original and root folder paths are resolved with the catalog as the document and are looked at+only when they are on this computer or on the network share the catalog itself is on+(`crates/engine/src/doc_path.rs`). An original on another computer (`\\server\share\…`,+`//server/…`, `file://server/…`), a device path, or one whose folder or file name in the catalog is+an absolute path is not looked at: the import lists it as missing with a warning and leaves the+photo and its virtual copies out of the library. To import originals on a share, open the catalog+from that share. A path that is not a path on this computer (a Windows drive path read on macOS or+Linux) is not looked at either and stays catalogued as missing.