Skip to content

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

Large document: large damage over the GPU budget redraws in the background; open warms layer bounds (#4024) (#5083)

Mohammed90b3f9e89186
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 2ad21c436..527bc6f22 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -382,6 +382,24 @@ pub fn edit_job<R: Send + 'static>(
)
}
+/// Scan every layer surface's content bounds into the shared tile bounds cache, so the first
+/// draw of a document opened in the background doesn't do it on the UI thread: GPU planning
+/// asks each layer for its bounds, a multi-second scan on a multi-gigabyte PSB (#4024).
+/// `check` runs between layers (cancellation).
+pub fn warm_layer_bounds(doc: &Document, mut check: impl FnMut() -> Result<()>) -> Result<()> {
+ let mut pending: Vec<&photocraft_doc::Layer> = doc.layers.iter().collect();
+ while let Some(layer) = pending.pop() {
+ check()?;
+ if let Some(children) = layer.children() {
+ pending.extend(children);
+ }
+ if let Some(surface) = layer.surface() {
+ photocraft_compose::bounds::content_bounds(surface);
+ }
+ }
+ Ok(())
+}
+
/// Where a background open reads its file from.
#[derive(Clone, Debug)]
pub enum OpenSource {
@@ -434,11 +452,15 @@ impl Session {
};
ctx.check()?;
ctx.progress(0.02, "Decoding");
- ctx.stage(0.02, 1.0, "Decoding", |ctl| photocraft_io::import_with_svg_group_depth_and_interrupt(&name_w, &bytes, max_svg_group_depth, ctl))
+ let imported = ctx
+ .stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_with_svg_group_depth_and_interrupt(&name_w, &bytes, max_svg_group_depth, ctl))
.map_err(|e| match e {
photocraft_io::IoError::Cancelled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
- })
+ })?;
+ ctx.progress(0.95, "Preparing layers");
+ warm_layer_bounds(&imported.document, || ctx.check())?;
+ Ok(imported)
},
move |s, r: photocraft_io::ImportResult| {
// Ask When Opening: held back until the prompt is answered (`take_held_open`). A
diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs_tests.rs
index 012692281..2bcdda76f 100644
--- a/crates/engine/src/jobs_tests.rs
+++ b/crates/engine/src/jobs_tests.rs
@@ -490,6 +490,32 @@ fn an_open_that_asks_about_its_profile_holds_the_document_back() {
assert_eq!(s.documents().len(), 1);
}
+#[test]
+fn warm_layer_bounds_visits_every_layer_and_can_be_cancelled() {
+ let mut s = session(40, 30);
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let doc = s.active().unwrap().doc.clone();
+ fn count(layers: &[photocraft_doc::Layer]) -> usize {
+ layers.iter().map(|l| 1 + l.children().map_or(0, count)).sum()
+ }
+ assert!(doc.layers.iter().any(|l| l.children().is_some_and(|c| !c.is_empty())), "a group with a layer in it");
+ let mut checks = 0;
+ warm_layer_bounds(&doc, || {
+ checks += 1;
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(checks, count(&doc.layers), "one check per layer, nested ones included");
+ let mut checks = 0;
+ let r = warm_layer_bounds(&doc, || {
+ checks += 1;
+ if checks > 1 { Err(EngineError::Cancelled) } else { Ok(()) }
+ });
+ assert!(matches!(r, Err(EngineError::Cancelled)));
+ assert_eq!(checks, 2, "stops at the first failed check");
+}
+
#[test]
fn wait_job_blocks_until_applied() {
let mut s = session(400, 300);
diff --git a/crates/ui-egui/src/background_redraw_tests.rs b/crates/ui-egui/src/background_redraw_tests.rs
index e054ffe2a..df5d467e1 100644
--- a/crates/ui-egui/src/background_redraw_tests.rs
+++ b/crates/ui-egui/src/background_redraw_tests.rs
@@ -163,3 +163,47 @@ fn closing_the_document_stops_its_redraw() {
g.harness.step();
assert!(g.harness.state().redraws.is_empty());
}
+
+#[test]
+fn hiding_a_large_layer_over_the_gpu_budget_redraws_in_the_background() {
+ let _gpu = photocraft_testkit::gpu_lock();
+ let Some(mut g) = gpu_app() else { return };
+ // A layer covering most, but not all, of the document: hiding it damages a large rect that
+ // isn't the whole canvas.
+ let app = g.harness.state_mut();
+ app.run("file.new", json!({"width": 5000, "height": 2000, "background": "#336699"})).expect("new");
+ app.run("layer.new.layer", json!({})).expect("layer");
+ app.run("select.rect", json!({"x": 0, "y": 0, "width": 4800, "height": 1800})).expect("select");
+ app.run("edit.fill", json!({"color": "#cc8844"})).expect("fill");
+ app.run("select.deselect", json!({})).expect("deselect");
+ let (doc, layer) = {
+ let st = app.session.active().expect("document");
+ (st.doc.id, st.active_layer.expect("layer"))
+ };
+ settle(&mut g);
+ assert!(g.harness.state().perf.last_refresh.starts_with("gpu"), "the document fits the GPU: {}", g.harness.state().perf.last_refresh);
+ // A budget the pages of one 2048 px page cell fit (about 33 MB here) but not those of the
+ // whole width (80 MB), as on a multi-gigabyte PSB. Damage refreshes keep it: `gpu_budget`
+ // recomputes it for full ones only. A small edit still draws on the GPU at once.
+ g.harness.state_mut().run("layer.new.layer", json!({})).expect("layer");
+ g.harness.step();
+ g.harness.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 64, "height": 64})).expect("select");
+ g.harness.step();
+ g.observer.set_memory_budget(48 << 20);
+ g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill");
+ g.harness.step();
+ assert_eq!(g.harness.state().perf.last_refresh, "gpu-rect", "{:?}", g.harness.state().perf.gpu_fallback);
+ g.harness.state_mut().run("select.deselect", json!({})).expect("deselect");
+ g.harness.step();
+ assert!(g.harness.state().redraws.is_empty());
+ g.observer.set_memory_budget(48 << 20);
+ g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide");
+ let damage = g.harness.state().session.active().expect("document").last_damage.expect("damage");
+ assert!(damage != Rect::new(0, 0, 5000, 2000) && damage.width() as u64 * damage.height() as u64 >= crate::gpu_canvas::DEFER_PX, "{damage:?}");
+ g.harness.step();
+ assert!(g.harness.state().redraws.contains_key(&doc), "not composited inline: {}", g.harness.state().perf.last_refresh);
+ settle(&mut g);
+ assert_eq!(g.harness.state().perf.last_refresh, "background");
+ assert_eq!(g.harness.state().perf.gpu_fallback.as_deref(), Some(crate::gpu_canvas::OVER_BUDGET));
+ assert_matches_synchronous(&mut g, doc);
+}
diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs
index ce45364c4..2e583e8e5 100644
--- a/crates/ui-egui/src/gpu_canvas.rs
+++ b/crates/ui-egui/src/gpu_canvas.rs
@@ -448,8 +448,10 @@ impl GpuCanvas {
}
// A full refresh whose layer pages don't fit the memory budget would re-upload the
// evicted ones every time (no faster than the CPU, and more memory): the banded CPU
- // compositor does it, and edits in the view (damage rects) stay on the GPU.
- if region == doc.bounds() && !comp.fits_budget(doc, region) {
+ // compositor does it (in the background on desktop). So does a large damage rect, such
+ // as hiding a big layer (#4024); small edits in the view stay on the GPU.
+ let large = region.width() as u64 * region.height() as u64 >= DEFER_PX;
+ if (region == doc.bounds() || large) && !comp.fits_budget(doc, region) {
res.compositor = Some(comp);
return Err(photocraft_gpu::Unsupported(OVER_BUDGET.into()));
}