PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Save in the background so large saves don't freeze the window (#2017) (#2072)
Brennan Stehling85572c61c302
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex c6138edd6..3c5a68221 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -166,6 +166,38 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())}+fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_io::ExportOptions {+ let mut opts = photocraft_io::ExportOptions::default();+ if let Some(q) = settings.jpeg_quality {+ opts.encode.jpeg_quality = q;+ }+ opts.encode.webp_lossless = settings.webp_lossless;+ if let Some(q) = settings.webp_quality {+ opts.encode.webp_quality = q;+ }+ opts.tiff_layers = settings.tiff_layers;+ opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };+ opts+}++/// A save on a worker thread (`Services::save_file`, #2017): encode, then write atomically.+/// Cancelling while encoding leaves the file on disk untouched; once writing starts the save+/// can't be cancelled.+fn save_file(+ doc: &Document,+ path: &str,+ settings: &photocraft_ui_egui::ExportSettings,+ ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,+) -> Result<Vec<String>, String> {+ ctl.progress(0.0, "Encoding");+ let opts = export_options(settings);+ let r = crate::crash_guard::guard("Save", || photocraft_io::export(doc, path, &opts).map_err(|e| e.to_string()))?;+ ctl.commit()?;+ ctl.progress(0.0, "Writing");+ write_atomic(Path::new(path), &r.bytes)?;+ Ok(r.warnings)+}+type SharedRecovery = Rc<RefCell<Option<RecoveryStore>>>;/// Run `f` on the recovery store (`Err` without a config directory). The service closures never@@ -266,18 +298,10 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->crate::crash_guard::guard("Open", || photocraft_io::import(name, bytes).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()))})),export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {- let mut opts = photocraft_io::ExportOptions::default();- if let Some(q) = settings.jpeg_quality {- opts.encode.jpeg_quality = q;- }- opts.encode.webp_lossless = settings.webp_lossless;- if let Some(q) = settings.webp_quality {- opts.encode.webp_quality = q;- }- opts.tiff_layers = settings.tiff_layers;- opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };+ let opts = export_options(settings);crate::crash_guard::guard("Export", || photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))})),+ save_file: Some(Arc::new(save_file)),file_dialog: Some(Box::new(show_file_dialog)),write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),automation_read,diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rsindex 64974cb29..a2e86bd59 100644--- a/crates/ui-egui/src/discard_ui.rs+++ b/crates/ui-egui/src/discard_ui.rs@@ -100,6 +100,13 @@ pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) {ctx.send_viewport_cmd(egui::ViewportCommand::Focus);return;}+ // A save still writing in the background finishes first (a saved copy, say, leaves nothing+ // unsaved); `jobs_ui` repeats the close when it ends.+ if app.saving() {+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);+ app.jobs.close_after_saves = true;+ return;+ }// Leaving: through the platform's own quit where there is one (see `Services::quit`), with// the window left open for it to close.if let Some(quit) = app.services.quit.as_mut() {@@ -150,7 +157,7 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool {return false;}match saved {- Ok(_) => app.tiff_options.is_none(),+ Ok(_) => app.tiff_options.is_none() && !app.saving(),// Backing out of the file dialog is the user's choice, not an error.Err(e) if e == crate::file_dialog::CANCELLED => false,Err(e) => {@@ -162,7 +169,8 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool {}/// A completed save may release the close prompt. Choosing a path only starts a layered TIFF-/// save; TIFF Options calls this after the write. Copies and failed writes leave the doc dirty.+/// save; TIFF Options calls this after the write, and `jobs_ui` when a background save ends.+/// Copies and failed writes leave the doc dirty.pub(crate) fn saved_document(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) {// Still the prompt that asked (quitting may have replaced it meanwhile).if app.tiff_options.is_none()@@ -179,8 +187,9 @@ fn couldnt_save(e: String) -> String {}pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {- // Save can ask for a path and then TIFF Options. Wait for both; cancellation brings us back.- if app.file_dialog_open() || app.tiff_options.is_some() {+ // Save can ask for a path and then TIFF Options, and then write in the background. Wait for+ // all three; cancellation or a failed save brings us back.+ if app.file_dialog_open() || app.tiff_options.is_some() || app.saving() {return;}let Some(p) = &app.discard else { return };@@ -563,6 +572,52 @@ mod tests {assert!(h.state().session.documents().is_empty());}+ #[test]+ fn saving_from_the_prompt_waits_for_a_background_save_then_closes() {+ use egui_kittest::kittest::Queryable;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::{Arc, Mutex};+ let (gate, written) = (Arc::new(AtomicBool::new(false)), Arc::new(Mutex::new(Vec::<String>::new())));+ let mut app = app_with_docs(1);+ make_dirty(&mut app, 0);+ app.session.active_mut().unwrap().path = Some("/pics/big.psd".into());+ app.background_jobs = true;+ let (g, w) = (gate.clone(), written.clone());+ app.services.save_file = Some(Arc::new(move |_, path, _, ctx| {+ while !g.load(Ordering::Relaxed) {+ ctx.check().map_err(|e| e.to_string())?;+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ w.lock().unwrap().push(path.to_string());+ Ok(Vec::new())+ }));+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(+ |ui, app| {+ crate::jobs_ui::tick(app, ui.ctx());+ show(app, ui.ctx());+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.ctx.set_os(egui::os::OperatingSystem::Windows);+ assert!(intercept(h.state_mut(), "file.close", &Value::Null));+ h.run_steps(2);+ h.key_press(Key::Y);+ h.run_steps(3);+ assert!(h.state().saving());+ assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits for the save");+ assert_eq!(h.state().session.documents().len(), 1, "still open while saving");+ gate.store(true, Ordering::Relaxed);+ let t = std::time::Instant::now();+ while h.state().saving() && t.elapsed() < std::time::Duration::from_secs(30) {+ h.step();+ }+ h.run_steps(2);+ assert_eq!(*written.lock().unwrap(), ["/pics/big.psd"]);+ assert!(h.state().discard.is_none());+ assert!(h.state().session.documents().is_empty(), "closed once saved");+ }+#[path = "tiff_tests.rs"]mod tiff_tests;diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex d00feeb07..042dca641 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2047,6 +2047,9 @@Cancelled {label} Zrušeno: {label}Esc to cancel Esc pro zrušeníOpening {name} Otevírání {name}+ Saving {name} Ukládání {name}+ A save to {name} is still running; try again when it finishes Ukládání do {name} stále probíhá; zkuste to znovu, až skončí+ {label} is writing the file and can no longer be cancelled {label} zapisuje soubor a už ho nelze zrušitOpening {name}… Otevírání {name}…Opening… Otevírání…Reading… Načítání…diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex aaf247647..410d5506a 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2019,6 +2019,9 @@Cancelled {label} {label} abgebrochenEsc to cancel Esc zum AbbrechenOpening {name} Öffne {name}+ Saving {name} Speichere {name}+ A save to {name} is still running; try again when it finishes {name} wird noch gespeichert; versuchen Sie es erneut, wenn der Vorgang abgeschlossen ist+ {label} is writing the file and can no longer be cancelled {label} schreibt die Datei und kann nicht mehr abgebrochen werdenOpening {name}… Öffne {name}…Opening… Öffnen…Reading… Lesen…diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex fa51168af..9d492def0 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -1530,6 +1530,9 @@Cancelled {label} Ακυρώθηκε: {label}Esc to cancel Esc για ακύρωσηOpening {name} Άνοιγμα του {name}+ Saving {name} Αποθήκευση του {name}+ A save to {name} is still running; try again when it finishes Η αποθήκευση στο {name} βρίσκεται ακόμη σε εξέλιξη· δοκιμάστε ξανά όταν ολοκληρωθεί+ {label} is writing the file and can no longer be cancelled {label}: γίνεται εγγραφή του αρχείου και δεν μπορεί πλέον να ακυρωθείOpening {name}… Άνοιγμα του {name}…Opening… Άνοιγμα…Reading… Ανάγνωση…diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex fe28cc538..01aa924af 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2031,6 +2031,9 @@Cancelled {label} Se canceló {label}Esc to cancel Esc para cancelarOpening {name} Abriendo {name}+ Saving {name} Guardando {name}+ A save to {name} is still running; try again when it finishes Todavía se está guardando {name}; inténtalo de nuevo cuando termine+ {label} is writing the file and can no longer be cancelled {label} está escribiendo el archivo y ya no se puede cancelarOpening {name}… Abriendo {name}…Opening… Abriendo…Reading… Leyendo…diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex d9668f1a0..edcca95c6 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -1997,6 +1997,9 @@Cancelled {label} {label} : annuléEsc to cancel Échap pour annulerOpening {name} Ouverture de {name}+ Saving {name} Enregistrement de {name}+ A save to {name} is still running; try again when it finishes Un enregistrement de {name} est encore en cours ; réessayez lorsqu’il sera terminé+ {label} is writing the file and can no longer be cancelled {label} écrit le fichier et ne peut plus être annuléOpening {name}… Ouverture de {name}…Opening… Ouverture…Reading… Lecture…diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex d8bf08499..f742d1182 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -1990,6 +1990,9 @@Cancelled {label} {label} dibatalkanEsc to cancel Esc untuk batalOpening {name} Membuka {name}+ Saving {name} Menyimpan {name}+ A save to {name} is still running; try again when it finishes Penyimpanan ke {name} masih berjalan; coba lagi setelah selesai+ {label} is writing the file and can no longer be cancelled {label} sedang menulis berkas dan tidak dapat dibatalkan lagiOpening {name}… Membuka {name}…Opening… Membuka…Reading… Membaca…diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex b44690896..e8b434244 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2029,6 +2029,9 @@Cancelled {label} {label} annullatoEsc to cancel Esc per annullareOpening {name} Apertura {name}+ Saving {name} Salvataggio {name}+ A save to {name} is still running; try again when it finishes Un salvataggio in {name} è ancora in corso; riprova quando termina+ {label} is writing the file and can no longer be cancelled {label} sta scrivendo il file e non può più essere annullatoOpening {name}… Apertura {name}…Opening… Apertura…Reading… Lettura…diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 10f968d25..759151438 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2035,6 +2035,9 @@Cancelled {label} {label} をキャンセルしましたEsc to cancel Esc キーでキャンセルOpening {name} {name} を開いています+ Saving {name} {name} を保存しています+ A save to {name} is still running; try again when it finishes {name} への保存がまだ実行中です。完了してからもう一度お試しください+ {label} is writing the file and can no longer be cancelled {label} はファイルを書き込み中のため、キャンセルできませんOpening {name}… {name} を開いています…Opening… 開いています…Reading… 読み込み中…diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 92c1a567a..43b5d2cf8 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -1992,6 +1992,9 @@Cancelled {label} {label} 작업을 취소했습니다Esc to cancel Esc 키로 취소Opening {name} {name} 여는 중+ Saving {name} {name} 저장 중+ A save to {name} is still running; try again when it finishes {name}에 저장하는 작업이 아직 진행 중입니다. 완료된 후 다시 시도하세요+ {label} is writing the file and can no longer be cancelled {label}: 파일을 쓰는 중이므로 더 이상 취소할 수 없습니다Opening {name}… {name} 여는 중…Opening… 여는 중…Reading… 읽는 중…diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex c22d1b6b3..795a0f4f4 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2009,6 +2009,9 @@Cancelled {label} {label} geannuleerdEsc to cancel Esc om te annulerenOpening {name} {name} openen+ Saving {name} {name} opslaan+ A save to {name} is still running; try again when it finishes Er wordt nog opgeslagen naar {name}; probeer het opnieuw zodra dat klaar is+ {label} is writing the file and can no longer be cancelled {label} schrijft het bestand en kan niet meer worden geannuleerdOpening {name}… {name} openen…Opening… Openen…Reading… Lezen…diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex c9d77f56a..030710e8f 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -2023,6 +2023,9 @@Cancelled {label} Anulowano: {label}Esc to cancel Esc, aby anulowaćOpening {name} Otwieranie {name}+ Saving {name} Zapisywanie {name}+ A save to {name} is still running; try again when it finishes Zapisywanie do {name} wciąż trwa; spróbuj ponownie, gdy się zakończy+ {label} is writing the file and can no longer be cancelled {label} zapisuje plik i nie można już tego anulowaćOpening {name}… Otwieranie {name}…Opening… Otwieranie…Reading… Odczyt…diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 28850d136..e35eb520d 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -1996,6 +1996,9 @@Cancelled {label} {label} canceladoEsc to cancel Esc para cancelarOpening {name} Abrindo {name}+ Saving {name} Salvando {name}+ A save to {name} is still running; try again when it finishes Um salvamento em {name} ainda está em andamento; tente novamente quando terminar+ {label} is writing the file and can no longer be cancelled {label} está gravando o arquivo e não pode mais ser canceladoOpening {name}… Abrindo {name}…Opening… Abrindo…Reading… Lendo…diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 9748b46dc..b6d0cedf9 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2315,6 +2315,9 @@Cancelled {label} {label}: отмененоEsc to cancel Esc — отменаOpening {name} Открытие {name}+ Saving {name} Сохранение {name}+ A save to {name} is still running; try again when it finishes Сохранение в {name} ещё выполняется; повторите попытку после его завершения+ {label} is writing the file and can no longer be cancelled {label}: идёт запись файла, отменить уже нельзяOpening {name}… Открытие {name}…Opening… Открытие…Reading… Чтение…diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 829930874..76e1e7c9c 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2304,6 +2304,9 @@Cancelled {label} Скасовано: {label}Esc to cancel Esc для скасуванняOpening {name} Відкриття {name}+ Saving {name} Збереження {name}+ A save to {name} is still running; try again when it finishes Збереження в {name} ще триває; спробуйте ще раз, коли воно завершиться+ {label} is writing the file and can no longer be cancelled {label}: триває запис файлу, скасувати вже не можнаOpening {name}… Відкриття {name}…Opening… Відкриття…Reading… Читання…diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 4469c27d7..c9ec65666 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2089,6 +2089,9 @@ cameraRaw Blending 混合Cancelled {label} 已取消 {label}Esc to cancel 按 Esc 取消Opening {name} 正在打开 {name}+ Saving {name} 正在保存 {name}+ A save to {name} is still running; try again when it finishes 仍在保存到 {name};请在完成后重试+ {label} is writing the file and can no longer be cancelled {label} 正在写入文件,已无法取消Opening {name}… 正在打开 {name}…Opening… 正在打开…Reading… 正在读取…diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex bb434c076..f0a7df176 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2029,6 +2029,9 @@Cancelled {label} 已取消 {label}Esc to cancel 按 Esc 取消Opening {name} 正在開啟 {name}+ Saving {name} 正在儲存 {name}+ A save to {name} is still running; try again when it finishes 仍在儲存到 {name};請在完成後再試一次+ {label} is writing the file and can no longer be cancelled {label} 正在寫入檔案,已無法取消Opening {name}… 正在開啟 {name}…Opening… 正在開啟…Reading… 正在讀取…diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rsindex 279b60a3c..5dbe6b3f8 100644--- a/crates/ui-egui/src/jobs_ui.rs+++ b/crates/ui-egui/src/jobs_ui.rs@@ -10,18 +10,22 @@//! shown after a short delay so quick jobs don't flash it. Esc cancels.//! - Files opening in the background get a document tab at once ([`OpenTab`]); its canvas area//! shows the progress, and closing the tab cancels the open.+//! - Saves encode and write on a worker ([`start_save`], #2017) under the modal progress dialog;+//! the document is locked meanwhile, and the save is recorded when the job ends.//!//! The canvas keeps showing the pre-job state: workers never touch the session's documents.use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};use std::sync::mpsc::Sender;use egui::{Color32, Rect, RichText, Sense, Stroke, vec2};-use photocraft_engine::jobs::{JobEvent, JobId, JobInfo, JobOutcome, OPEN_JOB, OpenSource, Started};+use photocraft_doc::DocId;+use photocraft_engine::jobs::{JobCtx, JobEvent, JobId, JobInfo, JobOutcome, OPEN_JOB, OpenSource, Started};use serde_json::{Value, json};use crate::theme::Tokens;-use crate::{ControlResponse, PhotocraftApp, notices};+use crate::{ControlResponse, ExportSettings, PhotocraftApp, SaveFileFn, notices};/// Delay before the modal progress dialog appears (quick jobs finish without it).pub const DIALOG_DELAY_MS: f64 = 250.0;@@ -38,6 +42,87 @@ pub struct OpenTab {pub slot: Option<usize>,}+/// The job command of a background save.+pub const SAVE_JOB: &str = "file.save";++const ENCODING: u8 = 0;+const WRITING: u8 = 1;+const CANCELLED: u8 = 2;++/// A save worker's stage, shared between the worker and the UI.+#[derive(Debug, Default)]+pub struct SaveState {+ stage: AtomicU8,+ finished: AtomicBool,+}++impl SaveState {+ /// Cancel unless writing has started; false once it has.+ fn try_cancel(&self) -> bool {+ matches!(self.stage.compare_exchange(ENCODING, CANCELLED, Ordering::AcqRel, Ordering::Acquire), Ok(_) | Err(CANCELLED))+ }++ /// The worker has returned (or unwound): nothing of this save can still touch the file.+ pub fn finished(&self) -> bool {+ self.finished.load(Ordering::Acquire)+ }+}++/// Marks the worker finished when the work closure is dropped, which also covers a panic.+struct WorkerDone(Arc<SaveState>);++impl Drop for WorkerDone {+ fn drop(&mut self) {+ self.0.finished.store(true, Ordering::Release);+ }+}++/// What a save worker gets (see [`crate::Services::save_file`]): the job's progress and+/// cancellation, and [`commit`](Self::commit), the point after which the save can no longer+/// be cancelled.+pub struct SaveCtl {+ pub job: JobCtx,+ state: Arc<SaveState>,+}++impl SaveCtl {+ pub fn progress(&self, fraction: f32, message: &str) {+ self.job.progress(fraction, message);+ }++ /// `Err` once the save was cancelled: stop, write nothing.+ pub fn check(&self) -> Result<(), String> {+ if self.job.cancelled() || self.state.stage.load(Ordering::Acquire) == CANCELLED { Err(SAVE_CANCELLED.into()) } else { Ok(()) }+ }++ /// Call once, right before replacing the file. `Ok`: the save can no longer be cancelled+ /// (Cancel and Esc are refused) and must run to the end; `Err`: it was cancelled first and+ /// nothing may be written.+ pub fn commit(&self) -> Result<(), String> {+ self.check()?;+ self.state.stage.compare_exchange(ENCODING, WRITING, Ordering::AcqRel, Ordering::Acquire).map(|_| ()).map_err(|_| SAVE_CANCELLED.into())+ }+}++/// The error a cancelled save worker returns.+const SAVE_CANCELLED: &str = "cancelled";++/// A save running in the background: what to record once the file is written.+#[derive(Clone, Debug)]+pub struct SaveJob {+ pub job: JobId,+ pub doc: DocId,+ /// The document's revision when the save started (the job locks it against edits).+ pub revision: u64,+ pub path: String,+ /// A copy leaves the document's path and unsaved state alone.+ pub copy: bool,+ pub state: Arc<SaveState>,+ /// The job has ended (cancelled, say) but its worker may still be running: kept until it+ /// returns, so quitting and another save to the same file wait for it.+ pub ended: bool,+}+/// The shell's job bookkeeping.#[derive(Default)]pub struct JobsUi {@@ -45,6 +130,10 @@ pub struct JobsUi {pub(crate) waiters: Vec<(JobId, Sender<ControlResponse>)>,/// Background opens, in tab order.pub opens: Vec<OpenTab>,+ /// Background saves.+ pub saves: Vec<SaveJob>,+ /// The window was asked to close while a save was writing: close it once none is left.+ pub close_after_saves: bool,/// The open tab shown in the canvas area instead of the active document.pub focus: Option<JobId>,/// The job the latest [`run`] started (the control channel waits on it).@@ -88,16 +177,115 @@ pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, sou}}+/// Save the active document to `path` in the background: `save` encodes and writes it on a+/// worker while the window keeps drawing and shows the progress dialog. The document is locked+/// until the job ends, which [`tick`] records like a synchronous save. `Ok(None)`: started;+/// `Ok(Some(..))`: it ran inline (wasm) and is already recorded.+pub fn start_save(+ app: &mut PhotocraftApp,+ path: String,+ settings: ExportSettings,+ copy: bool,+ save: SaveFileFn,+) -> Result<Option<(String, Vec<String>)>, String> {+ let st = app.session.active().ok_or("no document")?;+ if let Some(j) = app.session.job_on(st.doc.id) {+ // The engine's wording for a command refused while a job runs.+ return Err(format!("“{}” is still running on this document; wait for it to finish or cancel it (Esc)", j.label));+ }+ let name = crate::file_open::display_name(&path);+ // One writer per file: an older snapshot must not land after a newer one.+ if app.jobs.saves.iter().any(|s| s.path == path) {+ return Err(crate::i18n::fmt(tl!("A save to {name} is still running; try again when it finishes"), &[("name", &name)]));+ }+ let (snapshot, doc, revision) = (Arc::clone(&st.doc), st.doc.id, st.revision);+ let label = crate::i18n::fmt(tl!("Saving {name}"), &[("name", &name)]);+ let target = path.clone();+ let state = Arc::new(SaveState::default());+ let worker = Arc::clone(&state);+ let started = app.session.start_job(+ SAVE_JOB,+ json!({"path": path}),+ &label,+ true,+ move |ctx| {+ let _done = WorkerDone(Arc::clone(&worker));+ let ctl = SaveCtl { job: ctx.clone(), state: worker };+ save(&snapshot, &target, &settings, &ctl)+ .map_err(|e| if ctl.check().is_err() { photocraft_engine::EngineError::Cancelled } else { photocraft_engine::EngineError::Other(e) })+ },+ |_, warnings: Vec<String>| Ok(json!({"warnings": warnings})),+ );+ match started.map_err(|e| e.to_string())? {+ Started::Done(v) => {+ let warnings = warnings_of(&v);+ app.saved(doc, revision, &path, &warnings, copy);+ Ok(Some((path, warnings)))+ }+ Started::Job(job) => {+ app.jobs.saves.push(SaveJob { job, doc, revision, path, copy, state, ended: false });+ // Control and MCP requests wait on it, as for other jobs.+ app.jobs.last_started = Some(job);+ // The status bar's progress readout names the save; clear any old message.+ app.ui.status.clear();+ app.ui.status_error = false;+ Ok(None)+ }+ }+}++fn warnings_of(v: &Value) -> Vec<String> {+ v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default()+}++/// A background save ended: record it, or report why not. The close prompt waiting on it moves+/// on, or asks again.+fn finish_save(app: &mut PhotocraftApp, ctx: &egui::Context, save: SaveJob, label: &str, outcome: JobOutcome) {+ match outcome {+ JobOutcome::Done(v) => {+ app.saved(save.doc, save.revision, &save.path, &warnings_of(&v), save.copy);+ if !save.copy {+ crate::discard_ui::saved_document(app, ctx, save.doc);+ }+ }+ JobOutcome::Failed(err) => {+ // Don't close the window over the error.+ app.jobs.close_after_saves = false;+ notices::error(app, crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &err)]));+ }+ JobOutcome::Cancelled => {+ app.jobs.close_after_saves = false;+ app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", label)]);+ app.ui.status_error = false;+ }+ }+ close_after_saves(app, ctx);+}++/// Forget saves whose job ended and whose worker has returned; repeat a held window close once+/// no save worker is left.+fn close_after_saves(app: &mut PhotocraftApp, ctx: &egui::Context) {+ app.jobs.saves.retain(|s| !(s.ended && s.state.finished()));+ if !app.saving() && std::mem::take(&mut app.jobs.close_after_saves) {+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);+ }+}+/// Per frame: apply finished jobs and react to them; keep frames coming while jobs run; Esc/// cancels the job in view.pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {for e in app.session.poll_jobs() {- on_event(app, e);+ on_event(app, ctx, e);}// A focused open tab that ended (or was cancelled elsewhere) gives way to the documents.if app.jobs.focus.is_some_and(|j| !app.jobs.opens.iter().any(|o| o.job == j)) {app.jobs.focus = app.jobs.opens.last().map(|o| o.job);}+ if app.saving() {+ close_after_saves(app, ctx);+ // Keep checking on a cancelled save's worker until it returns.+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }if !app.session.has_jobs() {return;}@@ -123,6 +311,15 @@ pub fn job_in_view(app: &PhotocraftApp) -> Option<JobInfo> {/// Cancel job `id` (the status bar's ×, the dialog's Cancel, Esc, closing an opening tab).pub fn cancel(app: &mut PhotocraftApp, id: JobId) {let label = app.session.job(id).map(|j| j.label);+ // A save that has started replacing the file runs to the end: cancelling it now would leave+ // the file written but the document marked unsaved.+ if let Some(save) = app.jobs.saves.iter().find(|s| s.job == id)+ && !save.state.try_cancel()+ {+ app.ui.status = crate::i18n::fmt(tl!("{label} is writing the file and can no longer be cancelled"), &[("label", label.as_deref().unwrap_or_default())]);+ app.ui.status_error = false;+ return;+ }if app.session.cancel_job(id) {// The event (and its status text) arrives with the next poll; say so now as well.if let Some(l) = label {@@ -132,7 +329,7 @@ pub fn cancel(app: &mut PhotocraftApp, id: JobId) {}}-fn on_event(app: &mut PhotocraftApp, e: JobEvent) {+fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {// Control requests waiting on this job.let reply = match &e.outcome {JobOutcome::Done(v) => json!({"ok": true, "result": v}),@@ -151,6 +348,19 @@ fn on_event(app: &mut PhotocraftApp, e: JobEvent) {if crate::camera_raw_ui::on_redevelop_event(app, &e) {return;}+ if e.command == SAVE_JOB+ && let Some(i) = app.jobs.saves.iter().position(|s| s.job == e.id)+ {+ // A cancelled save's worker may still be running: keep it counted until it returns.+ let save = if app.jobs.saves[i].state.finished() {+ app.jobs.saves.remove(i)+ } else {+ app.jobs.saves[i].ended = true;+ app.jobs.saves[i].clone()+ };+ finish_save(app, ctx, save, &e.label, e.outcome);+ return;+ }if e.command == OPEN_JOB {let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return };let tab = app.jobs.opens.remove(i);@@ -382,6 +592,7 @@ pub fn inspect(app: &PhotocraftApp) -> Value {json!({"running": app.session.jobs(),"opening": app.jobs.opens.iter().map(|o| json!({"job": o.job.0, "name": o.name, "path": o.path})).collect::<Vec<_>>(),+ "saving": app.jobs.saves.iter().map(|s| json!({"job": s.job.0, "path": s.path})).collect::<Vec<_>>(),"focus": app.jobs.focus.map(|j| j.0),"background": app.background_jobs,})diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rsindex e02df99ce..aa6b391b7 100644--- a/crates/ui-egui/src/jobs_ui_tests.rs+++ b/crates/ui-egui/src/jobs_ui_tests.rs@@ -297,3 +297,229 @@ fn templates_open_untitled_in_the_background() {assert_eq!((st.doc.name.as_str(), st.path.as_deref()), ("Untitled-1", None));assert_eq!(h.state().ui.recent_files.first().map(String::as_str), Some("/tmp/photocraft-test/card.psdt"));}++/// Gates for a fake save: it encodes until `encode` opens and writes until `write` opens+/// (polling for cancellation only while encoding, as the real one does).+#[derive(Clone, Default)]+struct Gates {+ encode: Arc<AtomicBool>,+ write: Arc<AtomicBool>,+ written: Arc<std::sync::Mutex<Vec<String>>>,+}++impl Gates {+ fn open() -> Self {+ let g = Gates::default();+ g.encode.store(true, Ordering::Relaxed);+ g.write.store(true, Ordering::Relaxed);+ g+ }++ /// A `save_file` service held by these gates that records the path written, or fails with+ /// `fail` once encoded.+ fn save(&self, fail: Option<&'static str>) -> crate::SaveFileFn {+ let g = self.clone();+ Arc::new(move |_, path, _, ctl| {+ ctl.progress(0.0, "Encoding");+ while !g.encode.load(Ordering::Relaxed) {+ ctl.check()?;+ std::thread::sleep(Duration::from_millis(1));+ }+ if let Some(e) = fail {+ return Err(e.into());+ }+ ctl.commit()?;+ ctl.progress(0.0, "Writing");+ while !g.write.load(Ordering::Relaxed) {+ std::thread::sleep(Duration::from_millis(1));+ }+ g.written.lock().unwrap().push(path.to_string());+ Ok(vec!["a warning".into()])+ })+ }++ fn written(&self) -> Vec<String> {+ self.written.lock().unwrap().clone()+ }+}++fn noticed(app: &PhotocraftApp, text: &str) -> bool {+ app.ui.notices.iter().any(|n| n.title.contains(text) || n.lines.iter().any(|l| l.contains(text)))+}++fn step_until(h: &mut Harness<'_, PhotocraftApp>, done: impl Fn(&PhotocraftApp) -> bool) {+ let t = Instant::now();+ while !done(h.state()) && t.elapsed() < Duration::from_secs(30) {+ h.step();+ }+ h.run_steps(2);+}++#[test]+fn saves_run_in_the_background_and_are_recorded_when_they_end() {+ let mut h = app_harness();+ let gates = Gates { write: Arc::new(AtomicBool::new(true)), ..Gates::default() };+ h.state_mut().services.save_file = Some(gates.save(None));+ let r = h.state_mut().save_as(Some("/tmp/photocraft-test/big.psd".into())).unwrap();+ assert_eq!(r["pending"], true);+ assert_eq!(r["job"].as_u64(), h.state().jobs.saves.first().map(|s| s.job.0), "control clients get the job to wait on");+ assert!(h.state().saving());++ // The window keeps drawing; the document stays unsaved and can't be edited meanwhile.+ let (frames, _) = frames_for(&mut h, 400);+ assert!(frames >= 4, "only {frames} frames while saving");+ let st = h.state().session.active().unwrap();+ assert!(st.is_dirty() && st.path.is_none());+ assert!(h.state_mut().run("layer.new.layer", json!({})).is_err(), "the saving document is locked");+ // The progress dialog and the status bar name the save; the dialog shows its stage.+ assert_eq!(h.query_all_by_label("Saving big.psd").count(), 2);+ h.get_by_label("Encoding");++ gates.encode.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert_eq!(gates.written(), ["/tmp/photocraft-test/big.psd"]);+ let st = h.state().session.active().unwrap();+ assert!(!st.is_dirty());+ assert_eq!(st.path.as_deref(), Some("/tmp/photocraft-test/big.psd"));+ assert_eq!(st.doc.name, "big.psd", "the document takes the saved file's name, as a synchronous Save As does");+ assert_eq!(h.state().ui.status, "Saved big.psd: a warning");+ assert!(noticed(h.state(), "a warning"), "the export warnings are shown");+ assert!(h.state_mut().run("layer.new.layer", json!({})).is_ok(), "unlocked again");+}++#[test]+fn a_failed_save_or_one_cancelled_while_encoding_leaves_the_document_unsaved() {+ let mut h = app_harness();+ let gates = Gates::open();+ h.state_mut().services.save_file = Some(gates.save(Some("disk full")));+ h.state_mut().save_as(Some("/tmp/photocraft-test/a.psd".into())).unwrap();+ step_until(&mut h, |a| !a.saving());+ let st = h.state().session.active().unwrap();+ assert!(st.is_dirty() && st.path.is_none());+ assert!(noticed(h.state(), "disk full"), "the failure is reported");++ gates.encode.store(false, Ordering::Relaxed);+ h.state_mut().services.save_file = Some(gates.save(None));+ h.state_mut().save_as(Some("/tmp/photocraft-test/b.psd".into())).unwrap();+ h.run_steps(2);+ h.key_press(egui::Key::Escape);+ step_until(&mut h, |a| !a.saving());+ assert!(gates.written().is_empty(), "nothing written");+ let st = h.state().session.active().unwrap();+ assert!(st.is_dirty() && st.path.is_none());+ assert_eq!(h.state().ui.status, "Cancelled Saving b.psd");+}++/// Step until the save in `h` has started writing.+fn until_writing(h: &mut Harness<'_, PhotocraftApp>) {+ let t = Instant::now();+ while h.state().session.jobs().first().is_none_or(|j| j.message != "Writing") && t.elapsed() < Duration::from_secs(30) {+ h.step();+ }+}++#[test]+fn a_save_that_has_started_writing_cannot_be_cancelled() {+ let mut h = app_harness();+ let gates = Gates { encode: Arc::new(AtomicBool::new(true)), ..Gates::default() };+ h.state_mut().services.save_file = Some(gates.save(None));+ h.state_mut().save_as(Some("/tmp/photocraft-test/w.psd".into())).unwrap();+ until_writing(&mut h);+ let job = h.state().jobs.saves[0].job;+ crate::jobs_ui::cancel(h.state_mut(), job);+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!(h.state().ui.status, "Saving w.psd is writing the file and can no longer be cancelled");+ assert!(h.state().session.job(job).is_some(), "still running, the document still locked");++ gates.write.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert_eq!(gates.written(), ["/tmp/photocraft-test/w.psd"]);+ assert!(!h.state().session.active().unwrap().is_dirty(), "the written save is recorded");+}++/// One frame with the window's close button pressed; whether the guard cancelled the close.+fn press_window_close(app: &mut PhotocraftApp) -> bool {+ let mut info = egui::ViewportInfo::default();+ info.events.push(egui::ViewportEvent::Close);+ let mut input = egui::RawInput::default();+ input.viewports.insert(egui::ViewportId::ROOT, info);+ let mut out = egui::Context::default().run_ui(input, |ui| crate::discard_ui::guard_window_close(app, ui.ctx()));+ out.textures_delta.clear();+ out.viewport_output.remove(&egui::ViewportId::ROOT).is_some_and(|o| o.commands.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)))+}++/// A clean document (so the close prompt has nothing to ask) saved as a copy in the background.+fn save_a_copy(h: &mut Harness<'static, PhotocraftApp>, gates: &Gates, path: &str) {+ h.state_mut().services.save_file = Some(gates.save(None));+ let st = h.state_mut().session.active_mut().unwrap();+ st.saved_revision = st.revision;+ assert_eq!(h.state_mut().write_document(path.into(), &crate::ExportSettings::default(), true), Ok(None));+ h.run_steps(2);+}++#[test]+fn quitting_waits_for_a_background_save_to_finish() {+ let mut h = app_harness();+ let gates = Gates { write: Arc::new(AtomicBool::new(true)), ..Gates::default() };+ save_a_copy(&mut h, &gates, "/tmp/photocraft-test/copy.psd");+ assert!(press_window_close(h.state_mut()), "the close waits for the save");+ assert!(h.state().jobs.close_after_saves);++ gates.encode.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert_eq!(gates.written(), ["/tmp/photocraft-test/copy.psd"]);+ assert!(!h.state().jobs.close_after_saves, "the close is repeated once the save ends");+}++#[test]+fn a_failed_save_does_not_close_the_window_over_its_error() {+ let mut h = app_harness();+ let gates = Gates::default();+ h.state_mut().services.save_file = Some(gates.save(Some("disk full")));+ let st = h.state_mut().session.active_mut().unwrap();+ st.saved_revision = st.revision;+ h.state_mut().write_document("/tmp/photocraft-test/copy.psd".into(), &crate::ExportSettings::default(), true).unwrap();+ assert!(press_window_close(h.state_mut()));+ gates.encode.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert!(noticed(h.state(), "disk full"));+ assert!(!h.state().jobs.close_after_saves, "the window stays open to show the error");+}++#[test]+fn a_cancelled_save_still_counts_until_its_worker_returns() {+ let mut h = app_harness();+ // A worker that keeps encoding after the cancel, as the real encoder does (it checks only+ // before writing).+ let (encode, release) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));+ let (e, r) = (encode.clone(), release.clone());+ h.state_mut().services.save_file = Some(Arc::new(move |_, _, _, ctl| {+ while !r.load(Ordering::Relaxed) {+ e.store(true, Ordering::Relaxed);+ std::thread::sleep(Duration::from_millis(1));+ }+ ctl.commit()?;+ Ok(Vec::new())+ }));+ let st = h.state_mut().session.active_mut().unwrap();+ st.saved_revision = st.revision;+ h.state_mut().write_document("/tmp/photocraft-test/c.psd".into(), &crate::ExportSettings::default(), true).unwrap();+ while !encode.load(Ordering::Relaxed) {+ std::thread::sleep(Duration::from_millis(1));+ }+ let job = h.state().jobs.saves[0].job;+ crate::jobs_ui::cancel(h.state_mut(), job);+ h.run_steps(3);+ assert!(h.state().session.job(job).is_none(), "the job ended");+ assert!(h.state().saving(), "but its worker is still running");+ assert!(press_window_close(h.state_mut()), "quitting waits for the worker");+ assert!(+ h.state_mut().save_as(Some("/tmp/photocraft-test/c.psd".into())).unwrap_err().contains("still running"),+ "a second save to the same file waits for it too"+ );++ release.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert!(!h.state().jobs.close_after_saves, "the held close is repeated once the worker returns");+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 51d18202b..5989c6fc7 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -203,6 +203,10 @@ impl Default for ExportSettings {/// Encode a document: (file bytes, warnings about anything approximated or dropped).pub type ExportFn = Box<dyn Fn(&Document, &str, &ExportSettings) -> Result<(Vec<u8>, Vec<String>), String>>;pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;+/// Encode a document and write it to a path, reporting the stage to the job; returns the export+/// warnings. Runs on a worker thread (see [`Services::save_file`]). It must call+/// [`jobs_ui::SaveCtl::commit`] right before replacing the file, and write nothing if that fails.+pub type SaveFileFn = std::sync::Arc<dyn Fn(&Document, &str, &ExportSettings, &jobs_ui::SaveCtl) -> Result<Vec<String>, String> + Send + Sync>;/// Read bytes through the desktop control session's authorized read root.pub type AutomationReadFn = Box<dyn FnMut(&str) -> Result<(String, Vec<u8>), String>>;/// Write bytes through the desktop control session's authorized write root.@@ -269,6 +273,9 @@ pub struct Services {pub file_dialog: Option<FileDialogFn>,/// Write bytes to a path (native) or trigger a download (web).pub write: Option<WriteFn>,+ /// Encode and write in one step on a worker thread, so a large save doesn't freeze the+ /// window (#2017). With background jobs on, saves use it instead of `export` and `write`.+ pub save_file: Option<SaveFileFn>,/// File access used only by control/MCP requests. Interactive dialogs keep/// using `file_dialog` and `write` with the user's authority.pub automation_read: Option<AutomationReadFn>,@@ -962,34 +969,63 @@ impl PhotocraftApp {tiff_options_ui::park(self, path.clone())?;return Ok(serde_json::json!({"path": path, "warnings": []}));}- let (path, warnings) = self.write_document(path, &ExportSettings::default(), false)?;- Ok(serde_json::json!({"path": path, "warnings": warnings}))+ match self.write_document(path.clone(), &ExportSettings::default(), false)? {+ Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})),+ None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})),+ }}/// Encodes the active document with `settings` and writes it to `path`, which becomes the/// document's path unless saving a copy. A copy leaves the original's path and unsaved- /// changes intact. Returns the path and the export warnings (also shown to the user).- pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result<(String, Vec<String>), String> {+ /// changes intact. Returns the path and the export warnings (also shown to the user), or+ /// `None` when the save went to a background job (#2017), which finishes it in+ /// [`jobs_ui::tick`].+ pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result<Option<(String, Vec<String>)>, String> {+ if self.background_jobs+ && let Some(save) = self.services.save_file.clone()+ {+ return jobs_ui::start_save(self, path, settings.clone(), copy, save);+ }let st = self.session.active().ok_or("no document")?;+ let (doc, revision) = (st.doc.id, st.revision);let export = self.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(&st.doc, &path, settings)?;let write = self.services.write.as_mut().ok_or("no writer configured")?;write(&path, &bytes)?;- if !copy && let Some(st) = self.session.active_mut() {- st.saved_to(path.clone());- }+ self.saved(doc, revision, &path, &warnings, copy);+ Ok(Some((path, warnings)))+ }++ /// Record a written save of document `doc` as it was at `revision`: its name, path and saved+ /// state (unless a copy), the status, script events and the warnings.+ pub(crate) fn saved(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) {self.ui.status = format!("Saved {path}");- // "Save Document" script events and File › Generate › Image Assets.- if !copy- && let Some(i) = self.session.active_index()- && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut self.session, i)- {- self.ui.status = format!("Saved {path}; {} image assets in {}", r["files"].as_array().map_or(0, Vec::len), r["dir"].as_str().unwrap_or(""));+ if !copy {+ // A background save may finish while another document is active (or after its+ // document was closed, when there is nothing left to record).+ let _ = self.with_document(doc, |app| {+ if let Some(st) = app.session.active_mut() {+ st.saved_to(path.to_string());+ // The job locked the document, but record the revision that was written.+ st.saved_revision = revision;+ }+ // "Save Document" script events and File › Generate › Image Assets.+ if let Some(i) = app.session.active_index()+ && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, i)+ {+ app.ui.status = format!("Saved {path}; {} image assets in {}", r["files"].as_array().map_or(0, Vec::len), r["dir"].as_str().unwrap_or(""));+ }+ Ok(())+ });}self.ui.status_error = false;- notices::io_warnings(self, &format!("Saved {}", file_open::display_name(&path)), &warnings);+ notices::io_warnings(self, &format!("Saved {}", file_open::display_name(path)), warnings);self.sync_views();- Ok((path, warnings))+ }++ /// A save is running in the background.+ pub(crate) fn saving(&self) -> bool {+ !self.jobs.saves.is_empty()}/// Save through the control session's capability-scoped writer. No filediff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rsindex 8614ffcaa..163c71714 100644--- a/crates/ui-egui/src/tiff_options_ui.rs+++ b/crates/ui-egui/src/tiff_options_ui.rs@@ -71,11 +71,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);}let settings = ExportSettings { tiff_layers: !p.discard_layers, ..Default::default() };- if let Err(e) = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers)) {- app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);- app.ui.status_error = true;- } else if !p.discard_layers {- crate::discard_ui::saved_document(app, ctx, p.doc);+ match app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers)) {+ Err(e) => {+ app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);+ app.ui.status_error = true;+ }+ Ok(Some(_)) if !p.discard_layers => crate::discard_ui::saved_document(app, ctx, p.doc),+ // A background save releases the close prompt when it finishes (`jobs_ui`).+ Ok(_) => {}}} else if cancel {app.tiff_options = None;diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 79ddbe531..a7208f8f1 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -147,7 +147,7 @@ editing session; non-type layers return an error without changing the tool or do### Background jobs (#210)-Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`) and file opens run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke` and `ui.dialog.confirm` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.+Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`), file opens and interactive saves (File › Save, Save As and the TIFF Options continuation, #2017) run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke` and `ui.dialog.confirm` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files, saving files). `app.save` still writes before it replies. Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.## Preferences