Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/missing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn stored_hash(p: &Photo) -> Option<&str> {

/// The content hash of the file at `path` (as import computes it), if it can be read. Read in
/// pieces: the file is whatever is on the disk, of any size.
fn file_hash(path: &str) -> Option<String> {
pub(crate) fn file_hash(path: &str) -> Option<String> {
hash_reader(std::fs::File::open(path).ok()?)
}

Expand Down
73 changes: 59 additions & 14 deletions crates/engine/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ pub struct FolderMoved {
pub id: u64,
pub from: String,
pub to: String,
/// The content hash the scan read at `to`. Synchronizing relinks only while the file there
/// still has it: a scan of a big folder is confirmed minutes later, and a file put in its
/// place by then is not the photo. `None` when the scan had no file probe, and then there is
/// nothing to compare. Not part of the command's reply.
#[serde(skip)]
pub hash: Option<String>,
}

/// What [`synchronize`] does with the changes found.
Expand Down Expand Up @@ -293,17 +299,29 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges {
let missing = std::mem::take(&mut changes.missing);
for m in missing {
match moved_from.get(&m.path) {
Some(to) => changes.moved.push(FolderMoved { id: m.id, from: m.path, to: to.clone() }),
Some(to) => {
let hash = out.probes.get(to).and_then(|p| p.content_hash.clone());
changes.moved.push(FolderMoved { id: m.id, from: m.path, to: to.clone(), hash });
}
None => changes.missing.push(m),
}
}
changes.probes = out.probes;
changes
}

/// Whether a photo is the same as far as synchronizing goes: its file, its place in the library
/// and what a sidecar is compared with. Face and pet regions found in the background meanwhile
/// don't make a scan stale.
/// Whether a photo is the same file in the same place in the library: what decides whether it
/// is missing or moved, and which files beside it are new. Its rating, keywords and edits are
/// the person's work, not the folder's state.
fn same_file(a: &Arc<Photo>, b: &Arc<Photo>) -> bool {
Arc::ptr_eq(a, b)
|| (&a.source, a.deleted, a.local, a.copy_of, &a.content_hash, a.file_size)
== (&b.source, b.deleted, b.local, b.copy_of, &b.content_hash, b.file_size)
}

/// Whether a photo is the same as far as reading its sidecar goes: its file, its place in the
/// library and what a sidecar is compared with. Face and pet regions found in the background
/// meanwhile don't make a scan stale.
fn same_for_sync(a: &Arc<Photo>, b: &Arc<Photo>) -> bool {
if Arc::ptr_eq(a, b) {
return true;
Expand Down Expand Up @@ -577,19 +595,35 @@ fn not_there(path: &str) -> EngineError {

impl Session {
/// The last scan ([`Session::folder_changes`]) if it is of folder `path` and still current:
/// the folder holds the same photos, none of them changed. What the person was shown is what
/// gets done. Used once. (Changes elsewhere in the library don't matter.)
/// the folder holds the same photos (virtual copies aside), each the same file in the same
/// place ([`same_file`]).
/// What the person was shown is what gets done. Used once.
///
/// Work on the folder's photos since (ratings, labels, keywords, edits) leaves the scan
/// current: none of it changes which files are new, missing or moved, and a scan of a big
/// folder on a slow disk takes minutes in which the person is told to go on working. The one
/// thing such work does matter to is a sidecar the scan found news in: reading it would go
/// over that work, so for those photos nothing may have changed ([`same_for_sync`]).
/// (Changes elsewhere in the library don't matter.)
pub fn take_folder_changes(&mut self, path: &str) -> Option<FolderChanges> {
let c = self.folder_changes.take()?;
if lightcraft_catalog::query::folder_key(&c.path) != lightcraft_catalog::query::folder_key(path) {
return None;
}
let f = Filter { library_folder: Some(path.to_string()), ..Default::default() };
let mut now: Vec<PhotoId> = self.catalog.query(&f, &Sort::default());
let mut then: Vec<PhotoId> = c.seen.iter().map(|p| p.id).collect();
// (virtual copies made or deleted meanwhile are not files: the folder holds what it held,
// except for copies of photos the scan relinks or removes, which are acted on by id and
// would be left behind)
let acted: std::collections::HashSet<u64> = c.moved.iter().map(|m| m.id).chain(c.missing.iter().map(|m| m.id)).collect();
let counts = |p: &Photo| p.copy_of.is_none_or(|o| acted.contains(&o.0));
let mut now: Vec<PhotoId> =
self.catalog.query(&f, &Sort::default()).into_iter().filter(|id| self.catalog.photo(*id).is_some_and(|p| counts(p))).collect();
let mut then: Vec<PhotoId> = c.seen.iter().filter(|p| counts(p)).map(|p| p.id).collect();
now.sort();
then.sort();
let unchanged = now == then && c.seen.iter().all(|p| self.catalog.photo(p.id).is_some_and(|q| same_for_sync(p, q)));
let read: std::collections::HashSet<u64> = c.metadata.iter().map(|m| m.id).collect();
let same = |p: &Arc<Photo>, q: &Arc<Photo>| if read.contains(&p.id.0) { same_for_sync(p, q) } else { same_file(p, q) };
let unchanged = now == then && c.seen.iter().filter(|p| p.copy_of.is_none()).all(|p| self.catalog.photo(p.id).is_some_and(|q| same(p, q)));
unchanged.then_some(c)
}
}
Expand Down Expand Up @@ -763,11 +797,22 @@ impl SyncWork {
if cancel.load(Relaxed) {
return;
}
// still where the scan found it, and still gone from where the photo says
let checked = moved.len();
let relink: Vec<(PhotoId, String)> =
moved.into_iter().filter(|m| Path::new(&m.to).is_file() && !Path::new(&m.from).exists()).map(|m| (PhotoId(m.id), m.to)).collect();
step(checked);
// still where the scan found it (the same content, when the scan read it), and still gone
// from where the photo says
let mut relink: Vec<(PhotoId, String)> = Vec::with_capacity(moved.len());
for m in moved {
// each file is read again when the scan hashed it: this can take a while on a share
if cancel.load(Relaxed) {
return;
}
let still_the_file = Path::new(&m.to).is_file()
&& !Path::new(&m.from).exists()
&& m.hash.as_deref().is_none_or(|h| crate::cmd::missing::file_hash(&m.to).is_some_and(|now| base_hash(&now) == base_hash(h)));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if still_the_file {
relink.push((PhotoId(m.id), m.to));
}
step(1);
}
if !relink.is_empty() && !send(SyncStep::Relink(relink)) {
return;
}
Expand Down
93 changes: 89 additions & 4 deletions crates/engine/src/tests/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,23 +476,92 @@ fn a_scan_stays_current_while_only_other_folders_change() {
assert_eq!(r["imported"], 1, "{r}");
}

/// Work on the folder's photos while it is scanned (a rating, keywords, an edit) changes nothing
/// about what the scan found: a scan of a big folder on a slow disk takes minutes, and the
/// dialog says to go on working. Synchronize does what it showed.
#[test]
fn a_change_to_the_folders_photos_makes_the_scan_stale() {
let dir = Scratch::new("stale-folder");
fn working_on_the_folders_photos_meanwhile_leaves_the_scan_current() {
let dir = Scratch::new("worked-on");
let mut s = library(&dir);
write_png(&dir.path("trip/c.png"), 3);
scan(&mut s, &dir.path("trip"));
let a = s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id;
s.selection = crate::Selection::single(a);
s.execute("photo.rate", &json!({"ids": [a.0], "rating": 2})).unwrap();
// the dialog asks for exactly what it showed: refused, never redone on the spot
s.execute("photo.setMeta", &json!({"ids": [a.0], "addKeywords": ["Trips|Alps", "snow"], "title": "A"})).unwrap();
s.execute("photo.label", &json!({"ids": [a.0], "label": "red"})).unwrap();
s.execute("photo.pick", &json!({"ids": [a.0]})).unwrap();
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.5})).unwrap();
// into several albums, a virtual copy made of it, and one of its edits undone
s.execute("photo.virtualCopy", &json!({"ids": [a.0]})).unwrap();
s.selection = crate::Selection::single(a);
for name in ["One", "Two"] {
let album = s.execute("album.create", &json!({"name": name})).unwrap()["id"].as_u64().unwrap();
s.execute("album.addPhotos", &json!({"id": album, "ids": [a.0]})).unwrap();
}
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true})).unwrap();
assert_eq!(r["imported"], 1, "what the scan showed is done: {r}");
assert_eq!(s.catalog.photo(a).unwrap().rating, 2, "and the work stays");
}

/// A virtual copy made, meanwhile, of a photo whose file the scan found missing would be left
/// behind by removing the photo (the scan acts on exact ids): that scan is refused.
#[test]
fn a_virtual_copy_of_a_missing_photo_made_meanwhile_makes_the_scan_stale() {
let dir = Scratch::new("stale-copy-of-missing");
let mut s = library(&dir);
let b = s.catalog.photos().find(|p| p.file_name == "b.png").unwrap().id;
std::fs::remove_file(dir.path("trip/day1/b.png")).unwrap();
scan(&mut s, &dir.path("trip"));
s.selection = crate::Selection::single(b);
s.execute("photo.virtualCopy", &json!({"ids": [b.0]})).unwrap();
let e = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true, "removeMissing": true})).unwrap_err().to_string();
assert!(e.contains("scan again"), "{e}");
}

