diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 664ff410521..ff6b7a40dc7 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -456,6 +456,13 @@ impl Catalog { pub fn photos(&self) -> impl Iterator> { self.photos.values() } + /// The photos after `after` in id order (all of them for `None`): a long walk over the library + /// that must not hold the UI thread takes it up again from the last id it saw. + pub fn photos_after(&self, after: Option) -> impl Iterator> { + use std::ops::Bound::{Excluded, Unbounded}; + let from = after.map_or(Unbounded, Excluded); + self.photos.range((from, Unbounded)).map(|(_, p)| p) + } pub fn len(&self) -> usize { self.photos.len() } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 8ba08021f52..5114595c95a 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -41,7 +41,8 @@ pub use params::{ use place::Placer; pub use place::{write_file, write_file_durable, write_file_new}; pub use prepare::{ - AfterExport, Destination, DngCompression, Exported, PreparedExport, export_batch, export_photo, output_size, prepare_batch, prepare_export, + AfterExport, BatchPrep, Destination, DngCompression, Exported, PreparedExport, export_batch, export_photo, output_size, prepare_batch, + prepare_export, }; #[cfg(test)] use prepare::{render_weight, too_big_for_memory}; diff --git a/crates/engine/src/export/prepare.rs b/crates/engine/src/export/prepare.rs index 56cc71a4a77..8428dba56dc 100644 --- a/crates/engine/src/export/prepare.rs +++ b/crates/engine/src/export/prepare.rs @@ -97,6 +97,67 @@ pub fn prepare_batch(session: &mut crate::Session, ids: &[lightcraft_catalog::Ph ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone())).collect() } +/// [`prepare_batch`] a few photos at a time, so a window can keep drawing while a big batch is set +/// up: [`Self::advance`] works while its `more` callback says to, then gives the thread back. +/// The library's originals ([`crate::originals::OriginalGuard`]) are indexed in slices first, then +/// the photos are prepared in order, so the items and the first error are those of +/// [`prepare_batch`] on the library as it is when each photo's turn comes. +pub struct BatchPrep { + ids: Vec, + phase: PrepPhase, + items: Vec, +} + +enum PrepPhase { + /// Indexing the originals; resumes after the photo given. + Guard(crate::originals::OriginalGuard, Option), + Photos(std::sync::Arc), +} + +impl BatchPrep { + pub fn new(ids: Vec) -> Self { + let items = Vec::with_capacity(ids.len()); + Self { ids, phase: PrepPhase::Guard(Default::default(), None), items } + } + + /// Photos in the batch. + pub fn total(&self) -> usize { + self.ids.len() + } + + /// Photos prepared so far. + pub fn prepared(&self) -> usize { + self.items.len() + } + + /// Do some of the work: at least one step (one photo's originals, or one photo), then more + /// while `more()`. `Ok(true)` once every photo is prepared ([`Self::into_items`]); the first + /// photo that can't be exported is an error, as in [`prepare_batch`]. + pub fn advance(&mut self, session: &mut crate::Session, o: &ExportOptions, more: &mut dyn FnMut() -> bool) -> Result { + if let PrepPhase::Guard(guard, after) = &mut self.phase { + if let Some(last) = guard.extend(&session.catalog, *after, more) { + *after = Some(last); + return Ok(false); + } + let guard = std::mem::take(guard); + self.phase = PrepPhase::Photos(std::sync::Arc::new(guard)); + } + let PrepPhase::Photos(guard) = &self.phase else { return Ok(false) }; + while let Some(&id) = self.ids.get(self.items.len()) { + self.items.push(prepare_guarded(session, id, o, self.items.len() + 1, guard.clone())?); + if !more() { + break; + } + } + Ok(self.items.len() == self.ids.len()) + } + + /// The prepared photos, in batch order. + pub fn into_items(self) -> Vec { + self.items + } +} + fn prepare_guarded( session: &mut crate::Session, id: lightcraft_catalog::PhotoId, diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index c4dc644fd66..90839d46d36 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -1572,3 +1572,41 @@ fn a_graphic_past_the_pixel_cap_is_refused_before_it_is_decoded() { assert!(e.contains("too large") || e.contains("10000"), "{e}"); let _ = std::fs::remove_dir_all(&dir); } + +// A big batch is prepared a slice at a time: each `advance` that is told to stop does one step, the +// photos come out in order and as `prepare_batch` makes them, and the first photo that can't be +// exported is the error +#[test] +fn a_batch_is_prepared_a_step_at_a_time() { + let mut s = crate::Session::with_demo(); + let ids: Vec<_> = s.visible().iter().copied().take(5).collect(); + let o = ExportOptions::from_json(&json!({"format": "png", "width": 40})); + let whole: Vec<_> = prepare_batch(&mut s, &ids, &o).unwrap().iter().map(|i| (i.photo, i.file_name.clone())).collect(); + let mut prep = BatchPrep::new(ids.clone()); + assert_eq!((prep.total(), prep.prepared()), (5, 0)); + let mut calls = 0; + while !prep.advance(&mut s, &o, &mut || false).unwrap() { + calls += 1; + assert!(prep.prepared() <= calls, "a stopped call prepares at most one photo"); + assert!(calls < 10_000, "the batch gets prepared"); + } + assert!(calls >= 5, "five photos took {calls} calls"); + let got: Vec<_> = prep.into_items().iter().map(|i| (i.photo, i.file_name.clone())).collect(); + assert_eq!(got, whole); + // told to go on, one call does it all + let mut prep = BatchPrep::new(ids.clone()); + assert!(prep.advance(&mut s, &o, &mut || true).unwrap()); + assert_eq!(prep.prepared(), 5); + // a photo that can't be prepared is the error, in its turn + let mut bad = ids.clone(); + bad.insert(2, lightcraft_catalog::PhotoId(u64::MAX)); + let mut prep = BatchPrep::new(bad); + let e = loop { + match prep.advance(&mut s, &o, &mut || true) { + Ok(false) => continue, + Ok(true) => panic!("a photo that is not in the library was prepared"), + Err(e) => break e, + } + }; + assert_eq!((e.as_str(), prep.prepared()), ("no such photo", 2)); +} diff --git a/crates/engine/src/originals.rs b/crates/engine/src/originals.rs index e16a4963f84..d0842b2e2f5 100644 --- a/crates/engine/src/originals.rs +++ b/crates/engine/src/originals.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; use std::time::SystemTime; use lightcraft_catalog::safe_file::{same_file, same_file_strict}; -use lightcraft_catalog::{Catalog, Source}; +use lightcraft_catalog::{Catalog, PhotoId, Source}; /// The directory entry a screenshot is about to write, pinned at request admission. /// @@ -116,6 +116,21 @@ impl OriginalGuard { g } + /// [`Self::new`] in slices: add the originals of the photos after `after` while `more()` says + /// to go on (at least one is added). `None` once every photo is in; else the last photo added, + /// to take the walk up again from. Lets a large library's guard be built a frame at a time. + pub fn extend(&mut self, catalog: &Catalog, after: Option, more: &mut dyn FnMut() -> bool) -> Option { + for p in catalog.photos_after(after) { + if let Source::File { path } = &p.source { + self.add(Path::new(path), &p.file_name); + } + if !more() { + return Some(p.id); + } + } + None + } + /// Protect `path` (an original named `label`) and its sidecars (`IMG_1.xmp`, `IMG_1.CR3.xmp`). pub fn add(&mut self, path: &Path, label: &str) { let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; @@ -337,6 +352,46 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// The guard built in slices protects what [`OriginalGuard::new`] does, whatever the slice size, and + /// a slice that is told to stop still adds a photo (the walk always moves on). + #[test] + fn a_guard_built_in_slices_protects_the_same_originals() { + let d = std::env::temp_dir().join(format!("lc-guard-slices-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let mut c = Catalog::default(); + for n in [3u64, 1, 7, 5] { + let path = d.join(format!("IMG_{n}.jpg")); + std::fs::write(&path, b"original").unwrap(); + let name = format!("IMG_{n}.jpg"); + let p = Photo::new(PhotoId(n), Source::File { path: path.to_string_lossy().to_string() }, &name, "JPEG", 10, 10, "2026-01-01"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let ids = |after| c.photos_after(after).map(|p| p.id.0).collect::>(); + assert_eq!((ids(None), ids(Some(PhotoId(3))), ids(Some(PhotoId(7)))), (vec![1, 3, 5, 7], vec![5, 7], Vec::::new())); + for stop_after in [1usize, 2, 100] { + let mut g = OriginalGuard::default(); + let (mut after, mut calls) = (None, 0); + loop { + let mut left = stop_after; + let mut more = || { + left -= 1; + left > 0 + }; + calls += 1; + match g.extend(&c, after, &mut more) { + Some(last) => after = Some(last), + None => break, + } + } + assert!(calls >= 4usize.div_ceil(stop_after), "{stop_after}: {calls} calls"); + for n in [1, 3, 5, 7] { + assert!(g.check(&d.join(format!("IMG_{n}.jpg"))).unwrap_err().contains(&format!("original of IMG_{n}.jpg")), "{stop_after}: IMG_{n}"); + } + } + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn sidecars_the_reader_accepts_in_other_cases_are_protected() { let d = std::env::temp_dir().join(format!("lc-originals-case-sidecar-{}", std::process::id())); diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index d55dcd0312c..8e4ecbdbcfd 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -174,6 +174,7 @@ "This raw is now developed from its raw data": "Tento soubor RAW se nyní vyvolává z dat RAW", "This raw variant still can't be decoded": "Tuto variantu RAW stále nelze dekódovat", "Adding to Apple Photos…": "Přidávání do Apple Photos…", + "Preparing photos…": "Příprava fotografií…", "Advanced search…": "Rozšířené hledání…", "After": "Po", "After 30 days": "Po 30 dnech", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index ce7e116dbe2..b6122d2a5c8 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2169,6 +2169,7 @@ "Remove from favorites": "Aus Favoriten entfernen", "Add to Apple Photos": "Zu Apple Fotos hinzufügen", "Adding to Apple Photos…": "Wird zu Apple Fotos hinzugefügt…", + "Preparing photos…": "Fotos werden vorbereitet…", "not added to Apple Photos (cancelled)": "nicht zu Apple Fotos hinzugefügt (abgebrochen)", "The first time, macOS asks whether LightCraft may control Photos.": "Beim ersten Mal fragt macOS, ob LightCraft Fotos steuern darf.", "Adding to Apple Photos": "Wird zu Apple Fotos hinzugefügt", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index ff9e7355ff3..2ebff167ea5 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2193,6 +2193,7 @@ "Remove from favorites": "Quitar de favoritos", "Add to Apple Photos": "Añadir a Fotos de Apple", "Adding to Apple Photos…": "Añadiendo a Fotos de Apple…", + "Preparing photos…": "Preparando fotos…", "not added to Apple Photos (cancelled)": "no se añadieron a Fotos de Apple (cancelado)", "The first time, macOS asks whether LightCraft may control Photos.": "La primera vez, macOS pregunta si LightCraft puede controlar Fotos.", "Adding to Apple Photos": "Añadiendo a Fotos de Apple", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e971f91c99c..aafc8fb3f64 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -77,6 +77,7 @@ "Adding photos…": "Lisätään kuvia…", "Adding to Apple Photos": "Lisätään Apple Kuviin", "Adding to Apple Photos…": "Lisätään Apple Kuviin…", + "Preparing photos…": "Valmistellaan kuvia…", "Advanced search…": "Tarkennettu haku…", "After": "Jälkeen", "After 30 days": "30 päivän kuluttua", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 17dd17bd3fa..1c8653fdc8f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2009,6 +2009,7 @@ "Paper": "Papier", "Add to Apple Photos": "Ajouter à Apple Photos", "Adding to Apple Photos…": "Ajout à Apple Photos…", + "Preparing photos…": "Préparation des photos…", "not added to Apple Photos (cancelled)": "non ajouté à Apple Photos (annulé)", "The first time, macOS asks whether LightCraft may control Photos.": "La première fois, macOS demande si LightCraft peut contrôler Photos.", "Adding to Apple Photos": "Ajout à Apple Photos", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index a72b718fd58..3b965512bbf 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -78,6 +78,7 @@ "Adding photos…": "Menambahkan foto…", "Adding to Apple Photos": "Menambahkan ke Apple Photos", "Adding to Apple Photos…": "Menambahkan ke Apple Photos…", + "Preparing photos…": "Menyiapkan foto…", "Advanced search…": "Pencarian lanjutan…", "After": "Sesudah", "After 30 days": "Setelah 30 hari", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 2ddcf037fde..eecc3cfa126 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2162,6 +2162,7 @@ "Remove from favorites": "Rimuovi dai preferiti", "Add to Apple Photos": "Aggiungi a Foto di Apple", "Adding to Apple Photos…": "Aggiunta a Foto di Apple…", + "Preparing photos…": "Preparazione delle foto…", "not added to Apple Photos (cancelled)": "non aggiunte a Foto di Apple (annullato)", "The first time, macOS asks whether LightCraft may control Photos.": "La prima volta, macOS chiede se LightCraft può controllare Foto.", "Adding to Apple Photos": "Aggiunta a Foto di Apple", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 04db1f164aa..9fbf5fc3d2c 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2014,6 +2014,7 @@ "Remove from favorites": "お気に入りから削除", "Add to Apple Photos": "Appleの写真に追加", "Adding to Apple Photos…": "Appleの写真に追加中…", + "Preparing photos…": "写真を準備中…", "not added to Apple Photos (cancelled)": "Appleの写真には追加されませんでした(キャンセル)", "The first time, macOS asks whether LightCraft may control Photos.": "初回は、LightCraftに写真の操作を許可するかmacOSが確認します。", "Adding to Apple Photos": "Appleの写真に追加中", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 9791131d88b..98ba729e3ab 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -130,6 +130,7 @@ "Adding photos…": "ფოტოების დამატება…", "Adding to Apple Photos": "Apple Photos-ში დამატება", "Adding to Apple Photos…": "Apple Photos-ში დამატება…", + "Preparing photos…": "ფოტოების მომზადება…", "Advanced search…": "გაფართოებული ძიება…", "After": "შემდეგ", "After 30 days": "30 დღის შემდეგ", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 9fb5e336956..88dbea053b3 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2056,6 +2056,7 @@ "Adding photos…": "Dodawanie zdjęć…", "Adding to Apple Photos": "Dodawanie do aplikacji Zdjęcia", "Adding to Apple Photos…": "Dodawanie do aplikacji Zdjęcia…", + "Preparing photos…": "Przygotowywanie zdjęć…", "Albums hold library photos: Add to My Photos first": "Albumy zawierają zdjęcia z biblioteki: najpierw dodaj je do Moich zdjęć", "Appearance": "Wygląd", "Appearance Mode": "Tryb wyglądu", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e815f09a475..c4a94ef5db4 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2012,6 +2012,7 @@ "Remove from favorites": "Remover dos favoritos", "Add to Apple Photos": "Adicionar ao Fotos da Apple", "Adding to Apple Photos…": "Adicionando ao Fotos da Apple…", + "Preparing photos…": "Preparando fotos…", "not added to Apple Photos (cancelled)": "não adicionadas ao Fotos da Apple (cancelado)", "The first time, macOS asks whether LightCraft may control Photos.": "Na primeira vez, o macOS pergunta se o LightCraft pode controlar o Fotos.", "Adding to Apple Photos": "Adicionando ao Fotos da Apple", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b7bb62e7d60..7533bd967ee 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2418,6 +2418,7 @@ "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘+перетаскивание — выровнять, ⇧G — направляемое выравнивание, сетка при трансформации.", "Add to Apple Photos": "Добавить в Apple Фото", "Adding to Apple Photos…": "Добавление в Apple Фото…", + "Preparing photos…": "Подготовка фото…", "not added to Apple Photos (cancelled)": "не добавлено в Apple Фото (отменено)", "The first time, macOS asks whether LightCraft may control Photos.": "В первый раз macOS спросит, может ли LightCraft управлять приложением «Фото».", "Adding to Apple Photos": "Добавление в Apple Фото", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 6092355c95d..231b880e33b 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -89,6 +89,7 @@ "Adding photos…": "Lägger till foton…", "Adding to Apple Photos": "Lägger till i Apple Photos", "Adding to Apple Photos…": "Lägger till i Apple Photos…", + "Preparing photos…": "Förbereder foton…", "Advanced search…": "Avancerad sökning…", "After": "Efter", "After 30 days": "Efter 30 dagar", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09e5b0e1e84..79bdc400806 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2203,6 +2203,7 @@ "Paper": "Папір", "Add to Apple Photos": "Додати до Apple Фото", "Adding to Apple Photos…": "Додавання до Apple Фото…", + "Preparing photos…": "Підготовка фото…", "not added to Apple Photos (cancelled)": "не додано до Apple Фото (скасовано)", "The first time, macOS asks whether LightCraft may control Photos.": "Першого разу macOS запитає, чи може LightCraft керувати програмою «Фото».", "Adding to Apple Photos": "Додавання до Apple Фото", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index d31e48dff2c..58ec7029397 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -79,6 +79,7 @@ "Adding photos…": "Đang thêm ảnh…", "Adding to Apple Photos": "Đang thêm vào Ảnh Apple", "Adding to Apple Photos…": "Đang thêm vào Ảnh Apple…", + "Preparing photos…": "Đang chuẩn bị ảnh…", "Advanced search…": "Tìm kiếm nâng cao…", "After": "Sau", "After 30 days": "Sau 30 ngày", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 766d982552b..b098052df51 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2043,6 +2043,7 @@ "smart album value|Yes": "智能相册取值|是", "Add to Apple Photos": "添加到 Apple 照片", "Adding to Apple Photos…": "正在添加到 Apple 照片…", + "Preparing photos…": "正在准备照片…", "not added to Apple Photos (cancelled)": "未添加到 Apple 照片(已取消)", "The first time, macOS asks whether LightCraft may control Photos.": "首次使用时,macOS 会询问是否允许 LightCraft 控制“照片”。", "Adding to Apple Photos": "正在添加到 Apple 照片", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 26ec3e8f61f..7f31b5d3e6e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2012,6 +2012,7 @@ "Remove from favorites": "從最愛移除", "Add to Apple Photos": "加入 Apple 照片", "Adding to Apple Photos…": "正在加入 Apple 照片…", + "Preparing photos…": "正在準備照片…", "not added to Apple Photos (cancelled)": "未加入 Apple 照片(已取消)", "The first time, macOS asks whether LightCraft may control Photos.": "第一次使用時,macOS 會詢問是否允許 LightCraft 控制「照片」。", "Adding to Apple Photos": "正在加入 Apple 照片", diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a9138..99ed0f0ff46 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -85,6 +85,8 @@ impl LightcraftApp { // gate cannot express that (a slow discarded first pass would re-run it). if import_tick_allowed(ctx) { import::tick(self, ctx); + // an export's photos are set up a few at a time, once per host frame like the import's batches + export_task::prepare(self, ctx); } panels::library_problem::import_waiting(self, ctx); lightroom_import::tick(self, ctx); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b24..ae81ffbced7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -606,33 +606,37 @@ pub fn export_active(app: &mut LightcraftApp, p: &Value) -> Result = const { std::cell::Cell::new(PREP_BUDGET) }; +} + +/// Spend `budget` on each frame's preparing in this test's thread. +#[cfg(test)] +pub(crate) fn set_prep_budget(budget: std::time::Duration) { + TEST_PREP_BUDGET.with(|b| b.set(budget)); +} + +fn prep_budget() -> std::time::Duration { + #[cfg(test)] + return TEST_PREP_BUDGET.with(std::cell::Cell::get); + #[cfg(not(test))] + PREP_BUDGET +} + pub struct ExportTask { pub total: usize, /// Photos started so far and the file in progress. @@ -27,31 +53,80 @@ pub struct ExportTask { rx: Receiver, Option, bool), String>>, /// The export's row in the activity stack (`activity.cancel` sets `cancel`). guard: TaskGuard, + /// The photos still being set up, a few each frame ([`prepare`]); the worker starts when it is done. + preparing: Option, +} + +/// An image export whose photos are being prepared, and what its worker needs once they are. +struct Preparing { + /// The session's library when the export started: photo ids mean nothing in another one. + library: u64, + batch: BatchPrep, + opts: ExportOptions, + to: Destination, + after: AfterExport, + write: crate::SharedWrite, + tx: Sender, Option, bool), String>>, + /// The settings Export with Previous is to repeat, kept once the worker has started. + remember: Option, } impl ExportTask { - /// `{total, done, current}` for `ui.inspect`. + /// The photos are still being set up: nothing is rendered or written yet. + pub fn is_preparing(&self) -> bool { + self.preparing.is_some() + } + + /// `{total, done, current, preparing}` for `ui.inspect` (`preparing`: the photos are still being + /// set up, nothing is rendered yet). pub fn status(&self) -> Value { let (done, current) = self.progress.lock().map(|g| g.clone()).unwrap_or_default(); - json!({"total": self.total, "done": done, "current": current}) + json!({"total": self.total, "done": done, "current": current, "preparing": self.preparing.is_some()}) } } -/// Start exporting `items` in the background, then do `after` with the files written (Add to Apple -/// Photos). Errors per photo are collected, not fatal. -pub fn start(app: &mut LightcraftApp, items: Vec, opts: ExportOptions, to: Destination, after: AfterExport) -> Result { +/// Start exporting `ids` in the background, then do `after` with the files written (Add to Apple +/// Photos). The row in the activity stack is there at once; the photos are set up over the frames +/// that follow (see [`prepare`]) and then rendered, encoded and written on a worker. Errors per photo +/// are collected, not fatal; one that can't be set up at all (a photo gone, a demo photo's +/// original…) ends the export with that error, in a toast. `remember` is what Export with Previous is to +/// repeat: kept once the photos are prepared and the worker starts, not for an export that ends before. +pub fn start( + app: &mut LightcraftApp, + ids: Vec, + opts: ExportOptions, + to: Destination, + after: AfterExport, + remember: Value, +) -> Result { if app.export.is_some() { return Err("an export is already running".into()); } let write = app.services.write_shared.clone().ok_or("no background writer")?; - let total = items.len(); + // (a photo that isn't in the library is the request's error, as before the photos were set up in later frames; + // one that goes meanwhile is the export's, after the reply) + if ids.iter().any(|id| app.session.catalog.photo(*id).is_none()) { + return Err("no such photo".into()); + } + let total = ids.len(); let progress = Arc::new(Mutex::new((0, String::new()))); let cancel = Arc::new(AtomicBool::new(false)); let (tx, rx) = channel(); - let (p, c) = (progress.clone(), cancel.clone()); let guard = app.session.activity.start("export", "Exporting", Cancel::Flag(cancel.clone())); guard.progress(0, total as u64); - let row = guard.handle(); + guard.detail(crate::i18n::tr("Preparing photos…")); + let library = app.session.library_generation(); + let preparing = Some(Preparing { library, batch: BatchPrep::new(ids), opts, to, after, write, tx, remember: Some(remember) }); + app.export = Some(ExportTask { total, progress, cancel, rx, guard, preparing }); + Ok(json!({"background": true, "total": total})) +} + +/// Run the prepared photos (none when `stopped`) on a worker; its result reaches `task.rx`. +fn launch(task: &ExportTask, prep: Preparing, stopped: bool) -> Result<(), String> { + let Preparing { batch, opts, to, after, write, tx, .. } = prep; + let items = if stopped { Vec::new() } else { batch.into_items() }; + let (p, c) = (task.progress.clone(), task.cancel.clone()); + let row = task.guard.handle(); // translated here: the language is the UI thread's, and the worker would show English let adding = crate::i18n::tr("Adding to Apple Photos…").to_string(); let work = move || { @@ -81,8 +156,58 @@ pub fn start(app: &mut LightcraftApp, items: Vec, opts: ExportOp std::thread::Builder::new().name("export".into()).spawn(work).map_err(|e| e.to_string())?; #[cfg(target_arch = "wasm32")] work(); - app.export = Some(ExportTask { total, progress, cancel, rx, guard }); - Ok(json!({"background": true, "total": total})) + Ok(()) +} + +/// One frame's share of preparing an export's photos (the logic pass, so it goes on in a full-screen +/// preview, a slideshow and a hidden window): as many as fit [`prep_budget`] (at least one), then the +/// worker starts when all are ready. A stop (✕), or a library switched meanwhile (the photo ids are the +/// old library's), sends the worker off with no photos, so the export ends as a cancelled one does, and +/// `after` is told. An error ends the export. +pub fn prepare(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some(task) = app.export.as_mut() else { return }; + let Some(mut prep) = task.preparing.take() else { return }; + if prep.library != app.session.library_generation() { + task.cancel.store(true, Ordering::Relaxed); + } + let stopped = task.cancel.load(Ordering::Relaxed); + let ready = if stopped { + Ok(true) + } else { + let (began, budget) = (std::time::Instant::now(), prep_budget()); + prep.batch.advance(&mut app.session, &prep.opts, &mut || began.elapsed() < budget) + }; + match ready { + Ok(false) => { + task.preparing = Some(prep); + ctx.request_repaint(); + } + Ok(true) => { + let remember = prep.remember.take(); + match launch(task, prep, stopped) { + // (an export stopped before it got going, by ✕ or by another library, is not the last one) + Ok(()) if !stopped => { + if let Some(last) = remember { + crate::control::remember_export(&mut app.session, last); + } + } + Ok(()) => {} + Err(e) => failed(app, ctx, e), + } + } + // (the row goes with the task, and `after` is dropped unrun: Photos is free again) + Err(e) => failed(app, ctx, e), + } +} + +/// An export that ends after its reply with an error (a photo that can't be set up, a worker that won't start): +/// the row goes, the error is shown in a toast, and `export.last` of `ui.inspect` becomes +/// `{files: [], cancelled: false, applePhotos: null, error}`, so a client that polls sees why the export is over +/// (never the previous export's result as if it were this one's). +fn failed(app: &mut LightcraftApp, ctx: &egui::Context, error: String) { + app.export = None; + app.last_export_result = Some(json!({"files": [], "cancelled": false, "applePhotos": null, "error": error})); + app.toast(ctx, error); } /// Export a single paginated PDF with the same activity row and cancellation as image exports. @@ -128,7 +253,7 @@ pub fn start_contact_sheet(app: &mut LightcraftApp, params: &Value) -> Result Result, total: usize, cancell /// Per frame: keep the activity row up to date; when the batch finishes, report it. pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(task) = &app.export else { return }; + if task.preparing.is_some() { + return; + } match task.rx.try_recv() { Ok(r) => { let cancelled = matches!(&r, Ok((_, _, true))); diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index 48a1161bfdc..7277426408c 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -277,11 +277,34 @@ pub struct Headless { impl Drop for Headless { fn drop(&mut self) { #[cfg(not(target_arch = "wasm32"))] - self.app.session.wait_for_photos_imports(); + { + self.finish_preparing(); + // one still preparing (a run that is panicking, or a batch past the bound) holds Photos' slot + // with no worker to free it: the wait would last its whole hour, so it is let go + if self.app.export.as_ref().is_some_and(crate::export_task::ExportTask::is_preparing) { + self.app.export = None; + } + self.app.session.wait_for_photos_imports(); + } } } impl Headless { + /// Frames until a background export has set its photos up and started its worker. An export + /// still preparing holds its Apple Photos slot without writing anything, so a run that ends + /// now (or waits for Photos) would abandon it, or wait on a slot nothing is working to free. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn finish_preparing(&mut self) { + // (a run that is already failing draws no frame: a panic in one while unwinding aborts the process) + if std::thread::panicking() { + return; + } + let t0 = Instant::now(); + while self.app.export.as_ref().is_some_and(crate::export_task::ExportTask::is_preparing) && t0.elapsed() < Duration::from_secs(120) { + self.step(); + } + } + /// Wrap `app` (its control channel is replaced by the driver's). /// Invalid dimensions fall back to 1600×1000 at scale 1; external callers can use /// [`viewport_pixels`] to reject them before constructing the session. diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index eb05be0c4c9..5953a05c3ca 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -2083,6 +2083,8 @@ fn the_photos_progress_line_is_in_the_users_language() { let params = json!({"ids": ids, "dir": out, "longEdge": 48, "addToPhotos": true, "background": true}); let r = h.request("engine.execute", json!({"command": "app.export", "params": params}), t); assert_eq!(r["ok"], true, "{r}"); + // (the photos are set up over the frames after the request: the worker asks Photos once they are) + h.finish_preparing(); // Photos has been asked, and the window hasn't drawn a frame since (Codex review of #643): // the export's row already has no ✕, and a cancel is refused rather than half-honoured photos_asked.recv_timeout(Duration::from_secs(60)).expect("the export asks Photos"); @@ -2219,6 +2221,36 @@ fn a_headless_run_waits_for_its_exports_photos_import() { let _ = std::fs::remove_dir_all(&dir); } +/// A run that ends in a panic while its export is still setting its photos up draws no more frames, and the +/// export holds Photos' slot with no worker to free it: the drop lets the export go instead of waiting on +/// the slot for the full hour of the writing limit. +#[test] +fn a_headless_run_that_panics_while_an_export_prepares_does_not_wait_on_photos() { + if !cfg!(target_os = "macos") { + return; // addToPhotos is refused before exporting elsewhere + } + crate::export_task::set_prep_budget(Duration::ZERO); + let mut h = demo([800.0, 600.0]); + let dir = std::env::temp_dir().join(format!("lc-photos-headless-panic-drop-{}", std::process::id())); + h.app.services.write_shared = Some(Arc::new(|p: &str, bytes: &[u8]| lightcraft_engine::export::write_file(p, bytes))); + h.app.session.apple_photos = Some(Arc::new(|_: &[String], _| { + Ok(lightcraft_engine::apple_photos::Output { status: Some(0), stdout: "ID\n".into(), stderr: String::new() }) + })); + let ids: Vec = h.app.session.visible_cloned().iter().take(5).map(|p| p.0).collect(); + let p = json!({"ids": ids, "dir": dir.join("out").to_string_lossy(), "longEdge": 32, "addToPhotos": true, "background": true}); + let r = h.request("engine.execute", json!({"command": "app.export", "params": p}), Duration::from_secs(10)); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.export.as_ref().is_some_and(|e| e.is_preparing()), "still setting the photos up"); + let began = Instant::now(); + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _run = h; + panic!("the script failed"); + })); + assert!(run.is_err()); + assert!(began.elapsed() < Duration::from_secs(60), "the drop waited on Photos: {:?}", began.elapsed()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Review of #236: a background export adding to Photos holds the import from before it /// writes. While its files are being written, `export.addToPhotos` is refused with the /// export's job number; the export then adds its files under that job. diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index b353405ffca..40361638abb 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -269,6 +269,228 @@ fn dead_export_worker_leaves_no_row() { assert!(h.app.session.activity.list().is_empty()); } +/// A writer that records every path it is given (and takes `ms` per file). +fn recording_writer(ms: u64) -> (crate::SharedWrite, std::sync::Arc>>) { + let written = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let w = written.clone(); + let write: crate::SharedWrite = std::sync::Arc::new(move |p: &str, _: &[u8]| { + std::thread::sleep(Duration::from_millis(ms)); + w.lock().unwrap().push(p.to_string()); + Ok(()) + }); + (write, written) +} + +/// Starting an export answers at once, with its row in the stack and ✕: the photos are prepared over the +/// frames that follow (a few milliseconds each, on the UI thread), not before the answer. Then the batch +/// runs as ever. +#[test] +fn export_row_is_there_before_its_photos_are_prepared() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + start_export(&mut h, 5); + let seen = h.request("ui.inspect", json!({}), T)["result"].clone(); + assert_eq!(seen["export"]["running"]["preparing"], true, "{}", seen["export"]); + assert_eq!(seen["export"]["running"]["total"], 5, "{}", seen["export"]); + assert_eq!(seen["activity"][0]["kind"], "export", "{}", seen["activity"]); + assert_eq!(seen["activity"][0]["cancellable"], true, "{}", seen["activity"]); + assert!(written.lock().unwrap().is_empty(), "nothing is written before the photos are prepared"); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + assert_eq!(written.lock().unwrap().len(), 5, "{:?}", written.lock().unwrap()); + let last = h.app.last_export_result.clone().expect("the export reports"); + assert_eq!(last["files"].as_array().map(Vec::len), Some(5), "{last}"); + assert!(h.app.session.activity.list().is_empty(), "the row is gone"); +} + +/// The ✕ works while the photos are being prepared: nothing is prepared further or written, and the export +/// ends as a cancelled one does. +#[test] +fn export_can_be_stopped_while_its_photos_are_prepared() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + start_export(&mut h, 5); + let seen = h.request("ui.inspect", json!({}), T)["result"].clone(); + assert_eq!(seen["export"]["running"]["preparing"], true, "{}", seen["export"]); + let id = seen["activity"][0]["id"].as_u64().unwrap(); + assert_eq!(h.request("engine.execute", json!({"command": "activity.cancel", "params": {"id": id}}), T)["ok"], true); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + assert!(written.lock().unwrap().is_empty(), "{:?}", written.lock().unwrap()); + assert!(h.app.last_export_result.as_ref().is_some_and(|r| r["cancelled"] == true), "{:?}", h.app.last_export_result); + assert!(h.app.session.activity.list().is_empty()); +} + +/// A photo that can't be exported (here: a demo photo has no original file to copy) used to be refused by +/// `app.export` before anything started; now the export starts and ends with that error in a toast, with +/// nothing written and no row left. +#[test] +fn a_photo_that_cannot_be_prepared_ends_the_export_with_its_error() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + let params = json!({"ids": ids, "dir": "/lc-test-out", "format": "original", "background": true}); + let r = h.request("engine.execute", json!({"command": "app.export", "params": params}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + let toast = h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default(); + assert!(toast.contains("generated demo photo"), "{toast}"); + assert!(written.lock().unwrap().is_empty(), "nothing is written"); + assert!(h.app.session.activity.list().is_empty(), "no row is left"); + // a client that polls sees why the export is over, not the export before it + let seen = h.request("ui.inspect", json!({}), T)["result"]["export"]["last"].clone(); + assert!(seen["error"].as_str().is_some_and(|e| e.contains("generated demo photo")), "{seen}"); + assert_eq!((seen["files"].as_array().map(Vec::len), &seen["cancelled"]), (Some(0), &json!(false)), "{seen}"); +} + +/// What `export.last` held before is replaced by a deferred failure, not kept as if it were this export's result. +#[test] +fn a_deferred_failure_replaces_the_previous_exports_result() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, _written) = recording_writer(1); + h.app.services.write_shared = Some(write); + h.app.last_export_result = Some(json!({"files": [{"path": "old.jpg"}], "cancelled": false, "applePhotos": null})); + let ids: Vec = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let params = json!({"ids": ids, "dir": "/lc-test-out", "format": "original", "background": true}); + assert_eq!(h.request("engine.execute", json!({"command": "app.export", "params": params}), T)["ok"], true); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + let last = h.app.last_export_result.clone().expect("a result"); + assert!(last["error"].is_string() && last["files"] == json!([]), "{last}"); +} + +/// A photo id that is not in the library is the request's error, as it was before the photos were set up in later +/// frames: no row, no export, and the reply says why. +#[test] +fn an_unknown_photo_id_is_refused_by_the_request() { + let mut h = demo(); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + let params = json!({"ids": [9_999_999u64], "dir": "/lc-test-out", "format": "original", "background": true}); + let r = h.request("engine.execute", json!({"command": "app.export", "params": params}), T); + assert_eq!(r["ok"], false, "{r}"); + assert!(r.to_string().contains("no such photo"), "{r}"); + assert!(h.app.export.is_none() && h.app.session.activity.list().is_empty()); + assert!(written.lock().unwrap().is_empty()); +} + +fn preparing(h: &Headless) -> bool { + h.app.export.as_ref().is_some_and(|e| e.status()["preparing"] == true) +} + +/// The photos are set up whatever the window shows: a full-screen preview (which skips the panels' pass) +/// doesn't hold the export at "Preparing photos…". +#[test] +fn an_exports_photos_are_prepared_in_a_full_screen_preview() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + start_export(&mut h, 5); + assert!(preparing(&h)); + h.app.ui.fullscreen = true; + assert!(h.step_until(Duration::from_secs(60), |h| !preparing(h)), "still preparing in full screen"); + h.app.ui.fullscreen = false; + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + assert_eq!(written.lock().unwrap().len(), 5, "{:?}", written.lock().unwrap()); +} + +/// Photo ids belong to one library: when another is opened while the photos are being prepared, the export +/// ends as a cancelled one does, and nothing is exported from the new library. +#[test] +fn switching_library_while_an_export_prepares_stops_it() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + start_export(&mut h, 5); + assert!(preparing(&h)); + let dir = std::env::temp_dir().join(format!("lc-export-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + h.app.session.open_library(&dir, true).unwrap(); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + assert!(written.lock().unwrap().is_empty(), "{:?}", written.lock().unwrap()); + assert!(h.app.last_export_result.as_ref().is_some_and(|r| r["cancelled"] == true), "{:?}", h.app.last_export_result); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A one-shot headless run (`lightcraft-cli snapshot`) that ends, or waits for Apple Photos, while an export +/// is still setting its photos up would leave Photos' slot held by an export nothing is working on: it +/// first lets the photos get prepared and the worker start. +#[test] +fn a_headless_run_lets_an_exports_photos_get_prepared_before_it_ends() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, _written) = recording_writer(1); + h.app.services.write_shared = Some(write); + start_export(&mut h, 5); + assert!(preparing(&h)); + h.finish_preparing(); + assert!(!preparing(&h), "the worker has not started"); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); +} + +/// The settings of the export before the one a test starts (what Export with Previous would use). +fn previous_export() -> serde_json::Value { + json!({"format": "jpeg", "quality": 77, "dir": "/lc-previous-out"}) +} + +/// What Export with Previous and the Export dialog remember is the last export that got going: a background +/// export's settings are kept once its photos are prepared and the worker starts, not when it is asked for. +#[test] +fn an_export_is_remembered_once_its_photos_are_prepared() { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, _written) = recording_writer(1); + h.app.services.write_shared = Some(write); + h.app.session.last_export = Some(previous_export()); + start_export(&mut h, 5); + assert!(preparing(&h)); + assert_eq!(h.app.session.last_export, Some(previous_export()), "not yet: the photos are not prepared"); + assert!(h.step_until(Duration::from_secs(60), |h| !preparing(h)), "the photos get prepared"); + let last = h.app.session.last_export.clone().expect("remembered"); + assert_eq!(last["dir"], "/lc-test-out", "{last}"); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none())); + assert_eq!(h.app.session.last_export.as_ref().map(|l| &l["dir"]), Some(&json!("/lc-test-out"))); +} + +/// An export that ends before it gets going (a photo that can't be prepared, the ✕ while preparing) is not +/// "the last export": Export with Previous keeps the one before. +#[test] +fn an_export_that_never_got_going_leaves_the_previous_one_alone() { + let kinds: [(&str, fn(&mut Headless)); 2] = [ + ("a photo that can't be prepared", |h| { + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + let params = json!({"ids": ids, "dir": "/lc-test-out", "format": "original", "background": true}); + let r = h.request("engine.execute", json!({"command": "app.export", "params": params}), T); + assert_eq!(r["ok"], true, "{r}"); + }), + ("the ✕ while preparing", |h| { + start_export(h, 5); + let seen = h.request("ui.inspect", json!({}), T)["result"].clone(); + let id = seen["activity"][0]["id"].as_u64().unwrap(); + assert_eq!(h.request("engine.execute", json!({"command": "activity.cancel", "params": {"id": id}}), T)["ok"], true); + }), + // (a library opened meanwhile loads its own last export; the guard is the same `stopped` as the ✕'s: + // `switching_library_while_an_export_prepares_stops_it` shows it stops, and this test is not run for it) + ]; + for (what, go) in kinds { + let mut h = demo(); + crate::export_task::set_prep_budget(Duration::ZERO); + let (write, written) = recording_writer(1); + h.app.services.write_shared = Some(write); + h.app.session.last_export = Some(previous_export()); + go(&mut h); + assert!(h.step_until(Duration::from_secs(60), |h| h.app.export.is_none()), "{what}: the export ended"); + assert!(written.lock().unwrap().is_empty(), "{what}: nothing written"); + assert_eq!(h.app.session.last_export, Some(previous_export()), "{what}: the previous export is still the last"); + } +} + /// A folder of `n` stand-in JPEGs and an app whose file probe takes 100 ms each (a slow drive). fn slow_import(tag: &str, n: usize) -> (Headless, std::path::PathBuf) { gated_import(tag, n, None) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4f255823498..8dc58343d73 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -105,7 +105,7 @@ filmstrip is visible. | `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | -| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | +| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` (`running: {total, done, current, preparing}`: the photos are set up over the frames after the reply, a few milliseconds each, so `preparing` is true and `done` 0 until that is over; `activity.cancel` works throughout). Whatever is wrong with the request itself (params, folder, `ids` that aren't photos in the library, an export already running) is still the reply's error; a photo that can't be exported (gone, a demo photo with `format: "original"`, too big for memory) ends the export after the reply: nothing is written, its row goes, the error is shown in a toast and `export.last` becomes `{files: [], cancelled: false, applePhotos: null, error}`, so a client that polls sees why the export is over (`export.running.preparing` in `ui.inspect` is where preparing shows; `activity.list` rows carry no such field) | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index eb8906f2baf..b3d0e429271 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -463,7 +463,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); starting a background export only adds its row (“Preparing photos…”, with ✕): the photos are set up a few milliseconds a frame (`BatchPrep`), so the window keeps drawing however big the batch, and a photo that can't be exported ends the export with its error in a toast; one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | @@ -1058,3 +1058,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | | 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | +| 2026-10-29 | patch | LR-BEHAV-BG-TASKS: starting a background export (Export dialog, Export with Preset, Export with Previous) no longer freezes the window for about 3 ms per photo while its photos are set up (a second for 300): the row is there at once and the photos are prepared a few milliseconds a frame; ✕ also stops the preparing; a photo that can't be exported ends the export with its error in a toast instead of an error from `app.export`; Export with Previous keeps the last export that got going (the settings are kept once the photos are prepared); status unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index f3339263784..56c4316036e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -221,6 +221,21 @@ ## 2026-10-29 +### Starting an export no longer freezes the window +- Clicking Export (the Export dialog, File ▸ Export with Preset, Export with Previous) used to hold the window still for + about 3 ms per photo while the batch was set up: roughly a quarter of a second for 60 photos and a second for 300. + The export now starts at once, its activity row saying “Preparing photos…” (the stack shows a row once it is half a + second old, as for every task), and the photos are set up a few milliseconds per frame, so the window keeps + responding however big the batch is; ✕ stops the export during that time too. Each photo is read as it is when its + turn comes, so an edit made in those moments counts. A photo that can't be exported at all (for example a demo + photo with no original file when exporting the original, or one purged meanwhile) ends the export with its error in + a toast, and nothing is written; opening another library meanwhile stops the export as ✕ does. Export with + Previous (and the Export dialog's starting settings) keep the last export that got going: one that ends while its + photos are being set up doesn't replace them. A photo id that isn't in the library is refused at once, as before. +- Agents: `app.export {background: true}` still answers at once with `{background: true, total}`; `ui.inspect` → + `export.running.preparing` is true until the photos are set up, and an export that ends with an error after the reply + leaves it in `export.last.error`. See [Control protocol](control-protocol.md). + ### A person's page opens in seconds in a large library - Finding the unnamed faces that look like a person (a person's page, and again after each face confirmed there) now runs on every processor core, and each comparison of two faces uses the processor's vector instructions. In a