Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Engine: folder.synchronize acts on the scan the person saw

Nathaniel Ledford5345f0a3cf44
diff --git a/crates/engine/src/cmd/sync.rs b/crates/engine/src/cmd/sync.rs
index 1aefe94b7..ecb252df6 100644
--- a/crates/engine/src/cmd/sync.rs
+++ b/crates/engine/src/cmd/sync.rs
@@ -23,7 +23,9 @@ pub fn specs() -> Vec<CommandSpec> {
const C: &str = "folder.scanChanges";
let path = path(p, C)?;
let changes = scan(s, &path).map_err(|e| bad(C, e.to_string()))?;
- Ok(serde_json::to_value(changes).unwrap_or_default())
+ let v = serde_json::to_value(&changes).unwrap_or_default();
+ s.folder_changes = Some(changes);
+ Ok(v)
}
),
cmd!(
@@ -31,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Synchronize Folder",
[],
None,
- "{path, importNew?: true, removeMissing?: false, readMetadata?: false} — bring a folder of the library up to date with the disk (see folder.scanChanges): import its new files in place, move photos whose file is gone to Recently Deleted, read XMP sidecars saved by other apps (the sidecar wins); one undo step, no file is touched → {imported, removed, read, failed: [[path, error]]}",
+ "{path, importNew?: true, removeMissing?: false, readMetadata?: false} — bring a folder of the library up to date with the disk (see folder.scanChanges): import its new files in place, move photos whose file is gone to Recently Deleted, read XMP sidecars saved by other apps (the sidecar wins); acts on the last folder.scanChanges of the folder while nothing changed in the library since (else scans again); one undo step, no file is touched → {imported, removed, read, failed: [[path, error]]}",
always,
sync
),
@@ -47,7 +49,10 @@ fn sync(s: &mut Session, p: &Value) -> Result<Value> {
remove_missing: bool_or(p, "removeMissing", d.remove_missing),
read_metadata: bool_or(p, "readMetadata", d.read_metadata),
};
- let changes = scan(s, &path).map_err(|e| bad(C, e.to_string()))?;
+ let changes = match s.take_folder_changes(&path) {
+ Some(c) => c,
+ None => scan(s, &path).map_err(|e| bad(C, e.to_string()))?,
+ };
let r = synchronize(s, changes, choice)?;
Ok(json!({"imported": r.imported, "removed": r.removed, "read": r.read, "failed": r.failed}))
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index feeeccc60..02c3cd9c1 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -253,6 +253,9 @@ pub struct Session {
pub before: std::collections::HashMap<PhotoId, Arc<DevelopSettings>>,
/// File probes from the last import review (`library.importPreview`), reused by the import.
pub import_probes: std::collections::HashMap<String, media::ProbeInfo>,
+ /// The last Synchronize Folder scan, which `folder.synchronize` acts on while it is current
+ /// (see [`Session::take_folder_changes`]).
+ pub folder_changes: Option<sync::FolderChanges>,
/// The last (or running) Build Previews.
pub preview_build: Option<std::sync::Arc<cmd::previews::PreviewBuild>>,
/// Develop defaults applied on import (persisted in prefs.json).
@@ -335,6 +338,7 @@ impl Session {
recent_keywords: Vec::new(),
before: Default::default(),
import_probes: Default::default(),
+ folder_changes: None,
preview_build: None,
import_defaults: import::ImportDefaults::default(),
cache_mb: 0,
diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs
index c91e47fa0..2012381fa 100644
--- a/crates/engine/src/sync.rs
+++ b/crates/engine/src/sync.rs
@@ -42,6 +42,7 @@ const MAX_SIDECAR_BYTES: u64 = 16 * 1024 * 1024;
/// What a scan of a folder needs, taken from the session so it can run on a worker thread.
pub struct SyncInput {
folder: String,
+ revision: u64,
scan: ScanInput,
/// The library's photos in the folder, each with how its sidecar is named.
photos: Vec<(Arc<Photo>, SidecarNaming)>,
@@ -67,6 +68,9 @@ pub struct FolderChanges {
/// The probes of the new files, kept for the import that follows.
#[serde(skip)]
probes: HashMap<String, ProbeInfo>,
+ /// The catalog revision the scan was made against.
+ #[serde(skip)]
+ revision: u64,
}
/// A photo of the folder and its file.
@@ -122,15 +126,15 @@ impl SyncInput {
}
let photos = ids.iter().filter_map(|id| s.catalog.photo(*id).map(|p| (Arc::clone(p), s.sidecar_naming(*id)))).collect();
let (scan, _) = ScanInput::new(s, &[path.to_string()]);
- Ok(SyncInput { folder: path.to_string(), scan, photos, labels: s.catalog.clone() })
+ Ok(SyncInput { folder: path.to_string(), revision: s.catalog.revision, scan, photos, labels: s.catalog.clone() })
}
}
/// Find what changed in the folder (see the module docs). Reads the disk, never the session.
pub fn scan_with(input: SyncInput, progress: &ScanProgress) -> FolderChanges {
- let SyncInput { folder, scan, photos, labels } = input;
+ let SyncInput { folder, revision, scan, photos, labels } = input;
let out = crate::import::scan_with(scan, std::slice::from_ref(&folder), progress);
- let mut changes = FolderChanges { path: folder, probes: out.probes, ..Default::default() };
+ let mut changes = FolderChanges { path: folder, probes: out.probes, revision, ..Default::default() };
for c in out.candidates {
match (&c.duplicate, &c.error) {
(Some(d), _) if d == "path" => {}
@@ -159,6 +163,16 @@ pub fn scan(s: &mut Session, path: &str) -> Result<FolderChanges> {
Ok(scan_with(input, &ScanProgress::default()))
}
+impl Session {
+ /// The last scan ([`Session::folder_changes`]) if it is of folder `path` and nothing changed
+ /// in the library since: what the person was shown is what gets done. Used once.
+ pub fn take_folder_changes(&mut self, path: &str) -> Option<FolderChanges> {
+ let c = self.folder_changes.take()?;
+ let same = lightcraft_catalog::query::folder_key(&c.path) == lightcraft_catalog::query::folder_key(path);
+ (same && c.revision == self.catalog.revision).then_some(c)
+ }
+}
+
/// Whether `p`'s XMP sidecar file was saved after the library last had its say about the photo
/// (imported, or edited here) and says something the library doesn't.
fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming) -> bool {
diff --git a/crates/engine/src/tests_sync.rs b/crates/engine/src/tests_sync.rs
index 4822f1172..46a77fd21 100644
--- a/crates/engine/src/tests_sync.rs
+++ b/crates/engine/src/tests_sync.rs
@@ -209,3 +209,31 @@ fn only_a_folder_of_the_library_is_synchronized() {
assert!(s.execute(cmd, &p).is_err(), "{cmd}: {why}");
}
}
+
+#[test]
+fn synchronizing_acts_on_the_changes_just_scanned() {
+ let dir = Scratch::new("cached");
+ let mut s = library(&dir);
+ write_png(&dir.path("trip/c.png"), 3);
+ let r = scan(&mut s, &dir.path("trip"));
+ assert_eq!(paths(&r, "new").len(), 1);
+ // arrived after the scan the person was shown: not part of what they agreed to
+ write_png(&dir.path("trip/d.png"), 4);
+ let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip")})).unwrap();
+ assert_eq!(r["imported"], 1, "{r}");
+ // the scan is used once; the next synchronize looks again
+ let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip")})).unwrap();
+ assert_eq!(r["imported"], 1, "d.png now: {r}");
+}
+
+#[test]
+fn a_scan_is_stale_once_the_library_changed() {
+ let dir = Scratch::new("stale");
+ let mut s = library(&dir);
+ write_png(&dir.path("trip/c.png"), 3);
+ scan(&mut s, &dir.path("trip"));
+ // c.png comes in some other way between the scan and the synchronize
+ s.execute("library.import", &json!({"paths": [dir.path("trip/c.png")]})).unwrap();
+ let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip")})).unwrap();
+ assert_eq!(r["imported"], 0, "the library changed: it looked again: {r}");
+}