/// What the scan found is no longer true once the folder holds other photos, or one of them is
/// another file now: then it is refused, never redone on the spot.
#[test]
fn a_change_to_which_photos_the_folder_holds_makes_the_scan_stale() {
let dir = Scratch::new("stale-folder");
let mut s = library(&dir);
write_png(&dir.path("trip/c.png"), 3);
scan(&mut s, &dir.path("trip"));
let a = s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id;
s.selection = crate::Selection::single(a);
// one of its photos goes to Recently Deleted
s.execute("photo.delete", &json!({"ids": [a.0]})).unwrap();
let e = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true})).unwrap_err().to_string();
assert!(e.contains("scan again"), "{e}");
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 2, "nothing was done");
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1, "nothing was done");
// an agent that just asks to synchronize gets a fresh scan
let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip")})).unwrap();
assert_eq!(r["imported"], 1, "{r}");
}

/// A photo whose sidecar the scan found news in, changed here since: what the sidecar says would
/// go over that work, which the person was not shown. That scan is refused.
#[test]
fn a_change_to_a_photo_whose_sidecar_has_news_makes_the_scan_stale() {
let dir = Scratch::new("stale-sidecar");
let mut s = library(&dir);
write_sidecar(&dir.path("trip/a.png"), 5, Duration::ZERO);
let found = scan(&mut s, &dir.path("trip"));
assert_eq!(found["metadata"].as_array().map(Vec::len), Some(1), "{found}");
// work on another photo of the folder does not matter…
let (a, b) = (s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id, s.catalog.photos().find(|p| p.file_name == "b.png").unwrap().id);
s.selection = crate::Selection::single(b);
s.execute("photo.rate", &json!({"ids": [b.0], "rating": 1})).unwrap();
assert!(s.folder_changes.is_some());
// …work on the photo whose sidecar is to be read does
s.execute("photo.rate", &json!({"ids": [a.0], "rating": 2})).unwrap();
let e = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true, "readMetadata": true})).unwrap_err().to_string();
assert!(e.contains("scan again"), "{e}");
assert_eq!(s.catalog.photo(a).unwrap().rating, 2, "nothing was read over it");
}

