LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Issue #345: preview builds in the activity stack
Andrey Vyrodov9c8a72138986
diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rsindex 3dacc31f2..54f8d0529 100644--- a/crates/engine/src/cmd/previews.rs+++ b/crates/engine/src/cmd/previews.rs@@ -1,7 +1,7 @@//! Build previews ahead of time: each photo's grid thumbnail and its loupe view (standard size,//! or 1:1), rendered into the memory + disk preview cache so browsing and the loupe are instant.-//! Runs on a background thread (the app keeps working; progress / cancel by command), or inline-//! with `wait` (CLI, MCP, tests).+//! Runs on a background thread (the app keeps working; progress / cancel by command, and a row in+//! the activity stack, issue #345), or inline with `wait` (CLI, MCP, tests).use std::sync::Arc;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};@@ -9,6 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use serde_json::{Value, json};use super::{CommandSpec, always, bad, cmd, str_param};+use crate::activity::{Cancel, TaskGuard};use crate::media::{RenderJob, THUMB_SIZES};use crate::{Result, Session};@@ -21,7 +22,8 @@ pub struct PreviewBuild {pub total: usize,pub done: AtomicUsize,pub failed: AtomicUsize,- pub cancel: AtomicBool,+ /// Shared with the build's row in the activity stack (its ✕ sets it).+ pub cancel: Arc<AtomicBool>,pub finished: AtomicBool,/// Damaged smart previews rebuilt (Build Smart Previews only).pub repaired: AtomicUsize,@@ -62,7 +64,19 @@ fn jobs_for(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: Option<usizev}-fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild) {+/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]).+fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard {+ let (kind, label) = match state.what {+ "" => ("previews", "Building previews"),+ "smart previews" => ("smartPreviews", "Building smart previews"),+ _ => ("smartPreviews", "Discarding smart previews"),+ };+ let task = s.activity.start(kind, label, Cancel::Flag(state.cancel.clone()));+ task.progress(0, state.total as u64);+ task+}++fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard) {for photo_jobs in jobs {if state.cancel.load(Ordering::Relaxed) {break;@@ -71,7 +85,8 @@ fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild) {if !ok {state.failed.fetch_add(1, Ordering::Relaxed);}- state.done.fetch_add(1, Ordering::Relaxed);+ let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1);+ task.progress(done as u64, state.total as u64);}state.finished.store(true, Ordering::Relaxed);}@@ -91,17 +106,19 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {let jobs: Vec<Vec<RenderJob>> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect();let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() });s.preview_build = Some(state.clone());+ let task = task_for(s, &state);let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");if wait {- run_all(jobs, &state);+ run_all(jobs, &state, &task);return Ok(state.json());}#[cfg(not(target_arch = "wasm32"))]{+ // the row stays while the worker runs (it is dropped with the closure, however that ends)let st = state.clone();std::thread::Builder::new().name("lc-build-previews".into())- .spawn(move || run_all(jobs, &st))+ .spawn(move || run_all(jobs, &st, &task)).map_err(|e| bad(C, format!("could not start: {e}")))?;}Ok(state.json())@@ -134,7 +151,7 @@ fn smart_run(custom: bool,discard: bool,jobs: Vec<SmartJob>,- state: Option<&PreviewBuild>,+ state: Option<(&PreviewBuild, &TaskGuard)>,) -> std::result::Result<SmartCounts, String> {let mut n = SmartCounts::default();if !discard {@@ -146,7 +163,7 @@ fn smart_run(}}for (id, path, source) in jobs {- if state.is_some_and(|st| st.cancel.load(Ordering::Relaxed)) {+ if state.is_some_and(|(st, _)| st.cancel.load(Ordering::Relaxed)) {break;}if discard {@@ -173,22 +190,23 @@ fn smart_run(n.built += 1;if damaged {n.repaired += 1;- if let Some(st) = state {+ if let Some((st, _)) = state {st.repaired.fetch_add(1, Ordering::Relaxed);}}}Err(e) => {n.failed.push(json!([id.0, e]));- if let Some(st) = state {+ if let Some((st, _)) = state {st.failed.fetch_add(1, Ordering::Relaxed);}}}}}- if let Some(st) = state {- st.done.fetch_add(1, Ordering::Relaxed);+ if let Some((st, task)) = state {+ let done = st.done.fetch_add(1, Ordering::Relaxed).saturating_add(1);+ task.progress(done as u64, st.total as u64);}}Ok(n)@@ -222,11 +240,12 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {let what = if discard { "discarding smart previews" } else { "smart previews" };let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() });s.preview_build = Some(state.clone());+ let task = task_for(s, &state);let st = state.clone();std::thread::Builder::new().name("lc-smart-previews".into()).spawn(move || {- if let Err(e) = smart_run(&dir, custom, discard, jobs, Some(&st)) {+ if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) {log::warn!("{C}: {e}");*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 7b0f6cae7..eec58bc46 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -721,6 +721,42 @@ fn build_previews_fills_the_cache() {assert!(s.execute("library.buildPreviews", &json!({"size": "huge"})).is_err());}+/// Wait (at most a minute) until no background task is listed.+fn wait_activity_empty(s: &Session) {+ let t0 = std::time::Instant::now();+ while !s.activity.list().is_empty() {+ assert!(t0.elapsed().as_secs() < 60, "tasks still listed: {:?}", s.activity.list());+ std::thread::sleep(std::time::Duration::from_millis(20));+ }+}++/// Issue #345: a background preview build is a row in the activity stack while it runs.+#[test]+fn preview_build_shows_in_activity_until_it_finishes() {+ let mut s = demo();+ let ids: Vec<u64> = s.catalog.photos().take(4).map(|p| p.id.0).collect();+ let r = s.execute("library.buildPreviews", &json!({"ids": ids, "size": "full"})).unwrap();+ let tasks = s.activity.list();+ assert_eq!(tasks.first().map(|t| (t.kind, t.total, t.label.as_str())), Some(("previews", 4, "Building previews")), "{tasks:?} {r}");+ assert!(tasks[0].cancellable);+ wait_activity_empty(&s);+ assert_eq!(s.execute("library.previewProgress", &json!({})).unwrap()["running"], false);+}++/// Issue #345: `activity.cancel` stops a preview build like `library.cancelPreviews`.+#[test]+fn activity_cancel_stops_a_preview_build() {+ let mut s = demo();+ let ids: Vec<u64> = s.catalog.photos().map(|p| p.id.0).collect();+ s.execute("library.buildPreviews", &json!({"ids": ids, "size": "full"})).unwrap();+ let id = s.activity.list().first().map(|t| t.id).expect("a previews row");+ s.execute("activity.cancel", &json!({"id": id})).unwrap();+ wait_activity_empty(&s);+ let p = s.execute("library.previewProgress", &json!({})).unwrap();+ assert_eq!(p["cancelled"], true, "{p}");+ assert!(p["done"].as_u64() < p["total"].as_u64(), "stopped part-way: {p}");+}+/// Colour range: a click samples the colour under it, so the mask selects that colour (white/// in the mask view) and not a different one; ⇧ adds samples, up to five.#[test]diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rsindex 784200310..84da187c0 100644--- a/crates/engine/src/tests_import.rs+++ b/crates/engine/src/tests_import.rs@@ -497,6 +497,12 @@ fn damaged_smart_previews_are_rebuilt_and_failed_writes_leave_none() {};assert_eq!((r["done"].as_u64(), r["failed"].as_u64(), r["repaired"].as_u64()), (Some(1), Some(0), Some(1)), "{r}");assert_eq!(std::fs::read(&file).unwrap(), full, "rebuilt whole in the background");+ // its row in the activity stack (issue #345) goes with it+ let t0 = std::time::Instant::now();+ while !s.activity.list().is_empty() && t0.elapsed() < std::time::Duration::from_secs(10) {+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(s.activity.list().is_empty(), "{:?}", s.activity.list());let _ = std::fs::remove_dir_all(&src);let _ = std::fs::remove_dir_all(&lib);}diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.jsonindex ce6c51aa1..9b5f1920d 100644--- a/crates/ui-egui/locales/de.json+++ b/crates/ui-egui/locales/de.json@@ -2021,5 +2021,8 @@"Quit while tasks are running?": "Beenden, während Aufgaben laufen?","Exporting contact sheet": "Kontaktabzug wird exportiert","Reading folder": "Ordner wird gelesen",- "Scanning folder": "Ordner wird durchsucht"+ "Scanning folder": "Ordner wird durchsucht",+ "Building previews": "Vorschauen werden erstellt",+ "Building smart previews": "Smart-Vorschauen werden erstellt",+ "Discarding smart previews": "Smart-Vorschauen werden verworfen"}diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.jsonindex b85268d32..104e75965 100644--- a/crates/ui-egui/locales/es.json+++ b/crates/ui-egui/locales/es.json@@ -1866,5 +1866,8 @@"Quit while tasks are running?": "¿Salir con tareas en curso?","Exporting contact sheet": "Exportando hoja de contactos","Reading folder": "Leyendo carpeta",- "Scanning folder": "Explorando carpeta"+ "Scanning folder": "Explorando carpeta",+ "Building previews": "Generando vistas previas",+ "Building smart previews": "Generando vistas previas inteligentes",+ "Discarding smart previews": "Descartando vistas previas inteligentes"}diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.jsonindex 60962fa56..02dbbc81d 100644--- a/crates/ui-egui/locales/ja.json+++ b/crates/ui-egui/locales/ja.json@@ -1868,5 +1868,8 @@"Quit while tasks are running?": "タスクの実行中に終了しますか?","Exporting contact sheet": "コンタクトシートを書き出し中","Reading folder": "フォルダーを読み込み中",- "Scanning folder": "フォルダーをスキャン中"+ "Scanning folder": "フォルダーをスキャン中",+ "Building previews": "プレビューを作成中",+ "Building smart previews": "スマートプレビューを作成中",+ "Discarding smart previews": "スマートプレビューを破棄中"}diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.jsonindex d97e23dd0..fa1bcac40 100644--- a/crates/ui-egui/locales/pt-br.json+++ b/crates/ui-egui/locales/pt-br.json@@ -1866,5 +1866,8 @@"Quit while tasks are running?": "Sair com tarefas em andamento?","Exporting contact sheet": "Exportando folha de contato","Reading folder": "Lendo pasta",- "Scanning folder": "Verificando pasta"+ "Scanning folder": "Verificando pasta",+ "Building previews": "Gerando prévias",+ "Building smart previews": "Gerando prévias inteligentes",+ "Discarding smart previews": "Descartando prévias inteligentes"}diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.jsonindex f98484d86..453b1e212 100644--- a/crates/ui-egui/locales/ru.json+++ b/crates/ui-egui/locales/ru.json@@ -1579,5 +1579,8 @@"Quit while tasks are running?": "Выйти, пока выполняются задачи?","Exporting contact sheet": "Экспорт контрольного листа","Reading folder": "Чтение папки",- "Scanning folder": "Сканирование папки"+ "Scanning folder": "Сканирование папки",+ "Building previews": "Создание просмотров",+ "Building smart previews": "Создание смарт-просмотров",+ "Discarding smart previews": "Удаление смарт-просмотров"}diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.jsonindex 7fe1e57ff..adcc16f8f 100644--- a/crates/ui-egui/locales/zh-hans.json+++ b/crates/ui-egui/locales/zh-hans.json@@ -1866,5 +1866,8 @@"Quit while tasks are running?": "要在任务运行时退出吗?","Exporting contact sheet": "正在导出联系表","Reading folder": "正在读取文件夹",- "Scanning folder": "正在扫描文件夹"+ "Scanning folder": "正在扫描文件夹",+ "Building previews": "正在构建预览",+ "Building smart previews": "正在构建智能预览",+ "Discarding smart previews": "正在丢弃智能预览"}diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.jsonindex 9cf791417..2c4eca303 100644--- a/crates/ui-egui/locales/zh-hant.json+++ b/crates/ui-egui/locales/zh-hant.json@@ -1866,5 +1866,8 @@"Quit while tasks are running?": "要在工作執行時結束嗎?","Exporting contact sheet": "正在匯出聯絡表","Reading folder": "正在讀取檔案夾",- "Scanning folder": "正在掃描檔案夾"+ "Scanning folder": "正在掃描檔案夾",+ "Building previews": "正在建立預覽",+ "Building smart previews": "正在建立智慧型預覽",+ "Discarding smart previews": "正在捨棄智慧型預覽"}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 1b52ce0b1..03a23ef5a 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -477,7 +477,7 @@ impl LightcraftApp {ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.05, interval)));}- /// Announce the start and end of a Build Previews run.+ /// Announce the end of a Build Previews run.fn preview_build_status(&mut self, ctx: &egui::Context) {use std::sync::atomic::Ordering;let Some(b) = self.session.preview_build.clone() else { return };@@ -500,14 +500,7 @@ impl LightcraftApp {self.toast(ctx, msg);}} else {- if self.ui.preview_build_seen != Some((key, false)) {- self.ui.preview_build_seen = Some((key, false));- let msg = match b.what {- "" => crate::i18n::tr_format!("Building previews for {} photos…", b.total),- what => crate::i18n::tr_format!("Working on {what} for {} photos…", b.total, what = crate::i18n::tr(what)),- };- self.toast(ctx, msg);- }+ // The activity stack shows the run while it works; poll for the end.ctx.request_repaint_after(std::time::Duration::from_millis(250));}}