diff --git a/.config/nextest.toml b/.config/nextest.toml index 1e104a3072..ce481be0f7 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -13,11 +13,17 @@ nextest-version = "0.9.150" # serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so # this group caps them at 4. `cargo xtask ci tests --gpu` reads this group's filters directly: the # Linux gate runs the group in a shard of its own on lavapipe (scripts/ci-gpu-lavapipe.py). +# +# The group is photocraft-gpu and every test in a module named `gpu_tests` or `_gpu_tests`. +# A test that builds a wgpu device (a kittest `.wgpu()` harness, `create_render_state`, its own +# instance, or a harness `.render()`) lives in such a module and takes `gpu_lock()`. Every other +# test runs on the CPU canvas (the app draws on it unless `set_wgpu` hands it a device) at full +# parallelism. [test-groups] gpu = { max-threads = 4 } [[profile.default.overrides]] -filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/))) | (package(photocraft-automation) & test(/^gpu_backend::/))' +filter = 'package(photocraft-gpu) | test(/(^|::|_)gpu_tests::/)' test-group = 'gpu' # CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run @@ -71,16 +77,16 @@ filter = ''' (package(photocraft-engine) & test(=crop_content_aware_layers::unmeasured_active_targets_and_delete_off_keep_the_legacy_target)) | (package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) | (package(photocraft-ui-egui) & test(=tools::type_tool::canvas_tests::every_paragraph_box_handle_resizes_the_box_with_snapping_on)) | - (package(photocraft-ui-egui) & test(=checker_canvas::pixel_grid_is_solid_and_visible_gpu_2x)) | + (package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_gpu_2x)) | (package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) | - (package(photocraft-ui-egui) & test(=checker_canvas::pixel_grid_is_solid_and_visible_cpu_2x)) | - (package(photocraft-ui-egui) & test(=drag_preview_canvas::marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x)) | + (package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_cpu_2x)) | + (package(photocraft-ui-egui) & test(=gpu_tests::drag_preview_canvas::marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x)) | (package(photocraft-gpu) & test(=camera_raw::shadows_and_highlights_with_per_pixel_stages)) | (package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) | (package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) | - (package(photocraft-ui-egui) & test(=live_stroke_canvas::live_tool_camera_navigation_is_visible_in_the_input_frame)) | - (package(photocraft-ui-egui) & test(=live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_0)) | - (package(photocraft-ui-egui) & test(=full_res_preview::adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off)) | + (package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::live_tool_camera_navigation_is_visible_in_the_input_frame)) | + (package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_0)) | + (package(photocraft-ui-egui) & test(=gpu_tests::full_res_preview::adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off)) | (package(photocraft-ui-egui) & test(=input::hold_keys::tests::cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd)) | (package(photocraft-ui-egui) & test(=guide_cursor_tests::command_over_a_guide_takes_it_where_command_is_the_move_tool)) | (package(photocraft-gpu) & test(=parity::documents_larger_than_the_texture_limit)) | diff --git a/crates/automation/tests/it/gpu_backend.rs b/crates/automation/tests/it/gpu_backend.rs index e5b3c599a8..a80e557ebe 100644 --- a/crates/automation/tests/it/gpu_backend.rs +++ b/crates/automation/tests/it/gpu_backend.rs @@ -1,7 +1,7 @@ //! Tests for the headless GPU backend, capability isolation, cache mutation, and CPU/GPU parity. #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))] -mod tests { +mod gpu_tests { use std::fs; use photocraft_codecs::decode; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 670cb2b69b..b3ba2963a0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -614,11 +614,11 @@ mod zoom_animation_tests { mod display_memo_tests; #[cfg(test)] -mod cpu_background_tests; +mod cpu_background_gpu_tests; #[cfg(test)] -#[path = "canvas/blend_viewport_tests.rs"] -mod blend_viewport_regression; +#[path = "canvas/blend_viewport_gpu_tests.rs"] +mod blend_viewport_gpu_tests; #[cfg(test)] #[path = "canvas/pixel_alignment_tests.rs"] diff --git a/crates/ui-egui/src/canvas/background_redraw.rs b/crates/ui-egui/src/canvas/background_redraw.rs index 45297feecd..124601fa04 100644 --- a/crates/ui-egui/src/canvas/background_redraw.rs +++ b/crates/ui-egui/src/canvas/background_redraw.rs @@ -584,5 +584,7 @@ fn draw( } } +#[cfg(test)] +mod gpu_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs b/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs new file mode 100644 index 0000000000..43139138b9 --- /dev/null +++ b/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs @@ -0,0 +1,664 @@ +//! Background full CPU redraws (#4024) on a device: the GPU tests skip when there is no adapter. + +use super::*; +use serde_json::json; + +struct Gpu { + harness: egui_kittest::Harness<'static, Box>, + observer: GpuCanvas, +} + +/// The app on a real device with background jobs, or `None` without a GPU adapter. +fn gpu_app() -> Option { + let observer = Arc::new(std::sync::Mutex::new(None)); + let observer_out = observer.clone(); + let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .with_pixels_per_point(1.0) + .with_max_steps(64) + .wgpu_setup(crate::gpu_canvas::wgpu_setup()) + .build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + *observer_out.lock().expect("observer") = Some(GpuCanvas::new(rs)); + app.set_wgpu(rs.clone()); + } + app.background_jobs = true; + app + }) + })); + let Ok(harness) = built else { + eprintln!("skipping: no GPU adapter"); + return None; + }; + let observer = observer.lock().expect("observer").take()?; + Some(Gpu { harness, observer }) +} + +/// A document the wgpu compositor leaves to the CPU (knockout on its top layer, which also has +/// Blend If). +fn cpu_only_document(app: &mut PhotocraftApp, w: u32, h: u32) -> DocId { + app.run("file.new", json!({"width": w, "height": h, "background": "#336699"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("layer"); + app.run("edit.fill", json!({"color": "#cc8844"})).expect("fill"); + app.run("layer.layerStyle.blendingOptions", json!({"opacity": 60, "knockout": "shallow", "blendIf": {"channel": "gray", "underlying": [0, 10, 245, 255]}})) + .expect("blending options"); + app.session.active().expect("document").doc.id +} + +/// Frames until no redraw is running. +fn settle(g: &mut Gpu) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + loop { + g.harness.step(); + if g.harness.state().redraws.is_empty() { + return; + } + assert!(std::time::Instant::now() < deadline, "the redraw didn't finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} + +/// Run the frame that starts `doc`'s redraw with its worker held before the first batch, and wait +/// until that very worker reaches the hold: the redraw runs, every block still to draw, until the +/// returned guard drops. Without it a test that needs the redraw still running at its next frame +/// races the worker: a fast machine draws the document first, and so does a slow frame (a +/// software adapter's uploads) that keeps taking blocks as they land until the last one. +fn start_held_redraw(g: &mut Gpu, doc: DocId) -> HoldRedraws { + let held = hold_redraws(); + g.harness.step(); + let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; + assert!(wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), "the redraw worker never reached the pre-batch hold"); + held +} + +/// The canvas texture of `doc` against the synchronous CPU refresh of the current document. +fn assert_matches_synchronous(g: &mut Gpu, doc: DocId) { + let app = g.harness.state_mut(); + let d = app.session.active().expect("document").doc.clone(); + let (display, _) = crate::canvas::canvas_display(app, &d, None); + let reference = doc.0 ^ (1u64 << 60); + g.observer.upload_composite(reference, &d, display.as_deref()); + let (_, size, shown) = g.observer.read_texels(doc.0).expect("canvas texture"); + let (_, _, want) = g.observer.read_texels(reference).expect("reference texture"); + assert_eq!(size, [d.size.width, d.size.height]); + let differ = shown.iter().zip(&want).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "{differ} texels differ from the synchronous refresh"); +} + +#[test] +fn a_full_cpu_refresh_draws_in_the_background_with_the_synchronous_pixels() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); + // Held, so the frame's later runs can't see the redraw already finished. + let held = hold_redraws(); + g.harness.step(); + assert!(g.harness.state().redraws.contains_key(&doc), "the frame started a redraw instead of compositing inline"); + drop(held); + settle(&mut g); + let app = g.harness.state(); + assert_eq!(app.perf.last_refresh, "background"); + assert!(app.perf.gpu_fallback.as_deref().is_some_and(|f| f.contains("Advanced Blending")), "{:?}", app.perf.gpu_fallback); + assert_matches_synchronous(&mut g, doc); +} + +#[test] +fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + // Hold the worker before its first batch and wait until this very worker acknowledges that + // hold: when the fill lands, all 12 blocks of this 4×3 document are still to draw by it. + // Without the hold a fast machine finishes them before the next frame, so the edit never + // races the worker and this test only checked a completed redraw; without the per-worker + // acknowledgement an edit could beat the worker to the hold, and its restarted replacement + // would satisfy the checks. + let held = hold_redraws(); + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + g.harness.step(); + let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; + assert!( + wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), + "the redraw worker never reached the pre-batch hold; an edit would race an unstarted redraw" + ); + // A corner, drawn last (farthest from the view's centre), changes on a layer of its own while + // the redraw runs: a small edit, drawn 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": 3900, "y": 2900, "width": 150, "height": 150})).expect("select"); + g.harness.step(); + g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); + g.harness.step(); + assert_eq!(g.harness.state().perf.last_refresh, "rect", "the fill's damage was drawn synchronously"); + // Still running with blocks to draw, and drawing the edited document, not the state before it. + let current = g.harness.state().session.active().expect("document").doc.clone(); + let r = g.harness.state().redraws.get(&doc).expect("the redraw goes on"); + assert!(r.pending.iter().any(|p| *p), "blocks are still to draw"); + assert!(Arc::ptr_eq(&r.doc, ¤t) || *r.doc == *current, "the blocks left draw the edit"); + drop(held); + settle(&mut g); + assert_matches_synchronous(&mut g, doc); +} + +#[test] +fn an_edit_damaging_most_of_a_large_document_is_drawn_in_the_background_too() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); + settle(&mut g); + // Filling most of the Blend If layer touches tiles all over it: the whole canvas (a fill of a + // small part damages only its own tiles, #9329). + g.harness.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 2500, "height": 1500})).expect("select"); + g.harness.step(); + g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); + assert_eq!(g.harness.state().session.active().expect("document").last_damage, Some(Rect::new(0, 0, 2600, 1700))); + 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_matches_synchronous(&mut g, doc); +} + +#[test] +fn showing_a_hidden_layer_again_reuses_the_redraw_from_before_it_was_hidden() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); + let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); + settle(&mut g); + assert_eq!(g.harness.state().perf.last_refresh, "background"); + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); + settle(&mut g); + // Back to the state drawn before: its blocks come back, nothing is composited. + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show"); + g.harness.step(); + assert!(g.harness.state().redraws.is_empty(), "no redraw: {}", g.harness.state().perf.last_refresh); + assert_eq!(g.harness.state().perf.last_refresh, KEPT); + assert_matches_synchronous(&mut g, doc); + // A real change composites again. `last_refresh` is only set when that redraw finishes, so + // check that one started, then that it was a composite rather than kept blocks. + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "opacity": 0.3})).expect("opacity"); + g.harness.step(); + assert!(g.harness.state().redraws.contains_key(&doc), "not served from kept blocks: {}", g.harness.state().perf.last_refresh); + settle(&mut g); + assert_eq!(g.harness.state().perf.last_refresh, "background"); + assert_matches_synchronous(&mut g, doc); +} + +/// Memory Usage lowered while a redraw runs: the finished composite is kept within what it leaves +/// now, not what it left when the redraw began. +#[test] +fn a_redraw_finishing_after_memory_usage_drops_keeps_nothing_over_it() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + let held = start_held_redraw(&mut g, doc); + // Less than the document's own pixels: nothing is left for kept composites. + g.harness.state_mut().session.edit_prefs(|p| p.performance.memory_usage_mb = 1); + drop(held); + settle(&mut g); + assert!(g.harness.state().kept.entries.is_empty(), "a composite was kept over the current cap"); +} + +/// Color Settings › "Blend Text Colors Using Gamma" isn't part of the document, but type layers +/// composite with it: a state drawn before it changed is composited again, not uploaded from +/// blocks drawn with the old gamma. Only the session's setting changes here, not the process-wide +/// gamma compose reads, so tests compositing type layers at the same time aren't affected. +#[test] +fn a_state_drawn_before_the_text_gamma_changed_is_composited_again() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); + let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); + settle(&mut g); + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); + settle(&mut g); + g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show"); + g.harness.step(); + assert!(g.harness.state().redraws.contains_key(&doc), "served from blocks of the old gamma: {}", g.harness.state().perf.last_refresh); + settle(&mut g); + assert_eq!(g.harness.state().perf.last_refresh, "background"); + assert_matches_synchronous(&mut g, doc); +} + +/// The text gamma changing while a redraw runs: its blocks were drawn with both, so it isn't kept. +#[test] +fn a_redraw_across_a_text_gamma_change_is_not_kept() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + let held = start_held_redraw(&mut g, doc); + g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + drop(held); + settle(&mut g); + assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); +} + +/// Changed and changed back while a redraw runs: blocks drawn in between still mix both. +#[test] +fn a_redraw_across_a_text_gamma_change_and_back_is_not_kept() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + let gamma = g.harness.state().session.color.settings.blend_text_gamma; + let held = start_held_redraw(&mut g, doc); + g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.step(); + g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; + assert!(g.harness.state().redraws.contains_key(&doc), "the redraw finished before the change back"); + drop(held); + settle(&mut g); + assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); +} + +/// The same while another document is shown: its redraw goes on without being polled, so the +/// change is seen every frame, not only when it shows again. +#[test] +fn a_hidden_documents_redraw_across_a_text_gamma_change_and_back_is_not_kept() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + let gamma = g.harness.state().session.color.settings.blend_text_gamma; + let held = start_held_redraw(&mut g, doc); + g.harness.state_mut().run("file.new", json!({"width": 64, "height": 64})).expect("another document"); + g.harness.step(); + g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.step(); + g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; + g.harness.step(); + assert!(g.harness.state().redraws.contains_key(&doc), "the hidden document's redraw stopped"); + let i = g.harness.state().session.documents().iter().position(|st| st.doc.id == doc).expect("document"); + g.harness.state_mut().session.set_active(i); + drop(held); + settle(&mut g); + assert!(g.harness.state().kept.entries.iter().all(|k| k.id != doc), "a composite of two gammas was kept"); +} + +/// Memory Usage lowered with no redraw running: the kept composites go at the next frame, not +/// only when the next redraw starts. +#[test] +fn kept_composites_go_when_memory_usage_drops_between_redraws() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + cpu_only_document(g.harness.state_mut(), 2600, 1700); + settle(&mut g); + assert!(!g.harness.state().kept.entries.is_empty(), "the finished redraw is kept"); + g.harness.state_mut().session.edit_prefs(|p| p.performance.memory_usage_mb = 1); + g.harness.step(); + assert!(g.harness.state().redraws.is_empty()); + assert!(g.harness.state().kept.entries.is_empty(), "kept over the current cap"); +} + +/// An edit too small for a background redraw that grows the document past what Memory Usage +/// leaves: the kept composite goes at the next frame. The test holds the kept state itself, so +/// only the cap can drop it, not History letting go of the state. +#[test] +fn kept_composites_go_when_a_small_edit_grows_the_document_past_the_cap() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + cpu_only_document(g.harness.state_mut(), 2600, 1700); + settle(&mut g); + let app = g.harness.state_mut(); + let st = app.session.active().expect("document"); + let held = st.doc.clone(); + let (used, kept) = (st.memory_bytes() as u64, app.kept.bytes()); + assert!(kept > 0, "the finished redraw is kept"); + // Room for the kept composite and 2-3 MB more. + let mb = (used + kept).div_ceil(1 << 20) + 2; + app.session.edit_prefs(|p| p.performance.memory_usage_mb = mb as _); + g.harness.step(); + assert_eq!(g.harness.state().kept.entries.len(), 1, "still within the cap"); + // 2 MP of new pixels (8 MB): under the size that redraws in the background. + for (cmd, p) in + [("layer.new.layer", json!({})), ("select.rect", json!({"x": 0, "y": 0, "width": 2000, "height": 1000})), ("edit.fill", json!({"color": "#cc2244"}))] + { + g.harness.state_mut().run(cmd, p).expect(cmd); + g.harness.step(); + assert!(g.harness.state().redraws.is_empty(), "{cmd} redrew in the background"); + } + assert!(g.harness.state().kept.entries.is_empty(), "kept over the cap after the edit"); + drop(held); +} + +/// The same for an older kept composite of another document: every kept document's edits count, +/// not only the newest one's. +#[test] +fn an_older_kept_composite_goes_when_its_document_grows_past_the_cap() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let a = cpu_only_document(g.harness.state_mut(), 2600, 1700); + settle(&mut g); + let b = cpu_only_document(g.harness.state_mut(), 2600, 1700); + settle(&mut g); + let app = g.harness.state_mut(); + let held: Vec<_> = app.session.documents().iter().map(|st| st.doc.clone()).collect(); + assert_eq!(app.kept.entries.iter().map(|k| k.id).collect::>(), [b, a], "both kept, the second newest"); + let used = app.session.documents().iter().map(|st| st.memory_bytes() as u64).max().unwrap_or(0); + let mb = (used + app.kept.bytes()).div_ceil(1 << 20) + 2; + app.session.edit_prefs(|p| p.performance.memory_usage_mb = mb as _); + let i = app.session.documents().iter().position(|st| st.doc.id == a).expect("document"); + app.session.set_active(i); + g.harness.step(); + assert_eq!(g.harness.state().kept.entries.len(), 2, "still within the cap"); + for (cmd, p) in + [("layer.new.layer", json!({})), ("select.rect", json!({"x": 0, "y": 0, "width": 2000, "height": 1000})), ("edit.fill", json!({"color": "#cc2244"}))] + { + g.harness.state_mut().run(cmd, p).expect(cmd); + g.harness.step(); + assert!(g.harness.state().redraws.is_empty(), "{cmd} redrew in the background"); + } + assert!(g.harness.state().kept.entries.len() < 2, "kept over the cap after the older document grew"); + drop(held); +} + +/// A kept state History no longer holds goes at the next frame: its texels aren't held until +/// some later redraw. +#[test] +fn a_kept_state_history_purged_goes_at_the_next_frame() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + cpu_only_document(g.harness.state_mut(), 2600, 1700); + let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); + settle(&mut g); + // Hidden, the document is drawn on the GPU: the kept state is the one before, in History. + g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); + settle(&mut g); + assert_eq!(g.harness.state().kept.entries.len(), 1, "the state before hiding is kept"); + g.harness.state_mut().run("edit.purge.histories", json!({})).expect("purge"); + g.harness.step(); + assert!(g.harness.state().redraws.is_empty()); + assert!(g.harness.state().kept.entries.is_empty(), "the purged state's composite is still held"); +} + +#[test] +fn closing_the_document_stops_its_redraw() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); + // Held: the close lands while the redraw runs, and a cancelled worker leaves the hold. + let _held = start_held_redraw(&mut g, doc); + g.harness.state_mut().run("file.close", json!({"save": false})).expect("close"); + 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"); + let app = g.harness.state(); + assert!(matches!(app.render_path.current(doc.0), Some(crate::render_path::CpuReason::OverBudget { .. })), "{:?}", app.perf.gpu_fallback); + assert_matches_synchronous(&mut g, doc); +} + +/// The active document's render path: its reason's kind. +fn render_path_of(g: &Gpu) -> Option<&'static str> { + let app = g.harness.state(); + let doc = app.session.active().expect("document").doc.id.0; + app.render_path.current(doc).map(crate::render_path::CpuReason::kind) +} + +/// On the GPU canvas: no reason, or only a software adapter's (CI's runners have one). +fn on_gpu_canvas(g: &Gpu) -> bool { + matches!(render_path_of(g), None | Some("softwareAdapter")) +} + +#[test] +fn advanced_blending_fallback_is_shown_in_the_status_bar() { + use egui_kittest::kittest::Queryable; + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + cpu_only_document(g.harness.state_mut(), 800, 600); + g.harness.step(); + settle(&mut g); + g.harness.run_steps(2); + assert_eq!(render_path_of(&g), Some("unsupported")); + // PLAN: assumes the status bar's CPU Rendering message exposes its tooltip text to kittest after a hover (panels-w19). + g.harness.get_by_label("CPU Rendering").hover(); + g.harness.run_steps(40); + assert!(g.harness.query_by_label_contains("Advanced Blending").is_some(), "the tooltip names the cause"); +} + +#[test] +fn completed_compositor_build_refreshes_an_unchanged_cached_document() { + let _gpu = photocraft_testkit::gpu_lock(); + for success in [true, false] { + let Some(mut g) = gpu_app() else { return }; + let gpu = g.harness.state().gpu.as_ref().expect("GPU canvas").clone(); + gpu.simulate_compositor_build(); + g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); + g.harness.step(); + settle(&mut g); + let doc = g.harness.state().session.active().expect("document").doc.id; + let revision = g.harness.state().session.active().expect("document").revision; + assert_eq!(render_path_of(&g), Some("compositorBuilding")); + assert!(gpu.simulate_compositor_completion(success), "test compositor must build"); + g.harness.step(); + settle(&mut g); + g.harness.run_steps(2); + assert_eq!(g.harness.state().session.active().expect("document").revision, revision); + if success { + assert!(on_gpu_canvas(&g), "successful build should replace the temporary reason: {:?}", render_path_of(&g)); + } else { + assert_eq!(render_path_of(&g), Some("compositorBuild")); + assert!(g.harness.state().perf.gpu_fallback.as_deref().is_some_and(|s| s.contains("simulated build failure"))); + assert_matches_synchronous(&mut g, doc); + } + } +} + +#[test] +fn a_canvas_over_the_texture_budget_records_its_reason() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + // The app's canvas, not the observer: each `GpuCanvas::new` shares a new budget. + g.harness.state().gpu.as_ref().expect("gpu canvas").set_canvas_budget(1); + g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); + g.harness.run_steps(3); + assert_eq!(render_path_of(&g), Some("canvasTooLarge")); + let doc = g.harness.state().session.active().expect("document").doc.id.0; + assert_eq!(g.harness.state().render_path.history().filter(|c| c.doc == doc).count(), 1, "once, not every frame"); +} + +/// Frames until the active document's viewport pages are all rendered and uploaded. +fn settle_pages(g: &mut Gpu) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + loop { + g.harness.step(); + let app = g.harness.state(); + let id = app.session.active().expect("document").doc.id; + if app.streams.get(&id).is_some_and(|s| !s.busy() && s.stats.wanted > 0 && s.stats.ready == s.stats.wanted) { + return; + } + assert!(std::time::Instant::now() < deadline, "the viewport pages didn't finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} + +/// The screen pixel at the window's centre. +fn centre_pixel(g: &mut Gpu) -> [u8; 4] { + let img = g.harness.render().expect("render"); + let p = img.get_pixel(img.width() / 2, img.height() / 2); + p.0 +} + +/// #5332: a document whose texture set doesn't fit the canvas budget stays on the GPU canvas, +/// drawn from the pages in view instead of the CPU canvas, with the same pixels; an edit +/// re-renders only the pages, and closing it frees them. +#[test] +fn a_canvas_over_the_texture_budget_draws_its_viewport_pages_on_the_gpu() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + g.harness.state_mut().run("file.new", json!({"width": 3000, "height": 2000, "background": "#336699"})).expect("new"); + g.harness.run_steps(3); + assert!(on_gpu_canvas(&g)); + let whole = centre_pixel(&mut g); + let gpu = g.harness.state().gpu.clone().expect("gpu canvas"); + let doc = g.harness.state().session.active().expect("document").doc.clone(); + let key = crate::canvas::viewport_pages::stream_key(doc.id.0); + // Room for pages (half the budget), not for the document's texture set. + let (set, _) = gpu.canvas_fit(&doc).expect("fit"); + gpu.set_canvas_budget(set - 1); + settle_pages(&mut g); + assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); + assert!(gpu.texture_info(doc.id.0).is_none(), "no texture set"); + let (pages, bytes) = gpu.pages(key); + let stats = g.harness.state().streams[&doc.id].stats.clone(); + assert_eq!(pages.len(), stats.resident); + assert!(stats.wanted > 0 && stats.last_error.is_none(), "{stats:?}"); + assert!(bytes <= (set - 1) / 2, "pages stay within half the budget: {bytes}"); + let shown = centre_pixel(&mut g); + assert!((0..3).all(|i| shown[i].abs_diff(whole[i]) <= 2), "pages {shown:?}, texture set {whole:?}"); + // An edit re-renders the pages it reaches. + let uploads = stats.uploads; + g.harness.state_mut().run("edit.fill", json!({"color": "#cc8844"})).expect("fill"); + settle_pages(&mut g); + let stats = g.harness.state().streams[&doc.id].stats.clone(); + assert!(stats.dirtied > 0 && stats.uploads > uploads, "{stats:?}"); + let filled = centre_pixel(&mut g); + assert!(filled[0] > 0xb0 && filled[2] < 0x60, "the fill is shown: {filled:?}"); + // A small edit re-renders only the part of each page it reaches, into the page held. + let (held, partial) = (gpu.pages(key).0.len(), stats.partial); + // (A frame between the steps, as in use: the edit's damage is known one revision at a time.) + g.harness.state_mut().run("select.rect", json!({"x": 1400, "y": 900, "width": 200, "height": 200})).expect("select"); + settle_pages(&mut g); + g.harness.state_mut().run("edit.fill", json!({"color": "#22aa22"})).expect("small fill"); + settle_pages(&mut g); + let stats = g.harness.state().streams[&doc.id].stats.clone(); + assert!(stats.partial > partial, "{stats:?}"); + assert_eq!(gpu.pages(key).0.len(), held, "no new page textures"); + // Just its square is shown: 200 px at about 20% zoom, some 40 screen pixels a side. + let img = g.harness.render().expect("render"); + let green = img.pixels().filter(|p| p.0[1] > 0x90 && p.0[0] < 0x50 && p.0[2] < 0x50).count(); + assert!((1000..2500).contains(&green), "the small fill is shown: {green} pixels"); + // A budget too small for one page draws it on the CPU canvas, as before. + gpu.set_canvas_budget(1); + g.harness.run_steps(3); + assert_eq!(render_path_of(&g), Some("canvasTooLarge")); + // Its pages and their work are freed meanwhile (#5332 review). + assert!(gpu.pages(key).0.is_empty(), "pages freed"); + assert!(!g.harness.state().streams.contains_key(&doc.id), "stream dropped"); + gpu.set_canvas_budget(set - 1); + settle_pages(&mut g); + // Closing the document cancels its work and frees its pages. + g.harness.state_mut().run("file.close", json!({"save": false})).expect("close"); + g.harness.run_steps(3); + assert!(g.harness.state().streams.is_empty()); + assert!(gpu.pages(key).0.is_empty()); +} + +/// Runs a Window › Arrange command, as its menu item does, and lets the layout settle. +fn arrange(g: &mut Gpu, command: &str) { + let ctx = g.harness.ctx.clone(); + crate::menus::invoke(g.harness.state_mut(), &ctx, command, json!({})).expect("arrange"); + g.harness.run_steps(3); +} + +/// #5332 review: the open documents share one texture budget rather than each having all of +/// it. A document alone on screen keeps the whole budget; one in a background tab gives its +/// textures up when the shown one needs the room; and documents shown side by side split it, +/// a document over its share drawing from viewport pages. +#[test] +fn open_documents_share_one_texture_budget_with_the_shown_ones_first() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + let gpu = g.harness.state().gpu.clone().expect("gpu canvas"); + let new = |g: &mut Gpu| { + g.harness.state_mut().run("file.new", json!({"width": 3000, "height": 2000, "background": "#336699"})).expect("new"); + g.harness.run_steps(3); + assert!(on_gpu_canvas(g), "{:?}", render_path_of(g)); + g.harness.state().session.active().expect("document").doc.clone() + }; + let a = new(&mut g); + let (set, _) = gpu.canvas_fit(&a).expect("fit"); + // Room for one texture set and a half: a document alone on screen has all of it. + let budget = set + set / 2; + gpu.set_canvas_budget(budget); + assert_eq!(gpu.canvas_fit(&a), Some((set, budget)), "alone, the whole budget"); + assert!(gpu.texture_info(a.id.0).is_some()); + // A second tab: the shown document's texture set takes the room of the background one's. + let b = new(&mut g); + assert_eq!(gpu.canvas_fit(&b), Some((set, budget))); + assert!(gpu.texture_info(b.id.0).is_some()); + assert!(gpu.texture_info(a.id.0).is_none(), "the background document's textures are freed"); + // Back to the first tab: it gets its texture set back and the other gives its up. + g.harness.state_mut().session.set_active(0); + g.harness.run_steps(3); + assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); + assert!(gpu.texture_info(a.id.0).is_some()); + assert!(gpu.texture_info(b.id.0).is_none()); + // Side by side, they split the budget: neither set fits its half, so both draw from pages. + arrange(&mut g, "window.arrange.twoUpVertical"); + assert_eq!(gpu.canvas_fit(&a), Some((set, budget / 2))); + assert_eq!(gpu.canvas_fit(&b), Some((set, budget - budget / 2))); + settle_pages(&mut g); + assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); + let streams = &g.harness.state().streams; + assert!(streams.contains_key(&a.id) && streams.contains_key(&b.id), "both on pages"); + assert!(gpu.texture_info(a.id.0).is_none() && gpu.texture_info(b.id.0).is_none()); + // Switching between them re-splits nothing: no page set is dropped. + let held = gpu.pages(crate::canvas::viewport_pages::stream_key(a.id.0)).0; + g.harness.state_mut().session.set_active(1); + g.harness.run_steps(3); + assert_eq!(gpu.canvas_fit(&a), Some((set, budget / 2))); + assert_eq!(gpu.pages(crate::canvas::viewport_pages::stream_key(a.id.0)).0, held, "no churn on a switch"); + // Back to tabs: the shown document has the whole budget, and its texture set, again. + arrange(&mut g, "window.arrange.consolidateAllToTabs"); + assert_eq!(gpu.canvas_fit(&b), Some((set, budget))); + assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); + assert!(gpu.texture_info(b.id.0).is_some()); +} + +#[test] +fn a_flipped_view_records_why_it_draws_on_the_cpu() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); + g.harness.run_steps(3); + assert!(on_gpu_canvas(&g)); + g.harness.state_mut().ui.view.flip_horizontal = true; + g.harness.run_steps(3); + assert_eq!(render_path_of(&g), Some("viewTransform")); + g.harness.state_mut().ui.view.flip_horizontal = false; + g.harness.run_steps(3); + assert!(on_gpu_canvas(&g), "back on the GPU"); +} diff --git a/crates/ui-egui/src/canvas/background_redraw/tests.rs b/crates/ui-egui/src/canvas/background_redraw/tests.rs index 35d867df25..de022b91e6 100644 --- a/crates/ui-egui/src/canvas/background_redraw/tests.rs +++ b/crates/ui-egui/src/canvas/background_redraw/tests.rs @@ -1,7 +1,6 @@ -//! Background full CPU redraws (#4024). The GPU tests skip when there is no adapter. +//! Background full CPU redraws (#4024): block order and the kept composites. The redraws on a device are in `gpu_tests`. use super::*; -use serde_json::json; #[test] fn blocks_cover_the_document_once() { @@ -119,663 +118,3 @@ fn kept_composites_come_back_only_for_the_exact_state_and_stay_bounded() { cache.trim(u64::MAX); assert!(cache.entries.is_empty()); } - -struct Gpu { - harness: egui_kittest::Harness<'static, Box>, - observer: GpuCanvas, -} - -/// The app on a real device with background jobs, or `None` without a GPU adapter. -fn gpu_app() -> Option { - let observer = Arc::new(std::sync::Mutex::new(None)); - let observer_out = observer.clone(); - let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { - egui_kittest::Harness::builder() - .with_size(egui::vec2(1000.0, 700.0)) - .with_pixels_per_point(1.0) - .with_max_steps(64) - .wgpu_setup(crate::gpu_canvas::wgpu_setup()) - .build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); - if let Some(rs) = cc.wgpu_render_state.as_ref() { - *observer_out.lock().expect("observer") = Some(GpuCanvas::new(rs)); - app.set_wgpu(rs.clone()); - } - app.background_jobs = true; - app - }) - })); - let Ok(harness) = built else { - eprintln!("skipping: no GPU adapter"); - return None; - }; - let observer = observer.lock().expect("observer").take()?; - Some(Gpu { harness, observer }) -} - -/// A document the wgpu compositor leaves to the CPU (knockout on its top layer, which also has -/// Blend If). -fn cpu_only_document(app: &mut PhotocraftApp, w: u32, h: u32) -> DocId { - app.run("file.new", json!({"width": w, "height": h, "background": "#336699"})).expect("new"); - app.run("layer.new.layer", json!({})).expect("layer"); - app.run("edit.fill", json!({"color": "#cc8844"})).expect("fill"); - app.run("layer.layerStyle.blendingOptions", json!({"opacity": 60, "knockout": "shallow", "blendIf": {"channel": "gray", "underlying": [0, 10, 245, 255]}})) - .expect("blending options"); - app.session.active().expect("document").doc.id -} - -/// Frames until no redraw is running. -fn settle(g: &mut Gpu) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); - loop { - g.harness.step(); - if g.harness.state().redraws.is_empty() { - return; - } - assert!(std::time::Instant::now() < deadline, "the redraw didn't finish"); - std::thread::sleep(std::time::Duration::from_millis(2)); - } -} - -/// Run the frame that starts `doc`'s redraw with its worker held before the first batch, and wait -/// until that very worker reaches the hold: the redraw runs, every block still to draw, until the -/// returned guard drops. Without it a test that needs the redraw still running at its next frame -/// races the worker: a fast machine draws the document first, and so does a slow frame (a -/// software adapter's uploads) that keeps taking blocks as they land until the last one. -fn start_held_redraw(g: &mut Gpu, doc: DocId) -> HoldRedraws { - let held = hold_redraws(); - g.harness.step(); - let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; - assert!(wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), "the redraw worker never reached the pre-batch hold"); - held -} - -/// The canvas texture of `doc` against the synchronous CPU refresh of the current document. -fn assert_matches_synchronous(g: &mut Gpu, doc: DocId) { - let app = g.harness.state_mut(); - let d = app.session.active().expect("document").doc.clone(); - let (display, _) = crate::canvas::canvas_display(app, &d, None); - let reference = doc.0 ^ (1u64 << 60); - g.observer.upload_composite(reference, &d, display.as_deref()); - let (_, size, shown) = g.observer.read_texels(doc.0).expect("canvas texture"); - let (_, _, want) = g.observer.read_texels(reference).expect("reference texture"); - assert_eq!(size, [d.size.width, d.size.height]); - let differ = shown.iter().zip(&want).filter(|(a, b)| a != b).count(); - assert_eq!(differ, 0, "{differ} texels differ from the synchronous refresh"); -} - -#[test] -fn a_full_cpu_refresh_draws_in_the_background_with_the_synchronous_pixels() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); - // Held, so the frame's later runs can't see the redraw already finished. - let held = hold_redraws(); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc), "the frame started a redraw instead of compositing inline"); - drop(held); - settle(&mut g); - let app = g.harness.state(); - assert_eq!(app.perf.last_refresh, "background"); - assert!(app.perf.gpu_fallback.as_deref().is_some_and(|f| f.contains("Advanced Blending")), "{:?}", app.perf.gpu_fallback); - assert_matches_synchronous(&mut g, doc); -} - -#[test] -fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - // Hold the worker before its first batch and wait until this very worker acknowledges that - // hold: when the fill lands, all 12 blocks of this 4×3 document are still to draw by it. - // Without the hold a fast machine finishes them before the next frame, so the edit never - // races the worker and this test only checked a completed redraw; without the per-worker - // acknowledgement an edit could beat the worker to the hold, and its restarted replacement - // would satisfy the checks. - let held = hold_redraws(); - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - g.harness.step(); - let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; - assert!( - wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), - "the redraw worker never reached the pre-batch hold; an edit would race an unstarted redraw" - ); - // A corner, drawn last (farthest from the view's centre), changes on a layer of its own while - // the redraw runs: a small edit, drawn 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": 3900, "y": 2900, "width": 150, "height": 150})).expect("select"); - g.harness.step(); - g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); - g.harness.step(); - assert_eq!(g.harness.state().perf.last_refresh, "rect", "the fill's damage was drawn synchronously"); - // Still running with blocks to draw, and drawing the edited document, not the state before it. - let current = g.harness.state().session.active().expect("document").doc.clone(); - let r = g.harness.state().redraws.get(&doc).expect("the redraw goes on"); - assert!(r.pending.iter().any(|p| *p), "blocks are still to draw"); - assert!(Arc::ptr_eq(&r.doc, ¤t) || *r.doc == *current, "the blocks left draw the edit"); - drop(held); - settle(&mut g); - assert_matches_synchronous(&mut g, doc); -} - -#[test] -fn an_edit_damaging_most_of_a_large_document_is_drawn_in_the_background_too() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); - settle(&mut g); - // Filling most of the Blend If layer touches tiles all over it: the whole canvas (a fill of a - // small part damages only its own tiles, #9329). - g.harness.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 2500, "height": 1500})).expect("select"); - g.harness.step(); - g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); - assert_eq!(g.harness.state().session.active().expect("document").last_damage, Some(Rect::new(0, 0, 2600, 1700))); - 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_matches_synchronous(&mut g, doc); -} - -#[test] -fn showing_a_hidden_layer_again_reuses_the_redraw_from_before_it_was_hidden() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); - let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); - settle(&mut g); - assert_eq!(g.harness.state().perf.last_refresh, "background"); - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); - settle(&mut g); - // Back to the state drawn before: its blocks come back, nothing is composited. - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show"); - g.harness.step(); - assert!(g.harness.state().redraws.is_empty(), "no redraw: {}", g.harness.state().perf.last_refresh); - assert_eq!(g.harness.state().perf.last_refresh, KEPT); - assert_matches_synchronous(&mut g, doc); - // A real change composites again. `last_refresh` is only set when that redraw finishes, so - // check that one started, then that it was a composite rather than kept blocks. - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "opacity": 0.3})).expect("opacity"); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc), "not served from kept blocks: {}", g.harness.state().perf.last_refresh); - settle(&mut g); - assert_eq!(g.harness.state().perf.last_refresh, "background"); - assert_matches_synchronous(&mut g, doc); -} - -/// Memory Usage lowered while a redraw runs: the finished composite is kept within what it leaves -/// now, not what it left when the redraw began. -#[test] -fn a_redraw_finishing_after_memory_usage_drops_keeps_nothing_over_it() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let held = start_held_redraw(&mut g, doc); - // Less than the document's own pixels: nothing is left for kept composites. - g.harness.state_mut().session.edit_prefs(|p| p.performance.memory_usage_mb = 1); - drop(held); - settle(&mut g); - assert!(g.harness.state().kept.entries.is_empty(), "a composite was kept over the current cap"); -} - -/// Color Settings › "Blend Text Colors Using Gamma" isn't part of the document, but type layers -/// composite with it: a state drawn before it changed is composited again, not uploaded from -/// blocks drawn with the old gamma. Only the session's setting changes here, not the process-wide -/// gamma compose reads, so tests compositing type layers at the same time aren't affected. -#[test] -fn a_state_drawn_before_the_text_gamma_changed_is_composited_again() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); - let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); - settle(&mut g); - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); - settle(&mut g); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show"); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc), "served from blocks of the old gamma: {}", g.harness.state().perf.last_refresh); - settle(&mut g); - assert_eq!(g.harness.state().perf.last_refresh, "background"); - assert_matches_synchronous(&mut g, doc); -} - -/// The text gamma changing while a redraw runs: its blocks were drawn with both, so it isn't kept. -#[test] -fn a_redraw_across_a_text_gamma_change_is_not_kept() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let held = start_held_redraw(&mut g, doc); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; - drop(held); - settle(&mut g); - assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); -} - -/// Changed and changed back while a redraw runs: blocks drawn in between still mix both. -#[test] -fn a_redraw_across_a_text_gamma_change_and_back_is_not_kept() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let gamma = g.harness.state().session.color.settings.blend_text_gamma; - let held = start_held_redraw(&mut g, doc); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; - g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; - assert!(g.harness.state().redraws.contains_key(&doc), "the redraw finished before the change back"); - drop(held); - settle(&mut g); - assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); -} - -/// The same while another document is shown: its redraw goes on without being polled, so the -/// change is seen every frame, not only when it shows again. -#[test] -fn a_hidden_documents_redraw_across_a_text_gamma_change_and_back_is_not_kept() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let gamma = g.harness.state().session.color.settings.blend_text_gamma; - let held = start_held_redraw(&mut g, doc); - g.harness.state_mut().run("file.new", json!({"width": 64, "height": 64})).expect("another document"); - g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; - g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc), "the hidden document's redraw stopped"); - let i = g.harness.state().session.documents().iter().position(|st| st.doc.id == doc).expect("document"); - g.harness.state_mut().session.set_active(i); - drop(held); - settle(&mut g); - assert!(g.harness.state().kept.entries.iter().all(|k| k.id != doc), "a composite of two gammas was kept"); -} - -/// Memory Usage lowered with no redraw running: the kept composites go at the next frame, not -/// only when the next redraw starts. -#[test] -fn kept_composites_go_when_memory_usage_drops_between_redraws() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - cpu_only_document(g.harness.state_mut(), 2600, 1700); - settle(&mut g); - assert!(!g.harness.state().kept.entries.is_empty(), "the finished redraw is kept"); - g.harness.state_mut().session.edit_prefs(|p| p.performance.memory_usage_mb = 1); - g.harness.step(); - assert!(g.harness.state().redraws.is_empty()); - assert!(g.harness.state().kept.entries.is_empty(), "kept over the current cap"); -} - -/// An edit too small for a background redraw that grows the document past what Memory Usage -/// leaves: the kept composite goes at the next frame. The test holds the kept state itself, so -/// only the cap can drop it, not History letting go of the state. -#[test] -fn kept_composites_go_when_a_small_edit_grows_the_document_past_the_cap() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - cpu_only_document(g.harness.state_mut(), 2600, 1700); - settle(&mut g); - let app = g.harness.state_mut(); - let st = app.session.active().expect("document"); - let held = st.doc.clone(); - let (used, kept) = (st.memory_bytes() as u64, app.kept.bytes()); - assert!(kept > 0, "the finished redraw is kept"); - // Room for the kept composite and 2-3 MB more. - let mb = (used + kept).div_ceil(1 << 20) + 2; - app.session.edit_prefs(|p| p.performance.memory_usage_mb = mb as _); - g.harness.step(); - assert_eq!(g.harness.state().kept.entries.len(), 1, "still within the cap"); - // 2 MP of new pixels (8 MB): under the size that redraws in the background. - for (cmd, p) in - [("layer.new.layer", json!({})), ("select.rect", json!({"x": 0, "y": 0, "width": 2000, "height": 1000})), ("edit.fill", json!({"color": "#cc2244"}))] - { - g.harness.state_mut().run(cmd, p).expect(cmd); - g.harness.step(); - assert!(g.harness.state().redraws.is_empty(), "{cmd} redrew in the background"); - } - assert!(g.harness.state().kept.entries.is_empty(), "kept over the cap after the edit"); - drop(held); -} - -/// The same for an older kept composite of another document: every kept document's edits count, -/// not only the newest one's. -#[test] -fn an_older_kept_composite_goes_when_its_document_grows_past_the_cap() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let a = cpu_only_document(g.harness.state_mut(), 2600, 1700); - settle(&mut g); - let b = cpu_only_document(g.harness.state_mut(), 2600, 1700); - settle(&mut g); - let app = g.harness.state_mut(); - let held: Vec<_> = app.session.documents().iter().map(|st| st.doc.clone()).collect(); - assert_eq!(app.kept.entries.iter().map(|k| k.id).collect::>(), [b, a], "both kept, the second newest"); - let used = app.session.documents().iter().map(|st| st.memory_bytes() as u64).max().unwrap_or(0); - let mb = (used + app.kept.bytes()).div_ceil(1 << 20) + 2; - app.session.edit_prefs(|p| p.performance.memory_usage_mb = mb as _); - let i = app.session.documents().iter().position(|st| st.doc.id == a).expect("document"); - app.session.set_active(i); - g.harness.step(); - assert_eq!(g.harness.state().kept.entries.len(), 2, "still within the cap"); - for (cmd, p) in - [("layer.new.layer", json!({})), ("select.rect", json!({"x": 0, "y": 0, "width": 2000, "height": 1000})), ("edit.fill", json!({"color": "#cc2244"}))] - { - g.harness.state_mut().run(cmd, p).expect(cmd); - g.harness.step(); - assert!(g.harness.state().redraws.is_empty(), "{cmd} redrew in the background"); - } - assert!(g.harness.state().kept.entries.len() < 2, "kept over the cap after the older document grew"); - drop(held); -} - -/// A kept state History no longer holds goes at the next frame: its texels aren't held until -/// some later redraw. -#[test] -fn a_kept_state_history_purged_goes_at_the_next_frame() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - cpu_only_document(g.harness.state_mut(), 2600, 1700); - let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer"); - settle(&mut g); - // Hidden, the document is drawn on the GPU: the kept state is the one before, in History. - g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); - settle(&mut g); - assert_eq!(g.harness.state().kept.entries.len(), 1, "the state before hiding is kept"); - g.harness.state_mut().run("edit.purge.histories", json!({})).expect("purge"); - g.harness.step(); - assert!(g.harness.state().redraws.is_empty()); - assert!(g.harness.state().kept.entries.is_empty(), "the purged state's composite is still held"); -} - -#[test] -fn closing_the_document_stops_its_redraw() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - // Held: the close lands while the redraw runs, and a cancelled worker leaves the hold. - let _held = start_held_redraw(&mut g, doc); - g.harness.state_mut().run("file.close", json!({"save": false})).expect("close"); - 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"); - let app = g.harness.state(); - assert!(matches!(app.render_path.current(doc.0), Some(crate::render_path::CpuReason::OverBudget { .. })), "{:?}", app.perf.gpu_fallback); - assert_matches_synchronous(&mut g, doc); -} - -/// The active document's render path: its reason's kind. -fn render_path_of(g: &Gpu) -> Option<&'static str> { - let app = g.harness.state(); - let doc = app.session.active().expect("document").doc.id.0; - app.render_path.current(doc).map(crate::render_path::CpuReason::kind) -} - -/// On the GPU canvas: no reason, or only a software adapter's (CI's runners have one). -fn on_gpu_canvas(g: &Gpu) -> bool { - matches!(render_path_of(g), None | Some("softwareAdapter")) -} - -#[test] -fn advanced_blending_fallback_is_shown_in_the_status_bar() { - use egui_kittest::kittest::Queryable; - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - cpu_only_document(g.harness.state_mut(), 800, 600); - g.harness.step(); - settle(&mut g); - g.harness.run_steps(2); - assert_eq!(render_path_of(&g), Some("unsupported")); - // PLAN: assumes the status bar's CPU Rendering message exposes its tooltip text to kittest after a hover (panels-w19). - g.harness.get_by_label("CPU Rendering").hover(); - g.harness.run_steps(40); - assert!(g.harness.query_by_label_contains("Advanced Blending").is_some(), "the tooltip names the cause"); -} - -#[test] -fn completed_compositor_build_refreshes_an_unchanged_cached_document() { - let _gpu = photocraft_testkit::gpu_lock(); - for success in [true, false] { - let Some(mut g) = gpu_app() else { return }; - let gpu = g.harness.state().gpu.as_ref().expect("GPU canvas").clone(); - gpu.simulate_compositor_build(); - g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); - g.harness.step(); - settle(&mut g); - let doc = g.harness.state().session.active().expect("document").doc.id; - let revision = g.harness.state().session.active().expect("document").revision; - assert_eq!(render_path_of(&g), Some("compositorBuilding")); - assert!(gpu.simulate_compositor_completion(success), "test compositor must build"); - g.harness.step(); - settle(&mut g); - g.harness.run_steps(2); - assert_eq!(g.harness.state().session.active().expect("document").revision, revision); - if success { - assert!(on_gpu_canvas(&g), "successful build should replace the temporary reason: {:?}", render_path_of(&g)); - } else { - assert_eq!(render_path_of(&g), Some("compositorBuild")); - assert!(g.harness.state().perf.gpu_fallback.as_deref().is_some_and(|s| s.contains("simulated build failure"))); - assert_matches_synchronous(&mut g, doc); - } - } -} - -#[test] -fn a_canvas_over_the_texture_budget_records_its_reason() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - // The app's canvas, not the observer: each `GpuCanvas::new` shares a new budget. - g.harness.state().gpu.as_ref().expect("gpu canvas").set_canvas_budget(1); - g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); - g.harness.run_steps(3); - assert_eq!(render_path_of(&g), Some("canvasTooLarge")); - let doc = g.harness.state().session.active().expect("document").doc.id.0; - assert_eq!(g.harness.state().render_path.history().filter(|c| c.doc == doc).count(), 1, "once, not every frame"); -} - -/// Frames until the active document's viewport pages are all rendered and uploaded. -fn settle_pages(g: &mut Gpu) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); - loop { - g.harness.step(); - let app = g.harness.state(); - let id = app.session.active().expect("document").doc.id; - if app.streams.get(&id).is_some_and(|s| !s.busy() && s.stats.wanted > 0 && s.stats.ready == s.stats.wanted) { - return; - } - assert!(std::time::Instant::now() < deadline, "the viewport pages didn't finish"); - std::thread::sleep(std::time::Duration::from_millis(2)); - } -} - -/// The screen pixel at the window's centre. -fn centre_pixel(g: &mut Gpu) -> [u8; 4] { - let img = g.harness.render().expect("render"); - let p = img.get_pixel(img.width() / 2, img.height() / 2); - p.0 -} - -/// #5332: a document whose texture set doesn't fit the canvas budget stays on the GPU canvas, -/// drawn from the pages in view instead of the CPU canvas, with the same pixels; an edit -/// re-renders only the pages, and closing it frees them. -#[test] -fn a_canvas_over_the_texture_budget_draws_its_viewport_pages_on_the_gpu() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - g.harness.state_mut().run("file.new", json!({"width": 3000, "height": 2000, "background": "#336699"})).expect("new"); - g.harness.run_steps(3); - assert!(on_gpu_canvas(&g)); - let whole = centre_pixel(&mut g); - let gpu = g.harness.state().gpu.clone().expect("gpu canvas"); - let doc = g.harness.state().session.active().expect("document").doc.clone(); - let key = crate::canvas::viewport_pages::stream_key(doc.id.0); - // Room for pages (half the budget), not for the document's texture set. - let (set, _) = gpu.canvas_fit(&doc).expect("fit"); - gpu.set_canvas_budget(set - 1); - settle_pages(&mut g); - assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); - assert!(gpu.texture_info(doc.id.0).is_none(), "no texture set"); - let (pages, bytes) = gpu.pages(key); - let stats = g.harness.state().streams[&doc.id].stats.clone(); - assert_eq!(pages.len(), stats.resident); - assert!(stats.wanted > 0 && stats.last_error.is_none(), "{stats:?}"); - assert!(bytes <= (set - 1) / 2, "pages stay within half the budget: {bytes}"); - let shown = centre_pixel(&mut g); - assert!((0..3).all(|i| shown[i].abs_diff(whole[i]) <= 2), "pages {shown:?}, texture set {whole:?}"); - // An edit re-renders the pages it reaches. - let uploads = stats.uploads; - g.harness.state_mut().run("edit.fill", json!({"color": "#cc8844"})).expect("fill"); - settle_pages(&mut g); - let stats = g.harness.state().streams[&doc.id].stats.clone(); - assert!(stats.dirtied > 0 && stats.uploads > uploads, "{stats:?}"); - let filled = centre_pixel(&mut g); - assert!(filled[0] > 0xb0 && filled[2] < 0x60, "the fill is shown: {filled:?}"); - // A small edit re-renders only the part of each page it reaches, into the page held. - let (held, partial) = (gpu.pages(key).0.len(), stats.partial); - // (A frame between the steps, as in use: the edit's damage is known one revision at a time.) - g.harness.state_mut().run("select.rect", json!({"x": 1400, "y": 900, "width": 200, "height": 200})).expect("select"); - settle_pages(&mut g); - g.harness.state_mut().run("edit.fill", json!({"color": "#22aa22"})).expect("small fill"); - settle_pages(&mut g); - let stats = g.harness.state().streams[&doc.id].stats.clone(); - assert!(stats.partial > partial, "{stats:?}"); - assert_eq!(gpu.pages(key).0.len(), held, "no new page textures"); - // Just its square is shown: 200 px at about 20% zoom, some 40 screen pixels a side. - let img = g.harness.render().expect("render"); - let green = img.pixels().filter(|p| p.0[1] > 0x90 && p.0[0] < 0x50 && p.0[2] < 0x50).count(); - assert!((1000..2500).contains(&green), "the small fill is shown: {green} pixels"); - // A budget too small for one page draws it on the CPU canvas, as before. - gpu.set_canvas_budget(1); - g.harness.run_steps(3); - assert_eq!(render_path_of(&g), Some("canvasTooLarge")); - // Its pages and their work are freed meanwhile (#5332 review). - assert!(gpu.pages(key).0.is_empty(), "pages freed"); - assert!(!g.harness.state().streams.contains_key(&doc.id), "stream dropped"); - gpu.set_canvas_budget(set - 1); - settle_pages(&mut g); - // Closing the document cancels its work and frees its pages. - g.harness.state_mut().run("file.close", json!({"save": false})).expect("close"); - g.harness.run_steps(3); - assert!(g.harness.state().streams.is_empty()); - assert!(gpu.pages(key).0.is_empty()); -} - -/// Runs a Window › Arrange command, as its menu item does, and lets the layout settle. -fn arrange(g: &mut Gpu, command: &str) { - let ctx = g.harness.ctx.clone(); - crate::menus::invoke(g.harness.state_mut(), &ctx, command, json!({})).expect("arrange"); - g.harness.run_steps(3); -} - -/// #5332 review: the open documents share one texture budget rather than each having all of -/// it. A document alone on screen keeps the whole budget; one in a background tab gives its -/// textures up when the shown one needs the room; and documents shown side by side split it, -/// a document over its share drawing from viewport pages. -#[test] -fn open_documents_share_one_texture_budget_with_the_shown_ones_first() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - let gpu = g.harness.state().gpu.clone().expect("gpu canvas"); - let new = |g: &mut Gpu| { - g.harness.state_mut().run("file.new", json!({"width": 3000, "height": 2000, "background": "#336699"})).expect("new"); - g.harness.run_steps(3); - assert!(on_gpu_canvas(g), "{:?}", render_path_of(g)); - g.harness.state().session.active().expect("document").doc.clone() - }; - let a = new(&mut g); - let (set, _) = gpu.canvas_fit(&a).expect("fit"); - // Room for one texture set and a half: a document alone on screen has all of it. - let budget = set + set / 2; - gpu.set_canvas_budget(budget); - assert_eq!(gpu.canvas_fit(&a), Some((set, budget)), "alone, the whole budget"); - assert!(gpu.texture_info(a.id.0).is_some()); - // A second tab: the shown document's texture set takes the room of the background one's. - let b = new(&mut g); - assert_eq!(gpu.canvas_fit(&b), Some((set, budget))); - assert!(gpu.texture_info(b.id.0).is_some()); - assert!(gpu.texture_info(a.id.0).is_none(), "the background document's textures are freed"); - // Back to the first tab: it gets its texture set back and the other gives its up. - g.harness.state_mut().session.set_active(0); - g.harness.run_steps(3); - assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); - assert!(gpu.texture_info(a.id.0).is_some()); - assert!(gpu.texture_info(b.id.0).is_none()); - // Side by side, they split the budget: neither set fits its half, so both draw from pages. - arrange(&mut g, "window.arrange.twoUpVertical"); - assert_eq!(gpu.canvas_fit(&a), Some((set, budget / 2))); - assert_eq!(gpu.canvas_fit(&b), Some((set, budget - budget / 2))); - settle_pages(&mut g); - assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); - let streams = &g.harness.state().streams; - assert!(streams.contains_key(&a.id) && streams.contains_key(&b.id), "both on pages"); - assert!(gpu.texture_info(a.id.0).is_none() && gpu.texture_info(b.id.0).is_none()); - // Switching between them re-splits nothing: no page set is dropped. - let held = gpu.pages(crate::canvas::viewport_pages::stream_key(a.id.0)).0; - g.harness.state_mut().session.set_active(1); - g.harness.run_steps(3); - assert_eq!(gpu.canvas_fit(&a), Some((set, budget / 2))); - assert_eq!(gpu.pages(crate::canvas::viewport_pages::stream_key(a.id.0)).0, held, "no churn on a switch"); - // Back to tabs: the shown document has the whole budget, and its texture set, again. - arrange(&mut g, "window.arrange.consolidateAllToTabs"); - assert_eq!(gpu.canvas_fit(&b), Some((set, budget))); - assert!(on_gpu_canvas(&g), "{:?}", render_path_of(&g)); - assert!(gpu.texture_info(b.id.0).is_some()); -} - -#[test] -fn a_flipped_view_records_why_it_draws_on_the_cpu() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut g) = gpu_app() else { return }; - g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new"); - g.harness.run_steps(3); - assert!(on_gpu_canvas(&g)); - g.harness.state_mut().ui.view.flip_horizontal = true; - g.harness.run_steps(3); - assert_eq!(render_path_of(&g), Some("viewTransform")); - g.harness.state_mut().ui.view.flip_horizontal = false; - g.harness.run_steps(3); - assert!(on_gpu_canvas(&g), "back on the GPU"); -} diff --git a/crates/ui-egui/src/canvas/blend_viewport_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas/blend_viewport_tests.rs rename to crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs diff --git a/crates/ui-egui/src/canvas/cpu_background_tests.rs b/crates/ui-egui/src/canvas/cpu_background_gpu_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas/cpu_background_tests.rs rename to crates/ui-egui/src/canvas/cpu_background_gpu_tests.rs diff --git a/crates/ui-egui/src/canvas/gpu_canvas.rs b/crates/ui-egui/src/canvas/gpu_canvas.rs index 90a3114e43..1828dc5c88 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -1107,10 +1107,10 @@ impl GpuCanvas { } #[cfg(test)] -mod mip_tests; +mod mip_gpu_tests; #[cfg(test)] -mod sharp_tests; +mod sharp_gpu_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs rename to crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs diff --git a/crates/ui-egui/src/canvas/gpu_canvas/sharp_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/sharp_gpu_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas/gpu_canvas/sharp_tests.rs rename to crates/ui-egui/src/canvas/gpu_canvas/sharp_gpu_tests.rs diff --git a/crates/ui-egui/src/canvas/raster_source/tests.rs b/crates/ui-egui/src/canvas/raster_source/tests.rs index f359f91ca6..81868bff03 100644 --- a/crates/ui-egui/src/canvas/raster_source/tests.rs +++ b/crates/ui-egui/src/canvas/raster_source/tests.rs @@ -188,39 +188,6 @@ fn a_channel_view_draws_its_own_picture() { assert_eq!(composite[6], Color32::WHITE, "the composite stays the document's"); } -/// The proxy preview is the GPU canvas's: without a GPU a large document's adjustment previews through the CPU proxy, -/// and the layer path shows nothing (`adjust_preview::cheap`). -#[test] -fn during_a_proxy_adjustment_the_overlay_reads_the_preview_and_the_composite_the_document() { - let _gpu = photocraft_testkit::gpu_lock(); - let rs = match std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) { - Ok(rs) => rs, - Err(error) if std::env::var_os("PHOTOCRAFT_REQUIRE_GPU_TESTS").is_some() => std::panic::resume_unwind(error), - Err(_) => return, - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.set_wgpu(rs); - app.run("file.new", json!({"width": 2400, "height": 2200, "background": "#808080"})).unwrap(); - let st = app.session.active().unwrap(); - assert!(crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(&app)) > 1, "large enough for a proxy preview"); - // Only the red channel shows: an opaque view over the composite. - let view = &mut app.session.active_mut().unwrap().channel_view; - view.set_color_visible(1, false); - view.set_color_visible(2, false); - let ctx = app.ctx().clone(); - let at = PixelRect::new(0, 0, 1, 1); - let overlay_before = read(&OverlayPrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; - let composite_before = read(&CompositePrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; - let id = crate::adjust_dialog::open(&mut app, "image.adjustments.levels").unwrap(); - - assert!(crate::adjust_dialog::apply_params(&mut app, id, &json!({"inBlack": 100})), "the dialog takes the black point"); - assert!(crate::adjust_preview::display_doc(&mut app, 0).is_some(), "the adjustment previews"); - let overlay = read(&OverlayPrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; - let composite = read(&CompositePrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; - assert_ne!(overlay, overlay_before, "the overlay shows the live preview"); - assert_eq!(composite, composite_before, "the composite shows the document"); -} - /// The CPU canvas (no usable GPU; a flipped or pixel-aspect-corrected view, or a GPU fallback, on a GPU machine) shows /// a filter dialog's live preview. It showed the document unfiltered. #[test] @@ -340,3 +307,40 @@ fn channel_views_show_live_strokes_and_drop_discarded_ones() { assert_eq!(shown(&mut app), view(&app, &original), "{target}: a dropped stroke shows the channel as it was"); } } + +mod gpu_tests { + use super::*; + + /// The proxy preview is the GPU canvas's: without a GPU a large document's adjustment previews through the CPU proxy, + /// and the layer path shows nothing (`adjust_preview::cheap`). + #[test] + fn during_a_proxy_adjustment_the_overlay_reads_the_preview_and_the_composite_the_document() { + let _gpu = photocraft_testkit::gpu_lock(); + let rs = match std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) { + Ok(rs) => rs, + Err(error) if std::env::var_os("PHOTOCRAFT_REQUIRE_GPU_TESTS").is_some() => std::panic::resume_unwind(error), + Err(_) => return, + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width": 2400, "height": 2200, "background": "#808080"})).unwrap(); + let st = app.session.active().unwrap(); + assert!(crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(&app)) > 1, "large enough for a proxy preview"); + // Only the red channel shows: an opaque view over the composite. + let view = &mut app.session.active_mut().unwrap().channel_view; + view.set_color_visible(1, false); + view.set_color_visible(2, false); + let ctx = app.ctx().clone(); + let at = PixelRect::new(0, 0, 1, 1); + let overlay_before = read(&OverlayPrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; + let composite_before = read(&CompositePrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; + let id = crate::adjust_dialog::open(&mut app, "image.adjustments.levels").unwrap(); + + assert!(crate::adjust_dialog::apply_params(&mut app, id, &json!({"inBlack": 100})), "the dialog takes the black point"); + assert!(crate::adjust_preview::display_doc(&mut app, 0).is_some(), "the adjustment previews"); + let overlay = read(&OverlayPrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; + let composite = read(&CompositePrep::new(&mut app, &ctx, 0, None, None).unwrap().source(&app), at, 1).pixels; + assert_ne!(overlay, overlay_before, "the overlay shows the live preview"); + assert_eq!(composite, composite_before, "the composite shows the document"); + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c8ff36a3ea..222fb753cc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -82,35 +82,6 @@ fn redrawn_since(app: &mut PhotocraftApp, ctx: &egui::Context, seen: Revision) - prep.source(app).damage(seen).map(|r| i64::from(r.width()) * i64::from(r.height())) } -#[test] -fn gpu_display_luts_are_per_display() { - let _gpu = photocraft_testkit::gpu_lock(); - let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let mut app = app_on_two_displays(); - app.set_wgpu(rs); - let doc = app.session.documents()[0].doc.clone(); - let key = doc.id.0; - // sRGB on the sRGB display needs no LUT; on the P3 display it does. - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); - let gpu = app.gpu.clone().unwrap(); - let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap()); - assert_ne!(s1.0, s4.0); - assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1)); - // Drawing one window leaves the other's LUT alone. - for _ in 0..3 { - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); - } - assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4))); - assert!(gpu.has_display_lut(key, 4)); - // The shared texture's key is the same for both displays. - assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref(), &doc), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref(), &doc)); -} - /// The GPU canvas texture of a Multichannel document is filled by the CPU compositor, so its /// key carries the ink preview (Color Settings › Spot) like the CPU canvas key does. #[test] @@ -1098,3 +1069,36 @@ fn free_transform_redraws_only_the_moving_layer_when_the_box_opens_and_closes() assert!(committed.contains(20, 20) && committed.contains(139, 49), "{committed:?}"); assert!(damage_since(&app, 0, (rev, key ^ dk), (rev + 2, 0), dk, (rev + 1, Some(moved))).is_none(), "a later revision isn't ours"); } + +mod gpu_tests { + use super::*; + + #[test] + fn gpu_display_luts_are_per_display() { + let _gpu = photocraft_testkit::gpu_lock(); + let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = app_on_two_displays(); + app.set_wgpu(rs); + let doc = app.session.documents()[0].doc.clone(); + let key = doc.id.0; + // sRGB on the sRGB display needs no LUT; on the P3 display it does. + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + let gpu = app.gpu.clone().unwrap(); + let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap()); + assert_ne!(s1.0, s4.0); + assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1)); + // Drawing one window leaves the other's LUT alone. + for _ in 0..3 { + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + } + assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4))); + assert!(gpu.has_display_lut(key, 4)); + // The shared texture's key is the same for both displays. + assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref(), &doc), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref(), &doc)); + } +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs index 378fc09db3..3537889aba 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs @@ -186,7 +186,7 @@ impl CameraRawGpu { } #[cfg(test)] -mod tests { +mod gpu_tests { use super::*; use crate::camera_raw_ui::proxy::ProxyJob; use craft::imaging::ui::raw_develop::RawPreviewRequest; diff --git a/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs index b59dc0c2b8..a2bbee7ae6 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs @@ -123,11 +123,15 @@ fn existing_document_profile_preset_and_recorded_export_keep_source_colors() { verify_png(&writes.borrow()[0], [30, 30, 200], 0, true); } -#[test] -fn export_as_color_space_gpu_snapshots() { - let Some(dir) = std::env::var_os("PHOTOCRAFT_SRGB_SNAPSHOTS") else { return }; - let dir = std::path::PathBuf::from(dir); - let _gpu = photocraft_testkit::gpu_lock(); - std::fs::create_dir_all(&dir).unwrap(); - export_both_ways(Some(&dir)); +mod gpu_tests { + use super::*; + + #[test] + fn export_as_color_space_gpu_snapshots() { + let Some(dir) = std::env::var_os("PHOTOCRAFT_SRGB_SNAPSHOTS") else { return }; + let dir = std::path::PathBuf::from(dir); + let _gpu = photocraft_testkit::gpu_lock(); + std::fs::create_dir_all(&dir).unwrap(); + export_both_ways(Some(&dir)); + } } diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rs index d833e08723..f2197819f2 100644 --- a/crates/ui-egui/src/gpu_status.rs +++ b/crates/ui-egui/src/gpu_status.rs @@ -407,82 +407,86 @@ mod tests { assert!(launch(&files).session.prefs().performance.use_gpu, "the next launch retries the GPU"); } - /// #6564: an out-of-memory error on a device that still works rebuilds the GPU canvas by itself, - /// with no notice and the documents untouched, a few times a session; then the CPU renderer - /// stays until Retry GPU. Other errors and a loss still fall back at once. - #[test] - fn out_of_memory_rebuilds_the_gpu_canvas_by_itself() { - let _gpu = photocraft_testkit::gpu_lock(); - let rs = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())); - let Ok(rs) = rs else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.set_wgpu(rs); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - let ctx = app.ctx().clone(); - let oom = || photocraft_gpu::Fault::Error("Out of Memory".into()); - for n in 1..=OOM_AUTO_RETRIES { + mod gpu_tests { + use super::*; + + /// #6564: an out-of-memory error on a device that still works rebuilds the GPU canvas by itself, + /// with no notice and the documents untouched, a few times a session; then the CPU renderer + /// stays until Retry GPU. Other errors and a loss still fall back at once. + #[test] + fn out_of_memory_rebuilds_the_gpu_canvas_by_itself() { + let _gpu = photocraft_testkit::gpu_lock(); + let rs = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())); + let Ok(rs) = rs else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let ctx = app.ctx().clone(); + let oom = || photocraft_gpu::Fault::Error("Out of Memory".into()); + for n in 1..=OOM_AUTO_RETRIES { + app.gpu_health().unwrap().mark(oom()); + check(&mut app, &ctx); + assert!(app.gpu_active(), "retry {n}: the GPU canvas is back"); + assert!(app.gpu_health().unwrap().is_ok(), "retry {n}: with a fresh health flag"); + assert_eq!(app.perf.gpu_info.canvas, "gpu"); + assert!(app.ui.gpu_fallback_notice.is_none(), "retry {n}: no recovery dialog"); + assert_eq!(app.session.documents().len(), 1); + } + // Past the limit the CPU renderer stays and the dialog offers Retry GPU. app.gpu_health().unwrap().mark(oom()); check(&mut app, &ctx); - assert!(app.gpu_active(), "retry {n}: the GPU canvas is back"); - assert!(app.gpu_health().unwrap().is_ok(), "retry {n}: with a fresh health flag"); - assert_eq!(app.perf.gpu_info.canvas, "gpu"); - assert!(app.ui.gpu_fallback_notice.is_none(), "retry {n}: no recovery dialog"); - assert_eq!(app.session.documents().len(), 1); + assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); + assert_eq!(app.perf.gpu_info.canvas, "cpu"); + + // A validation error is not retried by itself. + let rs = egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into())); + check(&mut app, &ctx); + assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); } - // Past the limit the CPU renderer stays and the dialog offers Retry GPU. - app.gpu_health().unwrap().mark(oom()); - check(&mut app, &ctx); - assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); - assert_eq!(app.perf.gpu_info.canvas, "cpu"); - // A validation error is not retried by itself. - let rs = egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default()); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.set_wgpu(rs); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into())); - check(&mut app, &ctx); - assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); - } - - /// #6577: after a GPU error on a device that still works (out of memory, validation), Retry - /// GPU builds a new GPU canvas at once, without a restart or closing documents. After a loss - /// the device can't be used again, so the retry still waits for the next launch. - #[test] - fn retry_gpu_after_an_error_rebuilds_the_canvas_without_a_restart() { - let _gpu = photocraft_testkit::gpu_lock(); - let rs = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())); - let Ok(rs) = rs else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let mut app = launch(&std::sync::Arc::new(craft::settings::testing::MemoryFiles::new())); - app.set_wgpu(rs); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - let ctx = app.ctx().clone(); - // An error on a live device (one not retried by itself, see #6564): Retry GPU rebuilds - // the canvas now. - app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into())); - check(&mut app, &ctx); - assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); - assert!(can_retry_now(&app)); - choose_recovery(&mut app, true).unwrap(); - assert!(app.gpu_active(), "Retry GPU rebuilt the GPU canvas"); - assert!(app.gpu_health().unwrap().is_ok(), "with a fresh health flag"); - assert_eq!(app.perf.gpu_info.canvas, "gpu"); - assert_eq!((app.perf.gpu_info.lost.as_deref(), app.perf.gpu_fallback.as_deref()), (None, None)); - assert_eq!(app.ui.status, "GPU acceleration resumed."); - assert!(app.ui.gpu_fallback_notice.is_none() && app.ui.notices.is_empty(), "no restart notice"); - assert_eq!(app.session.documents().len(), 1, "the document stayed open"); - // A loss: the device can't be reused, so the retry is scheduled for the next launch. - app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Lost("simulated".into())); - check(&mut app, &ctx); - assert!(!can_retry_now(&app)); - choose_recovery(&mut app, true).unwrap(); - assert!(!app.gpu_active()); - assert_eq!(app.ui.notices.len(), 1, "the restart notice"); + /// #6577: after a GPU error on a device that still works (out of memory, validation), Retry + /// GPU builds a new GPU canvas at once, without a restart or closing documents. After a loss + /// the device can't be used again, so the retry still waits for the next launch. + #[test] + fn retry_gpu_after_an_error_rebuilds_the_canvas_without_a_restart() { + let _gpu = photocraft_testkit::gpu_lock(); + let rs = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())); + let Ok(rs) = rs else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = launch(&std::sync::Arc::new(craft::settings::testing::MemoryFiles::new())); + app.set_wgpu(rs); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let ctx = app.ctx().clone(); + // An error on a live device (one not retried by itself, see #6564): Retry GPU rebuilds + // the canvas now. + app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into())); + check(&mut app, &ctx); + assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some()); + assert!(can_retry_now(&app)); + choose_recovery(&mut app, true).unwrap(); + assert!(app.gpu_active(), "Retry GPU rebuilt the GPU canvas"); + assert!(app.gpu_health().unwrap().is_ok(), "with a fresh health flag"); + assert_eq!(app.perf.gpu_info.canvas, "gpu"); + assert_eq!((app.perf.gpu_info.lost.as_deref(), app.perf.gpu_fallback.as_deref()), (None, None)); + assert_eq!(app.ui.status, "GPU acceleration resumed."); + assert!(app.ui.gpu_fallback_notice.is_none() && app.ui.notices.is_empty(), "no restart notice"); + assert_eq!(app.session.documents().len(), 1, "the document stayed open"); + // A loss: the device can't be reused, so the retry is scheduled for the next launch. + app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Lost("simulated".into())); + check(&mut app, &ctx); + assert!(!can_retry_now(&app)); + choose_recovery(&mut app, true).unwrap(); + assert!(!app.gpu_active()); + assert_eq!(app.ui.notices.len(), 1, "the restart notice"); + } } } diff --git a/crates/ui-egui/src/zoom_mode_tests.rs b/crates/ui-egui/src/zoom_mode_tests.rs index 647c1ea297..8b3053f90b 100644 --- a/crates/ui-egui/src/zoom_mode_tests.rs +++ b/crates/ui-egui/src/zoom_mode_tests.rs @@ -17,74 +17,6 @@ fn doc_size() -> Size { Size::new(f64::from(DOC[0]), f64::from(DOC[1])) } -#[test] -fn gpu_zoom_animation_reuses_the_document_composite() { - let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let renderer = egui_kittest::wgpu::WgpuTestRenderer::from_render_state(rs); - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(1.0).renderer(renderer).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); - app.set_wgpu(cc.wgpu_render_state.clone().unwrap()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); - app - }); - // The harness sets egui's animation time to zero, which turns the framework's motion off; the ease needs it on. - h.ctx.all_styles_mut(|style| style.animation_time = egui::Style::default().animation_time); - let shown = |h: &Harness<'static, Box>| shown_camera(&h.ctx, CanvasHost::main(0), &h.state().ui.views[0], 1.0).0; - h.run_steps(4); - h.state_mut().run("view.actualPixels", json!({})).unwrap(); - h.step(); - let time = h.ctx.input(|i| i.time) + 0.3; - h.input_mut().time = Some(time); - h.step(); - let id = h.state().session.documents()[0].doc.id; - assert!(h.state().canvases[&(id, crate::canvas::GPU_OUTPUT)].on_gpu); - let directory = std::env::var_os("CRAFT_UI_ZOOM_FIXTURES").map(std::path::PathBuf::from); - if let Some(directory) = &directory { - std::fs::create_dir_all(directory).unwrap(); - } - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - // The canvas runs the command in its next pass: the zoom it asks for is the rung after 100 %. - let target = craft::behavior::canvas::ZoomLadder::step(1.0, 1, craft::behavior::kurbo::Size::new(400.0, 300.0)) as f32; - // The ease's length belongs to the framework's motion settings, so the steps are short and the test looks for a - // frame between the start and the target zoom rather than naming a time for it. - let mut midway = false; - for step in 0..=10 { - let name = format!("{:.2}s", f64::from(step) * 0.03); - h.state_mut().perf.last_refresh = ""; - h.input_mut().time = Some(time + f64::from(step) * 0.03); - h.step(); - assert!(h.state().perf.gpu, "{name}: keep the GPU canvas"); - assert_eq!(h.state().perf.last_refresh, "", "{name}: reuse the composite"); - let zoom = shown(&h); - midway |= zoom > 1.0 && zoom < target; - let image = h.render().unwrap(); - let center = h.state().last_canvas_rect.center(); - let pixel = image.get_pixel(center.x as u32, center.y as u32); - assert!(pixel[2] > pixel[0] * 2, "{name}: document remains visible: {pixel:?}"); - if let Some(directory) = &directory { - image.save(directory.join(format!("photocraft-zoom-{name}.png"))).unwrap(); - } - } - assert!(midway, "a frame of the ease showed a zoom between 1 and {target}"); - assert_eq!(shown(&h), target); - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.state_mut().perf.last_refresh = ""; - h.step(); - assert_eq!(shown(&h), h.state().current_zoom()); - assert!(h.state().perf.gpu); - assert_eq!(h.state().perf.last_refresh, "", "immediate zoom reuses the GPU composite"); - let image = h.render().unwrap(); - if let Some(directory) = &directory { - image.save(directory.join("photocraft-zoom-disabled.png")).unwrap(); - } -} - /// The platform's modifiers for `Cmd` (⌘ on the Mac, Ctrl elsewhere), as egui-winit reports them. fn platform(m: Modifiers) -> Modifiers { let mut out = Modifiers { alt: m.alt, shift: m.shift, ctrl: m.ctrl, ..Default::default() }; @@ -156,3 +88,75 @@ fn temporary_and_spring_zooms_ignore_the_zoom_out_mode() { assert!(!h.state().ui.tool_options.zoom_in, "{name}: Zoom Out stays selected"); } } + +mod gpu_tests { + use super::*; + + #[test] + fn gpu_zoom_animation_reuses_the_document_composite() { + let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let renderer = egui_kittest::wgpu::WgpuTestRenderer::from_render_state(rs); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(1.0).renderer(renderer).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.set_wgpu(cc.wgpu_render_state.clone().unwrap()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); + app + }); + // The harness sets egui's animation time to zero, which turns the framework's motion off; the ease needs it on. + h.ctx.all_styles_mut(|style| style.animation_time = egui::Style::default().animation_time); + let shown = |h: &Harness<'static, Box>| shown_camera(&h.ctx, CanvasHost::main(0), &h.state().ui.views[0], 1.0).0; + h.run_steps(4); + h.state_mut().run("view.actualPixels", json!({})).unwrap(); + h.step(); + let time = h.ctx.input(|i| i.time) + 0.3; + h.input_mut().time = Some(time); + h.step(); + let id = h.state().session.documents()[0].doc.id; + assert!(h.state().canvases[&(id, crate::canvas::GPU_OUTPUT)].on_gpu); + let directory = std::env::var_os("CRAFT_UI_ZOOM_FIXTURES").map(std::path::PathBuf::from); + if let Some(directory) = &directory { + std::fs::create_dir_all(directory).unwrap(); + } + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + // The canvas runs the command in its next pass: the zoom it asks for is the rung after 100 %. + let target = craft::behavior::canvas::ZoomLadder::step(1.0, 1, craft::behavior::kurbo::Size::new(400.0, 300.0)) as f32; + // The ease's length belongs to the framework's motion settings, so the steps are short and the test looks for a + // frame between the start and the target zoom rather than naming a time for it. + let mut midway = false; + for step in 0..=10 { + let name = format!("{:.2}s", f64::from(step) * 0.03); + h.state_mut().perf.last_refresh = ""; + h.input_mut().time = Some(time + f64::from(step) * 0.03); + h.step(); + assert!(h.state().perf.gpu, "{name}: keep the GPU canvas"); + assert_eq!(h.state().perf.last_refresh, "", "{name}: reuse the composite"); + let zoom = shown(&h); + midway |= zoom > 1.0 && zoom < target; + let image = h.render().unwrap(); + let center = h.state().last_canvas_rect.center(); + let pixel = image.get_pixel(center.x as u32, center.y as u32); + assert!(pixel[2] > pixel[0] * 2, "{name}: document remains visible: {pixel:?}"); + if let Some(directory) = &directory { + image.save(directory.join(format!("photocraft-zoom-{name}.png"))).unwrap(); + } + } + assert!(midway, "a frame of the ease showed a zoom between 1 and {target}"); + assert_eq!(shown(&h), target); + h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + h.state_mut().perf.last_refresh = ""; + h.step(); + assert_eq!(shown(&h), h.state().current_zoom()); + assert!(h.state().perf.gpu); + assert_eq!(h.state().perf.last_refresh, "", "immediate zoom reuses the GPU composite"); + let image = h.render().unwrap(); + if let Some(directory) = &directory { + image.save(directory.join("photocraft-zoom-disabled.png")).unwrap(); + } + } +} diff --git a/crates/ui-egui/tests/it/batch_export_options.rs b/crates/ui-egui/tests/it/batch_export_options.rs index 250a852965..13565f7fb1 100644 --- a/crates/ui-egui/tests/it/batch_export_options.rs +++ b/crates/ui-egui/tests/it/batch_export_options.rs @@ -20,13 +20,10 @@ fn form_fields(h: &mut Harness) -> Value { } fn harness() -> Harness { - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); app.session.prefs.edit(|p| p.interface.language = "en".into()); - if let Some(rs) = cc.wgpu_render_state.as_ref() { - app.set_wgpu(rs.clone()); - } app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); app.run("actions.record", json!({"name": "Invert"})).unwrap(); app.run("image.adjustments.invert", json!({})).unwrap(); @@ -81,7 +78,6 @@ fn edit_path(h: &mut Harness, name: &str, value: &Path) { #[test] fn batch_menu_offers_webp() { - let _gpu = photocraft_testkit::gpu_lock(); let mut h = harness(); open(&mut h, "file.automate.batch"); open_format_choices(&mut h); @@ -91,7 +87,6 @@ fn batch_menu_offers_webp() { #[test] fn batch_menu_offers_quality() { - let _gpu = photocraft_testkit::gpu_lock(); let mut h = harness(); open(&mut h, "file.automate.batch"); evidence(&mut h, "batch-quality"); @@ -100,7 +95,6 @@ fn batch_menu_offers_quality() { #[test] fn image_processor_menu_offers_independent_file_types() { - let _gpu = photocraft_testkit::gpu_lock(); let mut h = harness(); open(&mut h, "file.scripts.imageProcessor"); for label in ["Save as JPEG", "Save as PSD", "Save as TIFF"] { @@ -182,7 +176,6 @@ fn existing_engine_batch_and_image_processor_support_webp_quality() { #[test] fn batch_naming_controls_export_the_requested_names_and_reset_on_cancel() { - let _gpu = photocraft_testkit::gpu_lock(); let dir = Scratch::new(); let input = dir.0.join("input"); let output = dir.0.join("output"); @@ -232,7 +225,6 @@ fn batch_naming_controls_export_the_requested_names_and_reset_on_cancel() { #[test] fn batch_default_quality_keeps_lossless_webp_and_existing_jpeg_bytes() { - let _gpu = photocraft_testkit::gpu_lock(); let dir = Scratch::new(); let input = dir.0.join("input"); std::fs::create_dir(&input).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_device_loss.rs b/crates/ui-egui/tests/it/gpu_device_loss.rs index c08cfe3174..a3aa0bdca3 100644 --- a/crates/ui-egui/tests/it/gpu_device_loss.rs +++ b/crates/ui-egui/tests/it/gpu_device_loss.rs @@ -26,133 +26,6 @@ fn doc() -> Document { Document::with_background("t", Size::new(300, 200), ColorMode::Rgb, SampleType::U8, Color::rgba(0.2, 0.5, 0.8, 1.0)) } -#[test] -fn composite_reuse_reports_held_bytes_and_honors_the_canvas_override() { - let _gpu = gpu_lock(); - let Some(rs) = render_state() else { return }; - let g = GpuCanvas::new(&rs); - let mut d = doc(); - d.layers.push(photocraft_doc::Layer::new("top", photocraft_doc::LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgba(0.8, 0.1, 0.2, 0.5))))); - g.set_memory_budget(1 << 30); - g.set_composite_cache_budget(0); - assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); - assert_eq!(g.compositor_bytes().unwrap().1, 0, "no effect maps or composite chunks"); - g.set_composite_cache_budget(512 << 20); - assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); - let bpp = if photocraft_gpu::Compositor::preferred_acc_format(&rs.adapter) == eframe::wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; - // The cache holds whole chunk-aligned cells, not the document's exact rectangle. - let cell = u64::from(photocraft_gpu::CHUNK); - let cells = u64::from(d.size.width).div_ceil(cell) * cell * u64::from(d.size.height).div_ceil(cell) * cell; - assert_eq!(g.compositor_bytes().unwrap().1 as u64, cells * bpp); - d.layers[1].opacity = 0.4; - assert!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits > 0); - g.set_composite_cache_budget(0); - g.set_memory_budget(512 << 20); - assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); - assert_eq!(g.compositor_bytes().unwrap().1, 0, "override survives the overall budget update"); -} - -#[test] -fn injected_loss_stops_gpu_work_without_panicking() { - let _gpu = gpu_lock(); - let Some(rs) = render_state() else { return }; - let g = GpuCanvas::new(&rs); - let d = doc(); - let key = d.id.0; - let first = g.refresh(key, &d, None, None); - assert_ne!(first.kind, "lost"); - assert!(g.fault().is_none()); - g.health().mark(Fault::Lost("test".into())); - // Every entry point is a no-op or an error now. - let r = g.refresh(key, &d, None, None); - assert_eq!(r.kind, "lost"); - assert!(r.fallback.as_ref().is_some_and(|f| f.to_string().contains("GPU device lost"))); - assert!(g.composite(&d, d.bounds(), false).is_err()); - assert!(!g.upload_rect(key, [0, 0], [1, 1], &[0; 4])); - g.upload_full(key, [1, 1], &[0; 4]); - g.set_display_lut(key, 0, 2, Some(&[0; 32])); - assert!(g.read_texels(key).is_none()); - g.release(); - assert!(!g.has(key, [300, 200])); -} - -#[test] -fn destroyed_device_falls_back_without_panicking() { - let _gpu = gpu_lock(); - let Some(rs) = render_state() else { return }; - let g = GpuCanvas::new(&rs); - let d = doc(); - let key = d.id.0; - g.refresh(key, &d, None, None); - rs.device.destroy(); - // The next refreshes run into the destroyed device: errors are recorded, nothing panics. - let mut d2 = d.clone(); - d2.layers[0].opacity = 0.5; - for _ in 0..3 { - let r = g.refresh(key, &d2, Some(photocraft_geom::Rect::new(0, 0, 50, 50)), None); - if r.kind == "lost" { - break; - } - } - assert!(g.read_texels(key).is_none() || g.fault().is_some()); - assert!(g.fault().is_some(), "device loss not detected"); - assert_eq!(g.refresh(key, &d2, None, None).kind, "lost"); -} - -#[test] -fn app_switches_to_the_cpu_canvas_and_keeps_the_documents() { - let _gpu = gpu_lock(); - let Some(rs) = render_state() else { return }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); - app.set_wgpu(rs); - app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); - app.sync_views(); - assert!(app.gpu_active()); - assert_eq!(app.perf.gpu_info.canvas, "gpu"); - let started = std::rc::Rc::new(std::cell::Cell::new(false)); - let flag = started.clone(); - app.on_started(move |_| flag.set(true)); - let mut h = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1000.0, 700.0)).build_ui_state( - |ui, app: &mut Box| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - app.check_gpu(&ctx); - egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(app, ui)); - app.check_gpu(&ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, photocraft_ui_egui::theme::AppTheme::pro()); - h.run_steps(4); - assert!(h.state().gpu_active(), "GPU canvas in use before the loss"); - // The device is lost (e.g. the OS killed a huge submission). - h.state().gpu_health().unwrap().mark(Fault::Lost("killed by the OS".into())); - h.run_steps(3); - let app = h.state(); - assert!(!app.gpu_active(), "still on the GPU canvas"); - assert_eq!(app.session.documents().len(), 1, "document kept"); - assert_eq!(app.ui.status, gpu_status::LOST_MESSAGE); - assert!(app.ui.status_error); - assert!(app.ui.gpu_fallback_notice.as_deref().unwrap_or("").contains("killed by the OS")); - // UI passes drain the outbox into toasts, so the window's cards are checked as well. - let cards = craft::ui::runtime::toast::cards(&h.ctx, &craft::ui::runtime::env::WindowKey::main()); - assert!(app.ui.notices.is_empty() && cards.is_empty(), "one recovery warning, no duplicate notice"); - assert!(app.perf.gpu_info.lost.as_deref().unwrap_or("").contains("killed by the OS")); - assert_eq!(app.perf.gpu_info.canvas, "cpu"); - // The CPU path draws the document: a refresh after the loss is a CPU one. - assert!(matches!(app.perf.last_refresh, "full" | "rect"), "{}", app.perf.last_refresh); - // Editing keeps working. - h.state_mut().run("layer.new.layer", json!({})).unwrap(); - h.run_steps(2); - assert_eq!(h.state().session.active().map(|d| d.doc.layers.len()), Some(2)); - // The perf output carries the state for agents. - let perf = serde_json::to_value(&h.state().perf).unwrap(); - assert_eq!(perf["gpuInfo"]["canvas"], "cpu"); - let _ = started; -} - #[test] fn started_hook_runs_once_after_the_first_frames() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); @@ -189,241 +62,373 @@ fn system_info_lists_the_graphics_state() { assert_eq!(v["gpu"]["adapter"], "Test GPU"); } -/// A canvas whose display textures exceed the canvas budget gets none: no texture set is built, -/// the refresh says so and the app draws it on the CPU canvas instead (#2934). -#[test] -fn canvas_over_the_texture_budget_builds_no_textures() { - let _gpu = gpu_lock(); - let Some(rs) = render_state() else { return }; - let g = GpuCanvas::new(&rs); - let d = doc(); - let (key, size) = (d.id.0, [d.size.width, d.size.height]); - // Less than the full-resolution level alone. - g.set_canvas_budget(u64::from(size[0] * size[1]) * 4 - 1); - assert!(!g.fits_canvas(&d)); - let r = g.refresh(key, &d, None, None); - assert_eq!(r.kind, gpu_canvas::REFRESH_OVER_BUDGET); - assert!(!g.has(key, size) && g.texture_info(key).is_none()); - assert!(g.composite(&d, d.bounds(), false).is_err()); - g.upload_full(key, size, &vec![0; size[0] as usize * size[1] as usize * 4]); - assert!(g.texture_info(key).is_none(), "no entry point builds the set"); - // Within the budget the same document is drawn on the GPU, at the bytes it was priced at. - g.set_canvas_budget(1 << 30); - assert!(g.fits_canvas(&d)); - assert_ne!(g.refresh(key, &d, None, None).kind, gpu_canvas::REFRESH_OVER_BUDGET); - assert!(g.has(key, size)); - let (format, bytes) = g.texture_info(key).unwrap(); - let bpp = if format == eframe::wgpu::TextureFormat::Rgba16Float { 8 } else { 4 }; - assert_eq!(bytes, gpu_canvas::canvas_texture_bytes(size, gpu_canvas::DEFAULT_TILE, bpp)); - // Shrinking the budget below an existing set drops it on the next refresh. - g.set_canvas_budget(1); - assert_eq!(g.refresh(key, &d, None, None).kind, gpu_canvas::REFRESH_OVER_BUDGET); - assert!(g.texture_info(key).is_none()); - g.release(); -} +mod gpu_tests { + use super::*; -/// #3438, #1215: when the window's own device is really lost (a driver reset, for example after -/// the PC slept), egui-wgpu can't draw another frame. One with shapes panicked inside it ("Failed -/// to create staging buffer for index data"), and a frozen window's close button opened an -/// unsaved-changes prompt nobody could see. Now the app draws nothing, writes the unsaved document -/// for recovery and closes. Runs the real frame loop on the harness's own device. -#[test] -fn a_lost_window_device_saves_unsaved_work_for_recovery_and_closes() { - let _gpu = gpu_lock(); - let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); - let (autosaves, flushes) = (log.clone(), log.clone()); - let render_state = std::sync::Arc::new(std::sync::Mutex::new(None::)); - let window = render_state.clone(); - let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { - egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(16).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let services = photocraft_ui_egui::Services { - autosave: Some(Box::new(move |doc: &std::sync::Arc, revision: u64, _: Option<&str>| { - autosaves.lock().unwrap().push(format!("autosave {} {revision}", doc.id.0)); - Ok(()) - })), - flush_autosaves: Some(Box::new(move || { - flushes.lock().unwrap().push("flush".into()); - Vec::new() - })), - ..Default::default() - }; - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), services); - if let Some(rs) = cc.wgpu_render_state.as_ref() { - *window.lock().unwrap() = Some(rs.clone()); - app.set_wgpu(rs.clone()); + #[test] + fn composite_reuse_reports_held_bytes_and_honors_the_canvas_override() { + let _gpu = gpu_lock(); + let Some(rs) = render_state() else { return }; + let g = GpuCanvas::new(&rs); + let mut d = doc(); + d.layers.push(photocraft_doc::Layer::new("top", photocraft_doc::LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgba(0.8, 0.1, 0.2, 0.5))))); + g.set_memory_budget(1 << 30); + g.set_composite_cache_budget(0); + assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); + assert_eq!(g.compositor_bytes().unwrap().1, 0, "no effect maps or composite chunks"); + g.set_composite_cache_budget(512 << 20); + assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); + let bpp = if photocraft_gpu::Compositor::preferred_acc_format(&rs.adapter) == eframe::wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; + // The cache holds whole chunk-aligned cells, not the document's exact rectangle. + let cell = u64::from(photocraft_gpu::CHUNK); + let cells = u64::from(d.size.width).div_ceil(cell) * cell * u64::from(d.size.height).div_ceil(cell) * cell; + assert_eq!(g.compositor_bytes().unwrap().1 as u64, cells * bpp); + d.layers[1].opacity = 0.4; + assert!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits > 0); + g.set_composite_cache_budget(0); + g.set_memory_budget(512 << 20); + assert_eq!(g.composite(&d, d.bounds(), false).unwrap().prefix_hits, 0); + assert_eq!(g.compositor_bytes().unwrap().1, 0, "override survives the overall budget update"); + } + + #[test] + fn injected_loss_stops_gpu_work_without_panicking() { + let _gpu = gpu_lock(); + let Some(rs) = render_state() else { return }; + let g = GpuCanvas::new(&rs); + let d = doc(); + let key = d.id.0; + let first = g.refresh(key, &d, None, None); + assert_ne!(first.kind, "lost"); + assert!(g.fault().is_none()); + g.health().mark(Fault::Lost("test".into())); + // Every entry point is a no-op or an error now. + let r = g.refresh(key, &d, None, None); + assert_eq!(r.kind, "lost"); + assert!(r.fallback.as_ref().is_some_and(|f| f.to_string().contains("GPU device lost"))); + assert!(g.composite(&d, d.bounds(), false).is_err()); + assert!(!g.upload_rect(key, [0, 0], [1, 1], &[0; 4])); + g.upload_full(key, [1, 1], &[0; 4]); + g.set_display_lut(key, 0, 2, Some(&[0; 32])); + assert!(g.read_texels(key).is_none()); + g.release(); + assert!(!g.has(key, [300, 200])); + } + + #[test] + fn destroyed_device_falls_back_without_panicking() { + let _gpu = gpu_lock(); + let Some(rs) = render_state() else { return }; + let g = GpuCanvas::new(&rs); + let d = doc(); + let key = d.id.0; + g.refresh(key, &d, None, None); + rs.device.destroy(); + // The next refreshes run into the destroyed device: errors are recorded, nothing panics. + let mut d2 = d.clone(); + d2.layers[0].opacity = 0.5; + for _ in 0..3 { + let r = g.refresh(key, &d2, Some(photocraft_geom::Rect::new(0, 0, 50, 50)), None); + if r.kind == "lost" { + break; } - app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app - }) - })); - // Upload and submit the last frame's shapes the way the window's renderer does each frame: on - // a lost device, egui-wgpu panics here when there is anything to draw (#1215). - let upload = |h: &egui_kittest::Harness<'_, Box>| { - let rs = render_state.lock().unwrap().clone().expect("the harness renders with wgpu"); - let output = h.output(); - let jobs = h.ctx.tessellate(output.shapes.clone(), output.pixels_per_point); - let screen = eframe::egui_wgpu::ScreenDescriptor { size_in_pixels: [1000, 700], pixels_per_point: output.pixels_per_point }; - let mut encoder = rs.device.create_command_encoder(&Default::default()); - let uploaded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let commands = rs.renderer.write().update_buffers(&rs.device, &rs.queue, &mut encoder, &jobs, &screen); - rs.queue.submit(commands.into_iter().chain([encoder.finish()])); - })); - (jobs.len(), uploaded.is_ok()) - }; - let Ok(mut h) = built else { - eprintln!("skipping: no GPU adapter"); - return; - }; - h.run_steps(4); - let (jobs, uploaded) = upload(&h); - assert!(jobs > 0 && uploaded, "draws before the loss"); - let (doc, revision, dirty) = h.state().session.active().map(|d| (d.doc.id.0, d.revision, d.is_dirty())).unwrap(); - assert!(dirty, "the new layer is unsaved"); - assert!(log.lock().unwrap().is_empty(), "no autosave before the loss"); - assert!(h.state_mut().destroy_window_device()); - // wgpu reports a destroyed device lost once the work submitted before finished (slow on a - // software adapter); a driver reset reports it at once. - if let Some(rs) = render_state.lock().unwrap().as_ref() { - let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(30)) }); - } - h.run_steps(2); - assert!(h.state().window_lost(), "the loss was noticed"); - assert_eq!(*log.lock().unwrap(), vec![format!("autosave {doc} {revision}"), "flush".to_string()], "saved for recovery once"); - // The frame on the lost device has nothing to draw, so egui-wgpu has nothing to upload. - assert_eq!(upload(&h), (0, true), "a frame with shapes panics inside egui-wgpu on a lost device"); - assert_eq!(h.state().session.documents().len(), 1, "the document stays until the app closes"); -} - -/// #6464 review: when the recovery save fails (a full disk, say), closing would lose the work, so -/// the app stays open with the document and tries again until the write succeeds, then closes. -#[test] -fn a_lost_window_device_closes_only_once_unsaved_work_is_saved() { - let _gpu = gpu_lock(); - let disk_full = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); - let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let (full, tries) = (disk_full.clone(), attempts.clone()); - let pending = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(u64, u64)>::new())); - let queued = pending.clone(); - let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { - egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(16).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let services = photocraft_ui_egui::Services { - autosave: Some(Box::new(move |doc: &std::sync::Arc, revision: u64, _: Option<&str>| { - queued.lock().unwrap().push((doc.id.0, revision)); - Ok(()) - })), - autosave_results: Some(Box::new(Vec::new)), - flush_autosaves: Some(Box::new(move || { - tries.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let outcome = if full.load(std::sync::atomic::Ordering::SeqCst) { Err("disk full".to_string()) } else { Ok(()) }; - pending.lock().unwrap().drain(..).map(|(id, revision)| (id, revision, outcome.clone())).collect() - })), - ..Default::default() - }; - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), services); - if let Some(rs) = cc.wgpu_render_state.as_ref() { - app.set_wgpu(rs.clone()); - } - app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app - }) - })); - let Ok(mut h) = built else { - eprintln!("skipping: no GPU adapter"); - return; - }; - h.run_steps(4); - assert!(h.state_mut().destroy_window_device()); - for _ in 0..120 { - h.run_steps(1); - if h.state().window_lost() { - break; } - std::thread::sleep(std::time::Duration::from_millis(250)); + assert!(g.read_texels(key).is_none() || g.fault().is_some()); + assert!(g.fault().is_some(), "device loss not detected"); + assert_eq!(g.refresh(key, &d2, None, None).kind, "lost"); } - assert!(h.state().window_lost(), "the loss was noticed"); - let tries = || attempts.load(std::sync::atomic::Ordering::SeqCst); - assert_eq!(tries(), 1); - assert!(h.state().has_unsaved_work(), "a failed recovery save doesn't let the app close"); - // Each step is 0.25 s: no new attempt before the retry interval. - h.run_steps(4); - assert_eq!(tries(), 1, "waits before trying again"); - h.run_steps(5); - assert_eq!(tries(), 2, "tries again"); - assert!(h.state().has_unsaved_work()); - disk_full.store(false, std::sync::atomic::Ordering::SeqCst); - h.run_steps(9); - assert_eq!(tries(), 3); - assert!(!h.state().has_unsaved_work(), "closes once the work is saved"); - h.run_steps(9); - assert_eq!(tries(), 3, "saved once, not again"); - assert_eq!(h.state().session.documents().len(), 1, "the document stays until the app closes"); -} -/// Uploaded tiles retain their own placement when painted in the same view. -#[test] -fn tiled_canvas_keeps_tiles_in_place() { - use photocraft_ui_egui::gpu_canvas::ViewParams; - let tile_override = std::env::var("PHOTOCRAFT_GPU_TILE").ok().and_then(|v| v.parse::().ok()); - if tile_override.is_some_and(|tile| tile > 64) { - eprintln!("skipping: PHOTOCRAFT_GPU_TILE must be at most 64 for this two-tile test"); - return; - } - let _gpu = gpu_lock(); - const N: u32 = 2; - const W: u32 = N * 64; - const H: u32 = 64; - let color = |tile: u32| if tile == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }; - let rgba: Vec = (0..W * H).flat_map(|i| color((i % W) / 64)).collect(); - struct TileApp { - canvas: GpuCanvas, - params: ViewParams, - } - impl eframe::App for TileApp { - fn ui(&mut self, ui: &mut egui::Ui, _: &mut eframe::Frame) { - GpuCanvas::paint(ui.painter(), egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(W as f32, H as f32)), self.params); - } - } - let Ok(builder) = std::panic::catch_unwind(|| egui_kittest::Harness::builder().with_size(egui::vec2(W as f32, H as f32)).with_pixels_per_point(1.0).wgpu()) - else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let mut h = builder.build_eframe(|cc| { - let rs = cc.wgpu_render_state.as_ref().expect("render state"); - let info = rs.adapter.get_info(); - eprintln!("tiled canvas adapter {info:?}"); - // Small tiles exercise the placement bindings without a large canvas. - let canvas = GpuCanvas::with_tile(rs, Some(64)); - canvas.upload_full(1, [W, H], &rgba); - TileApp { - canvas, - params: ViewParams { - doc: 1, - doc_size: [W, H], - zoom: 1.0, - center: [W as f32 / 2.0, H as f32 / 2.0], - rotation: 0.0, - - view_key: 1, - display: 0, - output: 0, - hdr: None, + #[test] + fn app_switches_to_the_cpu_canvas_and_keeps_the_documents() { + let _gpu = gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + app.sync_views(); + assert!(app.gpu_active()); + assert_eq!(app.perf.gpu_info.canvas, "gpu"); + let started = std::rc::Rc::new(std::cell::Cell::new(false)); + let flag = started.clone(); + app.on_started(move |_| flag.set(true)); + let mut h = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut Box| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + app.check_gpu(&ctx); + egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(app, ui)); + app.check_gpu(&ctx); }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, photocraft_ui_egui::theme::AppTheme::pro()); + h.run_steps(4); + assert!(h.state().gpu_active(), "GPU canvas in use before the loss"); + // The device is lost (e.g. the OS killed a huge submission). + h.state().gpu_health().unwrap().mark(Fault::Lost("killed by the OS".into())); + h.run_steps(3); + let app = h.state(); + assert!(!app.gpu_active(), "still on the GPU canvas"); + assert_eq!(app.session.documents().len(), 1, "document kept"); + assert_eq!(app.ui.status, gpu_status::LOST_MESSAGE); + assert!(app.ui.status_error); + assert!(app.ui.gpu_fallback_notice.as_deref().unwrap_or("").contains("killed by the OS")); + // UI passes drain the outbox into toasts, so the window's cards are checked as well. + let cards = craft::ui::runtime::toast::cards(&h.ctx, &craft::ui::runtime::env::WindowKey::main()); + assert!(app.ui.notices.is_empty() && cards.is_empty(), "one recovery warning, no duplicate notice"); + assert!(app.perf.gpu_info.lost.as_deref().unwrap_or("").contains("killed by the OS")); + assert_eq!(app.perf.gpu_info.canvas, "cpu"); + // The CPU path draws the document: a refresh after the loss is a CPU one. + assert!(matches!(app.perf.last_refresh, "full" | "rect"), "{}", app.perf.last_refresh); + // Editing keeps working. + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().session.active().map(|d| d.doc.layers.len()), Some(2)); + // The perf output carries the state for agents. + let perf = serde_json::to_value(&h.state().perf).unwrap(); + assert_eq!(perf["gpuInfo"]["canvas"], "cpu"); + let _ = started; + } + + /// A canvas whose display textures exceed the canvas budget gets none: no texture set is built, + /// the refresh says so and the app draws it on the CPU canvas instead (#2934). + #[test] + fn canvas_over_the_texture_budget_builds_no_textures() { + let _gpu = gpu_lock(); + let Some(rs) = render_state() else { return }; + let g = GpuCanvas::new(&rs); + let d = doc(); + let (key, size) = (d.id.0, [d.size.width, d.size.height]); + // Less than the full-resolution level alone. + g.set_canvas_budget(u64::from(size[0] * size[1]) * 4 - 1); + assert!(!g.fits_canvas(&d)); + let r = g.refresh(key, &d, None, None); + assert_eq!(r.kind, gpu_canvas::REFRESH_OVER_BUDGET); + assert!(!g.has(key, size) && g.texture_info(key).is_none()); + assert!(g.composite(&d, d.bounds(), false).is_err()); + g.upload_full(key, size, &vec![0; size[0] as usize * size[1] as usize * 4]); + assert!(g.texture_info(key).is_none(), "no entry point builds the set"); + // Within the budget the same document is drawn on the GPU, at the bytes it was priced at. + g.set_canvas_budget(1 << 30); + assert!(g.fits_canvas(&d)); + assert_ne!(g.refresh(key, &d, None, None).kind, gpu_canvas::REFRESH_OVER_BUDGET); + assert!(g.has(key, size)); + let (format, bytes) = g.texture_info(key).unwrap(); + let bpp = if format == eframe::wgpu::TextureFormat::Rgba16Float { 8 } else { 4 }; + assert_eq!(bytes, gpu_canvas::canvas_texture_bytes(size, gpu_canvas::DEFAULT_TILE, bpp)); + // Shrinking the budget below an existing set drops it on the next refresh. + g.set_canvas_budget(1); + assert_eq!(g.refresh(key, &d, None, None).kind, gpu_canvas::REFRESH_OVER_BUDGET); + assert!(g.texture_info(key).is_none()); + g.release(); + } + + /// #3438, #1215: when the window's own device is really lost (a driver reset, for example after + /// the PC slept), egui-wgpu can't draw another frame. One with shapes panicked inside it ("Failed + /// to create staging buffer for index data"), and a frozen window's close button opened an + /// unsaved-changes prompt nobody could see. Now the app draws nothing, writes the unsaved document + /// for recovery and closes. Runs the real frame loop on the harness's own device. + #[test] + fn a_lost_window_device_saves_unsaved_work_for_recovery_and_closes() { + let _gpu = gpu_lock(); + let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let (autosaves, flushes) = (log.clone(), log.clone()); + let render_state = std::sync::Arc::new(std::sync::Mutex::new(None::)); + let window = render_state.clone(); + let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(16).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let services = photocraft_ui_egui::Services { + autosave: Some(Box::new(move |doc: &std::sync::Arc, revision: u64, _: Option<&str>| { + autosaves.lock().unwrap().push(format!("autosave {} {revision}", doc.id.0)); + Ok(()) + })), + flush_autosaves: Some(Box::new(move || { + flushes.lock().unwrap().push("flush".into()); + Vec::new() + })), + ..Default::default() + }; + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), services); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + *window.lock().unwrap() = Some(rs.clone()); + app.set_wgpu(rs.clone()); + } + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app + }) + })); + // Upload and submit the last frame's shapes the way the window's renderer does each frame: on + // a lost device, egui-wgpu panics here when there is anything to draw (#1215). + let upload = |h: &egui_kittest::Harness<'_, Box>| { + let rs = render_state.lock().unwrap().clone().expect("the harness renders with wgpu"); + let output = h.output(); + let jobs = h.ctx.tessellate(output.shapes.clone(), output.pixels_per_point); + let screen = eframe::egui_wgpu::ScreenDescriptor { size_in_pixels: [1000, 700], pixels_per_point: output.pixels_per_point }; + let mut encoder = rs.device.create_command_encoder(&Default::default()); + let uploaded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let commands = rs.renderer.write().update_buffers(&rs.device, &rs.queue, &mut encoder, &jobs, &screen); + rs.queue.submit(commands.into_iter().chain([encoder.finish()])); + })); + (jobs.len(), uploaded.is_ok()) + }; + let Ok(mut h) = built else { + eprintln!("skipping: no GPU adapter"); + return; + }; + h.run_steps(4); + let (jobs, uploaded) = upload(&h); + assert!(jobs > 0 && uploaded, "draws before the loss"); + let (doc, revision, dirty) = h.state().session.active().map(|d| (d.doc.id.0, d.revision, d.is_dirty())).unwrap(); + assert!(dirty, "the new layer is unsaved"); + assert!(log.lock().unwrap().is_empty(), "no autosave before the loss"); + assert!(h.state_mut().destroy_window_device()); + // wgpu reports a destroyed device lost once the work submitted before finished (slow on a + // software adapter); a driver reset reports it at once. + if let Some(rs) = render_state.lock().unwrap().as_ref() { + let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(30)) }); } - }); - let (_, size, pixels) = h.state().canvas.read_texels(1).expect("uploaded pixels"); - assert_eq!(size, [W, H]); - for tile in 0..N { - assert_eq!(pixels[(32 * W + tile * 64 + 32) as usize], color(tile).map(|v| f32::from(v) / 255.0), "upload tile {tile}"); + h.run_steps(2); + assert!(h.state().window_lost(), "the loss was noticed"); + assert_eq!(*log.lock().unwrap(), vec![format!("autosave {doc} {revision}"), "flush".to_string()], "saved for recovery once"); + // The frame on the lost device has nothing to draw, so egui-wgpu has nothing to upload. + assert_eq!(upload(&h), (0, true), "a frame with shapes panics inside egui-wgpu on a lost device"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays until the app closes"); + } + + /// #6464 review: when the recovery save fails (a full disk, say), closing would lose the work, so + /// the app stays open with the document and tries again until the write succeeds, then closes. + #[test] + fn a_lost_window_device_closes_only_once_unsaved_work_is_saved() { + let _gpu = gpu_lock(); + let disk_full = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (full, tries) = (disk_full.clone(), attempts.clone()); + let pending = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(u64, u64)>::new())); + let queued = pending.clone(); + let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(16).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let services = photocraft_ui_egui::Services { + autosave: Some(Box::new(move |doc: &std::sync::Arc, revision: u64, _: Option<&str>| { + queued.lock().unwrap().push((doc.id.0, revision)); + Ok(()) + })), + autosave_results: Some(Box::new(Vec::new)), + flush_autosaves: Some(Box::new(move || { + tries.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let outcome = if full.load(std::sync::atomic::Ordering::SeqCst) { Err("disk full".to_string()) } else { Ok(()) }; + pending.lock().unwrap().drain(..).map(|(id, revision)| (id, revision, outcome.clone())).collect() + })), + ..Default::default() + }; + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), services); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app + }) + })); + let Ok(mut h) = built else { + eprintln!("skipping: no GPU adapter"); + return; + }; + h.run_steps(4); + assert!(h.state_mut().destroy_window_device()); + for _ in 0..120 { + h.run_steps(1); + if h.state().window_lost() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(250)); + } + assert!(h.state().window_lost(), "the loss was noticed"); + let tries = || attempts.load(std::sync::atomic::Ordering::SeqCst); + assert_eq!(tries(), 1); + assert!(h.state().has_unsaved_work(), "a failed recovery save doesn't let the app close"); + // Each step is 0.25 s: no new attempt before the retry interval. + h.run_steps(4); + assert_eq!(tries(), 1, "waits before trying again"); + h.run_steps(5); + assert_eq!(tries(), 2, "tries again"); + assert!(h.state().has_unsaved_work()); + disk_full.store(false, std::sync::atomic::Ordering::SeqCst); + h.run_steps(9); + assert_eq!(tries(), 3); + assert!(!h.state().has_unsaved_work(), "closes once the work is saved"); + h.run_steps(9); + assert_eq!(tries(), 3, "saved once, not again"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays until the app closes"); + } + + /// Uploaded tiles retain their own placement when painted in the same view. + #[test] + fn tiled_canvas_keeps_tiles_in_place() { + use photocraft_ui_egui::gpu_canvas::ViewParams; + let tile_override = std::env::var("PHOTOCRAFT_GPU_TILE").ok().and_then(|v| v.parse::().ok()); + if tile_override.is_some_and(|tile| tile > 64) { + eprintln!("skipping: PHOTOCRAFT_GPU_TILE must be at most 64 for this two-tile test"); + return; + } + let _gpu = gpu_lock(); + const N: u32 = 2; + const W: u32 = N * 64; + const H: u32 = 64; + let color = |tile: u32| if tile == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }; + let rgba: Vec = (0..W * H).flat_map(|i| color((i % W) / 64)).collect(); + struct TileApp { + canvas: GpuCanvas, + params: ViewParams, + } + impl eframe::App for TileApp { + fn ui(&mut self, ui: &mut egui::Ui, _: &mut eframe::Frame) { + GpuCanvas::paint(ui.painter(), egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(W as f32, H as f32)), self.params); + } + } + let Ok(builder) = + std::panic::catch_unwind(|| egui_kittest::Harness::builder().with_size(egui::vec2(W as f32, H as f32)).with_pixels_per_point(1.0).wgpu()) + else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut h = builder.build_eframe(|cc| { + let rs = cc.wgpu_render_state.as_ref().expect("render state"); + let info = rs.adapter.get_info(); + eprintln!("tiled canvas adapter {info:?}"); + // Small tiles exercise the placement bindings without a large canvas. + let canvas = GpuCanvas::with_tile(rs, Some(64)); + canvas.upload_full(1, [W, H], &rgba); + TileApp { + canvas, + params: ViewParams { + doc: 1, + doc_size: [W, H], + zoom: 1.0, + center: [W as f32 / 2.0, H as f32 / 2.0], + rotation: 0.0, + + view_key: 1, + display: 0, + output: 0, + hdr: None, + }, + } + }); + let (_, size, pixels) = h.state().canvas.read_texels(1).expect("uploaded pixels"); + assert_eq!(size, [W, H]); + for tile in 0..N { + assert_eq!(pixels[(32 * W + tile * 64 + 32) as usize], color(tile).map(|v| f32::from(v) / 255.0), "upload tile {tile}"); + } + h.run_steps(3); + let image = h.render().expect("canvas frame"); + let actual: Vec<_> = (0..N).map(|tile| image.get_pixel(tile * 64 + 32, 32).0).collect(); + let expected: Vec<_> = (0..N).map(color).collect(); + assert_eq!(actual, expected, "each tile must retain its own screen placement"); + assert!(h.state().canvas.health().is_ok()); } - h.run_steps(3); - let image = h.render().expect("canvas frame"); - let actual: Vec<_> = (0..N).map(|tile| image.get_pixel(tile * 64 + 32, 32).0).collect(); - let expected: Vec<_> = (0..N).map(color).collect(); - assert_eq!(actual, expected, "each tile must retain its own screen placement"); - assert!(h.state().canvas.health().is_ok()); } diff --git a/crates/ui-egui/tests/it/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs similarity index 100% rename from crates/ui-egui/tests/it/adjust_preview_gpu.rs rename to crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs diff --git a/crates/ui-egui/tests/it/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs similarity index 100% rename from crates/ui-egui/tests/it/arbitrary_rotation_preview.rs rename to crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs diff --git a/crates/ui-egui/tests/it/canvas_16f.rs b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs similarity index 100% rename from crates/ui-egui/tests/it/canvas_16f.rs rename to crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs diff --git a/crates/ui-egui/tests/it/checker_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/checker_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs diff --git a/crates/ui-egui/tests/it/color_managed_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/color_managed_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/color_managed_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/color_managed_canvas.rs diff --git a/crates/ui-egui/tests/it/display_shadows.rs b/crates/ui-egui/tests/it/gpu_tests/display_shadows.rs similarity index 100% rename from crates/ui-egui/tests/it/display_shadows.rs rename to crates/ui-egui/tests/it/gpu_tests/display_shadows.rs diff --git a/crates/ui-egui/tests/it/drag_preview_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/drag_preview_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs diff --git a/crates/ui-egui/tests/it/full_res_preview.rs b/crates/ui-egui/tests/it/gpu_tests/full_res_preview.rs similarity index 100% rename from crates/ui-egui/tests/it/full_res_preview.rs rename to crates/ui-egui/tests/it/gpu_tests/full_res_preview.rs diff --git a/crates/ui-egui/tests/it/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/live_stroke_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs diff --git a/crates/ui-egui/tests/it/pattern_preview_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/pattern_preview_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/pattern_preview_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/pattern_preview_canvas.rs diff --git a/crates/ui-egui/tests/it/ui_scale_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs similarity index 100% rename from crates/ui-egui/tests/it/ui_scale_canvas.rs rename to crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs diff --git a/crates/ui-egui/tests/it/layout_perf.rs b/crates/ui-egui/tests/it/layout_perf.rs index d2f5ff81c7..124e5e6879 100644 --- a/crates/ui-egui/tests/it/layout_perf.rs +++ b/crates/ui-egui/tests/it/layout_perf.rs @@ -215,44 +215,48 @@ fn the_move_preview_is_what_the_move_commits() { } } -#[test] -fn layout_document_composites_on_the_gpu_like_the_cpu() { - let _gpu = photocraft_testkit::gpu_lock(); - use eframe::wgpu; - fn block_on(f: F) -> F::Output { - let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); - let mut f = std::pin::pin!(f); - loop { - if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) { - return v; +mod gpu_tests { + use super::*; + + #[test] + fn layout_document_composites_on_the_gpu_like_the_cpu() { + let _gpu = photocraft_testkit::gpu_lock(); + use eframe::wgpu; + fn block_on(f: F) -> F::Output { + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut f = std::pin::pin!(f); + loop { + if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) { + return v; + } + std::thread::yield_now(); } - std::thread::yield_now(); } - } - let Ok(adapter) = - block_on(wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default())) - else { - eprintln!("skipping: no GPU adapter"); - return; - }; - if photocraft_gpu::Compositor::preferred_acc_format(&adapter) != wgpu::TextureFormat::Rgba32Float { - eprintln!("skipping: adapter can't render Rgba32Float"); - return; - } - let Ok((device, queue)) = block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { return }; - let Ok(mut comp) = photocraft_gpu::Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgba32Float) else { return }; - let (d, _) = layout_doc::build(layout_doc::Spec::small()); - let (_, texts) = layout_doc::count(&d); - assert!(texts >= 10); - assert!(d.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)))); - let cpu = photocraft_compose::flatten(&d); - let gpu = photocraft_gpu::render_to_vec(&mut comp, &device, &queue, &d, d.bounds()).expect("the layout composites on the GPU"); - let mut worst = 0.0f32; - for (c, g) in cpu.px.iter().zip(&gpu) { - for k in 0..4 { - let (a, b) = if k == 3 { (c[3], g[3]) } else { (c[k] * c[3], g[k] * g[3]) }; - worst = worst.max((a - b).abs()); + let Ok(adapter) = block_on( + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default()), + ) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + if photocraft_gpu::Compositor::preferred_acc_format(&adapter) != wgpu::TextureFormat::Rgba32Float { + eprintln!("skipping: adapter can't render Rgba32Float"); + return; } + let Ok((device, queue)) = block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { return }; + let Ok(mut comp) = photocraft_gpu::Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgba32Float) else { return }; + let (d, _) = layout_doc::build(layout_doc::Spec::small()); + let (_, texts) = layout_doc::count(&d); + assert!(texts >= 10); + assert!(d.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)))); + let cpu = photocraft_compose::flatten(&d); + let gpu = photocraft_gpu::render_to_vec(&mut comp, &device, &queue, &d, d.bounds()).expect("the layout composites on the GPU"); + let mut worst = 0.0f32; + for (c, g) in cpu.px.iter().zip(&gpu) { + for k in 0..4 { + let (a, b) = if k == 3 { (c[3], g[3]) } else { (c[k] * c[3], g[k] * g[3]) }; + worst = worst.max((a - b).abs()); + } + } + assert!(worst <= 2.0 / 255.0, "GPU differs from the CPU by {}/255", worst * 255.0); } - assert!(worst <= 2.0 / 255.0, "GPU differs from the CPU by {}/255", worst * 255.0); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 279623dd09..d83da73138 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,26 +2,18 @@ mod actions_duplicate; mod actions_panel_menu; -mod adjust_preview_gpu; -mod arbitrary_rotation_preview; mod batch_export_options; mod brush_reset_defaults; mod camera_raw_histogram; mod camera_raw_scope; -mod canvas_16f; -mod checker_canvas; mod clipboard_svg; -mod color_managed_canvas; mod crop_ctrl_straighten; mod crop_defaults; mod crop_options_bar_chrome; mod crop_task_bar; mod display_names; -mod display_shadows; -mod drag_preview_canvas; mod eraser_reset_defaults; mod flatpak_updates; -mod full_res_preview; mod gpu_device_loss; mod healing_reset_tip; // The interactive bench's `#[cfg(test)]` reporting tests: CI runs `--tests`, never examples. @@ -30,15 +22,12 @@ mod healing_reset_tip; #[allow(dead_code)] mod interactive_bench_reporting; mod layout_perf; -mod live_stroke_canvas; mod magnetic_lasso_right_click; mod paint_bucket_all_layers; -mod pattern_preview_canvas; mod radial_blur_center; mod save_memory_gate; mod system_locale; mod tone_targets; -mod ui_scale_canvas; mod variables_data_sets; mod workspace_presets; @@ -51,3 +40,19 @@ pub(crate) static HEADROOM: Mutex<()> = Mutex::new(()); pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { lock.lock().unwrap_or_else(PoisonError::into_inner) } + +// Tests that draw on a GPU device. nextest runs every test in a `gpu_tests` module in its `gpu` +// test group (.config/nextest.toml); the rest run on the CPU canvas. +mod gpu_tests { + mod adjust_preview_gpu; + mod arbitrary_rotation_preview; + mod canvas_16f; + mod checker_canvas; + mod color_managed_canvas; + mod display_shadows; + mod drag_preview_canvas; + mod full_res_preview; + mod live_stroke_canvas; + mod pattern_preview_canvas; + mod ui_scale_canvas; +} diff --git a/docs/development.md b/docs/development.md index 98948548dd..4297bd541b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -65,7 +65,7 @@ cargo nextest run --workspace # parallel across binaries (cargo ins cargo test --doc --workspace # nextest does not run doctests ``` -[cargo-nextest](https://nexte.st) runs each test in its own process. `.config/nextest.toml` puts the GPU tests (`photocraft-gpu`, and ui-egui's integration and canvas/GPU tests) in a group of at most 4 at a time, because each process opens its own wgpu device and the in-process `gpu_lock()` no longer serializes them. On a 32-thread Windows machine the full workspace went from 297 s (`cargo test`) to about 120 s (#2204). Ignored tests run with `cargo nextest run --run-ignored only`. The longest sweeps (`photocraft-testkit`'s `Sweep`) run a quarter of their cases, a different quarter each UTC day; `PHOTOCRAFT_FULL_SWEEP=1` runs all of them, and `PHOTOCRAFT_SWEEP_PART=` replays the part a failing run printed. CI runs it with `--profile ci` (fail-fast, a 10-minute hang timeout), plus `cargo test --doc` for the doctests (#6117); `PHOTOCRAFT_FULL_SWEEP=1 cargo test --workspace` stays the final check before a PR. +[cargo-nextest](https://nexte.st) runs each test in its own process. `.config/nextest.toml` puts the GPU tests (`photocraft-gpu`, and every test in a module named `gpu_tests` or `_gpu_tests`: the tests that build a wgpu device) in a group of at most 4 at a time, because each process opens its own wgpu device and the in-process `gpu_lock()` no longer serializes them. Every other test runs on the CPU canvas at full parallelism, so a new test that needs a device goes in such a module. On a 32-thread Windows machine the full workspace went from 297 s (`cargo test`) to about 120 s (#2204). Ignored tests run with `cargo nextest run --run-ignored only`. The longest sweeps (`photocraft-testkit`'s `Sweep`) run a quarter of their cases, a different quarter each UTC day; `PHOTOCRAFT_FULL_SWEEP=1` runs all of them, and `PHOTOCRAFT_SWEEP_PART=` replays the part a failing run printed. CI runs it with `--profile ci` (fail-fast, a 10-minute hang timeout), plus `cargo test --doc` for the doctests (#6117); `PHOTOCRAFT_FULL_SWEEP=1 cargo test --workspace` stays the final check before a PR. ### Long matrix tests and CI timings