PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Filter previews compute off the UI thread; a stale one is cancelled once the slider settles (#1899)
kayrockscreenprinting82148e77f59e
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex b486698d7..bc39fa4f0 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -221,6 +221,8 @@ pub struct Jobs {/// Workers of cancelled jobs that may still be unwinding (native).#[cfg(not(target_arch = "wasm32"))]draining: Vec<std::thread::JoinHandle<()>>,+ /// The context inline job work runs under (see [`Session::set_inline_job_ctx`]).+ inline: Option<JobCtx>,}const RECENT: usize = 16;@@ -283,7 +285,7 @@ pub fn run<T: Send + 'static>(apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,) -> Result<Value> {if !s.jobs.spawn || cfg!(target_arch = "wasm32") {- let t = work(&JobCtx::new())?;+ let t = work(&s.jobs.inline.clone().unwrap_or_default())?;return apply(s, t);}if s.jobs.pending.is_some() {@@ -352,7 +354,7 @@ pub fn edit_job<R: Send + 'static>() -> Result<Value> {if !s.jobs.spawn || cfg!(target_arch = "wasm32") {// Inline: exactly `Session::edit`, as before jobs existed.- let ctx = JobCtx::new();+ let ctx = s.jobs.inline.clone().unwrap_or_default();let r = s.edit(label, |doc, active| f(doc, active, &ctx))?;return Ok(finish(r));}@@ -393,6 +395,14 @@ pub enum OpenSource {pub const OPEN_JOB: &str = "file.open";impl Session {+ /// Run the heavy part of inline (not background) job commands under `ctx`, so another thread+ /// can cancel them: a live preview whose parameters changed stops its stale computation+ /// (`Err(Cancelled)`, the document unchanged) instead of finishing it. `None` restores the+ /// default, a context nothing can cancel.+ pub fn set_inline_job_ctx(&mut self, ctx: Option<JobCtx>) {+ self.jobs.inline = ctx;+ }+/// Run a command, in the background when it supports it (see [`jobs`](crate::jobs)). Errors/// like [`Session::execute`] for unknown, disabled or failing commands.pub fn start(&mut self, id: &str, params: Value) -> Result<Started> {diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs_tests.rsindex 548fff28a..8da27e59f 100644--- a/crates/engine/src/jobs_tests.rs+++ b/crates/engine/src/jobs_tests.rs@@ -454,3 +454,26 @@ fn cancel_takes_effect_within_200_ms_on_24_mp() {assert!(worst < 200.0, "{cmd}: cancel took {worst:.1} ms");}}++#[test]+fn an_inline_job_ctx_lets_another_thread_cancel_inline_work() {+ // A live filter preview runs the filter inline in a private session; when the dialog's+ // parameters change, the stale computation is cancelled through this context.+ let mut s = session(96, 64);+ let before = pixels(&s);+ let revision = s.active().unwrap().revision;+ let ctx = JobCtx::new();+ ctx.cancel();+ s.set_inline_job_ctx(Some(ctx.clone()));+ for (id, p) in [("filter.blur.gaussianBlur", json!({"radius": 40})), ("filter.blur.motionBlur", json!({"distance": 40}))] {+ assert!(matches!(s.execute(id, p), Err(EngineError::Cancelled)), "{id}");+ assert_eq!(pixels(&s), before, "{id}: the document is unchanged");+ assert_eq!(s.active().unwrap().revision, revision, "{id}: no edit recorded");+ }+ // Not cancelled: the same session runs as before.+ s.set_inline_job_ctx(Some(JobCtx::new()));+ s.execute("filter.blur.gaussianBlur", json!({"radius": 4})).unwrap();+ assert_ne!(pixels(&s), before);+ s.set_inline_job_ctx(None);+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 4158d9322..1b4ccbbca 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1100,9 +1100,10 @@ fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx:app.perf.gpu_budget_allowance = allowance;}-/// Live preview for an open filter dialog: run the filter on the proxy and upload it. Heavy-/// commands compute on one background worker (`filter_preview_worker`); everything else keeps-/// the deterministic inline path (#1676), which also lets headless/CPU tests inspect previews+/// Live preview for an open filter dialog: run the filter on the proxy and upload it. With+/// background jobs (the desktop app) it computes on one background worker+/// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the+/// deterministic inline path (#1676), which also lets headless/CPU tests inspect previews/// without a GPU texture.fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> {if let Some(held) = committed_filter_preview(app, idx) {@@ -1133,8 +1134,12 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Contexk: crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)),};let key = request.doc.0 ^ (1u64 << 61);+ // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at+ // 1000 px takes long enough to freeze the window. Once the slider settles, a preview still+ // running for an older value is cancelled.#[cfg(not(target_arch = "wasm32"))]- if app.background_jobs && request.command == "image.mode.indexedColor" {+ if app.background_jobs {+ app.filter_preview_worker.supersede(&request, crate::gpu_canvas::now_ms());if let Some((finished, computed)) = app.filter_preview_worker.poll()&& finished == request{@@ -1150,9 +1155,9 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Contexif !fresh && !app.filter_preview_worker.busy() {let doc = app.session.documents().get(idx)?.doc.clone();let task = request.clone();- if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move || {+ if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| {let t0 = crate::gpu_canvas::now_ms();- let result = crate::filter_dialog::preview_document(&doc, task.active, &task.command, &task.params, task.k).map(|doc| {+ let result = crate::filter_dialog::preview_document_with(&doc, task.active, &task.command, &task.params, task.k, Some(cancel)).map(|doc| {let buffer = photocraft_compose::flatten(&doc);(std::sync::Arc::new(doc), buffer)});@@ -4054,6 +4059,71 @@ mod tabs_tests;#[cfg(test)]mod tests {+ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() {+ // Dragging Gaussian Blur's radius to 1000 px froze the window: the preview ran inline in+ // the frame, and every slider step waited for the previous blur to finish.+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();+ app.background_jobs = true;+ crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();+ let ctx = egui::Context::default();+ let wait_for = |app: &mut PhotocraftApp, radius: f64| {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);+ while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(radius)) {+ assert!(std::time::Instant::now() < deadline, "no preview for radius {radius}");+ ensure_filter_preview(app, 0, &ctx);+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ };+ // The first frame hands the blur to the worker and returns.+ assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none());+ assert!(app.filter_preview_worker.busy(), "the preview computes on the worker");+ let first = app.ui.dialogs[0].fields["radius"].as_f64().unwrap();+ wait_for(&mut app, first);+ assert!(app.filter_preview.as_ref().unwrap().result.is_some());++ // A preview for old values occupies the worker until it is cancelled.+ let st = app.session.active().unwrap();+ let d = &app.ui.dialogs[0];+ let stale = crate::filter_dialog::FilterPreviewKey {+ doc: st.doc.id,+ revision: st.revision,+ dialog: d.id,+ active: st.active_layer,+ command: "filter.blur.gaussianBlur".into(),+ params: json!({"radius": 999.0}),+ k: 1,+ };+ let (told, cancelled) = std::sync::mpsc::channel();+ app.filter_preview_worker+ .start(stale, ctx.clone(), move |job| {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while !job.cancelled() && std::time::Instant::now() < deadline {+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ let _ = told.send(job.cancelled());+ crate::filter_preview_worker::Computed { result: None, ms: 0.0 }+ })+ .unwrap();+ // The slider moves on and stops: once the value settles, the stale preview is cancelled+ // instead of being waited out.+ app.ui.dialogs[0].fields.insert("radius".into(), json!(12.0));+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ let was_cancelled = loop {+ ensure_filter_preview(&mut app, 0, &ctx);+ if let Ok(c) = cancelled.try_recv() {+ break c;+ }+ assert!(std::time::Instant::now() < deadline, "the stale preview was never cancelled");+ std::thread::sleep(std::time::Duration::from_millis(5));+ };+ assert!(was_cancelled, "the stale preview stopped because it was cancelled, not by timing out");+ wait_for(&mut app, 12.0);+ assert!(app.filter_preview.as_ref().unwrap().result.is_some());+ }+#[cfg(not(target_arch = "wasm32"))]#[test]fn indexed_preview_discards_a_finished_job_after_slider_change_or_reopening() {@@ -4076,7 +4146,7 @@ mod tests {let (release, wait) = std::sync::mpsc::channel();let ctx = egui::Context::default();app.filter_preview_worker- .start(old.clone(), ctx.clone(), move || {+ .start(old.clone(), ctx.clone(), move |_| {wait.recv_timeout(std::time::Duration::from_secs(5)).unwrap();crate::filter_preview_worker::Computed { result: None, ms: 0.0 }})diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 44b253367..d8c71f497 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -468,8 +468,22 @@ pub fn params_of(f: &Map<String, Value>) -> Value {/// Compute a preview document: run `command` with `params` on the proxy (scaled) copy of `doc`.pub fn preview_document(doc: &Document, active: Option<photocraft_doc::LayerId>, command: &str, params: &Value, k: u32) -> Option<Document> {+ preview_document_with(doc, active, command, params, k, None)+}++/// [`preview_document`] whose filter stops early, giving `None`, once `cancel` is cancelled+/// (a preview superseded by newer dialog values).+pub fn preview_document_with(+ doc: &Document,+ active: Option<photocraft_doc::LayerId>,+ command: &str,+ params: &Value,+ k: u32,+ cancel: Option<&photocraft_engine::jobs::JobCtx>,+) -> Option<Document> {let proxy = crate::proxy::proxy_document(doc, k);let mut s = photocraft_engine::Session::new();+ s.set_inline_job_ctx(cancel.cloned());s.add_document(proxy, None);if let Some(id) = active {s.select_layer(id).ok()?;diff --git a/crates/ui-egui/src/filter_preview_worker.rs b/crates/ui-egui/src/filter_preview_worker.rsindex aec8439f4..2704f8a6a 100644--- a/crates/ui-egui/src/filter_preview_worker.rs+++ b/crates/ui-egui/src/filter_preview_worker.rs@@ -1,8 +1,13 @@//! One native preview at a time. The canvas submits the current request again after an old-//! job finishes, so slider drags cannot queue copies of every intermediate document.+//! job finishes, so slider drags cannot queue copies of every intermediate document. While a+//! slider moves, the running preview finishes, so the canvas keeps updating during the drag;+//! once the dialog's values have settled, a preview still running for older ones is cancelled+//! ([`Worker::supersede`]) so a slow one (Gaussian Blur at 1000 px) doesn't hold up the last.use std::sync::mpsc::{Receiver, TryRecvError};+use photocraft_engine::jobs::JobCtx;+use crate::filter_dialog::FilterPreviewKey;pub(crate) struct Computed {@@ -10,9 +15,23 @@ pub(crate) struct Computed {pub ms: f64,}+/// How long the dialog's values must stay unchanged before a stale preview is cancelled. Shorter+/// than a pause in a drag is long; cancelling on every slider step meant no preview finished+/// until the slider stopped.+pub(crate) const SETTLE_MS: f64 = 150.0;++/// The preview being computed: its request, its result channel and its cancellation.+struct Running {+ key: FilterPreviewKey,+ rx: Receiver<Result<Computed, String>>,+ job: JobCtx,+}+#[derive(Default)]pub(crate) struct Worker {- running: Option<(FilterPreviewKey, Receiver<Result<Computed, String>>)>,+ running: Option<Running>,+ /// The dialog's latest request and when it was first seen (ms).+ latest: Option<(FilterPreviewKey, f64)>,}impl Worker {@@ -21,42 +40,67 @@ impl Worker {}/// Never wait for a previous computation and never spawn a second concurrent preview.- pub fn start(&mut self, key: FilterPreviewKey, ctx: egui::Context, compute: impl FnOnce() -> Computed + Send + 'static) -> Result<bool, String> {+ /// `compute` gets the preview's cancellation context ([`Worker::supersede`]).+ pub fn start(&mut self, key: FilterPreviewKey, ctx: egui::Context, compute: impl FnOnce(&JobCtx) -> Computed + Send + 'static) -> Result<bool, String> {if self.busy() {return Ok(false);}let (tx, rx) = std::sync::mpsc::sync_channel(1);+ let job = JobCtx::new();+ let work = job.clone();std::thread::Builder::new()- .name("indexed-color-preview".into())+ .name("filter-preview".into()).spawn(move || {- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compute)).map_err(|_| "Filter preview failed".to_string());+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compute(&work))).map_err(|_| "Filter preview failed".to_string());let _ = tx.send(result);ctx.request_repaint();}).map_err(|e| format!("Could not start filter preview: {e}"))?;- self.running = Some((key, rx));+ self.running = Some(Running { key, rx, job });Ok(true)}+ /// The dialog wants `latest` at time `now_ms`. Once that request has been unchanged for+ /// [`SETTLE_MS`], a running preview for anything else is cancelled, so it stops at its next+ /// check and the latest can start (the caller discards its result). While the request keeps+ /// changing (a slider drag) the running preview is left to finish and be shown.+ pub fn supersede(&mut self, latest: &FilterPreviewKey, now_ms: f64) {+ let since = match &self.latest {+ Some((key, t)) if key == latest => *t,+ _ => {+ self.latest = Some((latest.clone(), now_ms));+ now_ms+ }+ };+ if now_ms - since < SETTLE_MS {+ return;+ }+ if let Some(r) = &self.running+ && &r.key != latest+ {+ r.job.cancel();+ }+ }+pub fn poll(&mut self) -> Option<(FilterPreviewKey, Result<Computed, String>)> {- let (_, rx) = self.running.as_ref()?;- let result = match rx.try_recv() {+ let result = match self.running.as_ref()?.rx.try_recv() {Ok(result) => result,Err(TryRecvError::Empty) => return None,Err(TryRecvError::Disconnected) => Err("Filter preview worker disconnected".to_string()),};- let (key, _) = self.running.take()?;+ let key = self.running.take()?.key;Some((key, result))}}-/// Release results from closed dialogs even when their canvas is no longer being drawn.+/// Stop and release previews of closed dialogs even when their canvas is no longer being drawn.pub(crate) fn discard_closed(app: &mut crate::PhotocraftApp) {- let visible = app.ui.dialogs.iter().any(|d| {- d.fields.get("__command").and_then(serde_json::Value::as_str) == Some("image.mode.indexedColor")- && d.fields.get("__preview").and_then(serde_json::Value::as_bool) == Some(true)- });+ let visible =+ app.ui.dialogs.iter().any(|d| d.fields.contains_key("__filter") && d.fields.get("__preview").and_then(serde_json::Value::as_bool) == Some(true));if !visible {+ if let Some(r) = &app.filter_preview_worker.running {+ r.job.cancel();+ }let _ = app.filter_preview_worker.poll();}}@@ -96,7 +140,7 @@ mod tests {let (release, wait) = std::sync::mpsc::channel();assert!(worker- .start(key(1, 0, 8), ctx.clone(), move || {+ .start(key(1, 0, 8), ctx.clone(), move |_| {wait.recv_timeout(std::time::Duration::from_secs(5)).unwrap();Computed { result: None, ms: 0.0 }})@@ -109,14 +153,14 @@ mod tests {.textures_delta.clear();assert!(worker.poll().is_none());- assert!(!worker.start(key(1, 0, colors), ctx.clone(), || panic!("queued an intermediate request")).unwrap());+ assert!(!worker.start(key(1, 0, colors), ctx.clone(), |_| panic!("queued an intermediate request")).unwrap());}release.send(()).unwrap();let (old, result) = finish(&mut worker);assert!(result.is_ok());let latest = key(1, 0, 256);assert_ne!(old, latest); // The canvas must discard this result before uploading.- assert!(worker.start(latest.clone(), ctx, || Computed { result: None, ms: 1.0 }).unwrap());+ assert!(worker.start(latest.clone(), ctx, |_| Computed { result: None, ms: 1.0 }).unwrap());assert_eq!(finish(&mut worker).0, latest);}@@ -134,10 +178,52 @@ mod tests {#[test]fn escaped_panic_is_an_error_and_worker_can_be_reused() {let mut worker = Worker::default();- worker.start(key(1, 0, 64), Default::default(), || panic!("synthetic preview failure")).unwrap();+ worker.start(key(1, 0, 64), Default::default(), |_| panic!("synthetic preview failure")).unwrap();assert!(finish(&mut worker).1.is_err());assert!(!worker.busy());- worker.start(key(1, 0, 128), Default::default(), || Computed { result: None, ms: 0.0 }).unwrap();+ worker.start(key(1, 0, 128), Default::default(), |_| Computed { result: None, ms: 0.0 }).unwrap();assert!(finish(&mut worker).1.is_ok());}++ #[test]+ fn a_stale_preview_is_cancelled_only_once_the_values_settle() {+ // Cancelling on every slider step meant no preview finished until the slider stopped.+ let mut worker = Worker::default();+ let (send_job, job) = std::sync::mpsc::channel();+ let (release, wait) = std::sync::mpsc::channel::<()>();+ worker+ .start(key(1, 0, 8), Default::default(), move |ctx| {+ send_job.send(ctx.clone()).unwrap();+ let _ = wait.recv_timeout(std::time::Duration::from_secs(5));+ Computed { result: None, ms: 0.0 }+ })+ .unwrap();+ let job = job.recv_timeout(std::time::Duration::from_secs(5)).unwrap();+ // A drag: a new value every frame, never settled; the running preview is left to finish.+ for (i, colors) in [16, 32, 64, 128].into_iter().enumerate() {+ worker.supersede(&key(1, 0, colors), 1000.0 + i as f64 * 16.0);+ assert!(!job.cancelled(), "cancelled mid-drag at {colors}");+ }+ // The same request for less than the settle time: still running.+ worker.supersede(&key(1, 0, 128), 1048.0 + SETTLE_MS - 1.0);+ assert!(!job.cancelled());+ // Settled: the stale preview is cancelled.+ worker.supersede(&key(1, 0, 128), 1048.0 + SETTLE_MS);+ assert!(job.cancelled());+ release.send(()).unwrap();+ let (finished, _) = finish(&mut worker);+ assert_eq!(finished, key(1, 0, 8));+ // A running preview for the settled request itself is never cancelled.+ let (send_job, job) = std::sync::mpsc::channel();+ worker+ .start(key(1, 0, 128), Default::default(), move |ctx| {+ send_job.send(ctx.clone()).unwrap();+ Computed { result: None, ms: 0.0 }+ })+ .unwrap();+ let job = job.recv_timeout(std::time::Duration::from_secs(5)).unwrap();+ worker.supersede(&key(1, 0, 128), 99_999.0);+ assert!(!job.cancelled());+ let _ = finish(&mut worker);+ }}