Background jobs in the app: progress, Cancel, open-as-job (part of #210) (#290)

* Background jobs: engine job API, progress and cancel (part of #210) (#289)

* Test: retry the GPU startup sentinel check while a forked child briefly shares the lock

monitor_profile tests spawn osascript in the same binary; between fork and exec the child holds
a copy of the marker file descriptor, so flock reports WouldBlock and begin() returns Busy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Background jobs: engine job API, progress and cancel (part of #210) (#289)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Background jobs in the app: progress, Cancel, open-as-job (part of #210) (#290)

Translations for the new progress/cancel strings added to zh-hant, es, ru and cs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Brandon ThomasandClaude Opus 5.5 authored and GitHub committed 2026-10-06 15:41:53 -04:00
1 parent e83de8ae57
commit 62c16c1541
22 files changed
+1022 -26

No files matched your search

Generated
+1
View File
@@ -3736,6 +3736,7 @@ dependencies = [
"photocraft-gpu",
"photocraft-io",
"photocraft-plugins",
"photocraft-psd",
"photocraft-raster",
"photocraft-testkit",
"photocraft-text",
+2
View File
@@ -173,6 +173,8 @@ fn main() -> eframe::Result {
services.preset_store = presets;
let mut app = PhotocraftApp::new(Session::new(), services);
app.integrated_titlebar = cfg!(target_os = "macos");
// Long commands and file opens run as background jobs with progress and Cancel (#210).
app.background_jobs = std::env::var_os("PHOTOCRAFT_INLINE_JOBS").is_none();
if let Ok(Some(icc)) = monitor.recv_timeout(std::time::Duration::from_secs(2)) {
app.session.color.monitor_profile = Some(std::sync::Arc::new(icc));
}
+2
View File
@@ -39,3 +39,5 @@ photocraft-codecs = { workspace = true }
photocraft-format = { workspace = true }
# Benchmark helpers for the `--json` benches `cargo xtask perf` runs (in-process RSS, percentiles).
photocraft-testkit = { workspace = true }
# Only for examples/perf_scenarios.rs (a 500-brush .abr for the #210 import row).
photocraft-psd = { workspace = true }
+149
View File
@@ -571,6 +571,155 @@ fn job_scenarios(b: &mut Bench, sz: &Sizes) {
Err(e) => b.errors.push((caf.into(), e)),
}
}
background_job_scenarios(b, sz);
}
/// Wait (polling like the UI's frame loop) until job `id` has ended.
fn wait_job(s: &mut Session, id: photocraft_engine::jobs::JobId) -> Res<()> {
let t = Instant::now();
loop {
if s.poll_jobs().iter().any(|e| e.id == id) {
return Ok(());
}
if t.elapsed().as_secs() > 120 {
return Err("job did not finish in 120 s".into());
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
fn start_job(s: &mut Session, id: &str, p: Value) -> Res<photocraft_engine::jobs::JobId> {
match s.start(id, p).map_err(|e| format!("{id}: {e}"))? {
photocraft_engine::jobs::Started::Job(j) => Ok(j),
photocraft_engine::jobs::Started::Done(_) => Err(format!("{id} did not run as a background job")),
}
}
/// #210 background jobs: cancel latency (from `cancel_job` until the worker has exited) at
/// several points of a 24 MP Gaussian Blur and Content-Aware Fill; the UI thread's longest step
/// while 500 brushes import; the app's frame time while a 24 MP Gaussian Blur runs.
fn background_job_scenarios(b: &mut Bench, sz: &Sizes) {
let reps = b.reps.min(8);
let (w, h) = sz.big_photo;
let blur = "cancel Gaussian Blur r 50 job on 24 MP";
let caf = "cancel Content-Aware Fill job on 24 MP";
if b.wanted(blur) || b.wanted(caf) {
match open_photo(w, h) {
Ok(mut s) => {
for (name, cmd, params, select) in
[(blur, "filter.blur.gaussianBlur", json!({"radius": 50}), false), (caf, "edit.contentAwareFill", json!({}), true)]
{
if select && let Err(e) = exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 5, "height": h / 4})) {
b.errors.push((name.into(), e));
continue;
}
b.time(name, &mut s, reps, false, |_, s, i| {
let job = start_job(s, cmd, params.clone())?;
// Cancel early, midway and late in the run.
std::thread::sleep(std::time::Duration::from_millis(20 + (i as u64 * 97) % 700));
let t = Instant::now();
s.cancel_job(job);
s.join_cancelled_jobs();
let v = ms(t);
wait_job(s, job)?;
Ok(v)
});
}
}
Err(e) => b.errors.push((blur.into(), e)),
}
}
let brushes = "import 500 brushes: longest UI-thread step";
if b.wanted(brushes) {
use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12};
let list: Vec<LegacyBrush> = (0..500)
.map(|i| {
let side = 40 + (i % 60) as u32;
let data = (0..side * side).map(|k| ((k * 7 + i as u32) % 255) as u8).collect();
LegacyBrush {
name: format!("Brush {i}"),
spacing: 25,
anti_alias: true,
tip: LegacyTip::Sampled(AbrSample { id: String::new(), width: side, height: side, depth: 8, data }),
}
})
.collect();
match write_v12(2, &list, true) {
Ok(abr) => {
let data = photocraft_engine::paint::tile::b64_encode(&abr);
let mut s = Session::new();
b.time(brushes, &mut s, reps.min(5), true, |_, s, _| {
// The UI thread's work: starting the job, then each frame's poll (the last one
// applies the 500 presets).
let t = Instant::now();
let job = start_job(s, "brush.presets.importAbr", json!({"data": data, "group": "Bench"}))?;
let mut worst = ms(t);
let t0 = Instant::now();
loop {
let t = Instant::now();
let done = s.poll_jobs().iter().any(|e| e.id == job);
worst = worst.max(ms(t));
if done {
break;
}
if t0.elapsed().as_secs() > 120 {
return Err("import did not finish".into());
}
std::thread::sleep(std::time::Duration::from_millis(4));
}
Ok(worst)
});
}
Err(e) => b.errors.push((brushes.into(), e.to_string())),
}
}
let frame = "app frame during 24 MP Gaussian Blur r 50 job";
if b.wanted(frame) {
frame_scenario(b, frame, w, h);
}
}
/// The whole app (kittest harness, CPU canvas) with a 24 MP document: frame times while a
/// Gaussian Blur r 50 job runs, one sample per frame.
fn frame_scenario(b: &mut Bench, name: &str, w: u32, h: u32) {
let mut s = match open_photo(w, h) {
Ok(s) => s,
Err(e) => return b.errors.push((name.into(), e)),
};
let doc = std::mem::take(&mut s);
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(4).build_eframe(move |cc| {
photocraft_ui_egui::PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = photocraft_ui_egui::PhotocraftApp::new(doc, photocraft_ui_egui::Services::default());
app.background_jobs = true;
app
});
// Warm up: first frames build the canvas cache of the 24 MP document.
harness.run_steps(6);
b.current = Some(name.to_string());
b.sampler.reset();
let mut samples = Vec::new();
let run = (|| -> Res<()> {
let r = harness.state_mut().run("filter.blur.gaussianBlur", json!({"radius": 50}))?;
if r.get("pending").is_none() {
return Err("the blur did not start as a job".into());
}
let t0 = Instant::now();
while harness.state().session.has_jobs() {
let t = Instant::now();
harness.step();
samples.push(ms(t));
if t0.elapsed().as_secs() > 120 {
return Err("the job did not finish".into());
}
}
if samples.len() < 10 {
return Err(format!("only {} frames while the job ran", samples.len()));
}
Ok(())
})();
// The rows' document handle: the harness's session.
let st = std::mem::take(&mut harness.state_mut().session);
b.record(name, &st, &samples, run);
}
/// #211 rows: selection algorithms, Content-Aware Scale and Select Subject on 24 MP, and a brush
+9
View File
@@ -46,10 +46,15 @@ fn main() {
};
let open = arg(&args, "--open");
let safe_gpu = args.iter().any(|a| a == "--safe-gpu");
// `--background-jobs`: long commands run as background jobs, as in the desktop app (#210).
let background_jobs = args.iter().any(|a| a == "--background-jobs");
// `--settle-ms N`: keep rendering frames for N ms before the capture (e.g. mid-job).
let settle_ms: u64 = arg(&args, "--settle-ms").and_then(|s| s.parse().ok()).unwrap_or(0);
let mut harness =
egui_kittest::Harness::builder().with_size(egui::vec2(w, h)).with_pixels_per_point(scale).with_max_steps(64).wgpu().build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.background_jobs = background_jobs;
// `--safe-gpu`: the CPU canvas, as the desktop app's `--safe-gpu` launch.
if safe_gpu {
app.perf.gpu_info.selected = "cpu".into();
@@ -102,6 +107,10 @@ fn main() {
eprintln!("{:>8.1} ms {label}", t0.elapsed().as_secs_f64() * 1000.0);
}
}
let t_settle = std::time::Instant::now();
while t_settle.elapsed() < std::time::Duration::from_millis(settle_ms) {
harness.step();
}
// Let fade animations settle.
for _ in 0..12 {
harness.step();
+89 -10
View File
@@ -865,18 +865,24 @@ pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) {
pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
retain_gpu_documents(app);
let n = app.session.documents().len();
if app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen) {
// Files opening in the background (#210) have tabs before they have documents.
let opening = !app.jobs.opens.is_empty();
if !opening && app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen) {
start_screen(app, ui);
return;
}
if n == 0 {
if n == 0 && !opening {
// Auto show the Home Screen is off: an empty workspace, like Photoshop.
paint_dots(ui, ui.available_rect_before_wrap());
return;
}
if !app.ui.view.hides_tabs() {
if !app.ui.view.hides_tabs() || opening {
tabs(app, ui);
}
if let Some(job) = app.jobs.focus.or_else(|| (n == 0).then(|| app.jobs.opens.last().map(|o| o.job)).flatten()) {
crate::jobs_ui::open_card(app, ui, job);
return;
}
let Some(idx) = app.session.active_index() else { return };
let rect = ui.available_rect_before_wrap();
app.last_canvas_rect = rect;
@@ -915,11 +921,13 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let active = app.session.active_index();
let mut activate = None;
let mut close = None;
let (mut focus_open, mut cancel_open) = (None, None);
let focused_open = app.jobs.focus.is_some();
egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
for (i, st) in app.session.documents().iter().enumerate() {
let sel = Some(i) == active;
let sel = Some(i) == active && !focused_open;
let name = format!("{}{}", st.doc.name, if st.is_dirty() { " *" } else { "" });
let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits());
let name_g = ui.painter().layout_no_wrap(name, crate::theme::medium(12.5), t.text);
@@ -948,20 +956,67 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
activate = Some(i);
}
}
// Files opening in the background: a tab with a progress underline; × cancels.
for (job, name, frac) in crate::jobs_ui::open_tabs(app) {
let sel = app.jobs.focus == Some(job);
let name_g = ui.painter().layout_no_wrap(name, crate::theme::medium(12.5), t.text);
let meta_g = ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), egui::FontId::proportional(10.5), t.text_faint);
let w = name_g.size().x + meta_g.size().x + 44.0;
let (r, resp) = ui.allocate_exact_size(egui::vec2(w, 26.0), Sense::click());
if sel {
ui.painter().rect_filled(r, t.radius_sm, t.card);
ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);
} else if resp.hovered() {
ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5));
}
let ny = r.center().y - name_g.size().y / 2.0;
ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), if sel { t.text } else { t.text_dim });
ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint);
crate::jobs_ui::tab_underline(ui, r, frac, &t);
let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0));
let xresp = ui.interact(xr, ui.id().with(("tabjobx", job.0)), Sense::click());
if xresp.hovered() {
ui.painter().rect_filled(xr, 4.0, t.hover);
}
crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint });
if xresp.on_hover_text(tl!("Cancel opening")).clicked() {
cancel_open = Some(job);
} else if resp.clicked() {
focus_open = Some(job);
}
}
});
});
if let Some(i) = activate {
app.session.set_active(i);
}
open_tab_clicks(app, activate, focus_open, cancel_open);
if let Some(i) = close {
let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i}));
}
}
/// Apply tab-strip clicks: a document tab shows that document, an opening tab its progress, and
/// an opening tab's × cancels the open (closing the half-open tab).
fn open_tab_clicks(
app: &mut PhotocraftApp,
activate: Option<usize>,
focus_open: Option<photocraft_engine::jobs::JobId>,
cancel_open: Option<photocraft_engine::jobs::JobId>,
) {
if let Some(i) = activate {
app.session.set_active(i);
app.jobs.focus = None;
}
if let Some(job) = focus_open {
app.jobs.focus = Some(job);
}
if let Some(job) = cancel_open {
crate::jobs_ui::cancel(app, job);
}
}
/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels.
fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get(ui.ctx());
let active = app.session.active_index();
let active = app.session.active_index().filter(|_| app.jobs.focus.is_none());
let (mut activate, mut close) = (None, None);
let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 26.0), Sense::hover());
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
@@ -997,9 +1052,33 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
x = r.right();
}
if let Some(i) = activate {
app.session.set_active(i);
// Files opening in the background (#210): "name (Opening… 45%)" with a progress underline.
let (mut focus_open, mut cancel_open) = (None, None);
for (job, name, frac) in crate::jobs_ui::open_tabs(app) {
let title = format!("{name} ({} {:.0}%)", tl!("Opening…"), frac * 100.0);
let g = ui.painter().layout_no_wrap(title, egui::FontId::proportional(11.5), t.text);
let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(g.size().x + 42.0, strip.height()));
let resp = ui.interact(r, ui.id().with(("ptabjob", job.0)), Sense::click());
let sel = app.jobs.focus == Some(job);
if sel {
ui.painter().rect_filled(r, 0.0, t.chrome);
} else if resp.hovered() {
ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35));
}
ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator));
crate::jobs_ui::tab_underline(ui, r, frac, &t);
let xr = Rect::from_center_size(egui::pos2(r.left() + 13.0, r.center().y), egui::vec2(14.0, 14.0));
let xresp = ui.interact(xr, ui.id().with(("ptabjobx", job.0)), Sense::click());
crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint });
ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 26.0, r.center().y - g.size().y / 2.0), g, if sel { t.text } else { t.text_faint });
if xresp.on_hover_text(tl!("Cancel opening")).clicked() {
cancel_open = Some(job);
} else if resp.clicked() {
focus_open = Some(job);
}
x = r.right();
}
open_tab_clicks(app, activate, focus_open, cancel_open);
if let Some(i) = close {
let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i}));
}
+38 -1
View File
@@ -24,6 +24,9 @@
//! - `ui.focus`: bring the main window to the front
//! - `app.open {path}` / `app.save {path}`: relative file I/O under the automation roots; reply with `warnings`
//! - `app.quit`
//! - `jobs.list` / `jobs.cancel {job?}`: background jobs (#210) with progress; cancel one (or all).
//! `engine.execute` waits for a command that runs as a job unless `wait: false` (then the reply
//! is `{job, pending: true}`)
use std::sync::mpsc::Sender;
@@ -58,6 +61,9 @@ pub enum Outcome {
/// Synthetic input queued: reply once the app has processed all of it (so a following
/// `ui.inspect`/`engine.execute` observes the effect).
AfterInput,
/// A command started a background job and the caller waits for it: reply with its result
/// once it has been applied (or with its error / "cancelled").
AfterJob(photocraft_engine::jobs::JobId),
}
fn ok(v: Value) -> Outcome {
@@ -90,7 +96,17 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
// params and never open a dialog (an agent would otherwise get a modal instead of a
// result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog.
if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() {
return wrap(app.run_automation(id, params));
// Long commands may run as background jobs: by default the reply waits for the
// result (backward compatible); with `"wait": false` it is `{job, pending}`.
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true);
app.jobs.last_started = None;
let r = app.run_automation(id, params);
if let (Ok(_), Some(job)) = (&r, app.jobs.last_started.take())
&& wait
{
return Outcome::AfterJob(job);
}
return wrap(r);
}
let events_enabled = app.session.prefs().script_events.enabled;
if events_enabled {
@@ -103,6 +119,26 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
wrap(result)
}
"engine.commands" => wrap(app.run("command.list", json!({}))),
// Background jobs (#210): running ones with progress, then the last few that ended.
"jobs.list" => wrap(app.session.execute("jobs.list", json!({})).map_err(|e| e.to_string())),
"jobs.cancel" => {
let all = p.get("job").is_none_or(Value::is_null);
match p.get("job").and_then(Value::as_u64) {
Some(j) if app.session.job(photocraft_engine::jobs::JobId(j)).is_some() => {
crate::jobs_ui::cancel(app, photocraft_engine::jobs::JobId(j));
ok(json!({"cancelled": 1}))
}
Some(j) => err(format!("no running job {j}")),
None if all => {
let ids: Vec<_> = app.session.jobs().into_iter().map(|j| j.id).collect();
for j in &ids {
crate::jobs_ui::cancel(app, *j);
}
ok(json!({"cancelled": ids.len()}))
}
None => err("`job` must be a job id"),
}
}
"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()),
"ui.inspect" => ok(inspect(app, ctx)),
"ui.set" => {
@@ -463,6 +499,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
"perf": {"fps": app.fps, "timings": app.perf},
"brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity},
"distort": app.distort.describe(),
"jobs": crate::jobs_ui::inspect(app),
})
}
+12
View File
@@ -31,6 +31,11 @@ impl PhotocraftApp {
if let Some(r) = crate::preset_files_ui::open(self, path, bytes) {
return r.map(|()| Vec::new());
}
if self.background_jobs {
// The path and Open Recent are recorded when the background open finishes.
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes))?;
return Ok(Vec::new());
}
let warnings = self.open_bytes(&display_name(path), bytes)?;
if let Some(st) = self.session.active_mut() {
st.path = Some(path.to_string());
@@ -42,6 +47,13 @@ impl PhotocraftApp {
/// Read and open the file at `path` (see [`open_file`](Self::open_file)).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(&mut self, path: &str) -> Result<Vec<String>, String> {
// Documents opening in the background are read on the worker too (a 2 GB PSB read
// would block the window). Preset files (brushes, gradients) go the usual way.
let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
if self.background_jobs && !crate::preset_files_ui::PRESET_EXTS.contains(&ext.as_str()) {
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), photocraft_engine::jobs::OpenSource::Path(path.to_string()))?;
return Ok(Vec::new());
}
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
self.open_file(path, &bytes)
}
+9
View File
@@ -1976,3 +1976,12 @@
Vulkan Vulkan
Alt-click to define a source point to clone from Kliknutím s klávesou Alt určete zdrojový bod pro klonování
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Není k dispozici žádná cesta, ze které by šlo vytvořit výběr: nakreslete ji nástrojem Pero nebo ji vyberte na panelu Cesty.
Cancel opening Zrušit otevírání
Cancelled opening {name} Otevírání {name} zrušeno
Cancelled {label} Zrušeno: {label}
Esc to cancel Esc pro zrušení
Opening {name} Otevírání {name}
Opening {name}… Otevírání {name}…
Opening… Otevírání…
Reading… Načítání…
Working… Zpracování…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9
View File
@@ -1962,3 +1962,12 @@
Vulkan Vulkan
Alt-click to define a source point to clone from Alt+clic para definir un punto de origen para clonar
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. No hay ningún trazado para crear una selección: dibuje uno con la herramienta Pluma o seleccione uno en el panel Trazados.
Cancel opening Cancelar apertura
Cancelled opening {name} Se canceló la apertura de {name}
Cancelled {label} Se canceló {label}
Esc to cancel Esc para cancelar
Opening {name} Abriendo {name}
Opening {name}… Abriendo {name}…
Opening… Abriendo…
Reading… Leyendo…
Working… Procesando…
Can't render this file because it contains an unexpected character in line 4 and column 47.
+9
View File
@@ -1966,3 +1966,12 @@
Use tablet pressure タブレットの筆圧を使用
Vulkan Vulkan
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 選択範囲を作成するパスがありません。ペンツールで描くか、パスパネルでパスを選択してください。
Cancel opening 開くのをキャンセル
Cancelled opening {name} {name} を開くのをキャンセルしました
Cancelled {label} {label} をキャンセルしました
Esc to cancel Esc キーでキャンセル
Opening {name} {name} を開いています
Opening {name}… {name} を開いています…
Opening… 開いています…
Reading… 読み込み中…
Working… 処理中…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9
View File
@@ -2244,3 +2244,12 @@
Zoom with trackpad pinch Масштаб щипком на трекпаде
Alt-click to define a source point to clone from Alt+щелчок, чтобы задать точку-источник клонирования
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Нет контура для создания выделения: нарисуйте его инструментом «Перо» или выберите на панели «Контуры».
Cancel opening Отменить открытие
Cancelled opening {name} Открытие {name} отменено
Cancelled {label} {label}: отменено
Esc to cancel Esc — отмена
Opening {name} Открытие {name}
Opening {name}… Открытие {name}…
Opening… Открытие…
Reading… Чтение…
Working… Обработка…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9
View File
@@ -1958,3 +1958,12 @@
Vulkan Vulkan
Alt-click to define a source point to clone from 按 Alt 鍵並按一下以定義仿製來源點
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 沒有可用來建立選取範圍的路徑:請使用鋼筆工具繪製,或在路徑面板中選取一個路徑。
Cancel opening 取消開啟
Cancelled opening {name} 已取消開啟 {name}
Cancelled {label} 已取消 {label}
Esc to cancel 按 Esc 取消
Opening {name} 正在開啟 {name}
Opening {name}… 正在開啟 {name}…
Opening… 正在開啟…
Reading… 正在讀取…
Working… 處理中…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+382
View File
@@ -0,0 +1,382 @@
//! Background jobs in the shell (#210): long commands and file opens run on worker threads (see
//! `photocraft_engine::jobs`) while the window keeps drawing at full frame rate.
//!
//! - [`run`] starts a job-capable command in the background (when [`PhotocraftApp::background_jobs`]
//! is on: the desktop app; tests and the web run inline as before).
//! - [`tick`] (every frame) applies finished jobs, reports failures, answers control requests
//! waiting on a job, finishes background opens and keeps frames coming while anything runs.
//! - [`status_progress`] draws the status-bar progress with a Cancel button; [`dialog`] the modal
//! progress window for jobs that lock the active document (filters, Content-Aware Fill, …),
//! 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.
//!
//! The canvas keeps showing the pre-job state: workers never touch the session's documents.
use std::sync::Arc;
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 serde_json::{Value, json};
use crate::theme::Tokens;
use crate::{ControlResponse, PhotocraftApp, notices};
/// Delay before the modal progress dialog appears (quick jobs finish without it).
pub const DIALOG_DELAY_MS: f64 = 250.0;
/// A file opening in the background: shown as a document tab with progress.
#[derive(Clone, Debug)]
pub struct OpenTab {
pub job: JobId,
/// Display name (the file name).
pub name: String,
/// Where it was read from (File › Save writes back there; added to Open Recent).
pub path: Option<String>,
}
/// The shell's job bookkeeping.
#[derive(Default)]
pub struct JobsUi {
/// Control replies waiting for a job to end.
pub(crate) waiters: Vec<(JobId, Sender<ControlResponse>)>,
/// Background opens, in tab order.
pub opens: Vec<OpenTab>,
/// 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).
pub(crate) last_started: Option<JobId>,
}
/// Run command `id`: in the background when background jobs are on and the command is a job
/// (the result is then `{"job": id, "pending": true}` and the edit lands when [`tick`] applies
/// it), else synchronously like [`photocraft_engine::Session::execute`].
pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result<Value, String> {
if !app.background_jobs {
return app.session.execute(id, params).map_err(|e| e.to_string());
}
match app.session.start(id, params).map_err(|e| e.to_string())? {
Started::Done(v) => Ok(v),
Started::Job(job) => {
app.jobs.last_started = Some(job);
// The status bar's progress readout names the job; clear any old message.
app.ui.status.clear();
app.ui.status_error = false;
Ok(json!({"job": job.0, "pending": true}))
}
}
}
/// Open a file in the background: a tab appears at once and shows the progress; the document
/// replaces it when decoded. `path` is remembered for File › Save and Open Recent.
pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, source: OpenSource) -> Result<(), String> {
match app.session.start_open(name, source).map_err(|e| e.to_string())? {
// Inline (wasm): finish now, like a background open that ended at once.
Started::Done(v) => finish_open(app, name, path.as_deref(), &v),
Started::Job(job) => {
app.jobs.opens.push(OpenTab { job, name: name.to_string(), path });
app.jobs.focus = Some(job);
app.ui.chrome.home = None;
app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]);
app.ui.status_error = false;
Ok(())
}
}
}
/// 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);
}
// 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.session.has_jobs() {
return;
}
// Animate progress and poll for results at display rate; the UI thread only draws.
ctx.request_repaint_after(std::time::Duration::from_millis(16));
if let Some(job) = job_in_view(app)
&& !ctx.text_edit_focused()
&& ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
{
cancel(app, job.id);
}
}
/// The job the user is looking at: the open tab in view, the active document's job, or (for
/// the status bar) the newest running job.
pub fn job_in_view(app: &PhotocraftApp) -> Option<JobInfo> {
if let Some(j) = app.jobs.focus.and_then(|j| app.session.job(j)) {
return Some(j);
}
app.session.active_job().or_else(|| app.session.jobs().pop())
}
/// 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);
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 {
app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &l)]);
app.ui.status_error = false;
}
}
}
fn on_event(app: &mut PhotocraftApp, e: JobEvent) {
// Control requests waiting on this job.
let reply = match &e.outcome {
JobOutcome::Done(v) => json!({"ok": true, "result": v}),
JobOutcome::Failed(err) => json!({"ok": false, "error": err}),
JobOutcome::Cancelled => json!({"ok": false, "error": "cancelled"}),
};
app.jobs.waiters.retain(|(job, tx)| {
if *job == e.id {
let _ = tx.send(reply.clone());
false
} else {
true
}
});
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);
match e.outcome {
JobOutcome::Done(v) => {
if let Err(err) = finish_open(app, &tab.name, tab.path.as_deref(), &v) {
app.open_failed(&tab.name, &err);
}
}
JobOutcome::Failed(err) => app.open_failed(&tab.name, &err),
JobOutcome::Cancelled => {
app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &tab.name)]);
app.ui.status_error = false;
}
}
return;
}
match e.outcome {
JobOutcome::Done(v) if e.command == "brush.presets.importAbr" => {
let n = v.get("count").and_then(Value::as_u64).unwrap_or(0);
let group = v.get("group").and_then(Value::as_str).unwrap_or_default();
app.ui.status = format!("Imported {n} brushes from {group}");
app.ui.status_error = false;
app.ui.panels.brush_settings = true;
app.ui.brush_tab = 1;
}
JobOutcome::Done(_) => {
app.sync_views();
app.ui.status = e.label;
app.ui.status_error = false;
}
JobOutcome::Failed(err) => {
app.sync_views();
notices::error(app, format!("{}: {err}", e.label));
}
JobOutcome::Cancelled => {
app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]);
app.ui.status_error = false;
}
}
}
/// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result
/// (`{document, warnings, color}`).
fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value) -> Result<(), String> {
let index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
let warnings: Vec<String> =
v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default();
app.session.set_active(index);
if let (Some(p), Some(st)) = (path, app.session.active_mut()) {
st.path = Some(p.to_string());
}
if let Some(p) = path {
app.push_recent(p);
}
app.sync_views();
app.ui.status = format!("Opened {name}");
app.ui.status_error = false;
notices::io_warnings(app, &format!("Opened {name}"), &warnings);
// Script events bound to "Open Document".
photocraft_engine::automate_cmds::document_opened(&mut app.session);
app.sync_views();
let color = v.get("color").cloned().unwrap_or(Value::Null);
let ask = color.get("ask").and_then(Value::as_bool) == Some(true);
if ask && (color.get("mismatch").and_then(Value::as_bool) == Some(true) || color.get("missing").is_some()) {
crate::prefs_ui::open_mismatch(app, &color);
}
Ok(())
}
// ------------------------------------------------------------------------------------- drawing
/// A progress bar: `frac` of `rect` filled with the accent; `None` = indeterminate (a sliding
/// segment), for jobs that haven't reported progress yet.
pub fn bar(ui: &egui::Ui, rect: Rect, frac: Option<f32>, t: &Tokens) {
let p = ui.painter();
let r = rect.height() / 2.0;
p.rect_filled(rect, r, t.field);
p.rect_stroke(rect, r, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
let fill = match frac {
Some(f) => Rect::from_min_size(rect.min, vec2((rect.width() * f.clamp(0.0, 1.0)).max(rect.height()), rect.height())),
None => {
let time = ui.input(|i| i.time) as f32;
let w = rect.width() * 0.3;
let x = rect.left() + ((time * 0.8).fract() * (rect.width() + w)) - w;
Rect::from_min_max(egui::pos2(x.max(rect.left()), rect.top()), egui::pos2((x + w).min(rect.right()), rect.bottom()))
}
};
if fill.width() > 0.0 {
p.rect_filled(fill, r, t.accent);
}
}
/// Progress that has been reported, or `None` (indeterminate) while it's still 0.
fn shown_fraction(j: &JobInfo) -> Option<f32> {
(j.progress > 0.0).then_some(j.progress)
}
fn percent(j: &JobInfo) -> String {
// Nothing yet reported: the bar is indeterminate, so no number.
if j.progress > 0.0 { format!("{:.0}%", j.progress * 100.0) } else { String::new() }
}
/// The status bar's job readout: "Gaussian Blur ▬▬▬▭▭ 45 % ×". Draws nothing when no job runs.
pub fn status_progress(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let Some(j) = job_in_view(app) else { return };
let t = Tokens::get(ui.ctx());
let (bar_w, bar_h) = if t.pro { (120.0, 6.0) } else { (140.0, 6.0) };
let more = app.session.jobs().len().saturating_sub(1);
// Right to left: ×, percentage, bar, label.
let (xr, xresp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
if xresp.hovered() {
ui.painter().rect_filled(xr, t.radius_sm, t.hover);
}
crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_dim });
let xresp = xresp.on_hover_text(tl!("Cancel (Esc)"));
ui.label(RichText::new(percent(&j)).color(t.text_dim).size(11.5).monospace());
let (br, _) = ui.allocate_exact_size(vec2(bar_w, bar_h), Sense::hover());
bar(ui, br, shown_fraction(&j), &t);
let label = if more > 0 { format!("{} (+{more})", j.label) } else { j.label.clone() };
ui.label(RichText::new(label).color(t.text_dim).size(12.0));
if xresp.clicked() {
cancel(app, j.id);
}
}
/// The modal progress window for a job locking the active document (Photoshop shows one for
/// long filters): title, status, bar, percentage and elapsed time, Cancel. Appears after
/// [`DIALOG_DELAY_MS`]; Esc cancels (see [`tick`]).
pub fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(j) = app.session.active_job() else { return };
if j.elapsed_ms < DIALOG_DELAY_MS {
return;
}
let t = Tokens::get(ctx);
let mut cancel_it = false;
// Photoshop doesn't dim the window behind its progress dialog either.
let modal = egui::Modal::new(egui::Id::new("job-progress")).backdrop_color(Color32::from_black_alpha(36)).show(ctx, |ui| {
ui.set_width(360.0);
ui.label(RichText::new(&j.label).font(crate::theme::semibold(15.0)));
ui.add_space(4.0);
crate::widgets::hairline(ui);
ui.add_space(10.0);
let msg = if j.message.is_empty() || j.message == j.label { tl!("Working…").to_string() } else { j.message.clone() };
ui.label(RichText::new(msg).color(t.text_dim));
ui.add_space(8.0);
let (br, _) = ui.allocate_exact_size(vec2(ui.available_width(), 8.0), Sense::hover());
bar(ui, br, shown_fraction(&j), &t);
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label(RichText::new(percent(&j)).color(t.text_faint).size(11.5));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new(elapsed(j.elapsed_ms)).color(t.text_faint).size(11.5));
});
});
ui.add_space(12.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
cancel_it = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked();
ui.label(RichText::new(tl!("Esc to cancel")).color(t.text_faint).size(11.0));
});
});
// A click on the backdrop doesn't cancel the work; Esc is handled in `tick`.
let _ = modal;
if cancel_it {
cancel(app, j.id);
}
}
fn elapsed(ms: f64) -> String {
let s = (ms / 1000.0).max(0.0);
if s < 60.0 { format!("{s:.1} s") } else { format!("{}:{:02}", (s / 60.0).floor() as u64, (s % 60.0).floor() as u64) }
}
/// The canvas area of an opening tab: the file name, a bar and Cancel, centred on the
/// workspace backdrop.
pub fn open_card(app: &mut PhotocraftApp, ui: &mut egui::Ui, job: JobId) {
let Some(tab) = app.jobs.opens.iter().find(|o| o.job == job).cloned() else { return };
let Some(j) = app.session.job(job) else { return };
let t = Tokens::get(ui.ctx());
let area = ui.available_rect_before_wrap();
ui.painter().rect_filled(area, 0.0, t.canvas);
let card = Rect::from_center_size(area.center(), vec2(340.0, 132.0));
ui.painter().rect_filled(card, t.radius_lg, t.card);
ui.painter().rect_stroke(card, t.radius_lg, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(card.shrink(18.0)));
child.label(RichText::new(crate::i18n::fmt(tl!("Opening {name}"), &[("name", &tab.name)])).font(crate::theme::semibold(14.0)));
child.add_space(4.0);
let msg = if j.message.is_empty() { tl!("Reading…").to_string() } else { format!("{}…", j.message) };
child.label(RichText::new(msg).color(t.text_dim).size(12.0));
child.add_space(10.0);
let (br, _) = child.allocate_exact_size(vec2(child.available_width(), 8.0), Sense::hover());
bar(&child, br, shown_fraction(&j), &t);
child.add_space(10.0);
let mut cancel_it = false;
child.horizontal(|ui| {
ui.label(RichText::new(percent(&j)).color(t.text_faint).size(11.5));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
cancel_it = crate::widgets::secondary_button(ui, tl!("Cancel"), 76.0).clicked();
});
});
if cancel_it {
cancel(app, job);
}
}
/// Open tabs for the tab strips: (job, title, progress).
pub fn open_tabs(app: &PhotocraftApp) -> Vec<(JobId, String, f32)> {
app.jobs.opens.iter().map(|o| (o.job, o.name.clone(), app.session.job(o.job).map_or(0.0, |j| j.progress))).collect()
}
/// Draw one opening tab's progress underline inside tab rect `r`.
pub fn tab_underline(ui: &egui::Ui, r: Rect, frac: f32, t: &Tokens) {
let line = Rect::from_min_max(egui::pos2(r.left() + 4.0, r.bottom() - 3.0), egui::pos2(r.right() - 4.0, r.bottom() - 1.0));
ui.painter().rect_filled(line, 1.0, t.field_border);
let f = Rect::from_min_size(line.min, vec2(line.width() * frac.clamp(0.0, 1.0), line.height()));
ui.painter().rect_filled(f, 1.0, t.accent);
}
/// Jobs for `ui.inspect`.
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<_>>(),
"focus": app.jobs.focus.map(|j| j.0),
"background": app.background_jobs,
})
}
/// Bytes shared with a background open without copying them again.
pub fn bytes(b: &[u8]) -> OpenSource {
OpenSource::Bytes(Arc::new(b.to_vec()))
}
#[cfg(test)]
#[path = "jobs_ui_tests.rs"]
mod tests;
+216
View File
@@ -0,0 +1,216 @@
//! UI tests for background jobs (#210): the whole app (eframe harness, CPU canvas) keeps
//! rendering frames while a slow job runs, shows the status-bar progress and the modal progress
//! dialog, and Esc / Cancel leave the document unchanged.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use photocraft_engine::jobs::{JobId, Started};
use serde_json::{Value, json};
use crate::PhotocraftApp;
fn app_harness() -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(8).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 320, "height": 240})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap();
let mut app = PhotocraftApp::new(s, crate::Services::default());
app.background_jobs = true;
app
});
h.run_steps(4);
h
}
/// A fake document job that runs until `gate` opens (or it is cancelled), reporting 40 %.
fn slow_job(app: &mut PhotocraftApp, gate: &Arc<AtomicBool>) -> JobId {
let gate = gate.clone();
let r = app
.session
.start_job(
"test.slow",
json!({}),
"Slow Filter",
true,
move |ctx| {
ctx.progress(0.4, "Filtering tiles");
while !gate.load(Ordering::Relaxed) {
ctx.check()?;
std::thread::sleep(Duration::from_millis(1));
}
Ok(())
},
|s, ()| {
s.edit("Slow Filter", |_, _| Ok(()))?;
Ok(json!({"slow": true}))
},
)
.unwrap();
match r {
Started::Job(id) => id,
Started::Done(v) => panic!("ran inline: {v}"),
}
}
/// Step frames for `ms` of wall time; returns (frames, slowest frame in ms).
fn frames_for(h: &mut Harness<'_, PhotocraftApp>, ms: u64) -> (u64, f64) {
let t = Instant::now();
let (mut n, mut worst) = (0, 0.0f64);
while t.elapsed() < Duration::from_millis(ms) {
let f = Instant::now();
h.step();
worst = worst.max(f.elapsed().as_secs_f64() * 1000.0);
n += 1;
}
(n, worst)
}
#[test]
fn the_frame_loop_keeps_running_during_a_slow_job_and_esc_cancels_it() {
let mut h = app_harness();
let gate = Arc::new(AtomicBool::new(false));
let doc_before = h.state().session.active().unwrap().doc.clone();
let job = slow_job(h.state_mut(), &gate);
let frame0 = h.state().frame;
let (n, worst) = frames_for(&mut h, 400);
assert!(h.state().frame - frame0 >= 10, "the UI kept rendering ({n} frames)");
eprintln!("{n} frames during the job, slowest {worst:.1} ms");
// The status bar shows the job, and after the delay the modal progress dialog.
assert!(h.query_all_by_label("Slow Filter").count() >= 2, "job label in the status bar and the dialog title");
assert!(h.query_by_label("Cancel").is_some(), "the progress dialog's Cancel");
assert!(h.query_by_label("Filtering tiles").is_some(), "the job's status message");
// Commands that would edit the busy document are disabled with a clear reason.
assert!(!h.state().session.is_enabled("layer.new.layer"));
let err = h.state_mut().run("layer.new.layer", json!({})).unwrap_err();
assert!(err.contains("Slow Filter"), "{err}");
// Esc cancels; the document is untouched.
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(h.state().session.job(job).is_none());
assert!(Arc::ptr_eq(&h.state().session.active().unwrap().doc, &doc_before));
assert!(h.state().ui.status.contains("Cancelled"), "{}", h.state().ui.status);
assert!(h.query_by_label("Esc to cancel").is_none(), "the dialog closed");
}
#[test]
fn a_finished_job_lands_as_one_undo_step_and_the_dialog_cancel_button_works() {
let mut h = app_harness();
let gate = Arc::new(AtomicBool::new(false));
let steps = h.state().session.active().unwrap().history.past_len();
slow_job(h.state_mut(), &gate);
frames_for(&mut h, 320);
gate.store(true, Ordering::Relaxed);
let t = Instant::now();
while h.state().session.has_jobs() && t.elapsed() < Duration::from_secs(10) {
h.step();
}
h.run_steps(2);
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);
// A second job, cancelled from the dialog's button.
let gate = Arc::new(AtomicBool::new(false));
let job = slow_job(h.state_mut(), &gate);
frames_for(&mut h, 320);
h.get_by_label("Cancel").click();
h.run_steps(3);
assert!(h.state().session.job(job).is_none());
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);
}
#[test]
fn filters_from_the_ui_run_in_the_background() {
let mut h = app_harness();
let steps = h.state().session.active().unwrap().history.past_len();
let r = h.state_mut().run("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
assert_eq!(r["pending"], true, "{r}");
let t = Instant::now();
while h.state().session.has_jobs() && t.elapsed() < Duration::from_secs(30) {
h.step();
}
h.run_steps(2);
let st = h.state().session.active().unwrap();
assert_eq!(st.history.past_len(), steps + 1, "one step for the blur");
assert_eq!(h.state().ui.status, "Gaussian Blur");
}
#[test]
fn control_requests_wait_for_jobs_unless_asked_not_to() {
let mut h = app_harness();
let ctx = h.ctx.clone();
let (req, _rx) = crate::ControlRequest::new("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 2}}));
let job = match crate::control::handle(h.state_mut(), &ctx, &req) {
crate::control::Outcome::AfterJob(job) => job,
_ => panic!("expected a deferred reply"),
};
assert!(h.state().session.jobs().iter().any(|j| j.id == job) || h.state().session.jobs_with_recent().iter().any(|j| j.id == job));
// The app's frame loop answers the request when the job lands.
let (req, rx) = crate::ControlRequest::new("engine.execute", json!({"command": "jobs.list"}));
let _ = crate::control::handle(h.state_mut(), &ctx, &req);
drop(rx);
let (tx, rx) = std::sync::mpsc::channel();
h.state_mut().jobs.waiters.push((job, tx));
let t = Instant::now();
let reply: Value = loop {
h.step();
if let Ok(v) = rx.try_recv() {
break v;
}
assert!(t.elapsed() < Duration::from_secs(30));
};
assert_eq!(reply["ok"], true, "{reply}");
assert!(reply["result"]["filter"].is_object(), "{reply}");
// `wait: false` replies with the job id at once.
let (req, _rx) = crate::ControlRequest::new("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 2}, "wait": false}));
let crate::control::Outcome::Done(v) = crate::control::handle(h.state_mut(), &ctx, &req) else { panic!("expected an immediate reply") };
let id = v["result"]["job"].as_u64().unwrap();
let (req, _rx) = crate::ControlRequest::new("jobs.cancel", json!({"job": id}));
let crate::control::Outcome::Done(v) = crate::control::handle(h.state_mut(), &ctx, &req) else { panic!() };
assert_eq!(v["ok"], true, "{v}");
let (req, _rx) = crate::ControlRequest::new("jobs.cancel", json!({"job": 99999}));
let crate::control::Outcome::Done(v) = crate::control::handle(h.state_mut(), &ctx, &req) else { panic!() };
assert_eq!(v["ok"], false);
}
fn psd_bytes() -> Vec<u8> {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
let doc = (*s.active().unwrap().doc).clone();
photocraft_io::export(&doc, "x.psd", &Default::default()).unwrap().bytes
}
#[test]
fn files_open_in_the_background_with_a_tab_and_cancel_closes_it() {
let mut h = app_harness();
let bytes = psd_bytes();
h.state_mut().open_file("/tmp/photocraft-test/bg.psd", &bytes).unwrap();
// The tab is there before the document.
assert_eq!(h.state().jobs.opens.len(), 1);
assert_eq!(h.state().session.documents().len(), 1);
let t = Instant::now();
while !h.state().jobs.opens.is_empty() && t.elapsed() < Duration::from_secs(30) {
h.step();
}
h.run_steps(2);
let st = h.state().session.active().unwrap();
assert_eq!(st.doc.size.width, 64);
assert_eq!(st.path.as_deref(), Some("/tmp/photocraft-test/bg.psd"));
assert_eq!(h.state().ui.recent_files.first().map(String::as_str), Some("/tmp/photocraft-test/bg.psd"));
// Cancel: the half-open tab closes, no document is added.
h.state_mut().open_file("/tmp/photocraft-test/bg2.psd", &bytes).unwrap();
let job = h.state().jobs.opens[0].job;
crate::jobs_ui::cancel(h.state_mut(), job);
h.run_steps(3);
assert!(h.state().jobs.opens.is_empty());
assert_eq!(h.state().session.documents().len(), 2);
assert!(h.state().jobs.focus.is_none());
}
+22 -1
View File
@@ -58,6 +58,7 @@ pub mod hold_keys;
pub mod i18n;
mod icon_data;
pub mod icons;
pub mod jobs_ui;
pub mod layer_menu_ui;
pub mod layer_props_ui;
mod layer_reveal;
@@ -339,6 +340,12 @@ pub struct PhotocraftApp {
pub(crate) allow_close: bool,
/// Pen pressure/tilt from the platform (see `stylus`).
pub stylus: stylus::Stylus,
/// Run long commands and file opens as background jobs with progress and Cancel (#210; see
/// `jobs_ui`). The desktop app turns it on; off (the default), everything runs inline as
/// before, which tests and scripts rely on.
pub background_jobs: bool,
/// Background job bookkeeping: opening tabs, control replies waiting on a job.
pub jobs: jobs_ui::JobsUi,
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
live_tokens: theme::live::LiveTokens,
}
@@ -408,6 +415,8 @@ impl PhotocraftApp {
discard: None,
allow_close: false,
stylus: Default::default(),
background_jobs: false,
jobs: Default::default(),
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
live_tokens: theme::live::LiveTokens::from_env(),
};
@@ -484,7 +493,8 @@ impl PhotocraftApp {
return Ok(serde_json::json!({"pasted": false}));
}
}
let r = self.session.execute(id, params).map_err(|e| e.to_string());
// Long commands become background jobs when enabled (`jobs_ui`); the rest run inline.
let r = jobs_ui::run(self, id, params);
if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {
self.clip_external = false;
self.export_os_clipboard();
@@ -570,6 +580,12 @@ impl PhotocraftApp {
if let Some(r) = preset_files_ui::open(self, name, bytes) {
return r.map(|()| Vec::new());
}
// Decoded on a worker: a tab with progress appears now, the document when it's ready
// (warnings are shown then).
if self.background_jobs {
jobs_ui::start_open(self, name, None, jobs_ui::bytes(bytes))?;
return Ok(Vec::new());
}
let import = self.services.import.as_ref().ok_or("no importer configured")?;
let (doc, warnings) = import(name, bytes)?;
// Edit › Color Settings policies apply on open; mismatches can ask what to do.
@@ -713,6 +729,7 @@ impl PhotocraftApp {
let _ = reply.send(v);
}
control::Outcome::AfterInput => self.input_waiters.push(reply),
control::Outcome::AfterJob(job) => self.jobs.waiters.push((job, reply)),
control::Outcome::Screenshot { token, path } => {
// Wait out egui's fade animations (~83 ms) and a few rendered frames first.
let settle = ctx.global_style().animation_time as f64 * 2000.0 + 60.0;
@@ -806,6 +823,9 @@ impl eframe::App for PhotocraftApp {
// maximize it into the work area once (#315).
work_area::fit_window(ctx);
discard_ui::guard_window_close(self, ctx);
// Background jobs: apply finished ones, keep frames coming, Esc cancels (before the
// shortcuts see Esc).
jobs_ui::tick(self, ctx);
shortcuts::handle(self, ctx);
let arrived: Vec<(String, Vec<u8>)> =
self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();
@@ -873,6 +893,7 @@ impl eframe::App for PhotocraftApp {
workspace_ui::windows(self, &ctx);
palette::show(self, &ctx);
dialogs::show(self, &ctx);
jobs_ui::dialog(self, &ctx);
discard_ui::show(self, &ctx);
distort_ui::show(self, &ctx);
camera_raw_ui::show(self, &ctx);
+6
View File
@@ -854,6 +854,8 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.horizontal_centered(|ui| {
if t.pro {
crate::chrome_ui::status_bar_pro(app, ui);
// Background job progress with Cancel, at the right end (#210).
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| crate::jobs_ui::status_progress(app, ui));
return;
}
if let (Some(st), Some(i)) = (app.session.active(), app.session.active_index()) {
@@ -886,6 +888,10 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
{
app.ui.views[i].fit_pending = true;
}
if app.session.has_jobs() {
ui.add_space(6.0);
crate::jobs_ui::status_progress(app, ui);
}
});
});
});
+6
View File
@@ -43,6 +43,12 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
p["select"] = json!(true);
}
Some(app.run(cmd, p).map(|r| {
// A background import (#210): `jobs_ui` reports the count when it lands.
if r.get("pending").and_then(Value::as_bool) == Some(true) {
app.ui.status_error = false;
app.ui.status = format!("Importing {what} from {stem}…");
return;
}
let n = r.get("count").and_then(Value::as_u64).unwrap_or(0);
let warnings: Vec<String> = r.get("warnings").and_then(|w| serde_json::from_value(w.clone()).ok()).unwrap_or_default();
app.ui.status_error = false;
+1 -1
View File
@@ -180,7 +180,7 @@ pub fn pressed_command(app: &PhotocraftApp, ctx: &egui::Context, focus: Focus, e
/// Why `id` can't run now (the engine's reason when it has one).
pub fn disabled_reason(app: &PhotocraftApp, id: &str) -> String {
photocraft_engine::commands::find(id)
.and_then(|c| (c.enabled)(&app.session).err())
.and_then(|_| app.session.disabled_reason(id))
.unwrap_or_else(|| if app.session.active().is_none() { "no document open".into() } else { "not available in the current state".into() })
}
+8 -2
View File
@@ -74,6 +74,10 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
UI-level commands (`file.open`, `file.save`, `view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`.
### 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` still waits 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.
## Preferences
Preferences (Edit › Preferences, grouped like Photoshop's dialog sections) live in the engine, so
@@ -143,7 +147,8 @@ How each MCP tool maps onto control methods in bridge mode:
| MCP tool | Control method |
|---|---|
| `command_run {id, params}` | `engine.execute {command: id, params}` |
| `command_run {id, params, wait?}` | `engine.execute {command: id, params, wait}` |
| `jobs_list` / `jobs_cancel {job?}` | `jobs.list` / `jobs.cancel {job?}` |
| `command_list {filter?, enabled_only?}` | `engine.commands` (filtered by the MCP server) |
| `doc_new {…}` | `engine.execute {command: "file.new", params}` |
| `doc_inspect` | `engine.execute {command: "document.inspect"}` |
@@ -189,7 +194,8 @@ no MCP framing, no app start-up per command. Configure its file access with the
| Method | Params |
|---|---|
| `engine.execute` | `{command, params?}`: any engine command |
| `engine.execute` | `{command, params?, wait?}`: any engine command (`wait: false` starts a long one as a background job: `{job, pending}`) |
| `jobs.list` / `jobs.cancel` | `{}` / `{job?}`: background jobs (applying finished ones); cancel one or all |
| `engine.commands` | `{filter?}`: registry with params docs and enablement |
| `session.list` | open documents and the active index |
| `doc.open` / `doc.new` | `{path}` / `file.new` params |
+6 -4
View File
@@ -6,7 +6,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| Area | Done | Partial | Missing | Key numbers |
|---|---:|---:|---:|---|
| [Performance](#performance) | 3 | 22 | 10 | 44 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 0 not run, 10 not measurable yet (baseline 2026-10-05) |
| [Performance](#performance) | 3 | 22 | 12 | 46 scenarios: 3 within budget, 22 over budget or failing, 13 tracked only, 4 not run, 8 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 1 | 8 | 18 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 128/256, round trip ≥ 258/256 |
| [Tools](#tools) | 3 | 14 | 13 | |
| [Workspace and UI](#workspace-and-ui) | 0 | 3 | 20 | settings that do nothing: 61 of 133 (target 0) |
@@ -44,6 +44,10 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr
| P19 | Open a 20 MP layered PSD: editable | ≤ 3000 ms p95 | 1753 | 2794 | 2794 | 2.2 GB | 1.9 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) |
| P21 | Content-Aware Fill on 10 MP | ≤ 1500 ms p95 | 218 | 256 | 256 | 1.8 GB | 1.8 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) |
| P22 | Spot Healing stroke on 10 MP | ≤ 500 ms p95 | 157 | 247 | 247 | 1.8 GB | 1.9 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) |
| P24 | Import 500 brushes (longest UI-thread step) | ≤ 100 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |
| P25 | Cancel a Gaussian Blur job on 24 MP (until the worker exits) | ≤ 200 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |
| P49 | Cancel a Content-Aware Fill job on 24 MP (until the worker exits) | ≤ 200 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |
| P50 | App frame time while a 24 MP Gaussian Blur job runs | ≤ 16 ms p95 | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) |
| P26 | Select › Modify › Smooth on 24 MP (radius 50) | ≤ 100 ms p95 | 99.9 | 216 | 251 | 1.0 GB | – | over budget (target not met yet) | [#211](https://github.com/storytold/photocraft/issues/211) |
| P27 | Select › Modify › Feather on 24 MP (radius 50) | ≤ 100 ms p95 | 122 | 357 | 360 | 1.1 GB | – | over budget (target not met yet) | [#211](https://github.com/storytold/photocraft/issues/211) |
| P28 | Content-Aware Scale 24 MP (to 90 % width) | ≤ 3000 ms p95 | 954192 | 954192 | 954192 | 2.1 GB | – | over budget (target not met yet) | [#211](https://github.com/storytold/photocraft/issues/211) |
@@ -64,10 +68,8 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr
| Id | Scenario | Target | Why | Issue |
|---|---|---|---|---|
| P15 | Zoom / pan frame time on a 15000×10000 16-bit document | ≤ 16 ms per frame | no headless canvas frame harness yet (zoom and pan sample the GPU texture in the egui paint callback) | [#209](https://github.com/storytold/photocraft/issues/209) |
| P20 | Open a 2 GB PSD / 4–5 GB PSB | opens with progress, editable, never blank | no progress or background open (#210) and no generated large-file fixtures (#216) | [#210](https://github.com/storytold/photocraft/issues/210) |
| P20 | Open a 2 GB PSD / 4–5 GB PSB | opens with progress, editable, never blank | opens run in the background with progress (#210), but there are no generated large-file fixtures yet (#216) | [#210](https://github.com/storytold/photocraft/issues/210) |
| P23 | Warp / Puppet / Perspective preview at 4K | ≤ 16 ms per frame, commit in the background | the previews run inside the UI tools; no headless frame harness, no background commit | [#210](https://github.com/storytold/photocraft/issues/210) |
| P24 | Import 500 brushes | no UI pause over 100 ms | import runs synchronously on the UI thread (no job system, #210) | [#210](https://github.com/storytold/photocraft/issues/210) |
| P25 | Cancel any long job | takes effect within 200 ms, document unchanged | no operation can be cancelled yet (#210) | [#210](https://github.com/storytold/photocraft/issues/210) |
| P30 | Liquify 800 px brush on 3500×2200 at full resolution | ≤ 1 ms per update | the Liquify proxy is capped at 1600 px and the stroke path lives in the UI tool | [#211](https://github.com/storytold/photocraft/issues/211) |
| P31 | Camera Raw exposure change (proxy) | ≤ 10 ms | the proxy is built inside the dialog; no headless entry point yet | [#211](https://github.com/storytold/photocraft/issues/211) |
| P32 | Brush release on a long stroke | no hitch at mouse-up | the live renderer and the release re-render are UI-side; needs a frame harness | [#211](https://github.com/storytold/photocraft/issues/211) |
+28 -7
View File
@@ -233,7 +233,7 @@ id = "P20"
title = "Open a 2 GB PSD / 4–5 GB PSB"
issue = 210
target = "opens with progress, editable, never blank"
not_measurable = "no progress or background open (#210) and no generated large-file fixtures (#216)"
not_measurable = "opens run in the background with progress (#210), but there are no generated large-file fixtures yet (#216)"
[[scenario]]
id = "P21"
@@ -260,17 +260,38 @@ not_measurable = "the previews run inside the UI tools; no headless frame harnes
[[scenario]]
id = "P24"
title = "Import 500 brushes"
title = "Import 500 brushes (longest UI-thread step)"
issue = 210
target = "no UI pause over 100 ms"
not_measurable = "import runs synchronously on the UI thread (no job system, #210)"
bench = "perf_scenarios"
row = "import 500 brushes: longest UI-thread step"
metric = "max"
budget_ms = 100
[[scenario]]
id = "P25"
title = "Cancel any long job"
title = "Cancel a Gaussian Blur job on 24 MP (until the worker exits)"
issue = 210
target = "takes effect within 200 ms, document unchanged"
not_measurable = "no operation can be cancelled yet (#210)"
bench = "perf_scenarios"
row = "cancel Gaussian Blur r 50 job on 24 MP"
metric = "max"
budget_ms = 200
[[scenario]]
id = "P49"
title = "Cancel a Content-Aware Fill job on 24 MP (until the worker exits)"
issue = 210
bench = "perf_scenarios"
row = "cancel Content-Aware Fill job on 24 MP"
metric = "max"
budget_ms = 200
[[scenario]]
id = "P50"
title = "App frame time while a 24 MP Gaussian Blur job runs"
issue = 210
bench = "perf_scenarios"
row = "app frame during 24 MP Gaussian Blur r 50 job"
budget_ms = 16
# ---- #211: slow algorithms ---------------------------------------------------------------------