LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
UI: Synchronize Folder… dialog on Folders rows
Nathaniel Ledfordc520cf45746e
diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.jsonindex c24b59cc0..e747ad2f2 100644--- a/crates/ui-egui/locales/de.json+++ b/crates/ui-egui/locales/de.json@@ -1889,5 +1889,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "Ordner synchronisieren…",+ "Synchronize Folder": "Ordner synchronisieren",+ "Synchronize": "Synchronisieren",+ "Scanning…": "Wird durchsucht…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Fotos finden, die in diesem Ordner auf dem Datenträger hinzugekommen sind oder fehlen, und von anderen Apps geänderte XMP-Filialdateien",+ "Bring the library up to date with this folder and the folders inside it:": "Die Bibliothek mit diesem Ordner und den Ordnern darin abgleichen:",+ "Import new photos": "Neue Fotos importieren",+ "Remove missing photos from the library": "Fehlende Fotos aus der Bibliothek entfernen",+ "Read metadata updates from XMP sidecars": "Metadaten-Änderungen aus XMP-Filialdateien lesen",+ "The library is up to date with this folder.": "Die Bibliothek ist mit diesem Ordner auf dem neuesten Stand.",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "Fehlende Fotos werden nach „Zuletzt gelöscht“ verschoben und können wiederhergestellt werden; keine Datei auf dem Datenträger wird verändert.",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Beim Lesen einer Filialdatei werden Bewertung, Markierungen, Metadaten und Bearbeitungen des Fotos durch ihren Inhalt ersetzt.",+ "Skipped: files already in the library elsewhere": "Übersprungen: Dateien, die bereits an anderer Stelle in der Bibliothek sind",+ "Skipped: files that can't be read": "Übersprungen: Dateien, die nicht gelesen werden können"}diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.jsonindex 387ac9717..0b29f570b 100644--- a/crates/ui-egui/locales/es.json+++ b/crates/ui-egui/locales/es.json@@ -1734,5 +1734,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "Sincronizar carpeta…",+ "Synchronize Folder": "Sincronizar carpeta",+ "Synchronize": "Sincronizar",+ "Scanning…": "Explorando…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Buscar fotos añadidas a esta carpeta del disco o que faltan en ella, y archivos XMP complementarios cambiados por otras apps",+ "Bring the library up to date with this folder and the folders inside it:": "Poner la biblioteca al día con esta carpeta y las carpetas que contiene:",+ "Import new photos": "Importar fotos nuevas",+ "Remove missing photos from the library": "Quitar de la biblioteca las fotos que faltan",+ "Read metadata updates from XMP sidecars": "Leer cambios de metadatos de los archivos XMP complementarios",+ "The library is up to date with this folder.": "La biblioteca está al día con esta carpeta.",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "Las fotos que faltan pasan a Eliminadas recientemente y se pueden restaurar; no se toca ningún archivo del disco.",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Leer un archivo complementario sustituye la valoración, las etiquetas, los metadatos y las ediciones de la foto por lo que contiene.",+ "Skipped: files already in the library elsewhere": "Omitidos: archivos que ya están en la biblioteca en otro lugar",+ "Skipped: files that can't be read": "Omitidos: archivos que no se pueden leer"}diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.jsonindex b05baac24..ae2023ff7 100644--- a/crates/ui-egui/locales/ja.json+++ b/crates/ui-egui/locales/ja.json@@ -1734,5 +1734,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "フォルダを同期…",+ "Synchronize Folder": "フォルダを同期",+ "Synchronize": "同期",+ "Scanning…": "スキャン中…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "ディスク上のこのフォルダに追加された写真や見つからない写真、ほかのアプリで変更された XMP サイドカーを探します",+ "Bring the library up to date with this folder and the folders inside it:": "このフォルダとその中のフォルダに合わせてライブラリを最新にします:",+ "Import new photos": "新しい写真を読み込む",+ "Remove missing photos from the library": "見つからない写真をライブラリから除去",+ "Read metadata updates from XMP sidecars": "XMP サイドカーからメタデータの更新を読み込む",+ "The library is up to date with this folder.": "ライブラリはこのフォルダと一致しています。",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "見つからない写真は「最近削除した写真」に移動し、復元できます。ディスク上のファイルには手を加えません",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "サイドカーを読み込むと、写真のレーティング、ラベル、メタデータ、編集内容がその内容に置き換わります。",+ "Skipped: files already in the library elsewhere": "スキップ: 別の場所ですでにライブラリにあるファイル",+ "Skipped: files that can't be read": "スキップ: 読み込めないファイル"}diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.jsonindex ab7f39734..71369387f 100644--- a/crates/ui-egui/locales/pt-br.json+++ b/crates/ui-egui/locales/pt-br.json@@ -1734,5 +1734,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "Sincronizar pasta…",+ "Synchronize Folder": "Sincronizar pasta",+ "Synchronize": "Sincronizar",+ "Scanning…": "Verificando…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Encontrar fotos adicionadas a esta pasta no disco ou ausentes dela, e arquivos XMP auxiliares alterados por outros apps",+ "Bring the library up to date with this folder and the folders inside it:": "Atualizar a biblioteca com esta pasta e as pastas dentro dela:",+ "Import new photos": "Importar fotos novas",+ "Remove missing photos from the library": "Remover fotos ausentes da biblioteca",+ "Read metadata updates from XMP sidecars": "Ler atualizações de metadados dos arquivos XMP auxiliares",+ "The library is up to date with this folder.": "A biblioteca está atualizada com esta pasta.",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "As fotos ausentes vão para Excluídos recentemente e podem ser restauradas; nenhum arquivo no disco é alterado.",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Ler um arquivo auxiliar substitui a classificação, os rótulos, os metadados e as edições da foto pelo que ele contém.",+ "Skipped: files already in the library elsewhere": "Ignorados: arquivos que já estão na biblioteca em outro lugar",+ "Skipped: files that can't be read": "Ignorados: arquivos que não podem ser lidos"}diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.jsonindex 517e2613f..dc2b35756 100644--- a/crates/ui-egui/locales/ru.json+++ b/crates/ui-egui/locales/ru.json@@ -1407,5 +1407,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "Синхронизировать папку…",+ "Synchronize Folder": "Синхронизация папки",+ "Synchronize": "Синхронизировать",+ "Scanning…": "Сканирование…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Найти фото, добавленные в эту папку на диске или пропавшие из неё, и файлы XMP, изменённые другими приложениями",+ "Bring the library up to date with this folder and the folders inside it:": "Привести медиатеку в соответствие с этой папкой и вложенными папками:",+ "Import new photos": "Импортировать новые фото",+ "Remove missing photos from the library": "Убрать отсутствующие фото из медиатеки",+ "Read metadata updates from XMP sidecars": "Прочитать изменения метаданных из файлов XMP",+ "The library is up to date with this folder.": "Медиатека соответствует этой папке.",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "Отсутствующие фото перемещаются в «Недавно удалённые» и могут быть восстановлены; файлы на диске не затрагиваются.",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Чтение файла XMP заменяет рейтинг, метки, метаданные и правки фото его содержимым.",+ "Skipped: files already in the library elsewhere": "Пропущено: файлы, которые уже есть в медиатеке в другом месте",+ "Skipped: files that can't be read": "Пропущено: файлы, которые не удаётся прочитать"}diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.jsonindex 46728b628..2123391d6 100644--- a/crates/ui-egui/locales/zh-hans.json+++ b/crates/ui-egui/locales/zh-hans.json@@ -1734,5 +1734,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "同步文件夹…",+ "Synchronize Folder": "同步文件夹",+ "Synchronize": "同步",+ "Scanning…": "正在扫描…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "查找磁盘上此文件夹中新增或缺失的照片,以及被其他应用更改的 XMP 附属文件",+ "Bring the library up to date with this folder and the folders inside it:": "让图库与此文件夹及其中的文件夹保持一致:",+ "Import new photos": "导入新照片",+ "Remove missing photos from the library": "从图库中移除缺失的照片",+ "Read metadata updates from XMP sidecars": "从 XMP 附属文件读取元数据更新",+ "The library is up to date with this folder.": "图库与此文件夹一致。",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "缺失的照片会移到“最近删除”,可以恢复;磁盘上的文件不会被改动。",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "读取附属文件会用其内容替换照片的评级、标签、元数据和编辑。",+ "Skipped: files already in the library elsewhere": "已跳过:已在图库其他位置的文件",+ "Skipped: files that can't be read": "已跳过:无法读取的文件"}diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.jsonindex 083c98c2e..8fa254cdf 100644--- a/crates/ui-egui/locales/zh-hant.json+++ b/crates/ui-egui/locales/zh-hant.json@@ -1734,5 +1734,19 @@"Pending photo action cancelled": "Pending photo action cancelled","Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed","ONNX model": "ONNX model",- "commercial use subject to GPL conditions": "commercial use subject to GPL conditions"+ "commercial use subject to GPL conditions": "commercial use subject to GPL conditions",+ "Synchronize Folder…": "同步資料夾…",+ "Synchronize Folder": "同步資料夾",+ "Synchronize": "同步",+ "Scanning…": "正在掃描…",+ "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "尋找磁碟上此資料夾中新增或遺失的照片,以及被其他 App 更改的 XMP 附屬檔案",+ "Bring the library up to date with this folder and the folders inside it:": "讓照片庫與此資料夾及其中的資料夾保持一致:",+ "Import new photos": "匯入新照片",+ "Remove missing photos from the library": "從照片庫移除遺失的照片",+ "Read metadata updates from XMP sidecars": "從 XMP 附屬檔案讀取中繼資料更新",+ "The library is up to date with this folder.": "照片庫與此資料夾一致。",+ "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "遺失的照片會移至「最近刪除」,可以還原;磁碟上的檔案不會被更動。",+ "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "讀取附屬檔案會以其內容取代照片的評等、標籤、中繼資料和編輯。",+ "Skipped: files already in the library elsewhere": "已略過:已在照片庫其他位置的檔案",+ "Skipped: files that can't be read": "已略過:無法讀取的檔案"}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 705818911..61c226f1c 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -27,6 +27,7 @@ pub mod render;pub mod shortcuts;pub mod softpaint;pub mod state;+pub mod sync;pub mod tasks;pub mod theme;pub mod titlebar;@@ -63,6 +64,8 @@ mod tests_scroll;#[cfg(test)]mod tests_switch_library;#[cfg(test)]+mod tests_sync;+#[cfg(test)]mod tests_titlebar;#[cfg(test)]mod tests_unsaved;@@ -240,6 +243,8 @@ pub struct LightcraftApp {pub import: Option<import::ImportTask>,/// A folder scan in progress (feeds the import review).pub scan: Option<import::ScanTask>,+ /// A Synchronize Folder scan in progress (feeds its dialog).+ pub sync: Option<sync::SyncTask>,/// A Lightroom catalog inspect/import in progress.pub lightroom: Option<lightroom_import::LightroomTask>,/// Last terminal Lightroom result, exposed by the command's status/wait response.@@ -311,6 +316,7 @@ impl LightcraftApp {merge: merge::MergeState::default(),import: None,scan: None,+ sync: None,lightroom: None,lightroom_last: None,export: None,@@ -734,6 +740,7 @@ impl LightcraftApp {self.renderer.poll(ctx, &mut self.session);merge::poll(self, ctx);import::poll_scan(self, ctx);+ sync::poll(self, ctx);import::tick(self, ctx);lightroom_import::tick(self, ctx);tasks::poll(self, ctx);diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex fa2e6ad9e..2890ae1fc 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -103,6 +103,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::ConfirmDelete { .. } => "Delete Photos",Dialog::RemoveFolder { disk: true, .. } => "Remove Disk from Library",Dialog::RemoveFolder { .. } => "Remove Folder from Library",+ Dialog::SynchronizeFolder { .. } => "Synchronize Folder",// (nothing to download from in this build: the dialog explains the manual install)Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model",Dialog::SamModel { .. } => "Download the SAM 3 Model?",@@ -728,6 +729,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {ui.label(crate::i18n::tr_format!("Move {what} to Recently Deleted?", what = what));ui.label(egui::RichText::new(crate::i18n::tr("They can be restored from Recently Deleted until it is emptied.")).color(t.text_dim));}+ d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d),Dialog::RemoveFolder { name, count, path, disk } => {ui.label(crate::i18n::tr_format!("Remove “{name}” and its {count} photo{} from the library?",@@ -828,6 +830,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::FaceModel { .. } if !informational => "Install",Dialog::ConfirmDelete { .. } => "Delete",Dialog::RemoveFolder { .. } => "Remove",+ Dialog::SynchronizeFolder { .. } => "Synchronize",Dialog::SamModel { then: Some(_), .. } if sam_installed => "Continue",Dialog::SamModel { .. } if sam_installed || sam_running || sam_nowhere => "",Dialog::SamModel { error, .. } if error.is_some() || sam_failed => "Try Again",@@ -836,7 +839,12 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {_ => "OK",};// installing waits for the licence to be accepted- let can_confirm = informational || !matches!(&dlg, Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. });+ // (and Synchronize waits for the scan)+ let can_confirm = informational+ || !matches!(+ &dlg,+ Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. }+ );let r = (!ok.is_empty()).then(|| ui.add_enabled(can_confirm, egui::Button::new(crate::i18n::tr(ok))));if let Some(r) = &r {crate::widgets::register(ui.ctx(), "button:dialogOk", r.rect);@@ -1112,6 +1120,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jsoDialog::Import { opts } => crate::import::start(app, opts),Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})),Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})),+ d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d),Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } => Ok(serde_json::Value::Null),}}diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rsindex 7312bfc1a..3c0a0c216 100644--- a/crates/ui-egui/src/panels/left.rs+++ b/crates/ui-egui/src/panels/left.rs@@ -1225,6 +1225,7 @@ fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {} else if n.path != "/" {resp.context_menu(|ui| {folder_label_menu(app, ui, n);+ synchronize_item(app, ui, n, &n.name);ui.separator();if ui.button(crate::i18n::tr("Remove Disk from Library…"))@@ -1238,6 +1239,21 @@ fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {}}+/// Synchronize Folder… of a Folders row (widget `folderSynchronize`): opens its dialog, which+/// scans the folder in the background.+fn synchronize_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, name: &str) {+ let r = ui+ .button(crate::i18n::tr("Synchronize Folder…"))+ .on_hover_text(crate::i18n::tr("Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps"));+ crate::widgets::register(ui.ctx(), "folderSynchronize", r.rect);+ if r.clicked() {+ if let Err(e) = crate::sync::open(app, &n.path, name) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+}+/// Set Color Label ▸ of a Folders row (`folder.label`; the submenu is widget `folderLabelMenu`,/// its colours `folderLabel:<colour>`).fn folder_label_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode) {@@ -1289,6 +1305,7 @@ fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &Fui.close();}folder_label_menu(app, ui, n);+ synchronize_item(app, ui, n, &label);ui.separator();if ui.button(crate::i18n::tr("Remove from Library…"))diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 83b3df292..e1a754747 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -665,10 +665,33 @@ pub enum Dialog {/// A whole disk or share (`library.removeFolder` takes it only on request).disk: bool,},+ /// Synchronize Folder: what changed in a library folder on disk, and what to do about it+ /// (`folder.synchronize`; the scan runs in [`crate::sync`]).+ SynchronizeFolder {+ path: String,+ /// What the dialog calls it (a folder's last two names).+ name: String,+ /// What the scan found (`None` while it runs).+ counts: Option<SyncCounts>,+ import_new: bool,+ remove_missing: bool,+ read_metadata: bool,+ },About,Shortcuts,}+/// How many changes a Synchronize Folder scan found, by kind.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct SyncCounts {+ pub new: usize,+ pub duplicates: usize,+ pub unreadable: usize,+ pub missing: usize,+ pub metadata: usize,+}+impl Default for UiState {fn default() -> Self {UiState {diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rsnew file mode 100644index 000000000..24bad291a--- /dev/null+++ b/crates/ui-egui/src/sync.rs@@ -0,0 +1,162 @@+//! Synchronize Folder in the app: the folder is scanned on a worker thread (a network share can+//! take minutes; no frame waits for it) while its dialog is open, and the dialog then says what+//! changed and what to do about it. Synchronize runs `folder.synchronize`, which acts on exactly+//! the scan the dialog showed (see `lightcraft_engine::sync`).++use std::sync::Arc;+use std::sync::atomic::Ordering;++use lightcraft_engine::import::ScanProgress;+use lightcraft_engine::sync::{FolderChanges, SyncChoice, SyncInput, scan_with};+use serde_json::{Value, json};++use crate::LightcraftApp;+use crate::state::{Dialog, SyncCounts};+use crate::theme::Tokens;++/// A running scan of the dialog's folder.+pub struct SyncTask {+ path: String,+ progress: Arc<ScanProgress>,+ rx: std::sync::mpsc::Receiver<FolderChanges>,+}++/// Open the dialog for folder `path` (called `name` in it) and start scanning.+pub fn open(app: &mut LightcraftApp, path: &str, name: &str) -> Result<(), String> {+ cancel(app);+ let input = SyncInput::new(&mut app.session, path).map_err(|e| e.to_string())?;+ let progress = Arc::new(ScanProgress::default());+ let (tx, rx) = std::sync::mpsc::channel();+ let p = progress.clone();+ let job = move || {+ let _ = tx.send(scan_with(input, &p));+ };+ #[cfg(not(target_arch = "wasm32"))]+ std::thread::spawn(job);+ #[cfg(target_arch = "wasm32")]+ job();+ app.sync = Some(SyncTask { path: path.to_string(), progress, rx });+ let d = SyncChoice::default();+ app.ui.dialog = Some(Dialog::SynchronizeFolder {+ path: path.to_string(),+ name: name.to_string(),+ counts: None,+ import_new: d.import_new,+ remove_missing: d.remove_missing,+ read_metadata: d.read_metadata,+ });+ Ok(())+}++/// Stop a running scan and let go of a finished one.+fn cancel(app: &mut LightcraftApp) {+ if let Some(t) = app.sync.take() {+ t.progress.cancel.store(true, Ordering::Relaxed);+ }+ app.session.folder_changes = None;+}++/// Collect a finished scan into the dialog (called every frame). A scan whose dialog was closed+/// is cancelled.+pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {+ let open_for = match &app.ui.dialog {+ Some(Dialog::SynchronizeFolder { path, .. }) => Some(path.clone()),+ _ => None,+ };+ let Some(open_for) = open_for else {+ if app.sync.is_some() || app.session.folder_changes.is_some() {+ cancel(app);+ }+ return;+ };+ let Some(task) = app.sync.as_ref() else { return };+ if task.path != open_for {+ cancel(app);+ return;+ }+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ let changes = match task.rx.try_recv() {+ Ok(c) => c,+ Err(std::sync::mpsc::TryRecvError::Empty) => return,+ Err(_) => {+ app.sync = None;+ app.ui.dialog = None;+ app.toast(ctx, crate::i18n::tr("Scan failed"));+ return;+ }+ };+ app.sync = None;+ let c = SyncCounts {+ new: changes.new.len(),+ duplicates: changes.duplicates,+ unreadable: changes.unreadable.len(),+ missing: changes.missing.len(),+ metadata: changes.metadata.len(),+ };+ app.session.folder_changes = Some(changes);+ if let Some(Dialog::SynchronizeFolder { counts, .. }) = &mut app.ui.dialog {+ *counts = Some(c);+ }+}++/// How far the scan is (files probed, of how many).+fn progress(app: &LightcraftApp) -> Option<(usize, usize)> {+ app.sync.as_ref().map(|t| (t.progress.done.load(Ordering::Relaxed), t.progress.total.load(Ordering::Relaxed)))+}++/// The dialog's body.+pub fn body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) {+ let Dialog::SynchronizeFolder { path, name, counts, import_new, remove_missing, read_metadata } = dlg else { return };+ let t = Tokens::get(ui.ctx());+ ui.set_min_width(420.0);+ ui.label(crate::i18n::tr("Bring the library up to date with this folder and the folders inside it:"));+ ui.label(egui::RichText::new(name.as_str()).strong());+ ui.label(egui::RichText::new(path.as_str()).color(t.text_dim));+ ui.add_space(6.0);+ let Some(c) = counts.as_ref() else {+ ui.horizontal(|ui| {+ ui.spinner();+ match progress(app) {+ Some((done, total)) if total > 0 => ui.label(format!("{} {done} / {total}", crate::i18n::tr("Scanning…"))),+ _ => ui.label(crate::i18n::tr("Scanning…")),+ }+ });+ return;+ };+ let choice = |ui: &mut egui::Ui, on: &mut bool, n: usize, text: String, widget: &str| {+ let r = ui.add_enabled(n > 0, egui::Checkbox::new(on, text));+ crate::widgets::register(ui.ctx(), widget, r.rect);+ };+ let count = |text: &str, n: usize| format!("{} ({n})", crate::i18n::tr(text));+ choice(ui, import_new, c.new, count("Import new photos", c.new), "syncImportNew");+ choice(ui, remove_missing, c.missing, count("Remove missing photos from the library", c.missing), "syncRemoveMissing");+ choice(ui, read_metadata, c.metadata, count("Read metadata updates from XMP sidecars", c.metadata), "syncReadMetadata");+ ui.add_space(6.0);+ let dim = |ui: &mut egui::Ui, s: &str| ui.label(egui::RichText::new(s).color(t.text_dim));+ if c.new + c.missing + c.metadata == 0 {+ dim(ui, crate::i18n::tr("The library is up to date with this folder."));+ }+ if c.missing > 0 {+ dim(ui, crate::i18n::tr("Missing photos move to Recently Deleted and can be restored; no file on disk is touched."));+ }+ if c.metadata > 0 {+ dim(ui, crate::i18n::tr("Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says."));+ }+ if c.duplicates > 0 {+ dim(ui, &count("Skipped: files already in the library elsewhere", c.duplicates));+ }+ if c.unreadable > 0 {+ dim(ui, &count("Skipped: files that can't be read", c.unreadable));+ }+}++/// Synchronize: `folder.synchronize` with the dialog's choices.+pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result<Value, String> {+ let Dialog::SynchronizeFolder { path, counts: Some(_), import_new, remove_missing, read_metadata, .. } = dlg else {+ return Err("the folder is still being scanned".into());+ };+ let r =+ app.run("folder.synchronize", json!({"path": path, "importNew": import_new, "removeMissing": remove_missing, "readMetadata": read_metadata}));+ app.session.folder_changes = None;+ r+}diff --git a/crates/ui-egui/src/tests_sync.rs b/crates/ui-egui/src/tests_sync.rsnew file mode 100644index 000000000..bc831ca00--- /dev/null+++ b/crates/ui-egui/src/tests_sync.rs@@ -0,0 +1,151 @@+//! Synchronize Folder in the app (see `lightcraft_engine::sync`).+//!+//! Scenarios, in the words of someone whose folder changed outside LightCraft:+//!+//! * Right-click a folder in the sidebar's Folders section ▸ Synchronize Folder…: a dialog opens+//! at once and scans the folder without holding up the app, then says how many photos are new,+//! missing, or have metadata updates.+//! * Synchronize with the defaults imports the new photos and leaves missing ones alone.+//! * Ticking "Remove missing photos" also moves those to Recently Deleted.+//! * Cancel leaves the library as it was.++use std::time::Duration;++use serde_json::json;++use crate::headless::Headless;+use crate::state::Dialog;+use crate::{LightcraftApp, Services};++const T: Duration = Duration::from_secs(20);+const SETTLE: Duration = Duration::from_secs(120);++/// A scratch folder that goes away with the test, however it ends.+struct Scratch(std::path::PathBuf);++impl Scratch {+ fn new(tag: &str) -> Scratch {+ let dir = std::env::temp_dir().join(format!("lc-ui-sync-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ Scratch(dir)+ }+ /// The path as the folder tree writes it (forward slashes; widget ids carry it).+ fn path(&self, rel: &str) -> String {+ self.0.join(rel).to_string_lossy().replace('\\', "/")+ }+}++impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++fn write_png(path: &str, seed: u8) {+ let (w, h) = (24usize, 16usize);+ let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect();+ let img = lightcraft_raster::Rgba8 { width: w, height: h, data };+ let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ std::fs::create_dir_all(std::path::Path::new(path).parent().unwrap()).unwrap();+ std::fs::write(path, bytes).unwrap();+}++/// The app with `trip/a.png` and `trip/b.png` imported, then `c.png` added and `b.png` deleted+/// on disk behind its back.+fn changed_folder(dir: &Scratch) -> Headless {+ write_png(&dir.path("trip/a.png"), 1);+ write_png(&dir.path("trip/b.png"), 2);+ let mut session = lightcraft_engine::Session::new().with_fs();+ session.execute("library.import", &json!({"paths": [dir.path("trip")]})).unwrap();+ write_png(&dir.path("trip/c.png"), 3);+ std::fs::remove_file(dir.path("trip/b.png")).unwrap();+ let app = LightcraftApp::new(session, Services { png: None, ..Default::default() });+ let mut h = Headless::new(app, [1400.0, 900.0], 1.0);+ let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.settle(SETTLE);+ h+}++fn in_library(h: &Headless) -> Vec<String> {+ let mut v: Vec<String> = h.app.session.catalog.photos().filter(|p| p.in_library()).map(|p| p.file_name.clone()).collect();+ v.sort();+ v+}++/// Open the dialog from the folder's menu and wait for the scan.+fn open_and_scan(h: &mut Headless, folder: &str) {+ // the rows above it hold one folder each and open by themselves+ let row = format!("source:libfolder:{folder}");+ assert!(h.step_until(T, |h| h.app.widgets.iter().any(|(w, _)| *w == row)), "no row {row}");+ let rect = h.app.widgets.iter().find(|(w, _)| *w == row).map(|(_, r)| *r).unwrap_or_else(|| panic!("no row {row}"));+ let c = rect.center();+ let r = h.request("ui.click", json!({"x": c.x, "y": c.y, "button": "right"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+ let r = h.request("ui.clickWidget", json!({"id": "folderSynchronize"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert!(matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolder { .. })), "the dialog opens at once");+ let scanned = h.step_until(T, |h| matches!(&h.app.ui.dialog, Some(Dialog::SynchronizeFolder { counts: Some(_), .. })));+ assert!(scanned, "the scan finished: {:?}", h.app.ui.dialog);+}++fn counts(h: &Headless) -> crate::state::SyncCounts {+ match &h.app.ui.dialog {+ Some(Dialog::SynchronizeFolder { counts: Some(c), .. }) => c.clone(),+ d => panic!("no scanned dialog: {d:?}"),+ }+}++#[test]+fn the_dialog_says_what_changed_in_the_folder() {+ let dir = Scratch::new("counts");+ let mut h = changed_folder(&dir);+ open_and_scan(&mut h, &dir.path("trip"));+ let c = counts(&h);+ assert_eq!((c.new, c.missing, c.metadata), (1, 1, 0), "{c:?}");+ assert_eq!(in_library(&h), vec!["a.png", "b.png"], "scanning changed nothing");+}++#[test]+fn synchronizing_with_the_defaults_imports_the_new_photos_only() {+ let dir = Scratch::new("defaults");+ let mut h = changed_folder(&dir);+ open_and_scan(&mut h, &dir.path("trip"));+ let r = h.request("ui.dialog.confirm", json!({}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(in_library(&h), vec!["a.png", "b.png", "c.png"], "c came in; the missing b stays");+ assert!(h.app.ui.dialog.is_none());+}++#[test]+fn ticking_remove_missing_also_removes_the_missing_photos() {+ let dir = Scratch::new("remove");+ let mut h = changed_folder(&dir);+ open_and_scan(&mut h, &dir.path("trip"));+ let r = h.request("ui.clickWidget", json!({"id": "syncRemoveMissing"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ let r = h.request("ui.dialog.confirm", json!({}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(in_library(&h), vec!["a.png", "c.png"], "b went to Recently Deleted");+ let r = h.request("engine.execute", json!({"command": "edit.undo", "params": {}}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(in_library(&h), vec!["a.png", "b.png"], "one undo step");+}++#[test]+fn cancel_leaves_the_library_as_it_was() {+ let dir = Scratch::new("cancel");+ let mut h = changed_folder(&dir);+ open_and_scan(&mut h, &dir.path("trip"));+ h.request("ui.key", json!({"key": "escape"}), T);+ h.step();+ h.step();+ assert!(h.app.ui.dialog.is_none());+ assert_eq!(in_library(&h), vec!["a.png", "b.png"]);+ assert!(h.app.session.folder_changes.is_none(), "the scan is let go");+}