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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,13 @@ impl Catalog {
pub fn photos(&self) -> impl Iterator<Item = &Arc<Photo>> {
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<PhotoId>) -> impl Iterator<Item = &Arc<Photo>> {
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()
}
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
61 changes: 61 additions & 0 deletions crates/engine/src/export/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<lightcraft_catalog::PhotoId>,
phase: PrepPhase,
items: Vec<PreparedExport>,
}

enum PrepPhase {
/// Indexing the originals; resumes after the photo given.
Guard(crate::originals::OriginalGuard, Option<lightcraft_catalog::PhotoId>),
Photos(std::sync::Arc<crate::originals::OriginalGuard>),
}

impl BatchPrep {
pub fn new(ids: Vec<lightcraft_catalog::PhotoId>) -> 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<bool, String> {
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<PreparedExport> {
self.items
}
}

fn prepare_guarded(
session: &mut crate::Session,
id: lightcraft_catalog::PhotoId,
Expand Down
38 changes: 38 additions & 0 deletions crates/engine/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
57 changes: 56 additions & 1 deletion crates/engine/src/originals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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<PhotoId>, more: &mut dyn FnMut() -> bool) -> Option<PhotoId> {
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 };
Expand Down Expand Up @@ -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::<Vec<_>>();
assert_eq!((ids(None), ids(Some(PhotoId(3))), ids(Some(PhotoId(7)))), (vec![1, 3, 5, 7], vec![5, 7], Vec::<u64>::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()));
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -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の写真に追加中",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/ka.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 დღის შემდეგ",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/pt-br.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 Фото",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 Фото",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/zh-hans.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 照片",
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/locales/zh-hant.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 照片",
Expand Down
2 changes: 2 additions & 0 deletions crates/ui-egui/src/app/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading