Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

app.save: encode on the save worker, not the UI thread (#2488) (#2517)

Ahmed Hosnyc25630b5faca
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index bd8eb15f2..eba756471 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -200,24 +200,34 @@ fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_i
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(
+/// A save on a worker thread (`Services::save_file` and `Services::automation_save`, #2017):
+/// encode, then write through `write`. Cancelling while encoding leaves the target untouched;
+/// once writing starts the save can't be cancelled.
+fn save_through(
doc: &Document,
path: &str,
settings: &photocraft_ui_egui::ExportSettings,
ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,
+ write: impl Fn(&str, &[u8]) -> Result<(), String>,
) -> 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)?;
+ write(path, &r.bytes)?;
Ok(r.warnings)
}
+fn save_file(
+ doc: &Document,
+ path: &str,
+ settings: &photocraft_ui_egui::ExportSettings,
+ ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,
+) -> Result<Vec<String>, String> {
+ save_through(doc, path, settings, ctl, |p, b| write_atomic(Path::new(p), b))
+}
+
type SharedRecovery = Rc<RefCell<Option<RecoveryStore>>>;
/// Run `f` on the recovery store (`Err` without a config directory). The service closures never
@@ -315,6 +325,11 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
let automation_write = automation.clone().map(|workspace| {
Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn
});
+ let automation_save = automation.clone().map(|workspace| {
+ std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
+ save_through(doc, path, settings, ctl, |p, b| workspace.write(p, b).map_err(|e| e.to_string()))
+ }) as photocraft_ui_egui::SaveFileFn
+ });
let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step;
let automation_authorize = automation.is_some().then_some(step);
let automation_command = automation.map(|_| {
@@ -337,6 +352,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
automation_read,
automation_write,
+ automation_save,
automation_command,
automation_authorize,
encode_png: Some(Box::new(|w, h, rgba| {
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index f84969e9a..7710c228c 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -979,7 +979,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
}
None => err("missing `path`"),
},
- "app.save" => wrap(app.save_automation(s("path").map(str::to_string)).map(|(p, w)| json!({"path": p, "warnings": w}))),
+ "app.save" => run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), |app| app.save_automation(s("path").map(str::to_string))),
"app.quit" => {
app.allow_close = true;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
@@ -1854,6 +1854,130 @@ mod tests {
}
}
+ #[test]
+ fn app_save_runs_as_a_background_job_and_the_final_reply_carries_the_path() {
+ use photocraft_engine::automate_cmds::ScriptBinding;
+ use serde_json::json;
+ let saved: std::sync::Arc<std::sync::Mutex<Vec<String>>> = Default::default();
+ let record = saved.clone();
+ let services = crate::Services {
+ automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, _ctl| {
+ record.lock().unwrap().push(path.to_string());
+ Ok(vec!["Layers were flattened".to_string()])
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ app.background_jobs = true;
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ // A "Save Document" binding that would leave a trace: automation saves never fire it.
+ app.session.edit_prefs(|prefs| {
+ prefs.script_events.enabled = true;
+ prefs.script_events.bindings = vec![ScriptBinding {
+ event: "saveDocument".into(),
+ script: None,
+ steps: Some(json!([["layer.new.layer", {"name": "From the binding"}]])),
+ name: "Binding".into(),
+ }];
+ });
+ let ctx = egui::Context::default();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let app = app.with_control(rx);
+ let mut app = app;
+
+ let (mut req, reply) = ControlRequest::new("app.save", json!({"path": "out.psd"}));
+ req.deadline = None;
+ tx.send(req).unwrap();
+ app.drain_control(&ctx);
+ // Started in the background: no reply yet, the job is on the document.
+ assert!(reply.try_recv().is_err(), "the reply waits for the save job");
+ assert!(app.saving(), "the save runs as a background job");
+ for _ in 0..100 {
+ crate::jobs_ui::tick(&mut app, &ctx);
+ if !app.saving() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert!(!app.saving(), "the save finished");
+ assert_eq!(*saved.lock().unwrap(), vec!["out.psd".to_string()]);
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out.psd"), "the save was recorded");
+ assert_eq!(app.session.active().unwrap().doc.layer_count(), 1, "the saveDocument binding did not run for an automation save");
+ let r = reply.recv().unwrap();
+ assert_eq!(r["result"], json!({"path": "out.psd", "warnings": ["Layers were flattened"]}), "{r}");
+
+ // An interactive save (File › Save's worker) still fires the binding.
+ let save = std::sync::Arc::new(|_doc: &photocraft_doc::Document, path: &str, _settings: &crate::ExportSettings, _ctl: &crate::jobs_ui::SaveCtl| {
+ let _ = path;
+ Ok(Vec::new())
+ }) as crate::SaveFileFn;
+ crate::jobs_ui::start_save(&mut app, "user.psd".into(), crate::ExportSettings::default(), false, save, false).unwrap();
+ for _ in 0..100 {
+ crate::jobs_ui::tick(&mut app, &ctx);
+ if !app.saving() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert!(!app.saving(), "the interactive save finished");
+ assert_eq!(app.session.active().unwrap().doc.layer_count(), 2, "the binding runs for an interactive save");
+ }
+
+ #[test]
+ fn ui_inspect_replies_while_a_save_job_encodes() {
+ // #2488: the control channel must keep answering while a large save runs.
+ use serde_json::json;
+ let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let wait_for_gate = gate.clone();
+ let saved: std::sync::Arc<std::sync::Mutex<Vec<String>>> = Default::default();
+ let record = saved.clone();
+ let services = crate::Services {
+ automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, ctl| {
+ while !wait_for_gate.load(std::sync::atomic::Ordering::Acquire) {
+ ctl.check()?;
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ record.lock().unwrap().push(path.to_string());
+ Ok(Vec::new())
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ app.background_jobs = true;
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ let ctx = egui::Context::default();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let app = app.with_control(rx);
+ let mut app = app;
+
+ let (mut save_req, save_reply) = ControlRequest::new("app.save", json!({"path": "out.png", "wait": false}));
+ save_req.deadline = None;
+ tx.send(save_req).unwrap();
+ let (mut inspect_req, inspect_reply) = ControlRequest::new("ui.inspect", json!({}));
+ inspect_req.deadline = None;
+ tx.send(inspect_req).unwrap();
+ app.drain_control(&ctx);
+
+ let pending = save_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("the unwaited save replies at once");
+ assert_eq!(pending["result"]["pending"], true, "{pending}");
+ assert_eq!(pending["result"]["path"], "out.png", "{pending}");
+ assert!(pending["result"]["job"].is_u64(), "the caller can poll or wait: {pending}");
+ // While the save is still encoding, the channel answers other requests.
+ assert!(saved.lock().unwrap().is_empty(), "the save is still encoding");
+ let inspected = inspect_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("ui.inspect is not blocked by the save");
+ assert_eq!(inspected["ok"], true, "{inspected}");
+
+ gate.store(true, std::sync::atomic::Ordering::Release);
+ for _ in 0..500 {
+ crate::jobs_ui::tick(&mut app, &ctx);
+ if !app.saving() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert_eq!(*saved.lock().unwrap(), vec!["out.png".to_string()], "the save completed after the gate opened");
+ }
+
fn deny_smart_object_paths(id: &str, params: &Value) -> photocraft_engine::Result<()> {
// The production policy lives in the automation crate. This gate exercises the control
// session's state-derived path check without adding that dependency to the UI crate.
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 46190cd40..c0912a544 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2112,6 +2112,7 @@
Cancelled {label} Zrušeno: {label}
Esc to cancel Esc pro zrušení
Opening {name} Otevírání {name}
+ Saved {name} Uloženo: {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šit
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index bff7de733..f51f35698 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2080,6 +2080,7 @@
Cancelled {label} {label} abgebrochen
Esc to cancel Esc zum Abbrechen
Opening {name} Öffne {name}
+ Saved {name} Gespeichert: {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 werden
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 31f8a3f07..bf9617d2c 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -1548,6 +1548,7 @@
Cancelled {label} Ακυρώθηκε: {label}
Esc to cancel Esc για ακύρωση
Opening {name} Άνοιγμα του {name}
+ Saved {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}: γίνεται εγγραφή του αρχείου και δεν μπορεί πλέον να ακυρωθεί
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 75d4769c4..42eab0e04 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2095,6 +2095,7 @@
Cancelled {label} Se canceló {label}
Esc to cancel Esc para cancelar
Opening {name} Abriendo {name}
+ Saved {name} Guardado: {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 cancelar
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 4f14a381d..c4dd364a0 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2059,6 +2059,7 @@
Cancelled {label} {label} : annulé
Esc to cancel Échap pour annuler
Opening {name} Ouverture de {name}
+ Saved {name} Enregistré : {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é
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 75923eb57..b78e40ace 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2052,6 +2052,7 @@
Cancelled {label} {label} dibatalkan
Esc to cancel Esc untuk batal
Opening {name} Membuka {name}
+ Saved {name} Tersimpan: {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 lagi
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 3ee565406..62526f3c7 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2094,6 +2094,7 @@
Cancelled {label} {label} annullato
Esc to cancel Esc per annullare
Opening {name} Apertura {name}
+ Saved {name} Salvato: {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 annullato
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index e31bae079..d4b422958 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2095,6 +2095,7 @@
Cancelled {label} {label} をキャンセルしました
Esc to cancel Esc キーでキャンセル
Opening {name} {name} を開いています
+ Saved {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} はファイルを書き込み中のため、キャンセルできません
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 1ec3bf60a..ca5b9d257 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2053,6 +2053,7 @@
Cancelled {label} {label} 작업을 취소했습니다
Esc to cancel Esc 키로 취소
Opening {name} {name} 여는 중
+ Saved {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}: 파일을 쓰는 중이므로 더 이상 취소할 수 없습니다
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 297b0dc46..4a8edcb3f 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -2066,6 +2066,7 @@
Cancelled {label} {label} geannuleerd
Esc to cancel Esc om te annuleren
Opening {name} {name} openen
+ Saved {name} {name} opgeslagen
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 geannuleerd
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index e09a94bb7..5b4ad1144 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -2085,6 +2085,7 @@
Cancelled {label} Anulowano: {label}
Esc to cancel Esc, aby anulować
Opening {name} Otwieranie {name}
+ Saved {name} Zapisano: {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ć
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index b4f17afee..b24e76fbc 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2059,6 +2059,7 @@
Cancelled {label} {label} cancelado
Esc to cancel Esc para cancelar
Opening {name} Abrindo {name}
+ Saved {name} Salvo: {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 cancelado
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index aa6c705a2..db32045a9 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2377,6 +2377,7 @@
Cancelled {label} {label}: отменено
Esc to cancel Esc — отмена
Opening {name} Открытие {name}
+ Saved {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}: идёт запись файла, отменить уже нельзя
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index ea0014e21..da80fc3a6 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -2352,6 +2352,7 @@
Cancelled {label} Скасовано: {label}
Esc to cancel Esc для скасування
Opening {name} Відкриття {name}
+ Saved {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}: триває запис файлу, скасувати вже не можна
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 84a7017d8..7b2fac170 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2153,6 +2153,7 @@ cameraRaw Blending 混合
Cancelled {label} 已取消 {label}
Esc to cancel 按 Esc 取消
Opening {name} 正在打开 {name}
+ Saved {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} 正在写入文件,已无法取消
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index b00e15fbc..38671e3cd 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2094,6 +2094,7 @@
Cancelled {label} 已取消 {label}
Esc to cancel 按 Esc 取消
Opening {name} 正在開啟 {name}
+ Saved {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} 正在寫入檔案,已無法取消
diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs
index c81abf5ae..13f2174cf 100644
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@ -117,6 +117,8 @@ pub struct SaveJob {
pub path: String,
/// A copy leaves the document's path and unsaved state alone.
pub copy: bool,
+ /// An automation save records without firing user-configured hooks.
+ pub automation: 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.
@@ -187,6 +189,7 @@ pub fn start_save(
settings: ExportSettings,
copy: bool,
save: SaveFileFn,
+ automation: bool,
) -> 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) {
@@ -201,6 +204,7 @@ pub fn start_save(
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 result_path = path.clone();
let state = Arc::new(SaveState::default());
let worker = Arc::clone(&state);
let started = app.session.start_job(
@@ -214,16 +218,20 @@ pub fn start_save(
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})),
+ move |_, warnings: Vec<String>| Ok(json!({"path": result_path, "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);
+ if automation {
+ app.saved_automation(doc, revision, &path, &warnings, copy);
+ } else {
+ 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 });
+ app.jobs.saves.push(SaveJob { job, doc, revision, path, copy, automation, 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.
@@ -243,7 +251,11 @@ fn warnings_of(v: &Value) -> Vec<String> {
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.automation {
+ app.saved_automation(save.doc, save.revision, &save.path, &warnings_of(&v), save.copy);
+ } else {
+ 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);
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8a7a49759..c30796a5d 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -185,7 +185,7 @@ use std::sync::mpsc::{Receiver, Sender};
use photocraft_doc::{DocId, Document};
use photocraft_engine::Session;
-use serde_json::Value;
+use serde_json::{Value, json};
pub use control::{ControlRequest, ControlResponse};
pub use file_dialog::{FileDialogAnswer, FileDialogFn, FileDialogReply, FileDialogRequest};
@@ -247,6 +247,15 @@ pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
/// 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>;
+
+/// Who a finished save serves.
+#[derive(Clone, Copy)]
+pub(crate) enum SaveKind {
+ /// Interactive: arm the document's file and fire user-configured hooks.
+ User,
+ /// Automation: flat formats stay copies (#2579) and hooks never fire.
+ Automation,
+}
/// 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.
@@ -318,6 +327,9 @@ pub struct Services {
pub import: Option<ImportFn>,
/// Encode a document for a file name (format chosen by extension).
pub export: Option<ExportFn>,
+ /// Background save over the automation write authority (`app.save`, #2017): same worker
+ /// contract as `save_file`, but the bytes go through the capability-scoped workspace.
+ pub automation_save: Option<SaveFileFn>,
/// Show an Open or Save dialog without waiting for it (see `file_dialog`).
pub file_dialog: Option<FileDialogFn>,
/// Write bytes to a path (native) or trigger a download (web).
@@ -1192,7 +1204,7 @@ impl PhotocraftApp {
if self.background_jobs
&& let Some(save) = self.services.save_file.clone()
{
- return jobs_ui::start_save(self, path, settings.clone(), copy, save);
+ return jobs_ui::start_save(self, path, settings.clone(), copy, save, false);
}
let st = self.session.active().ok_or("no document")?;
let (doc, revision) = (st.doc.id, st.revision);
@@ -1207,18 +1219,36 @@ impl PhotocraftApp {
/// 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}");
+ self.saved_inner(doc, revision, path, warnings, copy, SaveKind::User);
+ }
+
+ /// [`Self::saved`] for automation saves: no user-configured hooks (docs/control-protocol.md).
+ pub(crate) fn saved_automation(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) {
+ self.saved_inner(doc, revision, path, warnings, copy, SaveKind::Automation);
+ }
+
+ fn saved_inner(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool, kind: SaveKind) {
+ // Automation: only a layered save becomes the document's file; a flat one is a
+ // copy, as in the headless server (#2579).
+ let (hooks, arm) = match kind {
+ SaveKind::User => (true, true),
+ SaveKind::Automation => (false, photocraft_engine::file_cmds::extension(path).is_some_and(|e| photocraft_engine::file_cmds::layered_extension(&e))),
+ };
+ self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]);
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() {
+ if let Some(st) = app.session.active_mut()
+ && arm
+ {
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()
+ if hooks
+ && 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(""));
@@ -1227,7 +1257,8 @@ impl PhotocraftApp {
});
}
self.ui.status_error = false;
- notices::io_warnings(self, &format!("Saved {}", file_open::display_name(path)), warnings);
+ let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]);
+ notices::io_warnings(self, &what, warnings);
self.sync_views();
}
@@ -1239,28 +1270,34 @@ impl PhotocraftApp {
/// Save through the control session's capability-scoped writer. No file
/// picker or ambient writer is reachable from this path. Returns the path
/// written and the export warnings (also shown to the user).
- pub fn save_automation(&mut self, path: Option<String>) -> Result<(String, Vec<String>), String> {
+ pub fn save_automation(&mut self, path: Option<String>) -> Result<Value, String> {
+ let target = {
+ let state = self.session.active().ok_or("no document")?;
+ // As File › Save: without `path` only a layered file is written back (#416).
+ path.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::saves_in_place(p)))
+ .ok_or("pass `path`: a save without one writes back only to the document's own PSD, PSB or .pcraft file")?
+ };
+ let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings});
+ // #2017: the File › Save worker path, so the encode doesn't block the frame loop.
+ if self.background_jobs
+ && let Some(save) = self.services.automation_save.clone()
+ {
+ return match jobs_ui::start_save(self, target.clone(), ExportSettings::default(), false, save, true)? {
+ Some((path, warnings)) => Ok(reply(&path, &warnings)),
+ None => {
+ let job = self.jobs.last_started;
+ Ok(json!({"path": target, "job": job, "pending": true, "warnings": []}))
+ }
+ };
+ }
let state = self.session.active().ok_or("no document")?;
- // As File › Save: without `path` only a layered file is written back (#416).
- let target = path
- .or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::saves_in_place(p)))
- .ok_or("pass `path`: a save without one writes back only to the document's own PSD, PSB or .pcraft file")?;
+ let (doc, revision) = (state.doc.id, state.revision);
let export = self.services.export.as_ref().ok_or("no exporter configured")?;
let (bytes, warnings) = export(&state.doc, &target, &ExportSettings::default())?;
let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;
write(&target, &bytes)?;
- // Only a layered save becomes the document's file; a flat one is a copy, as in the
- // headless server (#2579).
- if photocraft_engine::file_cmds::extension(&target).is_some_and(|e| photocraft_engine::file_cmds::layered_extension(&e))
- && let Some(state) = self.session.active_mut()
- {
- state.saved_to(target.clone());
- }
- self.ui.status = format!("Saved {target}");
- self.ui.status_error = false;
- notices::io_warnings(self, &format!("Saved {}", file_open::display_name(&target)), &warnings);
- self.sync_views();
- Ok((target, warnings))
+ self.saved_automation(doc, revision, &target, &warnings, false);
+ Ok(reply(&target, &warnings))
}
fn drain_control(&mut self, ctx: &egui::Context) {
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 0881e62e8..1c69df465 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -158,7 +158,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`), 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.
+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`, `ui.dialog.confirm` and `app.save` 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). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.
## Preferences