#[test]
fn the_progress_counts_the_photos_checked_too() {
use std::sync::atomic::Ordering::Relaxed;
Expand Down Expand Up @@ -535,6 +604,22 @@ fn a_renamed_photo_with_no_content_hash_is_relinked_when_its_file_is_unmistakabl
assert!(paths(&r, "missing").is_empty() && paths(&r, "new").is_empty(), "{r}");
}

#[test]
fn a_file_replaced_after_the_scan_is_not_relinked_to_the_photo() {
// a scan of a big folder takes minutes before it is confirmed: what stands at the new path by
// then may no longer be the photo's content
let dir = Scratch::new("replaced-after-scan");
let mut s = library(&dir);
let a = s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id;
std::fs::rename(dir.path("trip/a.png"), dir.path("trip/day1/a-renamed.png")).unwrap();
let r = scan(&mut s, &dir.path("trip"));
assert_eq!(r["moved"][0]["to"], dir.path("trip/day1/a-renamed.png"), "{r}");
write_png(&dir.path("trip/day1/a-renamed.png"), 9);
let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true, "removeMissing": false})).unwrap();
assert_eq!(r["relinked"], 0, "{r}");
assert_eq!(s.catalog.photo(a).unwrap().source, lightcraft_catalog::Source::File { path: dir.path("trip/a.png") });
}

#[test]
fn renamed_duplicates_are_each_relinked() {
let dir = Scratch::new("dups");
Expand Down
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/cs-formats.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,8 @@
"Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}",
"Added {n} photo{}": "Přidáno fotografií: {n}{:.0}",
"Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?",
"Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})"
"Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})",
"Changes found: {n}": "Nalezené změny: {n}",
"“{name}” is still being scanned: wait for it, or stop it with ✕ on its row": "„{name}“ se ještě prohledává: počkejte, nebo hledání zastavte × na jeho řádku",
"Look at the changes found in “{name}” first, or dismiss them": "Nejprve si prohlédněte změny nalezené v „{name}“, nebo je zahoďte"
}
8 changes: 7 additions & 1 deletion crates/ui-egui/locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -2408,5 +2408,11 @@
"Import dropped files without review": "Importovat přetažené soubory bez kontroly",
"An import is running": "Import už běží",
"An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí",
"Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky"
"Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky",
"Continue in Background": "Pokračovat na pozadí",
"Folder not found": "Složka nenalezena",
"Dismiss": "Zavřít",
"Review…": "Prohlédnout…",
"Open Synchronize Folder with what the scan found": "Otevřít Synchronizovat složku s tím, co hledání našlo",
"You can go on working: a notice at the top left says when the scan is done.": "Můžete pracovat dál: až hledání skončí, oznámí to upozornění vlevo nahoře."
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/de-formats.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,8 @@
"Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}",
"Added {n} photo{}": "{n} Foto{} hinzugefügt",
"Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?",
"Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})"
"Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})",
"Changes found: {n}": "Gefundene Änderungen: {n}",
"“{name}” is still being scanned: wait for it, or stop it with ✕ on its row": "„{name}“ wird noch durchsucht: Warte darauf oder beende die Suche mit × in ihrer Zeile",
"Look at the changes found in “{name}” first, or dismiss them": "Sieh dir zuerst die in „{name}“ gefundenen Änderungen an oder verwirf sie"
}
8 changes: 7 additions & 1 deletion crates/ui-egui/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -3440,5 +3440,11 @@
"Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren",
"An import is running": "Ein Import läuft",
"An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist",
"Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst"
"Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst",
"Continue in Background": "Im Hintergrund fortsetzen",
"Folder not found": "Ordner nicht gefunden",
"Dismiss": "Entfernen",
"Review…": "Ansehen…",
"Open Synchronize Folder with what the scan found": "„Ordner synchronisieren“ mit dem Ergebnis der Suche öffnen",
"You can go on working: a notice at the top left says when the scan is done.": "Du kannst weiterarbeiten: Ein Hinweis oben links meldet, wenn die Suche abgeschlossen ist."
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/es-formats.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,8 @@
"Could not read {name}: {e}": "No se pudo leer {name}: {e}",
"Added {n} photo{}": "{n} foto{0} añadida{0}",
"Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?",
"Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})"
"Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})",
"Changes found: {n}": "Cambios encontrados: {n}",
"“{name}” is still being scanned: wait for it, or stop it with ✕ on its row": "“{name}” aún se está analizando: espera a que termine o detenlo con × en su fila",
"Look at the changes found in “{name}” first, or dismiss them": "Revisa primero los cambios encontrados en “{name}” o descártalos"
}
8 changes: 7 additions & 1 deletion crates/ui-egui/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2358,5 +2358,11 @@
"Import dropped files without review": "Importar los archivos soltados sin revisión",
"An import is running": "Hay una importación en curso",
"An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine",
"Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos"
"Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos",
"Continue in Background": "Continuar en segundo plano",
"Folder not found": "Carpeta no encontrada",
"Dismiss": "Descartar",
"Review…": "Revisar…",
"Open Synchronize Folder with what the scan found": "Abrir Sincronizar carpeta con lo que encontró la búsqueda",
"You can go on working: a notice at the top left says when the scan is done.": "Puedes seguir trabajando: un aviso arriba a la izquierda indica cuándo termina la búsqueda."
}
Loading
Loading