From c3354976b86b007bf3116a4083eba418fb1f4296 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 19:40:30 +0100 Subject: [PATCH 01/25] Tests: tone_targets pairs modes with depths instead of crossing them (#15636) The three whole-app tests in tone_targets.rs looped over every colour mode x bit depth pairing. The planes they edit are single-channel gray in every mode, so each mode and each depth once covers the same code; the full cross product pushed one test past nextest's 600 s limit on Windows. The address resolution keeps all three selector forms on one pair. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/tone_targets.rs | 208 ++++++++++++------------ 1 file changed, 105 insertions(+), 103 deletions(-) diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index cedcb8a773..d1c02abb38 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -20,6 +20,14 @@ const MODES: [ColorMode; 3] = [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab]; const GRAY_TARGET_MODES: [ColorMode; 4] = [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale]; const DEPTHS: [SampleType; 3] = [SampleType::U8, SampleType::U16, SampleType::F32]; const TARGETS: [ChannelTarget; 3] = [ChannelTarget::Alpha(0), ChannelTarget::LayerMask, ChannelTarget::Composite]; +/// Every mode and every depth once, for the whole-app tests. The planes they edit are single-channel +/// gray whatever the document mode (the mode only changes the colour layer, which each case asserts +/// stays untouched), and the depth does not interact with the mode, so the full cross product reaches +/// no new code and ran a single test past nextest's 600 s limit on Windows (#15636). +const MODE_DEPTHS: [(ColorMode, SampleType); 3] = [(ColorMode::Rgb, SampleType::U8), (ColorMode::Cmyk, SampleType::U16), (ColorMode::Lab, SampleType::F32)]; +/// [`MODE_DEPTHS`] plus a grayscale document, for the tests that also cover gray documents. +const GRAY_MODE_DEPTHS: [(ColorMode, SampleType); 4] = + [(ColorMode::Rgb, SampleType::U8), (ColorMode::Cmyk, SampleType::U16), (ColorMode::Lab, SampleType::F32), (ColorMode::Grayscale, SampleType::U16)]; /// The keys the hosted adjustment dialog lists beside its engine parameters. const DIALOG_STATE: [&str; 4] = ["preview", "picker", "channel", "clipping"]; @@ -411,36 +419,34 @@ fn levels_auto_uses_the_selected_colour_channels_histogram() { #[test] fn grayscale_picker_controls_sample_the_plane_and_change_the_visible_curve() { for kind in ["curves", "levels"] { - for mode in GRAY_TARGET_MODES { - for depth in DEPTHS { - for target in TARGETS { - let mut h = open_on_canvas(fixture(mode, depth, target), kind); - assert!(h.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled()); - assert!(!h.get_by_label("Set White Point").accesskit_node().is_disabled()); - h.get_by_label("Set White Point").click(); - h.run_steps(2); - assert!(picker_armed(&h)); - let before = params(&h); - let original = h.state().session.active().unwrap().doc.clone(); - sample_at(&mut h, 4.0, 4.0); - let after = params(&h); - let key = if kind == "curves" { "points" } else { "inWhite" }; - assert_ne!(before[key], after[key], "{kind} {mode:?} {depth:?} {target:?}"); - let sampled_level = if kind == "curves" { - after["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() - } else { - after["inWhite"].as_f64().unwrap() - }; - assert!((sampled_level - 63.75).abs() < 0.3, "sample the plane's 25% gray, not the colour layer: {after}"); - for key in ["red", "green", "blue"] { - assert_eq!(before[key], after[key], "hidden {key} must not change"); - } - assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); - let id = top(&h); - confirm(&mut h, id).unwrap(); - assert!(value(h.state(), target) > 0.99, "{kind} {mode:?} {depth:?} {target:?}"); - assert_eq!(h.state().session.active().unwrap().doc.layers[0].content, original.layers[0].content); + for (mode, depth) in GRAY_MODE_DEPTHS { + for target in TARGETS { + let mut h = open_on_canvas(fixture(mode, depth, target), kind); + assert!(h.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled()); + assert!(!h.get_by_label("Set White Point").accesskit_node().is_disabled()); + h.get_by_label("Set White Point").click(); + h.run_steps(2); + assert!(picker_armed(&h)); + let before = params(&h); + let original = h.state().session.active().unwrap().doc.clone(); + sample_at(&mut h, 4.0, 4.0); + let after = params(&h); + let key = if kind == "curves" { "points" } else { "inWhite" }; + assert_ne!(before[key], after[key], "{kind} {mode:?} {depth:?} {target:?}"); + let sampled_level = if kind == "curves" { + after["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() + } else { + after["inWhite"].as_f64().unwrap() + }; + assert!((sampled_level - 63.75).abs() < 0.3, "sample the plane's 25% gray, not the colour layer: {after}"); + for key in ["red", "green", "blue"] { + assert_eq!(before[key], after[key], "hidden {key} must not change"); } + assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); + let id = top(&h); + confirm(&mut h, id).unwrap(); + assert!(value(h.state(), target) > 0.99, "{kind} {mode:?} {depth:?} {target:?}"); + assert_eq!(h.state().session.active().unwrap().doc.layers[0].content, original.layers[0].content); } } } @@ -895,38 +901,36 @@ fn filter_mask_fixture(mode: ColorMode, depth: SampleType, stored: bool) -> Box< /// New upstream filter masks use the same scalar controls, picker and preserved targeting in every document space. #[test] fn filter_mask_tone_dialogs_preserve_the_target_and_sample_its_own_levels() { - for mode in GRAY_TARGET_MODES { - for depth in DEPTHS { - for kind in ["levels", "curves"] { - for stored in [false, true] { - let app = filter_mask_fixture(mode, depth, stored); - let st = app.session.active().unwrap(); - let layer = st.active_layer.unwrap(); - let expected_name = format!("{} Filter Mask", st.doc.layer(layer).unwrap().name); - let before = st.doc.clone(); - let mut h = open_on_canvas(app, kind); - assert_eq!(names(&h), [expected_name], "{mode:?} {depth:?} {kind}"); - assert_eq!(params(&h)["target"], "filterMask"); - let id = top(&h); - arm(&mut h, "white"); - sample_at(&mut h, 4.0, 4.0); - assert!(picker_armed(&h), "the picker stays armed on {mode:?} {depth:?} stored={stored}"); - assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc), "sampling is read-only"); - assert_eq!(params(&h)["target"], "filterMask"); - if kind == "levels" { - let expected = if stored { 64.0 } else { 255.0 }; - assert!((params(&h)["inWhite"].as_f64().unwrap() - expected).abs() < 1.0); - } - confirm(&mut h, id).unwrap(); - let after = &h.state().session.active().unwrap().doc; - let LayerContent::Smart(old) = &before.layer(layer).unwrap().content else { panic!("smart fixture") }; - let LayerContent::Smart(new) = &after.layer(layer).unwrap().content else { panic!("smart result") }; - assert_eq!(new.smart_filters, old.smart_filters, "the adjustment edits the mask rather than adding a filter"); - assert_eq!(new.source, old.source); - assert_eq!(after.channels, before.channels); - assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); - assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99); + for (mode, depth) in GRAY_MODE_DEPTHS { + for kind in ["levels", "curves"] { + for stored in [false, true] { + let app = filter_mask_fixture(mode, depth, stored); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let expected_name = format!("{} Filter Mask", st.doc.layer(layer).unwrap().name); + let before = st.doc.clone(); + let mut h = open_on_canvas(app, kind); + assert_eq!(names(&h), [expected_name], "{mode:?} {depth:?} {kind}"); + assert_eq!(params(&h)["target"], "filterMask"); + let id = top(&h); + arm(&mut h, "white"); + sample_at(&mut h, 4.0, 4.0); + assert!(picker_armed(&h), "the picker stays armed on {mode:?} {depth:?} stored={stored}"); + assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc), "sampling is read-only"); + assert_eq!(params(&h)["target"], "filterMask"); + if kind == "levels" { + let expected = if stored { 64.0 } else { 255.0 }; + assert!((params(&h)["inWhite"].as_f64().unwrap() - expected).abs() < 1.0); } + confirm(&mut h, id).unwrap(); + let after = &h.state().session.active().unwrap().doc; + let LayerContent::Smart(old) = &before.layer(layer).unwrap().content else { panic!("smart fixture") }; + let LayerContent::Smart(new) = &after.layer(layer).unwrap().content else { panic!("smart result") }; + assert_eq!(new.smart_filters, old.smart_filters, "the adjustment edits the mask rather than adding a filter"); + assert_eq!(new.source, old.source); + assert_eq!(after.channels, before.channels); + assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); + assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99); } } } @@ -1119,49 +1123,47 @@ fn addressed_mask_app(mode: ColorMode, depth: SampleType, filter: bool) -> (Box< /// switching the selected layer. The matrix includes native raster and Smart Filter masks. #[test] fn review_mask_action_context_matches_the_addressed_layer() { - for mode in MODES { - for depth in DEPTHS { - for kind in ["levels", "curves"] { - for filter in [false, true] { - let (app, layer) = addressed_mask_app(mode, depth, filter); - for selector in [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})] { - let mut app = fixture_for_addressed_replay(&app); - let command = format!("image.adjustments.{kind}"); - let target = if filter { "filterMask" } else { "mask" }; - let raw = json!({"layer":selector,"target":target}); - add_action(&mut app, "Other mask", command.clone(), raw, true); - let original = app.session.active().unwrap().doc.clone(); - let active = app.session.active().unwrap().active_layer; - let expected = - photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); - let mut h = canvas_harness(app); - play(&mut h, "Other mask"); - assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); - let id = top(&h); - arm(&mut h, "white"); - sample_at(&mut h, 4.0, 4.0); - let p = params(&h); - let want = photocraft_engine::adjust_params::adjustment_eyedropper( - kind, - &json!({}), - photocraft_engine::adjust_params::CurvesEyedropper::White, - [expected; 3], - ColorMode::Grayscale, - ) - .unwrap(); - let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); - assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); - let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); - confirm(&mut h, id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.layers, preview.layers); - assert_eq!(doc.layers[0], original.layers[0]); - assert_eq!(doc.channels, original.channels); - assert!( - photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99 - ); - assert_eq!(h.state().session.active().unwrap().active_layer, active); - } + for (pair, (mode, depth)) in MODE_DEPTHS.into_iter().enumerate() { + for kind in ["levels", "curves"] { + for filter in [false, true] { + let (app, layer) = addressed_mask_app(mode, depth, filter); + // Resolving the address does not depend on the mode or depth: every selector form on the first pair. + let selectors = [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})]; + for selector in selectors.into_iter().take(if pair == 0 { 3 } else { 1 }) { + let mut app = fixture_for_addressed_replay(&app); + let command = format!("image.adjustments.{kind}"); + let target = if filter { "filterMask" } else { "mask" }; + let raw = json!({"layer":selector,"target":target}); + add_action(&mut app, "Other mask", command.clone(), raw, true); + let original = app.session.active().unwrap().doc.clone(); + let active = app.session.active().unwrap().active_layer; + let expected = + photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); + let mut h = canvas_harness(app); + play(&mut h, "Other mask"); + assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); + let id = top(&h); + arm(&mut h, "white"); + sample_at(&mut h, 4.0, 4.0); + let p = params(&h); + let want = photocraft_engine::adjust_params::adjustment_eyedropper( + kind, + &json!({}), + photocraft_engine::adjust_params::CurvesEyedropper::White, + [expected; 3], + ColorMode::Grayscale, + ) + .unwrap(); + let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); + assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); + let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); + confirm(&mut h, id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.layers, preview.layers); + assert_eq!(doc.layers[0], original.layers[0]); + assert_eq!(doc.channels, original.channels); + assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99); + assert_eq!(h.state().session.active().unwrap().active_layer, active); } } } From 08c4d76e9dc01a09be746b058984b912d6dcc047 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 19:42:10 +0100 Subject: [PATCH 02/25] WIP: trim redundant test loops (#15369) Co-Authored-By: Claude Opus 5.5 From 57feba3fc8d55d659a05dfcf4e7befe9f4609ffa Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 19:42:16 +0100 Subject: [PATCH 03/25] WIP: trim redundant test loops (#15368) Co-Authored-By: Claude Opus 5.5 From ed02f0cdf54592faecdd67ba2d04e6bd8d0b5e06 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 19:42:23 +0100 Subject: [PATCH 04/25] WIP: trim redundant test loops (#15367) Co-Authored-By: Claude Opus 5.5 From c55c0b7ce819affaaecff2de709d1b15634150af Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 18:51:38 +0000 Subject: [PATCH 05/25] gpu: build each compositor pipeline on first use (#15439) Every compositor built all ~30 pipelines when created. On the Windows CI runners (WARP, FXC) that took 3 to 7.5 s in every GPU test process, and a test that draws one layer needs two or three of them. The pipelines now sit in one table per compositor (shared with its siblings), one entry per kernel, each built the first time a draw needs it. try_new_with_format_threads(_classified), which the app uses for its background build, still builds every pipeline up front in parallel through the same table, so the app keeps its start-up error and its cached deterministic-failure path. A pipeline that fails on first use makes that render Unsupported (CPU fallback); a failed effect-map pipeline turns layer effects to the CPU as before. The #9173 rules hold: each kernel has its own vertex entry point, a kernel's formats are built on one thread, and every build in the process takes the same lock. every_compositor_pipeline_builds builds all pipelines through the threaded build, so FXC still compiles every shader on Windows CI. New count test: one layer builds a small share of the pipelines, and a second render or a sibling builds none. --- crates/gpu/src/cells.rs | 18 +-- crates/gpu/src/encode.rs | 4 +- crates/gpu/src/fx_passes.rs | 3 +- crates/gpu/src/kit.rs | 60 ++------ crates/gpu/src/lib.rs | 4 +- crates/gpu/src/pipelines.rs | 203 +++++++++++++++++++++++++ crates/gpu/src/setup.rs | 172 ++++++--------------- crates/gpu/src/tests.rs | 27 ++-- crates/gpu/tests/it/parity.rs | 11 +- crates/gpu/tests/it/pipeline_errors.rs | 24 +-- crates/gpu/tests/it/pipelines.rs | 41 ++++- 11 files changed, 340 insertions(+), 227 deletions(-) create mode 100644 crates/gpu/src/pipelines.rs diff --git a/crates/gpu/src/cells.rs b/crates/gpu/src/cells.rs index de858046d5..14ea29481d 100644 --- a/crates/gpu/src/cells.rs +++ b/crates/gpu/src/cells.rs @@ -115,9 +115,9 @@ impl Compositor { sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), // The previous intermediate submit, when this refresh may submit in between. batch: &mut Option<&mut Option>, - ) { + ) -> Result<(), Unsupported> { if chunks.is_empty() { - return; + return Ok(()); } // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. let first_pass = checkpoint @@ -126,7 +126,7 @@ impl Compositor { let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). if self.layer_alloc.is_some() { - return; + return Ok(()); } // Chunk pool. @@ -233,7 +233,7 @@ impl Compositor { self.recorded = 0; stats.flushes += 1; if self.fault().is_some() { - return; + return Ok(()); } } // Also after resuming from a lower checkpoint: the chunk moves up to this one. @@ -294,8 +294,9 @@ impl Compositor { } _ => (p.kernel, p.dst), }; - let target = &self.pool[dst as usize].1; let clear = p.kernel == Kernel::Clear; + let pipeline = if clear { None } else { Some(self.kit.pipelines.get(device, kernel, self.acc_format)?) }; + let target = &self.pool[dst as usize].1; let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("pc_compose_pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { @@ -312,10 +313,8 @@ impl Compositor { occlusion_query_set: None, multiview_mask: None, }); - if clear { - continue; - } - pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); + let Some(pipeline) = pipeline else { continue }; + pass.set_pipeline(pipeline); pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); pass.set_bind_group(1, bg1[i].as_ref(), &[]); @@ -330,6 +329,7 @@ impl Compositor { let (t, v) = &self.pool[plan.root as usize]; sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); } + Ok(()) } /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); diff --git a/crates/gpu/src/encode.rs b/crates/gpu/src/encode.rs index e704208bd0..8fc93d1440 100644 --- a/crates/gpu/src/encode.rs +++ b/crates/gpu/src/encode.rs @@ -217,7 +217,7 @@ impl Compositor { stats.chunks += chunks.len(); work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; let mut batch = flush.then_some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch)?; // The device was lost in a submit inside the cell: issue no more work. if let Some(f) = self.fault() { return Err(Unsupported(f.to_string())); @@ -251,7 +251,7 @@ impl Compositor { return Err(Unsupported(f.to_string())); } let mut batch = Some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch)?; if let Some(f) = self.fault() { return Err(Unsupported(f.to_string())); } diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index dbc61d0853..615677d840 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -258,8 +258,7 @@ impl Compositor { lut: s.lut.clone(), }); } - self.kit.run(device, queue, encoder, &draws); - Ok(()) + self.kit.run(device, queue, encoder, &draws) } } diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs index 12755b2dbf..9a916ccb14 100644 --- a/crates/gpu/src/kit.rs +++ b/crates/gpu/src/kit.rs @@ -1,12 +1,14 @@ -use super::consts::{CHUNK_UNIFORM, MAP16, MAP32, OP_UNIFORM, STRIDE}; +use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; use super::convert::{lut_texture, words}; +use super::pipelines::Pipelines; use super::textures::{ResKey, ResidentRef}; -use super::{Arc, HashMap, I, Kernel, NonZeroU64, Rect}; +use super::{Arc, I, Kernel, NonZeroU64, Rect, Unsupported}; -/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). +/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted; a sibling +/// compositor uses the pipelines any of them built). #[derive(Clone)] pub(crate) struct Kit { - pub(crate) pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, + pub(crate) pipelines: Arc, pub(crate) bgl0: wgpu::BindGroupLayout, pub(crate) bgl1: wgpu::BindGroupLayout, pub(crate) dummy: wgpu::TextureView, @@ -28,9 +30,9 @@ pub(crate) struct MapDraw { impl Kit { /// Record `draws` (each its own render pass) into `encoder`. - pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { + pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) -> Result<(), Unsupported> { if draws.is_empty() { - return; + return Ok(()); } let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; for (i, d) in draws.iter().enumerate() { @@ -47,6 +49,7 @@ impl Kit { queue.write_buffer(&ubuf, 0, &data); let bg0 = uniform_group(device, &self.bgl0, &ubuf); for (i, d) in draws.iter().enumerate() { + let pipeline = self.pipelines.get(device, d.kernel, d.format)?; let lut = d.lut.as_ref().map(|l| { let mut row = [0.0f32; 4096]; row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); @@ -70,12 +73,13 @@ impl Kit { occlusion_query_set: None, multiview_mask: None, }); - pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); + pass.set_pipeline(pipeline); pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); pass.set_bind_group(1, &bg1, &[]); pass.draw(0..3, 0..1); } + Ok(()) } } @@ -127,48 +131,6 @@ pub(crate) fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEnt /// The compositor's WGSL source (exposed for validation in tests). pub const SHADER: &str = include_str!("compose.wgsl"); -/// One thread's share of the compositor's pipelines: the vertex entry point (in -/// [`vertex_shader`]) and the (kernel, target format) pairs it builds. -pub(crate) struct BuildJob { - pub(crate) vertex: String, - pub(crate) keys: Vec<(Kernel, wgpu::TextureFormat)>, -} - -/// The compositor's pipelines, grouped by the thread that builds them: one job per kernel, and -/// an effect-map kernel's R32F and R16F pipelines in the same job. Each job has its own vertex -/// entry point, so no two jobs share a shader (see `Compositor::build`). -pub(crate) fn build_jobs(acc_format: wgpu::TextureFormat) -> Vec { - let one = |k: Kernel| if k.is_map() { vec![(k, MAP32), (k, MAP16)] } else { vec![(k, acc_format)] }; - let (plain, maps): (Vec, Vec) = Kernel::DRAWN.iter().partition(|k| !k.is_map()); - plain.into_iter().chain(maps).enumerate().map(|(job, k)| BuildJob { vertex: format!("vs_{job}"), keys: one(k) }).collect() -} - -/// The full-chunk triangle's vertex stage, once per build job under that job's name (`vs_0`, -/// `vs_1`, ...): the same code under distinct names, so each job compiles its own vertex shader. -/// -/// A workaround, not a design: wgpu-hal's D3D12 shader cache shares a compiled FXC blob between -/// threads, and FXC's blobs don't count references atomically, so a shared one can be freed -/// while still cached (gfx-rs/wgpu#10547, #9173). Each copy costs one compile of a three-line -/// shader. Once a wgpu release fixes the cache, go back to one `vs` in `compose.wgsl` and let -/// `build_jobs` split map kernels by format again. -pub(crate) fn vertex_shader(jobs: &[BuildJob]) -> String { - let mut s = String::from( - "struct VOut { @builtin(position) pos: vec4 }; -", - ); - for job in jobs { - s.push_str(&format!( - "@vertex fn {}(@builtin(vertex_index) vi: u32) -> VOut {{ - let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); - return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); -}} -", - job.vertex - )); - } - s -} - /// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect /// maps (view and region) per pass. pub(crate) struct Bound { diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 2beaedc233..8ba9d09a5f 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -118,9 +118,6 @@ pub struct Compositor { /// out of memory. fail_allocs: u32, acc_format: wgpu::TextureFormat, - /// Whether the effect-map pipelines could be built (else documents with layer effects are - /// [`Unsupported`] and use the CPU compositor). - effect_maps: bool, /// `CmykSpace::id` of the document being encoded (0: built-in coated CMYK). cmyk: u64, /// The device's health (see [`Compositor::set_health`]); `None` = assumed healthy. @@ -141,6 +138,7 @@ mod encode; mod fx_passes; mod kit; mod paging; +mod pipelines; #[cfg(not(target_arch = "wasm32"))] pub mod readback; mod setup; diff --git a/crates/gpu/src/pipelines.rs b/crates/gpu/src/pipelines.rs new file mode 100644 index 0000000000..8331f90946 --- /dev/null +++ b/crates/gpu/src/pipelines.rs @@ -0,0 +1,203 @@ +//! The compositor's render pipelines: one table per compositor and its siblings, each pipeline +//! built the first time a draw needs it, or all of them at once where a caller wants every +//! shader compiled up front (the app's background build). +//! +//! On DX12 the shader compiler is FXC, which compiles one shader at a time; the ~30 pipelines +//! took about 8 s on one core (#6419), and 3 to 7.5 s per test process on the Windows CI +//! runners' software adapter (#15439). A compositor that draws one plain layer needs two or three. + +use std::sync::OnceLock; + +use super::consts::{MAP16, MAP32}; +use super::kit::SHADER; +use super::{Kernel, Unsupported, first_error}; + +/// Why documents with layer effects can't use the GPU compositor on this device. +pub(crate) const NO_EFFECT_MAPS: &str = "layer effects need float effect-map render targets, which this GPU lacks"; + +/// Every pipeline of one compositor, shared by its siblings. +/// +/// No shader is used by two threads at once (#9173): wgpu-hal's D3D12 backend caches each +/// compiled shader and hands every pipeline a reference to it, but FXC's blobs count references +/// without atomics (gfx-rs/wgpu#10547), so threads sharing one could free it while the cache still +/// held it, and dropping the device then aborted the process. So each kernel has its own vertex +/// entry point ([`vertex_shader`]), a kernel's pipelines for its target formats are built +/// together on one thread, and every build in the process holds [`building`]: the tables of +/// several compositors on one device compile the same shaders. +pub(crate) struct Pipelines { + module: wgpu::ShaderModule, + vertex: wgpu::ShaderModule, + layout: wgpu::PipelineLayout, + kernels: Vec, +} + +/// One kernel's pipelines, one per target format, built together. +pub(crate) struct KernelPipelines { + pub(crate) kernel: Kernel, + entry: &'static str, + /// Its own vertex entry point in [`Pipelines::vertex`]. + pub(crate) vertex: String, + pub(crate) formats: Vec, + /// Per format, the pipeline or the error building it raised. + built: OnceLock>>, +} + +/// Held by every pipeline build in the process (see [`Pipelines`]). +fn building() -> std::sync::MutexGuard<'static, ()> { + static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +impl Pipelines { + /// The shaders and layout of every pipeline of [`table`]. Builds no pipeline. + pub(crate) fn new(device: &wgpu::Device, acc_format: wgpu::TextureFormat, bgl0: &wgpu::BindGroupLayout, bgl1: &wgpu::BindGroupLayout) -> Self { + let kernels = table(acc_format); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let vertex = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("pc_compose_vertex"), + source: wgpu::ShaderSource::Wgsl(vertex_shader(kernels.iter().map(|k| k.vertex.as_str())).into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_compose"), + bind_group_layouts: &[Some(bgl0), Some(bgl1)], + immediate_size: 0, + }); + Self { module, vertex, layout, kernels } + } + + /// The pipeline drawing `kernel` into `format`, built now if no draw needed it before. A + /// pipeline the device can't build is an [`Unsupported`] for every draw that needs it, so + /// that refresh uses the CPU compositor. + pub(crate) fn get(&self, device: &wgpu::Device, kernel: Kernel, format: wgpu::TextureFormat) -> Result<&wgpu::RenderPipeline, Unsupported> { + let missing = || Unsupported(format!("the compositor has no {kernel:?} pipeline for {format:?}")); + let k = self.kernels.iter().find(|k| k.kernel == kernel).ok_or_else(missing)?; + let i = k.formats.iter().position(|&f| f == format).ok_or_else(missing)?; + let built = match k.built.get() { + Some(built) => built, + None => { + let _building = building(); + k.built.get_or_init(|| self.build(device, k)) + } + }; + built[i].as_ref().map_err(|e| { + Unsupported(if kernel.is_map() { + format!("{NO_EFFECT_MAPS} ({e})") + } else { + format!("couldn't build the compositor's `{}` pipeline: {e}", k.entry) + }) + }) + } + + /// Build every pipeline no draw has built yet, one kernel per thread of the current Rayon + /// pool (or one after another), and return the first error a non-map pipeline raised. Effect + /// maps render to R32Float / R16Float, which some adapters (e.g. GL without float render + /// targets) can't: a failed map pipeline only turns layer effects to the CPU compositor + /// ([`Self::effect_maps`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn build_all(&self, device: &wgpu::Device, sequential: bool) -> Option { + let _building = building(); + let missing: Vec<&KernelPipelines> = self.kernels.iter().filter(|k| k.built.get().is_none()).collect(); + let build = |k: &KernelPipelines| { + k.built.get_or_init(|| self.build(device, k)); + }; + if sequential { + missing.into_iter().for_each(build); + } else { + super::fx::par_map(missing, build); + } + let first_error = |maps: bool| { + self.kernels.iter().filter(|k| k.kernel.is_map() == maps).flat_map(|k| k.built.get().into_iter().flatten()).find_map(|b| b.as_ref().err().cloned()) + }; + if let Some(e) = first_error(true) { + log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); + } + first_error(false) + } + + /// `k`'s pipelines, each inside its own error scope on the calling thread (wgpu's scopes are + /// per thread). The caller holds [`building`]. + fn build(&self, device: &wgpu::Device, k: &KernelPipelines) -> Vec> { + k.formats + .iter() + .map(|&format| { + let (pipeline, error) = first_error(device, || { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(k.entry), + layout: Some(&self.layout), + vertex: wgpu::VertexState { module: &self.vertex, entry_point: Some(&k.vertex), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &self.module, + entry_point: Some(k.entry), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }); + match error { + Some(e) => Err(e.to_string()), + None => Ok(pipeline), + } + }) + .collect() + } + + /// Whether no effect-map pipeline has failed to build (one not built yet is assumed to work). + pub(crate) fn effect_maps(&self) -> bool { + self.kernels.iter().filter(|k| k.kernel.is_map()).all(|k| k.built.get().is_none_or(|b| b.iter().all(Result::is_ok))) + } + + /// How many pipelines have been built (or failed to build) so far, and how many there are. + pub(crate) fn counts(&self) -> (usize, usize) { + let built = self.kernels.iter().filter(|k| k.built.get().is_some()).map(|k| k.formats.len()).sum(); + (built, self.kernels.iter().map(|k| k.formats.len()).sum()) + } +} + +/// Every drawn kernel, none built yet: plain kernels draw into `acc_format`, effect-map kernels +/// into R32F and R16F maps. +pub(crate) fn table(acc_format: wgpu::TextureFormat) -> Vec { + let (plain, maps): (Vec, Vec) = Kernel::DRAWN.iter().partition(|k| !k.is_map()); + plain + .into_iter() + .chain(maps) + .filter_map(|kernel| Some((kernel, kernel.entry()?))) + .enumerate() + .map(|(i, (kernel, entry))| KernelPipelines { + kernel, + entry, + vertex: format!("vs_{i}"), + formats: if kernel.is_map() { vec![MAP32, MAP16] } else { vec![acc_format] }, + built: OnceLock::new(), + }) + .collect() +} + +/// The full-chunk triangle's vertex stage, once under each of `names` (`vs_0`, `vs_1`, ...): the +/// same code under distinct names, so each kernel compiles its own vertex shader. +/// +/// A workaround, not a design: wgpu-hal's D3D12 shader cache shares a compiled FXC blob between +/// threads, and FXC's blobs don't count references atomically, so a shared one can be freed +/// while still cached (gfx-rs/wgpu#10547, #9173). Each copy costs one compile of a three-line +/// shader. Once a wgpu release fixes the cache, go back to one `vs` in `compose.wgsl` and build +/// each pipeline on its own. +pub(crate) fn vertex_shader<'a>(names: impl Iterator) -> String { + let mut s = String::from( + "struct VOut { @builtin(position) pos: vec4 }; +", + ); + for name in names { + s.push_str(&format!( + "@vertex fn {name}(@builtin(vertex_index) vi: u32) -> VOut {{ + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); +}} +" + )); + } + s +} diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index e84b2571e4..9f4d44ac43 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -1,11 +1,10 @@ use super::batch::tile_grid; use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAX_PATTERN_TEXTURE_BYTES, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; -use super::kit::{Kit, SHADER, build_jobs, tex_entry, uniform_entry, vertex_shader}; +use super::kit::{Kit, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; +use super::pipelines::{NO_EFFECT_MAPS, Pipelines}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::{ - Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Kernel, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing, -}; +use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; /// Classification of a synchronous compositor pipeline build failure. /// @@ -55,84 +54,61 @@ impl Compositor { if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } } - /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a - /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back - /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed - /// to have worked. + /// [`Compositor::new_with_format`], but a shader the driver can't take is an `Err` instead of + /// a panic. Pipelines are built by the first draw that needs each one; one the driver can't + /// build (e.g. a D3D12 shader-compiler failure) makes that render [`Unsupported`], so the + /// caller falls back to the CPU compositor. Where errors only arrive asynchronously (WebGPU), + /// creation is assumed to have worked. pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { - match first_error(device, || Self::build(device, acc_format, false)) { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), + match first_error(device, || Self::build(device, acc_format)) { + (comp, None) => Ok(comp), + (_, Some(e)) => Err(Unsupported(format!("couldn't create the compositor: {e}"))), } } - /// Build pipelines using a dedicated Rayon pool instead of the process-wide pool. + /// [`Compositor::try_new_with_format`] that also builds every pipeline now, on a dedicated + /// Rayon pool of `threads` instead of the process-wide pool, so a failing one is an `Err` + /// here rather than on a later draw. /// - /// This keeps shader compilation from occupying workers needed by CPU compositing. - /// If the pool cannot be created, pipeline enumeration runs sequentially on the calling - /// thread. The outer and per-pipeline wgpu error scopes are kept on their respective - /// build threads. + /// The dedicated pool keeps shader compilation from occupying workers needed by CPU + /// compositing. If the pool cannot be created, the pipelines are built one after another on + /// the calling thread. #[cfg(not(target_arch = "wasm32"))] pub fn try_new_with_format_threads(device: &wgpu::Device, acc_format: wgpu::TextureFormat, threads: usize) -> Result { Self::try_new_with_format_threads_classified(device, acc_format, threads).map_err(|e| Unsupported(e.message)) } - /// Build the compositor pipelines with an explicit failure classification for callers - /// that cache deterministic failures across launches. Only recognized shader compiler + /// [`Compositor::try_new_with_format_threads`] with an explicit failure classification for + /// callers that cache deterministic failures across launches. Only recognized shader compiler /// diagnostics are marked deterministic; all other wgpu errors are transient or unknown. #[cfg(not(target_arch = "wasm32"))] pub fn try_new_with_format_threads_classified(device: &wgpu::Device, acc_format: wgpu::TextureFormat, threads: usize) -> Result { + let comp = Self::try_new_with_format(device, acc_format).map_err(|e| BuildFailure { kind: BuildFailureKind::TransientOrUnknown, message: e.0 })?; + let pipelines = &comp.kit.pipelines; let pool = rayon::ThreadPoolBuilder::new().num_threads(threads.max(1)).thread_name(|index| format!("photocraft-gpu-build-{index}")).build(); - let built = match pool { - Ok(pool) => pool.install(|| first_error(device, || Self::build(device, acc_format, false))), + let error = match pool { + Ok(pool) => pool.install(|| pipelines.build_all(device, false)), Err(e) => { log::warn!("GPU compositor: couldn't create dedicated build pool; building sequentially: {e}"); - first_error(device, || Self::build(device, acc_format, true)) + pipelines.build_all(device, true) } }; - match built { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), None) => { - let kind = classify_build_diagnostic(&e.to_string()); - Err(BuildFailure { kind, message: format!("couldn't build the compositor's pipelines: {e}") }) - } - (_, Some(e)) => { - Err(BuildFailure { kind: BuildFailureKind::TransientOrUnknown, message: format!("couldn't build the compositor's pipelines: {e}") }) - } + match error { + None => Ok(comp), + Some(e) => Err(BuildFailure { kind: classify_build_diagnostic(&e), message: format!("couldn't build the compositor's pipelines: {e}") }), } } /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), - /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. + /// which otherwise fails at render-pipeline creation. See `Compositor::preferred_acc_format`. + /// Pipelines are built on first use (see [`Compositor::try_new_with_format`]). pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { - let (comp, error) = Self::build(device, acc_format, false); - if let Some(e) = error { - log::error!("GPU compositor: couldn't build its pipelines: {e}"); - } - comp + Self::build(device, acc_format) } - /// The compositor and the first error raised building its (non-map) pipelines. They are - /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's - /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines - /// took about 8 s on one core (#6419). - /// - /// No shader is used by two threads at once (#9173): wgpu-hal's D3D12 backend caches each - /// compiled shader and hands every pipeline a reference to it, but FXC's blobs count - /// references without atomics (gfx-rs/wgpu#10547), so threads sharing one could free it - /// while the cache still held it, and dropping the device then aborted the process. So each - /// job has its own vertex entry point and fragment shaders ([`build_jobs`]), and builds of - /// several compositors take turns. - fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat, sequential: bool) -> (Self, Option) { - static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let _building = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); - let jobs = build_jobs(acc_format); - let vertex = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("pc_compose_vertex"), - source: wgpu::ShaderSource::Wgsl(vertex_shader(&jobs).into()), - }); + /// The compositor's shaders, layouts and pipeline table ([`Pipelines`]); no pipeline yet. + fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_uniforms"), entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], @@ -141,86 +117,29 @@ impl Compositor { label: Some("pc_compose_textures"), entries: &(0..8).map(tex_entry).collect::>(), }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_compose"), - bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], - immediate_size: 0, - }); - // `None` only for kernels without a fragment entry point, which are never drawn. - let pipeline = |k: Kernel, format: wgpu::TextureFormat, vs: &str| { - let entry = k.entry()?; - Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(entry), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &vertex, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(entry), - targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - })) - }; - // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float - // render targets) can't: then layer effects use the CPU compositor and the rest stays here. - let build_one = |job: super::kit::BuildJob| { - job.keys - .into_iter() - .map(|key| { - let (built, error) = first_error(device, || pipeline(key.0, key.1, &job.vertex)); - (key, built, error) - }) - .collect::>() - }; - let built: Vec<_> = if sequential { jobs.into_iter().map(build_one).collect() } else { fx::par_map(jobs, build_one) }; - let built = built.into_iter().flatten(); - let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); - let (mut error, mut map_error) = (None, None); - for (key, built, e) in built { - let map = key.0.is_map(); - // A failed map pipeline turns all effect maps off below. A failed non-map pipeline - // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would - // turn a validation error into a missing-key panic on the first draw. - if let Some(e) = e { - if map { - map_error.get_or_insert(e); - continue; - } - error.get_or_insert(e); - } - let Some(p) = built else { continue }; - if map { - maps.push((key, p)); - } else { - pipelines.insert(key, p); - } - } - if let Some(e) = &map_error { - log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); - } else { - pipelines.extend(maps); - } + let pipelines = std::sync::Arc::new(Pipelines::new(device, acc_format, &bgl0, &bgl1)); let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; let kit = Kit { pipelines, bgl0, bgl1, dummy }; - let comp = Self::from_kit(kit, device.limits().max_texture_dimension_2d, acc_format, map_error.is_none()); - (comp, error) + Self::from_kit(kit, device.limits().max_texture_dimension_2d, acc_format) + } + + /// Test hook: how many of the compositor's pipelines have been built so far (shared with its + /// siblings), and how many it has. + #[doc(hidden)] + pub fn pipeline_counts(&self) -> (usize, usize) { + self.kit.pipelines.counts() } /// Create an independent compositor on the same device, reusing compiled pipelines. /// Texture caches, budgets, focus and timing start at their defaults; no document state is /// shared. Render with the same device and queue as this compositor. pub fn sibling(&self) -> Self { - let mut sibling = Self::from_kit(self.kit.clone(), self.device_max, self.acc_format, self.effect_maps); + let mut sibling = Self::from_kit(self.kit.clone(), self.device_max, self.acc_format); sibling.health = self.health.clone(); sibling } - fn from_kit(kit: Kit, device_max: u32, acc_format: wgpu::TextureFormat, effect_maps: bool) -> Self { + fn from_kit(kit: Kit, device_max: u32, acc_format: wgpu::TextureFormat) -> Self { Self { kit, pool: Vec::new(), @@ -250,7 +169,6 @@ impl Compositor { admit_freed: 0, fail_allocs: 0, acc_format, - effect_maps, cmyk: 0, health: None, timer: None, @@ -455,8 +373,8 @@ impl Compositor { /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and /// patterns in one texture. pub(crate) fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { - if !self.effect_maps && !p.fx.is_empty() { - return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); + if !p.fx.is_empty() && !self.kit.pipelines.effect_maps() { + return Err(Unsupported(NO_EFFECT_MAPS.into())); } for f in &p.fx { if self.fx_paged(f.region) { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 50b8fdb6b5..62a69033a5 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -132,31 +132,26 @@ fn half_roundtrip() { } } -/// #9173: no two pipeline build jobs share a shader, so no FXC blob is shared across threads. +/// #9173: no two kernels' pipelines share a shader, so no FXC blob is shared across threads. #[test] -fn build_jobs_share_no_shader() { +fn kernel_pipelines_share_no_shader() { use super::consts::{MAP16, MAP32}; - use super::kit::{build_jobs, vertex_shader}; - let jobs = build_jobs(wgpu::TextureFormat::Rgba32Float); + use super::pipelines::{table, vertex_shader}; + let jobs = table(wgpu::TextureFormat::Rgba32Float); let mut seen = std::collections::HashSet::new(); for job in &jobs { - let fragments: std::collections::HashSet<_> = job.keys.iter().filter_map(|k| k.0.entry()).collect(); - for f in fragments { - assert!(seen.insert(f.to_string()), "fragment shader {f} is built by two jobs"); - } + let f = job.kernel.entry().expect("a drawn kernel"); + assert!(seen.insert(f.to_string()), "fragment shader {f} is built by two kernels"); assert!(seen.insert(job.vertex.clone()), "vertex entry {} is shared", job.vertex); } - // Every drawn pipeline is still built, in the same formats. - let keys: Vec<_> = jobs.iter().flat_map(|job| job.keys.iter().copied()).collect(); - let plain = Kernel::DRAWN.iter().filter(|k| !k.is_map()).count(); - assert_eq!(keys.len(), plain + 2 * (Kernel::DRAWN.len() - plain)); + // Every drawn kernel has its pipelines, in the same formats. for k in Kernel::DRAWN { - let formats: Vec<_> = keys.iter().filter(|key| key.0 == k).map(|key| key.1).collect(); + let formats: Vec<_> = jobs.iter().filter(|job| job.kernel == k).flat_map(|job| job.formats.iter().copied()).collect(); let want = if k.is_map() { vec![MAP32, MAP16] } else { vec![wgpu::TextureFormat::Rgba32Float] }; assert_eq!(formats, want, "{k:?}"); } - // The vertex module validates and has every job's entry point. - let src = vertex_shader(&jobs); + // The vertex module validates and has every kernel's entry point. + let src = vertex_shader(jobs.iter().map(|job| job.vertex.as_str())); let module = wgpu::naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src))); wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) .validate(&module) @@ -167,7 +162,7 @@ fn build_jobs_share_no_shader() { // The fragment module has no vertex stage, so the build can't fall back to one shared `vs`. let compose = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); let shared: Vec<_> = compose.entry_points.iter().filter(|ep| ep.stage == wgpu::naga::ShaderStage::Vertex).map(|ep| ep.name.as_str()).collect(); - assert!(shared.is_empty(), "compose.wgsl has a vertex entry point every job would share: {shared:?}"); + assert!(shared.is_empty(), "compose.wgsl has a vertex entry point every kernel would share: {shared:?}"); } #[test] diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 5301c49da7..9b4e2b62f8 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -135,7 +135,7 @@ fn gpu() -> Option { None } }; - let comp = timed("pipeline creation", compositor)?; + let comp = timed("compositor creation", compositor)?; let mut paged = comp.sibling(); paged.set_texture_limit(PAGED_LIMIT); Some(Gpu { device, queue, comp, paged, _lock: lock }) @@ -3067,15 +3067,16 @@ fn rgba16f_fallback_path_renders() { #[test] fn unbuildable_pipelines_are_an_error_not_a_panic() { - // The app falls back to the CPU compositor on Err; a panic here would crash it (as FXC once - // did on D3D12). A depth format can't be a colour target, so its pipelines fail to build. + // The app builds every pipeline up front and falls back to the CPU compositor on Err; a panic + // here would crash it (as FXC once did on D3D12). A depth format can't be a colour target, so + // its pipelines fail to build. let Some((adapter, device, _, _lock)) = any_device() else { return }; - let e = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Depth32Float).err().expect("depth target must fail"); + let e = Compositor::try_new_with_format_threads(&device, wgpu::TextureFormat::Depth32Float, 4).err().expect("depth target must fail"); assert!(e.0.contains("pipelines"), "{e}"); // The format the app picks builds (effect maps the adapter can't render are left out, not fatal). let f = Compositor::preferred_acc_format(&adapter); if adapter.get_texture_format_features(f).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { - assert!(Compositor::try_new_with_format(&device, f).is_ok()); + assert!(Compositor::try_new_with_format_threads(&device, f, 4).is_ok()); } } diff --git a/crates/gpu/tests/it/pipeline_errors.rs b/crates/gpu/tests/it/pipeline_errors.rs index e4cd97c52b..56b93b020d 100644 --- a/crates/gpu/tests/it/pipeline_errors.rs +++ b/crates/gpu/tests/it/pipeline_errors.rs @@ -1,6 +1,7 @@ -//! #6419: the compositor's pipelines are built on several threads. A pipeline the device can't -//! build is still an `Err` from `try_new_with_format`, not a panic from wgpu's default error -//! handler (error scopes are per thread). Skips when no GPU adapter exists. +//! #6419: the compositor's pipelines are built on several threads, or one by one on first use +//! (#15439). A pipeline the device can't build is an `Err` from the build or the draw, not a panic +//! from wgpu's default error handler (error scopes are per thread). Skips when no GPU adapter +//! exists. use std::sync::Arc; @@ -26,17 +27,16 @@ fn a_pipeline_built_on_another_thread_fails_as_an_error() { let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((adapter, device, _queue)) = device() else { return }; // Never a render target, so every accumulation pipeline fails validation. - let Err(e) = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgb9e5Ufloat) else { + let Err(e) = Compositor::try_new_with_format_threads(&device, wgpu::TextureFormat::Rgb9e5Ufloat, 4) else { panic!("a compositor accumulating into Rgb9e5Ufloat"); }; assert!(e.0.contains("couldn't build the compositor's pipelines"), "{e:?}"); // The device is still usable for a compositor it can build. - assert!(Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).is_ok()); + assert!(Compositor::try_new_with_format_threads(&device, Compositor::preferred_acc_format(&adapter), 4).is_ok()); } -/// `new_with_format` on a device whose errors go to the caller's handler: a pipeline that failed -/// to build stays in the compositor as an invalid handle, so a draw reports GPU errors instead of -/// panicking on a missing pipeline. +/// A compositor whose pipelines fail to build on first use, on a device whose errors go to the +/// caller's handler: the draw is an `Err`, not a panic. #[test] fn a_compositor_with_failed_pipelines_draws_without_panicking() { let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -46,10 +46,10 @@ fn a_compositor_with_failed_pipelines_draws_without_panicking() { let mut comp = Compositor::new_with_format(&device, wgpu::TextureFormat::Rgb9e5Ufloat); let doc = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.5, 0.5, 0.5, 1.0)); // Drawing into an unrenderable format can't succeed, but must not panic. - let _ = render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()); + assert!(render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).is_err()); } -/// #9173: the compositor builds its pipelines on several threads (#6419). On Direct3D 12 with FXC, +/// #9173: the threaded build builds the compositor's pipelines on several threads (#6419). On Direct3D 12 with FXC, /// wgpu-hal caches each compiled shader as an `ID3DBlob` whose reference count isn't atomic /// (gfx-rs/wgpu#10547), so two threads building pipelines from the same shader could free a blob /// the cache still holds; dropping the device then aborted the process (`null reference @@ -83,12 +83,12 @@ fn parallel_compositor_builds_leave_the_shader_cache_intact() { let format = Compositor::preferred_acc_format(&adapter); // The first build compiles every shader; the rest are cache hits, so their threads take // and release references to the cached shaders densely. The builds start together, so - // overlapping `Compositor::build` calls are exercised too (the process-wide lock). + // overlapping builds are exercised too (the process-wide lock). std::thread::scope(|scope| { let handles: Vec<_> = (0..builds) .map(|_| { scope.spawn(|| { - let built = Compositor::try_new_with_format(&device, format); + let built = Compositor::try_new_with_format_threads(&device, format, 4); assert!(built.is_ok(), "round {round}: {:?}", built.err()); }) }) diff --git a/crates/gpu/tests/it/pipelines.rs b/crates/gpu/tests/it/pipelines.rs index 119ace7d72..fa4b684ad9 100644 --- a/crates/gpu/tests/it/pipelines.rs +++ b/crates/gpu/tests/it/pipelines.rs @@ -9,6 +9,11 @@ //! //! The Windows CI runners have no GPU: their adapter is WARP over DX12, so this runs FXC there. +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Document; +use photocraft_geom::Size; +use photocraft_gpu::{Compositor, render_to_vec}; + use crate::GPU_LOCK; #[test] @@ -45,10 +50,42 @@ fn every_compositor_pipeline_builds() { continue; }; let info = adapter.get_info(); - let format = photocraft_gpu::Compositor::preferred_acc_format(&adapter); - if let Err(e) = photocraft_gpu::Compositor::try_new_with_format(&device, format) { + let format = Compositor::preferred_acc_format(&adapter); + // Draws build only the pipelines they use; this builds every one. + let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get); + if let Err(e) = Compositor::try_new_with_format_threads(&device, format, threads) { panic!("{:?} adapter {} (driver {}): {e}", info.backend, info.name, info.driver_info); } } } } + +/// #15439: a compositor builds a pipeline when a draw first needs it, so a process that draws one +/// layer compiles a few shaders, not all of them (FXC on the Windows runners' WARP adapter took +/// 3 to 7.5 s per process for all of them). Siblings share what any of them built. +#[test] +fn a_draw_builds_only_the_pipelines_it_uses() { + let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let instance = crate::instance(); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + return eprintln!("skipping: no adapter"); + }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { + return eprintln!("skipping: no device"); + }; + let mut comp = match Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)) { + Ok(c) => c, + Err(e) => return eprintln!("skipping: {e}"), + }; + let (built, all) = comp.pipeline_counts(); + assert_eq!(built, 0, "creating a compositor builds no pipeline"); + let doc = Document::with_background("one layer", Size::new(16, 16), ColorMode::Rgb, SampleType::U8, Color::rgba(0.25, 0.5, 0.75, 1.0)); + render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).expect("one layer renders on the GPU"); + let (one_layer, _) = comp.pipeline_counts(); + assert!(one_layer > 0 && one_layer * 4 < all, "one layer built {one_layer} of {all} pipelines"); + // Drawing it again, or from a sibling, builds nothing new. + render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).expect("second render"); + let mut sibling = comp.sibling(); + render_to_vec(&mut sibling, &device, &queue, &doc, doc.bounds()).expect("sibling render"); + assert_eq!(sibling.pipeline_counts(), (one_layer, all)); +} From cfa67e97f134670eddb3678df4c58af632bc3f41 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 18:51:43 +0000 Subject: [PATCH 06/25] Delay-load opengl32.dll on Windows MSVC (#15444) wgpu's GL backend (glutin_wgl_sys) puts opengl32.dll in the import table of every binary that links wgpu, and a process that has loaded it takes about 60 ms longer to exit. That is every Windows test process and every app exit on DX12 or Vulkan. Delay-load it from the workspace's .cargo/config.toml, the one place that reaches every package's binaries (a build script's link arguments reach only its own package). Cargo joins these flags with the CARGO_TARGET__RUSTFLAGS set by CI and the Windows packaging script. The print DLLs keep their delay-loads in the app's and CLI's build.rs, since the exe must start without them whatever invokes cargo. --- .cargo/config.toml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.cargo/config.toml b/.cargo/config.toml index 5592118f6c..11a0baa22e 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,14 @@ [alias] xtask = "run -p xtask --" + +# wgpu's GL backend (glutin_wgl_sys) imports opengl32.dll, so every binary that links wgpu loads +# it at start, and a process that has loaded it takes about 60 ms longer to exit (#15444): every +# test process and every app exit on DX12 or Vulkan. Delay-loaded, it loads on the first WGL +# call, which only the GL backend makes. Here rather than in a build script, because a link +# argument from a build script reaches only its own package's binaries, and every package whose +# binaries link wgpu would need one. Cargo joins these with `CARGO_TARGET__RUSTFLAGS` +# (CI, packaging); only `RUSTFLAGS` replaces them. The print DLLs' delay-loads stay in the app's +# and CLI's build.rs: without those the exe doesn't start on some Windows images (#5884), so +# they must hold for any cargo invocation, also one that never reads this file. +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-Clink-arg=/DELAYLOAD:opengl32.dll", "-Clink-arg=delayimp.lib"] From 0e3523cdcdf240f1e7cdd55ed2e6dad664dcc8a1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:04:43 +0000 Subject: [PATCH 07/25] CI: shard the Linux and Windows tests, lint leg, xtask environment fix, rust-cache v2.9.3 - xtask starts every cargo without the variables `cargo run` sets for xtask (CARGO_MANIFEST_DIR, CARGO_PKG_*, ...), so a build script that declares `rerun-if-env-changed` for them (ring) no longer reruns, with the whole craft facade above it, between builds inside and outside xtask. - `cargo xtask ci` splits into the gate's parts without a second step list: `lint` (fmt, egui-fork, clippy, layers, panel-commands, scorecard, wasm, i18n report), `archive` (test build into the nextest archive, doctests), `tests --from ` (test and panic_hunt from the extracted archive, on $NEXTEST_PARTITION; --gpu / --no-gpu select by the gpu test group) and `build` (cache warm-up). Plain `cargo xtask ci` still runs every step. PHOTOCRAFT_CI_EXCLUDE leaves packages out of the test build and doctests. - The `ci` nextest profile's archive carries the xtask binary, so a shard builds nothing (scripts/ci-test-shard.sh). - Linux gate: lint leg, one build, four shards. Shard 1 runs the gpu group alone on lavapipe and checks its output (scripts/ci-gpu-lavapipe.py now wraps that run); the second GPU run and its rebuild are gone. - Windows unit, integration, clippy and warm legs move onto the shared gate (Windows runner, lint leg for Clippy, four shards), keeping the PR selection from the platforms job, rust-lld, /OPT:NOICF, /DEBUG:NONE and the D:\t target dir. - The slowest-tests-first priorities apply on Linux too. - Swatinem/rust-cache v2.9.3 by commit for this repository's own cache steps, with fresh keys; cache-version v2 for the gate and docs entries. `test (without heif)` restores the gate's entry through the shared action. Dispatch-only jobs no longer save caches no pull request reads; the quick perf suite restores perf-nightly's entry. - windows_delay_loads reads the app from NEXTEST_BIN_EXE_photocraft, as the other app tests do, since archives relocate binaries. --- .config/nextest.toml | 17 +- .github/workflows/ci.yml | 295 ++++-------- .github/workflows/docs.yml | 2 +- .github/workflows/perf-nightly.yml | 3 +- apps/photocraft/tests/windows_delay_loads.rs | 3 +- docs/development.md | 3 +- scripts/ci-gpu-lavapipe.py | 51 ++- scripts/ci-test-shard.sh | 34 ++ scripts/test-ci-gpu-lavapipe.py | 34 +- xtask/src/cargo_env.rs | 70 +++ xtask/src/main.rs | 456 ++++++++++++++++--- 11 files changed, 646 insertions(+), 322 deletions(-) create mode 100755 scripts/ci-test-shard.sh create mode 100644 xtask/src/cargo_env.rs diff --git a/.config/nextest.toml b/.config/nextest.toml index ee1a1a5390..d4ed05c1a6 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -11,7 +11,8 @@ nextest-version = "0.9.150" # # GPU tests: each test is its own process here, so the in-process `gpu_lock()` mutexes no longer # serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so -# this group caps them at 4. scripts/ci-gpu-lavapipe.py reads this group's filters directly. +# 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). [test-groups] gpu = { max-threads = 4 } @@ -26,6 +27,12 @@ test-group = 'gpu' fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" +# The gate's shards run the tests from a nextest archive (`cargo xtask ci archive`) and start them +# with the xtask binary the archive carries, so a shard builds nothing. Only one of the two exists. +archive.include = [ + { path = "debug/xtask", relative-to = "target", depth = 0, on-missing = "ignore" }, + { path = "debug/xtask.exe", relative-to = "target", depth = 0, on-missing = "ignore" }, +] # Keep phase timings for the remaining expensive Windows GPU regressions visible. This does # not relax their timeout, isolate failures differently or remove any test cases. @@ -48,11 +55,10 @@ threads-required = 2 # Slowest tests start first. nextest starts higher-priority tests first, so a long test no longer # begins at the end of the run and extends the job. Every test that took over 60 s on the Windows -# runner in the cold run of #15474 (unit and integration legs); the list names the test, so a test -# that gets faster stays harmless and a new slow one is added here. Priority only orders the -# start; it changes no timeout, group or result. +# runner in the cold run of #15474 (unit and integration legs); the same tests are the slowest on +# Linux. The list names the test, so a test that gets faster stays harmless and a new slow one is +# added here. Priority only orders the start; it changes no timeout, group or result. [[profile.ci.overrides]] -platform = 'cfg(target_os = "windows")' # over 200 s filter = ''' (package(photocraft-ui-egui) & test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is)) | @@ -64,7 +70,6 @@ filter = ''' priority = 100 [[profile.ci.overrides]] -platform = 'cfg(target_os = "windows")' # 60 to 200 s filter = ''' (package(photocraft-gpu) & test(=camera_raw::clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages)) | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1995b78014..f243587b31 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,8 @@ name: CI -# Quality gates for every push to main and every pull request. The Linux gate runs through the -# suite's shared gate workflow in craft-common-actions (`cargo xtask ci`); the Windows legs, the -# test variant and the corpus, web and fuzz jobs are PhotoCraft's own. +# Quality gates for every push to main and every pull request. The Linux and Windows tests run +# through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the +# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. on: push: branches: [main] @@ -135,10 +135,22 @@ jobs: fi gpu=$(python3 scripts/ci-windows-gpu-tests.py "$BASE") echo "windows_gpu=$gpu" >> "$GITHUB_OUTPUT" + if [ "$gpu" = false ]; then + echo "::notice::photocraft-gpu's tests are skipped on Windows: this pull request changes nothing they are built from (the Linux gate still runs them)." + fi skip=$(python3 scripts/ci-windows-gpu-tests.py --skip-neutral "$BASE") echo "windows_skip=$skip" >> "$GITHUB_OUTPUT" + if [ -n "$skip" ]; then + echo "::notice::Tests of platform-neutral packages the pull request does not reach are skipped on Windows (the Linux gate still runs them): $skip" + fi - # The Linux gate. Its rust-cache entry is the one `test (without heif)` restores. + # The Linux gate (craft-common-actions gate.yml). Its `lint` leg runs the checks that need no test + # build; its build job builds the tests once into a nextest archive and runs the doctests; four + # test shards run the tests from that archive. Shard 1 runs nextest's `gpu` group alone, on + # lavapipe, and fails on a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split + # the other tests. With the five slowest UI tests (three of them in the `gpu` group) the GPU shard + # takes ~12 min of tests and the others ~8. Its rust-cache entry is the one `test (without heif)` + # restores. gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. @@ -153,199 +165,71 @@ jobs: craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 # Cargo.toml's dev profile already keeps line tables only. dev-debug: "" + cache-version: v2 env: | PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }} PHOTOCRAFT_NO_PRINT=1 LPDEST=photocraft-no-such-printer timeout-minutes: 100 - # On main, a `cache warm` leg builds the tests and saves the dependency cache as soon as the - # build succeeds; the gate legs then only restore, so a failing test cannot keep the entry - # from being saved (craft-common-actions#270). The same targets as the gate's test step (TEST_TARGETS in xtask/src/main.rs). - warm-command: cargo test --workspace --no-run --locked --features heif --lib --bins --tests - # fmt, clippy, layers, panel-commands, scorecard, tests, panic_hunt, doctests and the wasm32 check, with - # `--locked --features heif`, then the missing-translations report (xtask/src/main.rs). - command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci && python3 scripts/ci-gpu-lavapipe.py + # On main, a `cache warm` leg builds xtask and the tests and saves the dependency cache as + # soon as the build succeeds; the build job then only restores, so a failing test cannot keep + # the entry from being saved (craft-common-actions#270). The lint leg keeps its own entry. + warm-command: cargo xtask ci build + # fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the + # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' + # own tests. + lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint + test-shards: 4 + # The test build with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs) into + # $NEXTEST_ARCHIVE_FILE, then the doctests. + archive-command: cargo xtask ci archive + # The tests and panic_hunt, from the archive. + shard-command: bash scripts/ci-test-shard.sh --gpu-shard - # Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job - # they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration - # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is - # tracked by storytold/craft-common-actions#212. + # The Windows tests and Clippy on the same gate, when `platforms` says the run needs them: a + # `lint` leg runs Clippy, the build job builds the tests into a nextest archive and runs the + # doctests, and four shards split the tests (Windows runs them ~1.75x slower than Linux, ~50 min + # of tests on one runner). The browser apps are wasm targets, so their native tests are left out; + # pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they change + # reaches (`windows_gpu`, `windows_skip`). The `cache warm` leg (main only) builds what main's + # build job builds. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' - timeout-minutes: 100 - name: test (windows-latest, ${{ matrix.part }}) - runs-on: windows-latest - strategy: - fail-fast: false - matrix: - # `warm` builds everything the other legs build and saves the dependency cache. Only main - # runs it; the other legs only restore. - part: ${{ fromJSON(github.ref == 'refs/heads/main' && '["unit","integration","clippy","warm"]' || '["unit","integration","clippy"]') }} - env: - # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit - # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. - # The dependency rust-cache below stays enabled; only compiler caching is disabled. - RUSTC_WRAPPER: "" + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-latest"]' + # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with + # kittest's strict `MissingGlyphPolicy::Panic`, and a hosted Windows image has no guaranteed + # Japanese or Simplified Chinese system font. Same pinned central fonts as Linux and release. + craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 + # No wasm32 check on Windows: the Linux lint leg runs it. + targets: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). - CARGO_PROFILE_DEV_DEBUG: "0" - # The Windows compiler command line carries one -L path per built dependency; keep each - # target path short enough for CreateProcess when the graph is large. - CARGO_TARGET_DIR: 'D:\t' - # rust-lld (shipped with the toolchain) links the test binaries instead of link.exe, and the - # test links skip identical-code folding and PDBs. The link arguments in build.rs - # (/DELAYLOAD, delayimp.lib) are lld-link options too. - CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER: rust-lld - CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS: -Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE - # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels - # with kittest's strict `MissingGlyphPolicy::Panic`. A hosted Windows image has no - # guaranteed Japanese or Simplified Chinese system font, and egui 0.37 panics on a - # missing glyph; the app's lazy system fallback runs after layout, too late for the - # first headless frame. Use the same pinned central fonts as Linux and release, so every - # language is drawn by a real embedded face rather than skipping. Same commit as the gate - # above and release.yml. - CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts - CRAFT_FONTS_REQUIRED: "1" - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Check out craft-fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: storytold/craft-fonts - ref: cc9269cd8d8258785dac603fba3122e5d2556795 - path: craft-fonts - persist-credentials: false - - # The translations at the commit in craft-i18n.rev, as the gate and release.yml embed them - # (sets CRAFT_I18N_DIR and CRAFT_I18N_REQUIRED=1). - - name: Check out craft-i18n - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: stable - components: clippy - - # rust-cache only looks at `/` (it joins the two), so the short - # CARGO_TARGET_DIR above must be passed as a path relative to the checkout. Without it the - # cache found nothing to restore or save and every run built all dependencies from scratch. - - name: Target directory for the dependency cache - id: cache-target - # An empty path would make rust-cache treat the checkout itself as the target directory, - # which its cleanup then prunes, so stop rather than write one. - run: | - relative=$(realpath -m --relative-to="$(cygpath -u "$GITHUB_WORKSPACE")" "$(cygpath -u "$CARGO_TARGET_DIR")") - if [ -z "$relative" ] || [ "$relative" = . ]; then - echo "::error::no target directory for rust-cache from CARGO_TARGET_DIR='$CARGO_TARGET_DIR'" - exit 1 - fi - echo "relative=$relative" >> "$GITHUB_OUTPUT" - shell: bash - - # Only main saves caches; PRs restore main's, so the repo's 10 GB cache budget keeps main's. - # All legs share one key (same dependencies). Only the `warm` leg saves it, as soon as the - # build is done and before any test runs, so a failing test never keeps the entry from being - # saved. It also runs Clippy, so the entry holds Clippy's dependency metadata for the `clippy` - # leg. A failed warm run saves nothing: an entry saved from a half-finished build would lack - # dependencies, and rust-cache never replaces an entry with the same key, so every later run - # would restore that half-filled entry until Cargo.lock changes. - # v2.9.1 on purpose: v2.9.2 is an ES-module bundle in which minimatch's `require('path')` fails, - # so it assumes "/" as the path separator and, on Windows, its glob never matches a backslash - # path. The save step then finds no cache paths ("Path Validation Error") and never saves. - # v2.9.1 is the last release with the CommonJS bundle. Move back once a release fixes this. - - uses: step-security/rust-cache@851174d9a2fdc03e0896e02844dcc61d81dd7851 # v2.9.1 - with: - workspaces: . -> ${{ steps.cache-target.outputs.relative }} - save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'warm' }} - cache-on-failure: false - - # Clippy has its own parallel leg: after the test build it ran in the integration leg's - # critical path (#15446). - - name: Clippy - if: matrix.part == 'clippy' - run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings - - - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 - if: matrix.part != 'clippy' && matrix.part != 'warm' - with: - tool: cargo-nextest@0.9.150 - - # The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every - # integration-test target); the feature selection stays the same, so both legs share the - # dependency cache. photocraft-gpu's tests run when the `platforms` job says they can be - # affected (`windows_gpu`); excluding the package also skips building its test binaries. - - name: Test - if: matrix.part != 'clippy' - env: - PART: ${{ matrix.part }} - GPU: ${{ needs.platforms.outputs.windows_gpu }} - SKIP_NEUTRAL: ${{ needs.platforms.outputs.windows_skip }} - run: | - case "$PART" in - unit) targets=(--lib --bins) ;; - warm) targets=(--lib --bins --test '*') ;; - *) targets=(--test '*') ;; - esac - # The two browser apps are wasm targets; their native test builds check nothing the web job - # (and the Linux gate's wasm32 check) does not. Excluding them changes no other crate's - # features (`cargo tree -e features --workspace` is identical for every other package). - skip=(--exclude photocraft-web --exclude photocraft-web-boot) - # Only an explicit `false` skips them: a missing output runs everything. - if [ "$GPU" = false ]; then - skip+=(--exclude photocraft-gpu) - echo "::notice::photocraft-gpu's tests are skipped on Windows: this pull request changes nothing they are built from (the Linux gate still runs them)." - fi - # nextest reuses this build. The separate step writes cargo's --timings report for it. - # Pull requests without `full-ci` also skip the packages with no platform-specific code - # that nothing in the pull request reaches (scripts/ci-windows-gpu-tests.py); the Linux - # gate runs them. Main and `full-ci` run everything. - if [ -n "$SKIP_NEUTRAL" ]; then - for package in $SKIP_NEUTRAL; do skip+=(--exclude "$package"); done - echo "::notice::Tests of platform-neutral packages the pull request does not reach are skipped on Windows (the Linux gate still runs them): $SKIP_NEUTRAL" - fi - cargo test --no-run --timings --workspace "${skip[@]}" --locked --features heif "${targets[@]}" - if [ "$PART" != warm ]; then - cargo nextest run --profile ci --workspace "${skip[@]}" --locked --features heif "${targets[@]}" - fi - shell: bash - - # Fills the cache entry's Clippy metadata (the `clippy` leg only restores it). A Clippy - # failure is the `clippy` leg's to report, not a reason to skip saving the cache. - - name: Clippy dependency metadata - if: matrix.part == 'warm' - continue-on-error: true - run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings - - # Per-crate compile and link times of this leg's build (open the HTML in a browser). - - name: Upload cargo build timings - if: always() && matrix.part != 'clippy' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: cargo-timings-windows-${{ matrix.part }} - # CARGO_TARGET_DIR above; the glob needs forward slashes. - path: D:/t/cargo-timings/*.html - if-no-files-found: ignore - retention-days: 14 - - - name: Doctests - if: matrix.part == 'unit' - env: - SKIP_NEUTRAL: ${{ needs.platforms.outputs.windows_skip }} - run: | - skip=(--exclude photocraft-web --exclude photocraft-web-boot) - for package in $SKIP_NEUTRAL; do skip+=(--exclude "$package"); done - cargo test --workspace "${skip[@]}" --locked --features heif --doc - shell: bash + dev-debug: "0" + cache-version: v2 + # CARGO_TARGET_DIR: the Windows compiler command line carries one -L path per built + # dependency; a short target path keeps it within CreateProcess's limit. rust-lld (shipped + # with the toolchain) links the test binaries instead of link.exe, and the test links skip + # identical-code folding and PDBs; the link arguments in build.rs (/DELAYLOAD, delayimp.lib) + # are lld-link options too. + env: | + PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }} + PHOTOCRAFT_NO_PRINT=1 + LPDEST=photocraft-no-such-printer + CARGO_TARGET_DIR=D:\t + CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER=rust-lld + CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE + PHOTOCRAFT_CI_EXCLUDE=photocraft-web photocraft-web-boot ${{ needs.platforms.outputs.windows_gpu == 'false' && 'photocraft-gpu' || '' }} ${{ needs.platforms.outputs.windows_skip }} + timeout-minutes: 100 + warm-command: cargo xtask ci build + lint-command: cargo xtask ci clippy + test-shards: 4 + archive-command: cargo xtask ci archive + shard-command: bash scripts/ci-test-shard.sh # The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error # for distributors who leave it out. Runs beside the gate and restores the gate's dependency @@ -386,12 +270,14 @@ jobs: with: toolchain: stable - # gate.yml keys its cache `-rust--gate`. - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + # The gate's own key (the shared action computes it), restore only. The toolchain action + # exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of + # the key. + - uses: storytold/craft-common-actions/actions/rust-cache@main with: - prefix-key: v1-rust - shared-key: ${{ hashFiles('Cargo.toml') }}-gate - save-if: false + cache-version: v2 + job: gate + align-environment: "true" - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 with: @@ -427,8 +313,9 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: + prefix-key: v1-rust key: corpus save-if: ${{ github.ref == 'refs/heads/main' }} cache-on-failure: true @@ -470,8 +357,9 @@ jobs: with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: + prefix-key: v1-rust key: ci-web save-if: ${{ github.ref == 'refs/heads/main' }} cache-on-failure: true @@ -546,9 +434,6 @@ jobs: with: toolchain: nightly - run: rustc -Vv - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - workspaces: crates/${{ matrix.target.crate }}/fuzz - name: Install cargo-fuzz run: cargo install cargo-fuzz --locked - name: Fuzz @@ -586,9 +471,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: color-range-perf - name: Compare exact outputs and release timings on 24 MP run: | set -o pipefail @@ -622,9 +504,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: selection-morphology-perf - name: Compare exact outputs and release timings on 36 MP run: | set -o pipefail @@ -657,9 +536,12 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + # perf-nightly.yml's entry (same key and runner); only that job saves it. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: + prefix-key: v1-rust key: perf-release + save-if: false - name: Quick performance suite run: cargo xtask perf --quick - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -687,9 +569,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - key: selection-combining-perf - name: Compare exact outputs and release timings on 36 MP run: | set -o pipefail @@ -723,12 +602,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 - with: - workspaces: | - before -> target - after -> target - key: brush-tip-release - name: Build the same benchmark against both versions run: | cp after/crates/paint/examples/big_dab_bench.rs before/crates/paint/examples/big_dab_bench.rs diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 443638eb73..2edb7a3931 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -38,5 +38,5 @@ jobs: free-disk-space: false # Prebuilt mdBook, the version cargo install built before. tools: mdbook@0.4.52 - cache-version: v1-docs + cache-version: v2-docs command: mdbook build book diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index 488ca56126..3e1bdfd67e 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -55,8 +55,9 @@ jobs: with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: + prefix-key: v1-rust key: perf-release - name: Run benchmarks diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index f7b7504ced..14143fea87 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -10,7 +10,8 @@ const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; /// The built exe names each print-only DLL in its delay-load table, never its import table. #[test] fn print_only_system_dlls_are_delay_loaded() { - let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); + // Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. + let exe = std::fs::read(std::env::var_os("NEXTEST_BIN_EXE_photocraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft").into())).unwrap(); let pe = Pe::parse(&exe); let imports = pe.dll_names(1, 20, 12); let delayed = pe.dll_names(13, 32, 4); diff --git a/docs/development.md b/docs/development.md index 3b14f7dbc2..3f5872d712 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,6 +45,7 @@ cargo run --release -p photocraft -- --control 7878 --control-token-file .privat cargo test --workspace # everything cargo xtask test # tests (nextest when installed) + doctests cargo xtask ci # the CI gate: fmt, clippy, layers, scorecard, tests, panic_hunt, doctests, wasm, i18n report +cargo xtask ci lint # only the gate's steps that need no test build (its lint leg) cargo xtask stats # tests and lines per crate cargo xtask parity # Photoshop menu coverage -> docs/parity-checklist.md ``` @@ -113,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. After the regular gate, `python3 scripts/ci-gpu-lavapipe.py` reruns the configured `gpu` group with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected. It requires Vulkan parity evidence and rejects authored skips, except the documented software-adapter timing exceptions. It reads the filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1` and run the same script. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index 4d1fe78661..7ff41e10c7 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -1,21 +1,19 @@ #!/usr/bin/env python3 -"""Run the configured GPU group on lavapipe without silently losing comparisons.""" +"""Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. + +The Linux gate runs nextest's `gpu` test group in a shard of its own through this script +(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu +device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output +is checked here for authored skips and for the parity tests' Vulkan backend line. + +Usage: ci-gpu-lavapipe.py COMMAND [ARGS...] +""" import glob import os -from pathlib import Path import re import subprocess import sys import tempfile -import tomllib - - -def gpu_filter(config): - filters = [row['filter'] for row in config['profile']['default']['overrides'] - if row.get('test-group') == 'gpu'] - if not filters: - raise ValueError('nextest GPU group has no filters') - return ' | '.join(f'({value})' for value in filters) def validate_log(lines): @@ -37,23 +35,16 @@ def validate_log(lines): return rejected -def main(): - root = Path(__file__).resolve().parents[1] - with (root / '.config/nextest.toml').open('rb') as source: - selected = gpu_filter(tomllib.load(source)) - icds = sorted(glob.glob('/usr/share/vulkan/icd.d/lvp_icd*.json')) - if not icds: - raise RuntimeError('Install mesa-vulkan-drivers and libvulkan1 before this check') +def run(command, icds, out=sys.stdout): + """Runs `command` on the Vulkan drivers in `icds`; returns its exit status, or 1 when it passed + but its output shows a skipped comparison.""" env = dict(os.environ, WGPU_BACKEND='vulkan', VK_ICD_FILENAMES=os.pathsep.join(icds)) - command = ['cargo', 'nextest', 'run', '--profile', 'ci', '--workspace', '--locked', - '--features', 'heif', '--lib', '--bins', '--tests', '-E', selected, - '--success-output', 'immediate', '--color', 'never'] # Stream output and keep it on disk, rather than buffering every successful test in memory. with tempfile.TemporaryFile(mode='w+t') as log: - with subprocess.Popen(command, cwd=root, env=env, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, text=True) as process: + with subprocess.Popen(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) as process: for line in process.stdout: - sys.stdout.write(line) + out.write(line) log.write(line) result = process.wait() log.seek(0) @@ -63,5 +54,15 @@ def main(): return result if result else int(bool(errors)) +def main(argv): + if not argv: + print(__doc__, file=sys.stderr) + return 2 + icds = sorted(glob.glob('/usr/share/vulkan/icd.d/lvp_icd*.json')) + if not icds: + raise RuntimeError('Install mesa-vulkan-drivers and libvulkan1 before this check') + return run(argv, icds) + + if __name__ == '__main__': - sys.exit(main()) + sys.exit(main(sys.argv[1:])) diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh new file mode 100755 index 0000000000..0420e0c67d --- /dev/null +++ b/scripts/ci-test-shard.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's +# build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive +# carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps +# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, +# GATE_SHARDS and NEXTEST_PARTITION. +# +# ci-test-shard.sh the shard runs its hash partition of every test +# ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by +# scripts/ci-gpu-lavapipe.py; the other shards split the other tests +set -euo pipefail + +archive=target/nextest-archive +mkdir -p "$archive" +cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --extract-to "$archive" --extract-overwrite -E 'none()' --no-tests=pass +xtask=("$archive/target/debug/xtask" ci tests --from "$archive") + +case "${1:-}" in + "") exec "${xtask[@]}" ;; + --gpu-shard) + if [ "$GATE_SHARDS" -lt 2 ]; then + echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" + exit 1 + fi + if [ "$GATE_SHARD" = 1 ]; then + exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu + fi + NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu + ;; + *) + echo "usage: $0 [--gpu-shard]" >&2 + exit 2 + ;; +esac diff --git a/scripts/test-ci-gpu-lavapipe.py b/scripts/test-ci-gpu-lavapipe.py index e2a21a96ad..b389c26141 100644 --- a/scripts/test-ci-gpu-lavapipe.py +++ b/scripts/test-ci-gpu-lavapipe.py @@ -1,5 +1,7 @@ import importlib.util +import io from pathlib import Path +import sys import unittest spec = importlib.util.spec_from_file_location('gpu_check', Path(__file__).with_name('ci-gpu-lavapipe.py')) @@ -29,15 +31,29 @@ class LogChecks(unittest.TestCase): 'SKIP the comparison: this GPU finishes a 6 MP composite in 1 ms against 2 ms of encoding', 'SKIP the sum: this refresh still fit one command buffer'])) - def test_selects_all_gpu_filters_from_config(self): - config = {'profile': {'default': {'overrides': [ - {'filter': 'package(a)', 'test-group': 'gpu'}, - {'filter': 'package(b)', 'test-group': 'cpu'}, - {'filter': 'test(c)', 'test-group': 'gpu'}]}}} - self.assertEqual(check.gpu_filter(config), '(package(a)) | (test(c))') - config['profile']['default']['overrides'] = [] - with self.assertRaises(ValueError): - check.gpu_filter(config) + +class Wrapper(unittest.TestCase): + """The gate's GPU shard runs xtask through `run`: its output is shown and checked.""" + + def status(self, script, icds=('/icd/lvp_icd.x86_64.json',)): + out = io.StringIO() + return check.run([sys.executable, '-c', script], list(icds), out), out.getvalue() + + def test_runs_on_the_given_vulkan_driver_and_shows_the_output(self): + status, out = self.status( + "import os; print('GPU parity backend: Vulkan', os.environ['WGPU_BACKEND'], os.environ['VK_ICD_FILENAMES'])") + self.assertEqual(status, 0) + self.assertIn('GPU parity backend: Vulkan vulkan /icd/lvp_icd.x86_64.json', out) + + def test_a_passing_run_with_a_skip_fails(self): + status, _ = self.status("print('GPU parity backend: Vulkan'); print('skipping GPU parity tests: no device')") + self.assertEqual(status, 1) + status, _ = self.status("print('no parity test ran')") + self.assertEqual(status, 1) + + def test_a_failing_run_keeps_its_status(self): + status, _ = self.status("print('GPU parity backend: Vulkan'); raise SystemExit(100)") + self.assertEqual(status, 100) if __name__ == '__main__': diff --git a/xtask/src/cargo_env.rs b/xtask/src/cargo_env.rs new file mode 100644 index 0000000000..0678706b5f --- /dev/null +++ b/xtask/src/cargo_env.rs @@ -0,0 +1,70 @@ +//! The environment of the cargo processes xtask starts. +//! +//! `cargo xtask` is `cargo run -p xtask`, so xtask runs with the variables Cargo sets for the +//! binary it runs: `CARGO_MANIFEST_DIR`, `CARGO_PKG_NAME`, `CARGO_PKG_VERSION_*` and the rest, all +//! describing xtask. A cargo started from xtask passes them on to every build script it runs. Cargo +//! compares a build script's `rerun-if-env-changed` variables with its own environment, so a script +//! that declares one of them (ring declares `CARGO_PKG_NAME` and the version parts) reruns, and +//! everything that depends on it rebuilds, each time one build starts inside xtask and the next +//! outside it (a CI script, the cache warm-up, a developer's own `cargo test`). + +use std::ffi::OsStr; +use std::process::Command; + +/// Whether `name` is a variable Cargo sets for the binary `cargo run` starts (rather than one it +/// reads from the environment of whoever started it). `CARGO` stays: it names the cargo that ran +/// xtask, which is the one xtask starts. +pub fn set_by_cargo_run(name: &OsStr) -> bool { + let Some(name) = name.to_str() else { return false }; + matches!(name, "CARGO_MANIFEST_DIR" | "CARGO_MANIFEST_PATH" | "CARGO_CRATE_NAME" | "CARGO_BIN_NAME" | "CARGO_PRIMARY_PACKAGE" | "OUT_DIR") + || name.starts_with("CARGO_PKG_") + || name.starts_with("CARGO_BIN_EXE_") +} + +/// Removes from `cmd` every variable of the current environment that Cargo set for this binary, +/// so the cargo it starts sees the environment xtask itself was started with. +pub fn without_cargo_run_vars(cmd: &mut Command) -> &mut Command { + for (name, _) in std::env::vars_os() { + if set_by_cargo_run(&name) { + cmd.env_remove(name); + } + } + cmd +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn removes_only_the_variables_cargo_run_sets() { + for name in [ + "CARGO_MANIFEST_DIR", + "CARGO_MANIFEST_PATH", + "CARGO_PKG_NAME", + "CARGO_PKG_VERSION_PRE", + "CARGO_CRATE_NAME", + "CARGO_BIN_NAME", + "CARGO_PRIMARY_PACKAGE", + "CARGO_BIN_EXE_photocraft", + "OUT_DIR", + ] { + assert!(set_by_cargo_run(OsStr::new(name)), "{name}"); + } + // What the developer or CI set: build settings, the target dir, the cargo to run. + for name in ["CARGO", "CARGO_HOME", "CARGO_TARGET_DIR", "CARGO_INCREMENTAL", "CARGO_PROFILE_DEV_DEBUG", "RUSTFLAGS", "PATH", "PKG_CONFIG_PATH"] { + assert!(!set_by_cargo_run(OsStr::new(name)), "{name}"); + } + } + + // A test process runs with the variables Cargo sets for test binaries, CARGO_PKG_NAME among them. + #[test] + fn a_child_cargo_does_not_inherit_them() { + assert!(std::env::var_os("CARGO_PKG_NAME").is_some(), "cargo sets CARGO_PKG_NAME for tests"); + let mut cmd = Command::new("true"); + without_cargo_run_vars(&mut cmd); + let removed: Vec<_> = cmd.get_envs().filter(|(_, value)| value.is_none()).map(|(name, _)| name.to_owned()).collect(); + assert!(removed.iter().any(|name| name == "CARGO_PKG_NAME"), "{removed:?}"); + assert!(removed.iter().all(|name| set_by_cargo_run(name)), "{removed:?}"); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3fe247e33c..d854afd74f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -3,6 +3,7 @@ //! Pure Rust (std + serde_json). External tools (`cargo`, `curl`, `tar`) are //! invoked through `std::process::Command`. +mod cargo_env; mod corpus; mod corpus_pins; mod i18n_report; @@ -31,9 +32,16 @@ commands: wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call, plus one per optional web feature) test workspace tests (cargo nextest when installed, else cargo test), then doctests - ci the CI gate: fmt --check, egui-fork, clippy -D warnings, layers, panel-commands, scorecard --check, tests - (nextest --profile ci), panic_hunt, doctests and wasm, with --locked --features heif - (stops at first failure), then the i18n-report + ci [lint | archive | build | tests --from [--gpu | --no-gpu] | ] + the CI gate: fmt --check, egui-fork, clippy -D warnings, layers, panel-commands, scorecard --check, + tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked + --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the + steps that need no test build; `archive` builds the tests into the nextest archive at + $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that + archive extracted to , on the partition in $NEXTEST_PARTITION (`--gpu`: only nextest's + gpu test group, each test's output shown; `--no-gpu`: every other test); `build` only builds + the tests (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves + packages out of the test build and the doctests corpus [--all | --pngsuite | --psd | --psd-tools | --pixls | --atn | --photoshop | --gimp] [--local] [--update-manifest] show where test corpora live and their pins (xtask/src/corpus_pins.rs), or fetch them into corpus/ (pinned commits, sha256-verified; --all = every corpus but pixls, @@ -70,7 +78,7 @@ fn main() -> ExitCode { Some("panel-commands") => panel_commands::run(&root()), Some("wasm") => cmd_wasm(), Some("test") => cmd_test().and_then(|()| cmd_doctest()), - Some("ci") => cmd_ci(), + Some("ci") => ci_from_args(&rest, ci_exclude()).and_then(|(plan, options)| cmd_ci(&plan, &options)), Some("corpus") => corpus::cmd(&rest), Some("test-corpus") => corpus::test_cmd(&rest), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), @@ -101,9 +109,11 @@ pub fn root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("xtask has a parent dir").to_path_buf() } +/// A cargo command in the workspace root, without the variables `cargo run` set for xtask. pub fn cargo() -> Command { let mut c = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into())); c.current_dir(root()); + cargo_env::without_cargo_run_vars(&mut c); c } @@ -241,25 +251,223 @@ fn cmd_test() -> Result<(), String> { /// official builds open HEIC photos with. const GATE_ARGS: [&str; 4] = ["--workspace", "--locked", "--features", "heif"]; -/// The gate's tests. nextest's `ci` profile stops at the first failure and terminates hung tests -/// (.config/nextest.toml). `panic_hunt` runs only the engine's `#[ignore]`d panic hunt (AGENTS.md -/// Rule 9) with the same packages, features and targets as the tests, so nothing rebuilds. -fn cmd_gate_tests(panic_hunt: bool) -> Result<(), String> { +/// Where a `ci` step runs when the gate splits the work over its jobs. `cargo xtask ci` alone runs +/// every step, in the order of [`CI_STEPS`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Part { + /// Checks that need no test build: the gate's lint leg. + Lint, + /// Steps that need the test build, in the job that builds it. + Build, + /// The tests, which the gate builds once and runs from the archive in several shards. + Test, +} + +/// How `ci` gets the test binaries. +#[derive(Clone, Debug, PartialEq)] +enum TestSource { + /// Builds and runs them here. + InPlace, + /// Builds them only (the cache warm-up). + BuildOnly, + /// Builds them into a nextest archive at this path instead of running them. + Archive(PathBuf), + /// Runs them from a nextest archive extracted to this directory (`--extract-to`), on the + /// partition given, if any. + Extracted { dir: PathBuf, partition: Option }, +} + +/// Which tests a run from the archive takes, by nextest's `gpu` test group. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Selection { + All, + /// Only the group, with each test's output shown: the Linux gate runs it on lavapipe, and + /// scripts/ci-gpu-lavapipe.py checks that output for skipped GPU comparisons. + Gpu, + /// Every test outside the group. + NoGpu, +} + +#[derive(Clone, Debug, PartialEq)] +struct CiOptions { + tests: TestSource, + selection: Selection, + /// Workspace packages left out of the test build and the doctests ($PHOTOCRAFT_CI_EXCLUDE). + exclude: Vec, +} + +type StepFn = fn(&CiOptions) -> Result<(), String>; + +/// The CI gate's steps, in the order `cargo xtask ci` runs them. +const CI_STEPS: [(&str, Part, StepFn); 11] = [ + ("fmt", Part::Lint, step_fmt), + ("egui-fork", Part::Lint, |_| cmd_egui_fork()), + ("clippy", Part::Lint, step_clippy), + ("layers", Part::Lint, |_| cmd_layers()), + ("panel-commands", Part::Lint, |_| panel_commands::run(&root())), + ("scorecard", Part::Lint, |_| scorecard::run(&root(), &["--check"])), + ("test", Part::Test, |o| step_tests(o, false)), + ("panic_hunt", Part::Test, |o| step_tests(o, true)), + ("doctest", Part::Build, step_doctest), + ("wasm", Part::Lint, |_| cmd_wasm()), + ("i18n", Part::Lint, step_i18n), +]; + +fn step_fmt(_: &CiOptions) -> Result<(), String> { let mut c = cargo(); - if nextest_available() { - c.args(["nextest", "run", "--profile", "ci"]).args(GATE_ARGS).args(&TEST_TARGETS[1..]); - if panic_hunt { - c.args(["--run-ignored", "only", "-E", "binary_id(photocraft-engine::panic_hunt)"]); - } - } else if panic_hunt { - // `-- --ignored` across the workspace would run every ignored test, not only the hunt. The - // engine has no `heif` feature of its own; it reaches the decoder through photocraft-io. - c.args(["test", "-p", "photocraft-engine", "--locked", "--features", "photocraft-io/heif", "--test", "panic_hunt", "--", "--ignored"]); - } else { - eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); - c.arg("test").args(GATE_ARGS).args(&TEST_TARGETS[1..]); + c.args(["fmt", "--all", "--", "--check"]); + run(c, "cargo fmt --all -- --check") +} + +fn step_clippy(_: &CiOptions) -> Result<(), String> { + let mut c = cargo(); + c.arg("clippy").args(GATE_ARGS).args(["--all-targets", "--keep-going", "--", "-D", "warnings"]); + run(c, "cargo clippy --workspace --locked --features heif --all-targets --keep-going -- -D warnings") +} + +fn step_doctest(o: &CiOptions) -> Result<(), String> { + let mut c = cargo(); + c.arg("test").args(gate_args(&o.exclude)).arg("--doc"); + let what = shown(&c); + run(c, &what) +} + +fn step_i18n(_: &CiOptions) -> Result<(), String> { + // Lists missing translations for the log; a missing string shows in English, so it never fails CI. + if let Err(e) = i18n_report::run(&root()) { + eprintln!("warning: i18n report failed: {e}"); } - let what = format!("cargo {}", c.get_args().map(|a| a.to_string_lossy()).collect::>().join(" ")); + Ok(()) +} + +/// GATE_ARGS without the excluded packages. +fn gate_args(exclude: &[String]) -> Vec { + let mut args: Vec = GATE_ARGS.iter().map(|a| a.to_string()).collect(); + for package in exclude { + args.extend(["--exclude".to_string(), package.clone()]); + } + args +} + +/// The test build every test step shares: the gate's packages and features, TEST_TARGETS. +fn test_build_args(exclude: &[String]) -> Vec { + let mut args = gate_args(exclude); + args.extend(TEST_TARGETS[1..].iter().map(|a| a.to_string())); + args +} + +/// The filter of nextest's `gpu` test group: the default profile's overrides that put tests in it. +fn gpu_filter(config: &toml::Table) -> Result { + let filters: Vec = config + .get("profile") + .and_then(|p| p.get("default")) + .and_then(|d| d.get("overrides")) + .and_then(toml::Value::as_array) + .into_iter() + .flatten() + .filter(|row| row.get("test-group").and_then(toml::Value::as_str) == Some("gpu")) + .filter_map(|row| row.get("filter").and_then(toml::Value::as_str)) + .map(|filter| format!("({})", filter.trim())) + .collect(); + if filters.is_empty() { + return Err("the nextest `gpu` test group has no filters (.config/nextest.toml)".into()); + } + Ok(filters.join(" | ")) +} + +fn read_gpu_filter() -> Result { + let path = root().join(".config/nextest.toml"); + let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + gpu_filter(&toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?) +} + +/// The nextest command line of a test step. `panic_hunt` runs only the engine's `#[ignore]`d panic +/// hunt (AGENTS.md Rule 9), from the same test build as the tests, so nothing rebuilds. `gpu` is +/// the group's filter, read only when the selection needs it. nextest's `ci` profile terminates +/// hung tests and repeats every failure at the end of the log (.config/nextest.toml). +fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>) -> Vec { + let mut args: Vec = ["nextest", "run", "--profile", "ci"].map(String::from).to_vec(); + let mut filters = Vec::new(); + if panic_hunt { + args.extend(["--run-ignored", "only"].map(String::from)); + filters.push("binary_id(photocraft-engine::panic_hunt)".to_string()); + } + match &o.tests { + TestSource::Extracted { dir, partition } => { + let target = dir.join("target"); + let path = |p: PathBuf| p.to_string_lossy().into_owned(); + args.extend([ + "--binaries-metadata".to_string(), + path(target.join("nextest").join("binaries-metadata.json")), + "--cargo-metadata".to_string(), + path(target.join("nextest").join("cargo-metadata.json")), + "--target-dir-remap".to_string(), + path(target.clone()), + "--workspace-remap".to_string(), + path(root()), + ]); + if let Some(partition) = partition { + args.extend(["--partition".to_string(), partition.clone()]); + } + // A partition or a selection may hold no panic hunt; the shard that does runs it. + if panic_hunt { + args.extend(["--no-tests", "warn"].map(String::from)); + } + } + _ => args.extend(test_build_args(&o.exclude)), + } + match (o.selection, gpu) { + (Selection::Gpu, Some(gpu)) => { + filters.push(format!("({gpu})")); + args.extend(["--success-output", "immediate"].map(String::from)); + } + (Selection::NoGpu, Some(gpu)) => filters.push(format!("not ({gpu})")), + _ => {} + } + if !filters.is_empty() { + args.extend(["-E".to_string(), filters.join(" & ")]); + } + args +} + +fn shown(c: &Command) -> String { + format!("cargo {}", c.get_args().map(|a| a.to_string_lossy()).collect::>().join(" ")) +} + +/// The `test` and `panic_hunt` steps. +fn step_tests(o: &CiOptions, panic_hunt: bool) -> Result<(), String> { + let mut c = cargo(); + if o.tests == TestSource::InPlace && !nextest_available() { + if panic_hunt { + // `-- --ignored` across the workspace would run every ignored test, not only the hunt. The + // engine has no `heif` feature of its own; it reaches the decoder through photocraft-io. + c.args(["test", "-p", "photocraft-engine", "--locked", "--features", "photocraft-io/heif", "--test", "panic_hunt", "--", "--ignored"]); + } else { + eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + c.arg("test").args(test_build_args(&o.exclude)); + } + } else { + let gpu = if o.selection == Selection::All { None } else { Some(read_gpu_filter()?) }; + c.args(nextest_args(o, panic_hunt, gpu.as_deref())); + } + let what = shown(&c); + run(c, &what) +} + +/// Builds the test steps' binaries without running them: into a nextest archive the shards run +/// from, or only into the target directory (the cache warm-up). The `ci` profile's archive also +/// carries this xtask binary, so a shard runs the test steps without building anything. +fn build_tests(o: &CiOptions) -> Result<(), String> { + let mut c = cargo(); + match &o.tests { + TestSource::Archive(file) => { + c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file); + } + _ => { + c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); + } + } + let what = shown(&c); run(c, &what) } @@ -276,55 +484,93 @@ fn cmd_parity() -> Result<(), String> { run(c, "cargo run -p photocraft-ui-egui --example parity") } -fn cmd_ci() -> Result<(), String> { - type Step = (&'static str, Box Result<(), String>>); - let steps: Vec = vec![ - ( - "fmt", - Box::new(|| { - let mut c = cargo(); - c.args(["fmt", "--all", "--", "--check"]); - run(c, "cargo fmt --all -- --check") - }), - ), - ("egui-fork", Box::new(cmd_egui_fork)), - ( - "clippy", - Box::new(|| { - let mut c = cargo(); - c.arg("clippy").args(GATE_ARGS).args(["--all-targets", "--keep-going", "--", "-D", "warnings"]); - run(c, "cargo clippy --workspace --locked --features heif --all-targets --keep-going -- -D warnings") - }), - ), - ("layers", Box::new(cmd_layers)), - ("panel-commands", Box::new(|| panel_commands::run(&root()))), - ("scorecard", Box::new(|| scorecard::run(&root(), &["--check"]))), - ("test", Box::new(|| cmd_gate_tests(false))), - ("panic_hunt", Box::new(|| cmd_gate_tests(true))), - ( - "doctest", - Box::new(|| { - let mut c = cargo(); - c.arg("test").args(GATE_ARGS).arg("--doc"); - run(c, "cargo test --workspace --locked --features heif --doc") - }), - ), - ("wasm", Box::new(cmd_wasm)), - ( - "i18n", - Box::new(|| { - // Lists missing translations for the log; a missing string shows in English, so it never fails CI. - if let Err(e) = i18n_report::run(&root()) { - eprintln!("warning: i18n report failed: {e}"); +/// The packages the gate leaves out of a test build: the Windows legs skip the browser apps, and +/// on pull requests the packages nothing changed reaches (.github/workflows/ci.yml). +fn ci_exclude() -> Vec { + std::env::var("PHOTOCRAFT_CI_EXCLUDE").unwrap_or_default().split_whitespace().map(String::from).collect() +} + +/// The steps `cargo xtask ci ` runs, and how: no argument runs every step; a part (`lint`, +/// `archive`, `build`, `tests`) runs the steps of one gate job; a step's name runs that step. +fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(Vec<(&'static str, StepFn)>, CiOptions), String> { + let mut options = CiOptions { tests: TestSource::InPlace, selection: Selection::All, exclude }; + let mut what = None; + let mut from = None; + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--from" => { + let dir = it.next().ok_or("--from needs the directory the archive was extracted to")?; + from = Some(std::path::absolute(dir).map_err(|e| format!("--from {dir}: {e}"))?); + } + "--gpu" => options.selection = Selection::Gpu, + "--no-gpu" => options.selection = Selection::NoGpu, + _ if what.is_none() && !arg.starts_with('-') => what = Some(arg), + _ => return Err(format!("ci: unexpected argument `{arg}`")), + } + } + let parts: &[Part] = match what { + None => &[Part::Lint, Part::Test, Part::Build], + Some("lint") => &[Part::Lint], + Some("archive") => { + let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; + options.tests = TestSource::Archive(file.into()); + &[Part::Test, Part::Build] + } + Some("build") => { + options.tests = TestSource::BuildOnly; + &[Part::Test] + } + Some("tests") => { + let dir = from.take().ok_or("ci tests: --from names the directory the archive was extracted to")?; + let partition = std::env::var("NEXTEST_PARTITION").ok().filter(|p| !p.is_empty()); + options.tests = TestSource::Extracted { dir, partition }; + &[Part::Test] + } + Some(step) => { + let plan: Vec<_> = CI_STEPS.iter().filter(|s| s.0 == step).map(|&(name, _, f)| (name, f)).collect(); + if plan.is_empty() { + return Err(format!("ci: no part or step `{step}`")); + } + return Ok((plan, options)); + } + }; + if from.is_some() || (options.selection != Selection::All && !matches!(options.tests, TestSource::Extracted { .. })) { + return Err("ci: --from, --gpu and --no-gpu go with `ci tests`".into()); + } + Ok((ci_plan(parts, &options.tests), options)) +} + +/// The steps of `parts`, in CI_STEPS order. When the tests are only built (into an archive or the +/// target directory), the test steps become that one build. +fn ci_plan(parts: &[Part], tests: &TestSource) -> Vec<(&'static str, StepFn)> { + let build_only = match tests { + TestSource::Archive(_) => Some("archive"), + TestSource::BuildOnly => Some("build"), + _ => None, + }; + let mut plan: Vec<(&'static str, StepFn)> = Vec::new(); + for &(name, part, f) in &CI_STEPS { + if !parts.contains(&part) { + continue; + } + match (part, build_only) { + (Part::Test, Some(build)) => { + if !plan.iter().any(|s| s.0 == build) { + plan.push((build, build_tests)); } - Ok(()) - }), - ), - ]; + } + _ => plan.push((name, f)), + } + } + plan +} + +fn cmd_ci(steps: &[(&'static str, StepFn)], options: &CiOptions) -> Result<(), String> { let mut done = Vec::new(); - for (name, f) in &steps { + for (name, f) in steps { eprintln!("\n=== ci: {name} ==="); - if let Err(e) = f() { + if let Err(e) = f(options) { println!("\nCI summary:"); for d in &done { println!(" ok {d}"); @@ -340,3 +586,79 @@ fn cmd_ci() -> Result<(), String> { println!("\nCI summary: all {} steps passed ({})", done.len(), done.join(", ")); Ok(()) } + +#[cfg(test)] +mod ci_tests { + use super::*; + + fn names(args: &[&str]) -> Vec<&'static str> { + ci_from_args(args, Vec::new()).unwrap().0.into_iter().map(|s| s.0).collect() + } + + #[test] + fn the_gate_jobs_together_run_every_step_once() { + let all = names(&[]); + assert_eq!(all, CI_STEPS.map(|s| s.0)); + let lint = names(&["lint"]); + let tests = names(&["tests", "--from", "x"]); + assert_eq!(tests, ["test", "panic_hunt"]); + let archive = ci_plan(&[Part::Test, Part::Build], &TestSource::Archive("a.tar.zst".into())).into_iter().map(|s| s.0).collect::>(); + assert_eq!(archive, ["archive", "doctest"]); + let mut split: Vec<_> = lint.iter().chain(&tests).chain(archive.iter().filter(|s| **s != "archive")).copied().collect(); + split.sort_unstable(); + let mut every = all.clone(); + every.sort_unstable(); + assert_eq!(split, every); + assert_eq!(names(&["build"]), ["build"]); + assert_eq!(names(&["clippy"]), ["clippy"]); + assert!(ci_from_args(&["nope"], Vec::new()).is_err()); + assert!(ci_from_args(&["lint", "--gpu"], Vec::new()).is_err()); + } + + #[test] + fn a_shard_runs_its_partition_from_the_extracted_archive() { + let options = CiOptions { + tests: TestSource::Extracted { dir: "/x".into(), partition: Some("hash:2/3".into()) }, + selection: Selection::NoGpu, + exclude: Vec::new(), + }; + let args = nextest_args(&options, false, Some("package(g)")).join(" "); + assert!(args.starts_with("nextest run --profile ci --binaries-metadata /x/target/nextest/binaries-metadata.json"), "{args}"); + assert!(args.contains("--target-dir-remap /x/target --workspace-remap ") && args.contains("--partition hash:2/3"), "{args}"); + assert!(args.ends_with("-E not (package(g))") && !args.contains("--workspace "), "{args}"); + let gpu = CiOptions { selection: Selection::Gpu, ..options.clone() }; + let hunt = nextest_args(&gpu, true, Some("package(g)")).join(" "); + assert!(hunt.contains("--run-ignored only") && hunt.contains("--no-tests warn") && hunt.contains("--success-output immediate"), "{hunt}"); + assert!(hunt.ends_with("-E binary_id(photocraft-engine::panic_hunt) & (package(g))"), "{hunt}"); + // In place, a test step builds what the archive holds. + let here = CiOptions { tests: TestSource::InPlace, selection: Selection::All, exclude: vec!["photocraft-web".into()] }; + assert_eq!( + nextest_args(&here, false, None).join(" "), + "nextest run --profile ci --workspace --locked --features heif --exclude photocraft-web --lib --bins --tests" + ); + } + + #[test] + fn the_gpu_group_takes_every_filter_that_selects_it() { + let config: toml::Table = toml::from_str( + r#" + [[profile.default.overrides]] + filter = 'package(a)' + test-group = 'gpu' + [[profile.default.overrides]] + filter = 'package(b)' + test-group = 'cpu' + [[profile.default.overrides]] + filter = ''' + test(c) + ''' + test-group = 'gpu' + "#, + ) + .unwrap(); + assert_eq!(gpu_filter(&config).unwrap(), "(package(a)) | (test(c))"); + assert!(gpu_filter(&toml::from_str("[profile.default]").unwrap()).is_err()); + // The workspace's own group exists and parses. + assert!(read_gpu_filter().unwrap().contains("package(photocraft-gpu)")); + } +} From eee31b0d11d56f45f741e6c44ed6a0eae8f4c99a Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:09:59 +0000 Subject: [PATCH 08/25] CI: shards build their own tests instead of running from an archive The gate's archive of ~98 test binaries would be 10-18 GB compressed, so every shard restores the dependency cache, builds the tests and runs its partition (scripts/ci-test-shard.sh). `cargo xtask ci tests` runs the test steps on $NEXTEST_PARTITION, `ci build` builds exactly what a shard builds (main's cache warm-up), and `ci doctest` runs in one shard. The `ci archive` part, the archive's xtask binary and the extraction are gone. The Linux GPU shard keeps the gpu group alone on lavapipe; shards 2-4 split the rest. Windows uses six shards: ~55 min of tests on one runner, and its slowest test alone takes ~9.6 min, so a seventh would not shorten the slowest shard. --- .config/nextest.toml | 6 - .github/workflows/ci.yml | 36 ++-- apps/photocraft/tests/windows_delay_loads.rs | 3 +- docs/development.md | 2 +- scripts/ci-gpu-lavapipe.py | 2 +- scripts/ci-test-shard.sh | 37 ++-- xtask/src/main.rs | 176 ++++++------------- 7 files changed, 99 insertions(+), 163 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index d4ed05c1a6..1e104a3072 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -27,12 +27,6 @@ test-group = 'gpu' fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" -# The gate's shards run the tests from a nextest archive (`cargo xtask ci archive`) and start them -# with the xtask binary the archive carries, so a shard builds nothing. Only one of the two exists. -archive.include = [ - { path = "debug/xtask", relative-to = "target", depth = 0, on-missing = "ignore" }, - { path = "debug/xtask.exe", relative-to = "target", depth = 0, on-missing = "ignore" }, -] # Keep phase timings for the remaining expensive Windows GPU regressions visible. This does # not relax their timeout, isolate failures differently or remove any test cases. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f243587b31..8bf8c05de8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -145,12 +145,13 @@ jobs: fi # The Linux gate (craft-common-actions gate.yml). Its `lint` leg runs the checks that need no test - # build; its build job builds the tests once into a nextest archive and runs the doctests; four - # test shards run the tests from that archive. Shard 1 runs nextest's `gpu` group alone, on - # lavapipe, and fails on a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split - # the other tests. With the five slowest UI tests (three of them in the `gpu` group) the GPU shard - # takes ~12 min of tests and the others ~8. Its rust-cache entry is the one `test (without heif)` - # restores. + # build; four test shards each build the tests from the restored cache and run their share + # (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and fails on + # a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other tests, and + # shard 2 runs the doctests. The `gpu` group is ~2400 test-seconds on 4 slots (~12 min with its + # slowest test, ~8 once the five slow UI tests are fixed); the other ~5900 test-seconds over 3 + # shards are ~8 min each, so a fifth shard would not shorten the gate. Its rust-cache entry is + # the one `test (without heif)` restores. gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. @@ -171,25 +172,25 @@ jobs: PHOTOCRAFT_NO_PRINT=1 LPDEST=photocraft-no-such-printer timeout-minutes: 100 - # On main, a `cache warm` leg builds xtask and the tests and saves the dependency cache as - # soon as the build succeeds; the build job then only restores, so a failing test cannot keep - # the entry from being saved (craft-common-actions#270). The lint leg keeps its own entry. + # On main, a `cache warm` leg builds xtask and the tests, as each shard does, and saves the + # dependency cache as soon as the build succeeds; the shards then only restore, so a failing + # test cannot keep the entry from being saved (craft-common-actions#270). The lint leg keeps + # its own entry. warm-command: cargo xtask ci build # fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' # own tests. lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint test-shards: 4 - # The test build with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs) into - # $NEXTEST_ARCHIVE_FILE, then the doctests. - archive-command: cargo xtask ci archive - # The tests and panic_hunt, from the archive. + # The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs). shard-command: bash scripts/ci-test-shard.sh --gpu-shard # The Windows tests and Clippy on the same gate, when `platforms` says the run needs them: a - # `lint` leg runs Clippy, the build job builds the tests into a nextest archive and runs the - # doctests, and four shards split the tests (Windows runs them ~1.75x slower than Linux, ~50 min - # of tests on one runner). The browser apps are wasm targets, so their native tests are left out; + # `lint` leg runs Clippy, and six shards each build the tests and run their hash partition; + # shard 1 also runs the doctests. Windows runs the tests ~1.75x slower than Linux: ~55 min on + # one runner, ~9 min per shard. A seventh shard would not shorten the slowest one while its + # slowest test alone takes ~9.6 min (the shortcut-dispatch UI test). The browser apps are wasm + # targets, so their native tests are left out; # pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they change # reaches (`windows_gpu`, `windows_skip`). The `cache warm` leg (main only) builds what main's # build job builds. @@ -227,8 +228,7 @@ jobs: timeout-minutes: 100 warm-command: cargo xtask ci build lint-command: cargo xtask ci clippy - test-shards: 4 - archive-command: cargo xtask ci archive + test-shards: 6 shard-command: bash scripts/ci-test-shard.sh # The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index 14143fea87..f7b7504ced 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -10,8 +10,7 @@ const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; /// The built exe names each print-only DLL in its delay-load table, never its import table. #[test] fn print_only_system_dlls_are_delay_loaded() { - // Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. - let exe = std::fs::read(std::env::var_os("NEXTEST_BIN_EXE_photocraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft").into())).unwrap(); + let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); let pe = Pe::parse(&exe); let imports = pe.dll_names(1, 20, 12); let delayed = pe.dll_names(13, 32, 4); diff --git a/docs/development.md b/docs/development.md index 3f5872d712..98948548dd 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate runs the tests in shards (`scripts/ci-test-shard.sh`, which calls `cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1` and run `python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu`. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index 7ff41e10c7..ab3d46d5a7 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -2,7 +2,7 @@ """Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. The Linux gate runs nextest's `gpu` test group in a shard of its own through this script -(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu +(`ci-gpu-lavapipe.py cargo xtask ci tests --gpu`, scripts/ci-test-shard.sh): every wgpu device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output is checked here for authored skips and for the parity tests' Vulkan backend line. diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh index 0420e0c67d..c1c380de6f 100755 --- a/scripts/ci-test-shard.sh +++ b/scripts/ci-test-shard.sh @@ -1,34 +1,41 @@ #!/usr/bin/env bash -# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's -# build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive -# carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps -# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, -# GATE_SHARDS and NEXTEST_PARTITION. +# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). Each shard +# restores the dependency cache, builds the tests (`cargo xtask ci build` builds the same on main's +# cache warm-up leg) and runs its share with `cargo xtask ci tests`. The gate sets GATE_SHARD (1..N), +# GATE_SHARDS (N) and NEXTEST_PARTITION (hash:GATE_SHARD/GATE_SHARDS). # -# ci-test-shard.sh the shard runs its hash partition of every test +# ci-test-shard.sh each shard runs its hash partition of every test; shard 1 also +# runs the doctests # ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by -# scripts/ci-gpu-lavapipe.py; the other shards split the other tests +# scripts/ci-gpu-lavapipe.py; the other shards split the other tests, +# and shard 2 also runs the doctests set -euo pipefail -archive=target/nextest-archive -mkdir -p "$archive" -cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --extract-to "$archive" --extract-overwrite -E 'none()' --no-tests=pass -xtask=("$archive/target/debug/xtask" ci tests --from "$archive") - case "${1:-}" in - "") exec "${xtask[@]}" ;; + "") + cargo xtask ci tests + doctests=1 + ;; --gpu-shard) if [ "$GATE_SHARDS" -lt 2 ]; then echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" exit 1 fi if [ "$GATE_SHARD" = 1 ]; then - exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu + # Build first, so only the test run goes through the lavapipe check. + cargo xtask ci build + python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu + else + NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" cargo xtask ci tests --no-gpu fi - NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu + doctests=2 ;; *) echo "usage: $0 [--gpu-shard]" >&2 exit 2 ;; esac + +if [ "$GATE_SHARD" = "$doctests" ]; then + cargo xtask ci doctest +fi diff --git a/xtask/src/main.rs b/xtask/src/main.rs index d854afd74f..ed1a34e7e0 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -32,15 +32,14 @@ commands: wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call, plus one per optional web feature) test workspace tests (cargo nextest when installed, else cargo test), then doctests - ci [lint | archive | build | tests --from [--gpu | --no-gpu] | ] + ci [lint | build | tests [--gpu | --no-gpu] | ] the CI gate: fmt --check, egui-fork, clippy -D warnings, layers, panel-commands, scorecard --check, tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the - steps that need no test build; `archive` builds the tests into the nextest archive at - $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that - archive extracted to , on the partition in $NEXTEST_PARTITION (`--gpu`: only nextest's - gpu test group, each test's output shown; `--no-gpu`: every other test); `build` only builds - the tests (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves + steps that need no test build; `tests` runs the tests and panic_hunt on the partition in + $NEXTEST_PARTITION (`--gpu`: only nextest's gpu test group, each test's output shown; + `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` + builds (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves packages out of the test build and the doctests corpus [--all | --pngsuite | --psd | --psd-tools | --pixls | --atn | --photoshop | --gimp] [--local] [--update-manifest] show where test corpora live and their pins (xtask/src/corpus_pins.rs), or fetch @@ -255,29 +254,15 @@ const GATE_ARGS: [&str; 4] = ["--workspace", "--locked", "--features", "heif"]; /// every step, in the order of [`CI_STEPS`]. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Part { - /// Checks that need no test build: the gate's lint leg. + /// Checks that need no test build: the gate's lint leg (`ci lint`). Lint, - /// Steps that need the test build, in the job that builds it. - Build, - /// The tests, which the gate builds once and runs from the archive in several shards. + /// The tests, which the gate splits over its shards (`ci tests`). Test, + /// The doctests, which the gate runs in one shard (`ci doctest`). + Doc, } -/// How `ci` gets the test binaries. -#[derive(Clone, Debug, PartialEq)] -enum TestSource { - /// Builds and runs them here. - InPlace, - /// Builds them only (the cache warm-up). - BuildOnly, - /// Builds them into a nextest archive at this path instead of running them. - Archive(PathBuf), - /// Runs them from a nextest archive extracted to this directory (`--extract-to`), on the - /// partition given, if any. - Extracted { dir: PathBuf, partition: Option }, -} - -/// Which tests a run from the archive takes, by nextest's `gpu` test group. +/// Which tests a test step takes, by nextest's `gpu` test group. #[derive(Clone, Copy, Debug, PartialEq)] enum Selection { All, @@ -290,7 +275,10 @@ enum Selection { #[derive(Clone, Debug, PartialEq)] struct CiOptions { - tests: TestSource, + /// Build the tests without running them (`ci build`, the cache warm-up). + build_only: bool, + /// The nextest partition the test steps run ($NEXTEST_PARTITION with `ci tests`). + partition: Option, selection: Selection, /// Workspace packages left out of the test build and the doctests ($PHOTOCRAFT_CI_EXCLUDE). exclude: Vec, @@ -308,7 +296,7 @@ const CI_STEPS: [(&str, Part, StepFn); 11] = [ ("scorecard", Part::Lint, |_| scorecard::run(&root(), &["--check"])), ("test", Part::Test, |o| step_tests(o, false)), ("panic_hunt", Part::Test, |o| step_tests(o, true)), - ("doctest", Part::Build, step_doctest), + ("doctest", Part::Doc, step_doctest), ("wasm", Part::Lint, |_| cmd_wasm()), ("i18n", Part::Lint, step_i18n), ]; @@ -382,7 +370,7 @@ fn read_gpu_filter() -> Result { } /// The nextest command line of a test step. `panic_hunt` runs only the engine's `#[ignore]`d panic -/// hunt (AGENTS.md Rule 9), from the same test build as the tests, so nothing rebuilds. `gpu` is +/// hunt (AGENTS.md Rule 9), with the same build arguments as the tests, so nothing rebuilds. `gpu` is /// the group's filter, read only when the selection needs it. nextest's `ci` profile terminates /// hung tests and repeats every failure at the end of the log (.config/nextest.toml). fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>) -> Vec { @@ -392,29 +380,13 @@ fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>) -> Vec { - let target = dir.join("target"); - let path = |p: PathBuf| p.to_string_lossy().into_owned(); - args.extend([ - "--binaries-metadata".to_string(), - path(target.join("nextest").join("binaries-metadata.json")), - "--cargo-metadata".to_string(), - path(target.join("nextest").join("cargo-metadata.json")), - "--target-dir-remap".to_string(), - path(target.clone()), - "--workspace-remap".to_string(), - path(root()), - ]); - if let Some(partition) = partition { - args.extend(["--partition".to_string(), partition.clone()]); - } - // A partition or a selection may hold no panic hunt; the shard that does runs it. - if panic_hunt { - args.extend(["--no-tests", "warn"].map(String::from)); - } - } - _ => args.extend(test_build_args(&o.exclude)), + args.extend(test_build_args(&o.exclude)); + if let Some(partition) = &o.partition { + args.extend(["--partition".to_string(), partition.clone()]); + } + // A partition or a selection may hold no panic hunt; the shard that does runs it. + if panic_hunt && (o.partition.is_some() || o.selection != Selection::All) { + args.extend(["--no-tests", "warn"].map(String::from)); } match (o.selection, gpu) { (Selection::Gpu, Some(gpu)) => { @@ -437,7 +409,7 @@ fn shown(c: &Command) -> String { /// The `test` and `panic_hunt` steps. fn step_tests(o: &CiOptions, panic_hunt: bool) -> Result<(), String> { let mut c = cargo(); - if o.tests == TestSource::InPlace && !nextest_available() { + if o.partition.is_none() && o.selection == Selection::All && !nextest_available() { if panic_hunt { // `-- --ignored` across the workspace would run every ignored test, not only the hunt. The // engine has no `heif` feature of its own; it reaches the decoder through photocraft-io. @@ -454,19 +426,11 @@ fn step_tests(o: &CiOptions, panic_hunt: bool) -> Result<(), String> { run(c, &what) } -/// Builds the test steps' binaries without running them: into a nextest archive the shards run -/// from, or only into the target directory (the cache warm-up). The `ci` profile's archive also -/// carries this xtask binary, so a shard runs the test steps without building anything. +/// Builds the test steps' binaries without running them: what every shard builds, so the cache +/// warm-up's entry covers each shard's build. fn build_tests(o: &CiOptions) -> Result<(), String> { let mut c = cargo(); - match &o.tests { - TestSource::Archive(file) => { - c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file); - } - _ => { - c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); - } - } + c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); let what = shown(&c); run(c, &what) } @@ -491,40 +455,30 @@ fn ci_exclude() -> Vec { } /// The steps `cargo xtask ci ` runs, and how: no argument runs every step; a part (`lint`, -/// `archive`, `build`, `tests`) runs the steps of one gate job; a step's name runs that step. +/// `build`, `tests`) runs the steps of one gate job; a step's name runs that step. fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(Vec<(&'static str, StepFn)>, CiOptions), String> { - let mut options = CiOptions { tests: TestSource::InPlace, selection: Selection::All, exclude }; + let mut options = CiOptions { build_only: false, partition: None, selection: Selection::All, exclude }; let mut what = None; - let mut from = None; - let mut it = args.iter(); - while let Some(&arg) = it.next() { + for &arg in args { match arg { - "--from" => { - let dir = it.next().ok_or("--from needs the directory the archive was extracted to")?; - from = Some(std::path::absolute(dir).map_err(|e| format!("--from {dir}: {e}"))?); - } "--gpu" => options.selection = Selection::Gpu, "--no-gpu" => options.selection = Selection::NoGpu, _ if what.is_none() && !arg.starts_with('-') => what = Some(arg), _ => return Err(format!("ci: unexpected argument `{arg}`")), } } + if options.selection != Selection::All && what != Some("tests") { + return Err("ci: --gpu and --no-gpu go with `ci tests`".into()); + } let parts: &[Part] = match what { - None => &[Part::Lint, Part::Test, Part::Build], + None => &[Part::Lint, Part::Test, Part::Doc], Some("lint") => &[Part::Lint], - Some("archive") => { - let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; - options.tests = TestSource::Archive(file.into()); - &[Part::Test, Part::Build] - } Some("build") => { - options.tests = TestSource::BuildOnly; + options.build_only = true; &[Part::Test] } Some("tests") => { - let dir = from.take().ok_or("ci tests: --from names the directory the archive was extracted to")?; - let partition = std::env::var("NEXTEST_PARTITION").ok().filter(|p| !p.is_empty()); - options.tests = TestSource::Extracted { dir, partition }; + options.partition = std::env::var("NEXTEST_PARTITION").ok().filter(|p| !p.is_empty()); &[Part::Test] } Some(step) => { @@ -535,32 +489,23 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(Vec<(&'static st return Ok((plan, options)); } }; - if from.is_some() || (options.selection != Selection::All && !matches!(options.tests, TestSource::Extracted { .. })) { - return Err("ci: --from, --gpu and --no-gpu go with `ci tests`".into()); - } - Ok((ci_plan(parts, &options.tests), options)) + Ok((ci_plan(parts, options.build_only), options)) } -/// The steps of `parts`, in CI_STEPS order. When the tests are only built (into an archive or the -/// target directory), the test steps become that one build. -fn ci_plan(parts: &[Part], tests: &TestSource) -> Vec<(&'static str, StepFn)> { - let build_only = match tests { - TestSource::Archive(_) => Some("archive"), - TestSource::BuildOnly => Some("build"), - _ => None, - }; +/// The steps of `parts`, in CI_STEPS order. When the tests are only built, the test steps become +/// that one build. +fn ci_plan(parts: &[Part], build_only: bool) -> Vec<(&'static str, StepFn)> { let mut plan: Vec<(&'static str, StepFn)> = Vec::new(); for &(name, part, f) in &CI_STEPS { if !parts.contains(&part) { continue; } - match (part, build_only) { - (Part::Test, Some(build)) => { - if !plan.iter().any(|s| s.0 == build) { - plan.push((build, build_tests)); - } + if part == Part::Test && build_only { + if !plan.iter().any(|s| s.0 == "build") { + plan.push(("build", build_tests)); } - _ => plan.push((name, f)), + } else { + plan.push((name, f)); } } plan @@ -600,11 +545,9 @@ mod ci_tests { let all = names(&[]); assert_eq!(all, CI_STEPS.map(|s| s.0)); let lint = names(&["lint"]); - let tests = names(&["tests", "--from", "x"]); + let tests = names(&["tests", "--no-gpu"]); assert_eq!(tests, ["test", "panic_hunt"]); - let archive = ci_plan(&[Part::Test, Part::Build], &TestSource::Archive("a.tar.zst".into())).into_iter().map(|s| s.0).collect::>(); - assert_eq!(archive, ["archive", "doctest"]); - let mut split: Vec<_> = lint.iter().chain(&tests).chain(archive.iter().filter(|s| **s != "archive")).copied().collect(); + let mut split: Vec<_> = lint.iter().chain(&tests).chain(&names(&["doctest"])).copied().collect(); split.sort_unstable(); let mut every = all.clone(); every.sort_unstable(); @@ -616,26 +559,19 @@ mod ci_tests { } #[test] - fn a_shard_runs_its_partition_from_the_extracted_archive() { - let options = CiOptions { - tests: TestSource::Extracted { dir: "/x".into(), partition: Some("hash:2/3".into()) }, - selection: Selection::NoGpu, - exclude: Vec::new(), - }; + fn a_shard_builds_what_the_warm_up_builds_and_runs_its_partition() { + let options = CiOptions { build_only: false, partition: Some("hash:2/3".into()), selection: Selection::NoGpu, exclude: vec!["photocraft-web".into()] }; + let build = "--workspace --locked --features heif --exclude photocraft-web --lib --bins --tests"; let args = nextest_args(&options, false, Some("package(g)")).join(" "); - assert!(args.starts_with("nextest run --profile ci --binaries-metadata /x/target/nextest/binaries-metadata.json"), "{args}"); - assert!(args.contains("--target-dir-remap /x/target --workspace-remap ") && args.contains("--partition hash:2/3"), "{args}"); - assert!(args.ends_with("-E not (package(g))") && !args.contains("--workspace "), "{args}"); - let gpu = CiOptions { selection: Selection::Gpu, ..options.clone() }; + assert_eq!(args, format!("nextest run --profile ci {build} --partition hash:2/3 -E not (package(g))")); + let gpu = CiOptions { selection: Selection::Gpu, partition: None, ..options.clone() }; let hunt = nextest_args(&gpu, true, Some("package(g)")).join(" "); assert!(hunt.contains("--run-ignored only") && hunt.contains("--no-tests warn") && hunt.contains("--success-output immediate"), "{hunt}"); assert!(hunt.ends_with("-E binary_id(photocraft-engine::panic_hunt) & (package(g))"), "{hunt}"); - // In place, a test step builds what the archive holds. - let here = CiOptions { tests: TestSource::InPlace, selection: Selection::All, exclude: vec!["photocraft-web".into()] }; - assert_eq!( - nextest_args(&here, false, None).join(" "), - "nextest run --profile ci --workspace --locked --features heif --exclude photocraft-web --lib --bins --tests" - ); + // The whole run keeps nextest's default: a panic hunt that matches nothing fails. + let here = CiOptions { partition: None, selection: Selection::All, ..options }; + assert!(!nextest_args(&here, true, None).join(" ").contains("--no-tests")); + assert_eq!(test_build_args(&here.exclude).join(" "), build); } #[test] From 0081fd10e1021761936c9081a9048b65af5cfca5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:11:27 +0000 Subject: [PATCH 09/25] Tests: merge single-file integration test binaries into one binary per crate Each crate's top-level tests/*.rs files become modules of tests/it/main.rs, and a new xtask check (test-binaries) refuses a new single-file test binary. --- crates/automation/tests/it/main.rs | 5 + crates/automation/tests/{ => it}/mcp_live.rs | 0 crates/automation/tests/{ => it}/mcp_wait.rs | 0 .../tests/{ => it}/save_snapshot.rs | 0 .../automation/tests/{ => it}/scratch_save.rs | 0 .../{ => it}/smart_filter_stack_cache.rs | 2 +- crates/compose/tests/{ => it}/artboard.rs | 0 crates/compose/tests/{ => it}/buffer_reuse.rs | 0 .../tests/{ => it}/interrupt_surface.rs | 0 crates/compose/tests/it/main.rs | 9 ++ .../compose/tests/{ => it}/scratch_retry.rs | 0 .../tests/{ => it}/shape_split_cache.rs | 0 .../{ => it}/shape_split_source_budget.rs | 0 .../compose/tests/{ => it}/spot_dot_gain.rs | 0 .../tests/{ => it}/atn_mapped_identifiers.rs | 0 .../tests/{ => it}/cmyk_flatten_profile.rs | 0 .../tests/{ => it}/content_aware_fill_atn.rs | 0 .../{ => it}/content_aware_fill_options.rs | 0 .../tests/{ => it}/content_aware_rotation.rs | 0 .../tests/{ => it}/convert_profile_atn.rs | 0 .../tests/{ => it}/convert_profile_dither.rs | 0 .../tests/{ => it}/convert_profile_options.rs | 0 crates/engine/tests/{ => it}/csh_import.rs | 2 +- .../tests/{ => it}/image_size_scale_styles.rs | 0 .../{ => it}/image_size_scale_styles_atn.rs | 0 .../tests/{ => it}/live_dab_matches_replay.rs | 0 .../tests/{ => it}/lut_row_cache_purge.rs | 0 .../{ => it}/magnetic_lasso_composite.rs | 0 crates/engine/tests/it/main.rs | 32 +++++++ .../engine/tests/{ => it}/mask_cache_purge.rs | 0 crates/engine/tests/{ => it}/memory_gate.rs | 0 crates/engine/tests/{ => it}/memory_prefs.rs | 0 .../tests/{ => it}/multi_channel_editing.rs | 0 .../tests/{ => it}/paste_style_options.rs | 0 .../engine/tests/{ => it}/pen_path_append.rs | 0 .../tests/{ => it}/place_steps_measure.rs | 0 crates/engine/tests/{ => it}/scratch_disk.rs | 0 crates/engine/tests/{ => it}/scratch_pause.rs | 0 .../engine/tests/{ => it}/scratch_release.rs | 0 .../tests/{ => it}/shape_kernel_budget.rs | 0 .../tests/{ => it}/smart_filter_stages.rs | 0 .../tests/{ => it}/smart_rerender_fallback.rs | 0 .../tests/{ => it}/smart_source_cache.rs | 0 .../tests/{ => it}/smart_source_peak.rs | 0 crates/engine/tests/{ => it}/spot_dot_gain.rs | 0 crates/engine/tests/{ => it}/text_gamma.rs | 0 .../tests/{ => it}/vector_paste_options.rs | 0 crates/format/tests/it/main.rs | 1 + crates/format/tests/{ => it}/scratch_retry.rs | 0 crates/io/tests/{ => it}/large_png_export.rs | 0 crates/io/tests/it/main.rs | 1 + crates/plugins/tests/{ => it}/abi.rs | 2 +- crates/plugins/tests/it/main.rs | 3 + crates/raster/tests/it/main.rs | 8 ++ crates/raster/tests/{ => it}/scratch.rs | 0 .../raster/tests/{ => it}/scratch_capacity.rs | 0 .../raster/tests/{ => it}/scratch_recovery.rs | 0 .../tests/{ => it}/scratch_slow_folder.rs | 0 .../tests/{ => it}/scratch_translate.rs | 0 crates/raster/tests/{ => it}/spill.rs | 0 .../ui-egui/tests/{ => it}/display_names.rs | 0 .../ui-egui/tests/{ => it}/flatpak_updates.rs | 4 +- crates/ui-egui/tests/it/main.rs | 3 + .../tests/{ => it}/save_memory_gate.rs | 0 xtask/src/main.rs | 5 + xtask/src/test_binaries.rs | 96 +++++++++++++++++++ 66 files changed, 168 insertions(+), 5 deletions(-) rename crates/automation/tests/{ => it}/mcp_live.rs (100%) rename crates/automation/tests/{ => it}/mcp_wait.rs (100%) rename crates/automation/tests/{ => it}/save_snapshot.rs (100%) rename crates/automation/tests/{ => it}/scratch_save.rs (100%) rename crates/automation/tests/{ => it}/smart_filter_stack_cache.rs (95%) rename crates/compose/tests/{ => it}/artboard.rs (100%) rename crates/compose/tests/{ => it}/buffer_reuse.rs (100%) rename crates/compose/tests/{ => it}/interrupt_surface.rs (100%) create mode 100644 crates/compose/tests/it/main.rs rename crates/compose/tests/{ => it}/scratch_retry.rs (100%) rename crates/compose/tests/{ => it}/shape_split_cache.rs (100%) rename crates/compose/tests/{ => it}/shape_split_source_budget.rs (100%) rename crates/compose/tests/{ => it}/spot_dot_gain.rs (100%) rename crates/engine/tests/{ => it}/atn_mapped_identifiers.rs (100%) rename crates/engine/tests/{ => it}/cmyk_flatten_profile.rs (100%) rename crates/engine/tests/{ => it}/content_aware_fill_atn.rs (100%) rename crates/engine/tests/{ => it}/content_aware_fill_options.rs (100%) rename crates/engine/tests/{ => it}/content_aware_rotation.rs (100%) rename crates/engine/tests/{ => it}/convert_profile_atn.rs (100%) rename crates/engine/tests/{ => it}/convert_profile_dither.rs (100%) rename crates/engine/tests/{ => it}/convert_profile_options.rs (100%) rename crates/engine/tests/{ => it}/csh_import.rs (99%) rename crates/engine/tests/{ => it}/image_size_scale_styles.rs (100%) rename crates/engine/tests/{ => it}/image_size_scale_styles_atn.rs (100%) rename crates/engine/tests/{ => it}/live_dab_matches_replay.rs (100%) rename crates/engine/tests/{ => it}/lut_row_cache_purge.rs (100%) rename crates/engine/tests/{ => it}/magnetic_lasso_composite.rs (100%) rename crates/engine/tests/{ => it}/mask_cache_purge.rs (100%) rename crates/engine/tests/{ => it}/memory_gate.rs (100%) rename crates/engine/tests/{ => it}/memory_prefs.rs (100%) rename crates/engine/tests/{ => it}/multi_channel_editing.rs (100%) rename crates/engine/tests/{ => it}/paste_style_options.rs (100%) rename crates/engine/tests/{ => it}/pen_path_append.rs (100%) rename crates/engine/tests/{ => it}/place_steps_measure.rs (100%) rename crates/engine/tests/{ => it}/scratch_disk.rs (100%) rename crates/engine/tests/{ => it}/scratch_pause.rs (100%) rename crates/engine/tests/{ => it}/scratch_release.rs (100%) rename crates/engine/tests/{ => it}/shape_kernel_budget.rs (100%) rename crates/engine/tests/{ => it}/smart_filter_stages.rs (100%) rename crates/engine/tests/{ => it}/smart_rerender_fallback.rs (100%) rename crates/engine/tests/{ => it}/smart_source_cache.rs (100%) rename crates/engine/tests/{ => it}/smart_source_peak.rs (100%) rename crates/engine/tests/{ => it}/spot_dot_gain.rs (100%) rename crates/engine/tests/{ => it}/text_gamma.rs (100%) rename crates/engine/tests/{ => it}/vector_paste_options.rs (100%) rename crates/format/tests/{ => it}/scratch_retry.rs (100%) rename crates/io/tests/{ => it}/large_png_export.rs (100%) rename crates/plugins/tests/{ => it}/abi.rs (99%) create mode 100644 crates/plugins/tests/it/main.rs create mode 100644 crates/raster/tests/it/main.rs rename crates/raster/tests/{ => it}/scratch.rs (100%) rename crates/raster/tests/{ => it}/scratch_capacity.rs (100%) rename crates/raster/tests/{ => it}/scratch_recovery.rs (100%) rename crates/raster/tests/{ => it}/scratch_slow_folder.rs (100%) rename crates/raster/tests/{ => it}/scratch_translate.rs (100%) rename crates/raster/tests/{ => it}/spill.rs (100%) rename crates/ui-egui/tests/{ => it}/display_names.rs (100%) rename crates/ui-egui/tests/{ => it}/flatpak_updates.rs (82%) rename crates/ui-egui/tests/{ => it}/save_memory_gate.rs (100%) create mode 100644 xtask/src/test_binaries.rs diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 9a551dd087..f83222b58d 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -11,6 +11,8 @@ mod krita; mod layered_save_dirty; mod linked_save_bytes; mod mcp; +mod mcp_live; +mod mcp_wait; mod mcp_wire; mod missing_font_warnings; mod native_full_composite; @@ -19,4 +21,7 @@ mod openraster; mod raw_defaults; mod read_roots; mod renderer_save; +mod save_snapshot; +mod scratch_save; mod smart_filter_authorization; +mod smart_filter_stack_cache; diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/it/mcp_live.rs similarity index 100% rename from crates/automation/tests/mcp_live.rs rename to crates/automation/tests/it/mcp_live.rs diff --git a/crates/automation/tests/mcp_wait.rs b/crates/automation/tests/it/mcp_wait.rs similarity index 100% rename from crates/automation/tests/mcp_wait.rs rename to crates/automation/tests/it/mcp_wait.rs diff --git a/crates/automation/tests/save_snapshot.rs b/crates/automation/tests/it/save_snapshot.rs similarity index 100% rename from crates/automation/tests/save_snapshot.rs rename to crates/automation/tests/it/save_snapshot.rs diff --git a/crates/automation/tests/scratch_save.rs b/crates/automation/tests/it/scratch_save.rs similarity index 100% rename from crates/automation/tests/scratch_save.rs rename to crates/automation/tests/it/scratch_save.rs diff --git a/crates/automation/tests/smart_filter_stack_cache.rs b/crates/automation/tests/it/smart_filter_stack_cache.rs similarity index 95% rename from crates/automation/tests/smart_filter_stack_cache.rs rename to crates/automation/tests/it/smart_filter_stack_cache.rs index f7698a4db1..f9ab205c2c 100644 --- a/crates/automation/tests/smart_filter_stack_cache.rs +++ b/crates/automation/tests/it/smart_filter_stack_cache.rs @@ -4,7 +4,7 @@ use photocraft_automation::workspace::authorize_desktop_engine_step; use photocraft_engine::{Session, smart_cmds}; use serde_json::json; -#[path = "support/smart_filter_fixture.rs"] +#[path = "../support/smart_filter_fixture.rs"] mod fixture; use fixture::{Fixture, assert_denied}; diff --git a/crates/compose/tests/artboard.rs b/crates/compose/tests/it/artboard.rs similarity index 100% rename from crates/compose/tests/artboard.rs rename to crates/compose/tests/it/artboard.rs diff --git a/crates/compose/tests/buffer_reuse.rs b/crates/compose/tests/it/buffer_reuse.rs similarity index 100% rename from crates/compose/tests/buffer_reuse.rs rename to crates/compose/tests/it/buffer_reuse.rs diff --git a/crates/compose/tests/interrupt_surface.rs b/crates/compose/tests/it/interrupt_surface.rs similarity index 100% rename from crates/compose/tests/interrupt_surface.rs rename to crates/compose/tests/it/interrupt_surface.rs diff --git a/crates/compose/tests/it/main.rs b/crates/compose/tests/it/main.rs new file mode 100644 index 0000000000..75dc82f400 --- /dev/null +++ b/crates/compose/tests/it/main.rs @@ -0,0 +1,9 @@ +//! The crate's integration tests, linked into one test binary. + +mod artboard; +mod buffer_reuse; +mod interrupt_surface; +mod scratch_retry; +mod shape_split_cache; +mod shape_split_source_budget; +mod spot_dot_gain; diff --git a/crates/compose/tests/scratch_retry.rs b/crates/compose/tests/it/scratch_retry.rs similarity index 100% rename from crates/compose/tests/scratch_retry.rs rename to crates/compose/tests/it/scratch_retry.rs diff --git a/crates/compose/tests/shape_split_cache.rs b/crates/compose/tests/it/shape_split_cache.rs similarity index 100% rename from crates/compose/tests/shape_split_cache.rs rename to crates/compose/tests/it/shape_split_cache.rs diff --git a/crates/compose/tests/shape_split_source_budget.rs b/crates/compose/tests/it/shape_split_source_budget.rs similarity index 100% rename from crates/compose/tests/shape_split_source_budget.rs rename to crates/compose/tests/it/shape_split_source_budget.rs diff --git a/crates/compose/tests/spot_dot_gain.rs b/crates/compose/tests/it/spot_dot_gain.rs similarity index 100% rename from crates/compose/tests/spot_dot_gain.rs rename to crates/compose/tests/it/spot_dot_gain.rs diff --git a/crates/engine/tests/atn_mapped_identifiers.rs b/crates/engine/tests/it/atn_mapped_identifiers.rs similarity index 100% rename from crates/engine/tests/atn_mapped_identifiers.rs rename to crates/engine/tests/it/atn_mapped_identifiers.rs diff --git a/crates/engine/tests/cmyk_flatten_profile.rs b/crates/engine/tests/it/cmyk_flatten_profile.rs similarity index 100% rename from crates/engine/tests/cmyk_flatten_profile.rs rename to crates/engine/tests/it/cmyk_flatten_profile.rs diff --git a/crates/engine/tests/content_aware_fill_atn.rs b/crates/engine/tests/it/content_aware_fill_atn.rs similarity index 100% rename from crates/engine/tests/content_aware_fill_atn.rs rename to crates/engine/tests/it/content_aware_fill_atn.rs diff --git a/crates/engine/tests/content_aware_fill_options.rs b/crates/engine/tests/it/content_aware_fill_options.rs similarity index 100% rename from crates/engine/tests/content_aware_fill_options.rs rename to crates/engine/tests/it/content_aware_fill_options.rs diff --git a/crates/engine/tests/content_aware_rotation.rs b/crates/engine/tests/it/content_aware_rotation.rs similarity index 100% rename from crates/engine/tests/content_aware_rotation.rs rename to crates/engine/tests/it/content_aware_rotation.rs diff --git a/crates/engine/tests/convert_profile_atn.rs b/crates/engine/tests/it/convert_profile_atn.rs similarity index 100% rename from crates/engine/tests/convert_profile_atn.rs rename to crates/engine/tests/it/convert_profile_atn.rs diff --git a/crates/engine/tests/convert_profile_dither.rs b/crates/engine/tests/it/convert_profile_dither.rs similarity index 100% rename from crates/engine/tests/convert_profile_dither.rs rename to crates/engine/tests/it/convert_profile_dither.rs diff --git a/crates/engine/tests/convert_profile_options.rs b/crates/engine/tests/it/convert_profile_options.rs similarity index 100% rename from crates/engine/tests/convert_profile_options.rs rename to crates/engine/tests/it/convert_profile_options.rs diff --git a/crates/engine/tests/csh_import.rs b/crates/engine/tests/it/csh_import.rs similarity index 99% rename from crates/engine/tests/csh_import.rs rename to crates/engine/tests/it/csh_import.rs index 7c48d6a3a9..e3e31fa539 100644 --- a/crates/engine/tests/csh_import.rs +++ b/crates/engine/tests/it/csh_import.rs @@ -4,7 +4,7 @@ use photocraft_engine::Session; use serde_json::json; -#[path = "common/csh_fixture.rs"] +#[path = "../common/csh_fixture.rs"] mod fixture; use fixture::{polygon_csh, triangle_csh}; diff --git a/crates/engine/tests/image_size_scale_styles.rs b/crates/engine/tests/it/image_size_scale_styles.rs similarity index 100% rename from crates/engine/tests/image_size_scale_styles.rs rename to crates/engine/tests/it/image_size_scale_styles.rs diff --git a/crates/engine/tests/image_size_scale_styles_atn.rs b/crates/engine/tests/it/image_size_scale_styles_atn.rs similarity index 100% rename from crates/engine/tests/image_size_scale_styles_atn.rs rename to crates/engine/tests/it/image_size_scale_styles_atn.rs diff --git a/crates/engine/tests/live_dab_matches_replay.rs b/crates/engine/tests/it/live_dab_matches_replay.rs similarity index 100% rename from crates/engine/tests/live_dab_matches_replay.rs rename to crates/engine/tests/it/live_dab_matches_replay.rs diff --git a/crates/engine/tests/lut_row_cache_purge.rs b/crates/engine/tests/it/lut_row_cache_purge.rs similarity index 100% rename from crates/engine/tests/lut_row_cache_purge.rs rename to crates/engine/tests/it/lut_row_cache_purge.rs diff --git a/crates/engine/tests/magnetic_lasso_composite.rs b/crates/engine/tests/it/magnetic_lasso_composite.rs similarity index 100% rename from crates/engine/tests/magnetic_lasso_composite.rs rename to crates/engine/tests/it/magnetic_lasso_composite.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f4c9ea401d..6ab284747a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -16,6 +16,7 @@ mod atn_crystallize_cell_size; mod atn_dialog_filters; mod atn_direct_adjustments; mod atn_layer_style; +mod atn_mapped_identifiers; mod atn_newer_events; mod atn_perspective_warp; mod atn_reference_forms; @@ -39,13 +40,21 @@ mod camera_raw_noise_clamp; mod canvas_artboard_crop; mod clipping_semantics; mod close_document; +mod cmyk_flatten_profile; mod command_lookup; +mod content_aware_fill_atn; +mod content_aware_fill_options; +mod content_aware_rotation; mod convert_keeps_references; +mod convert_profile_atn; +mod convert_profile_dither; +mod convert_profile_options; mod copy_shape_placement; mod corpus_atn; mod crop_content_aware; mod crop_content_aware_layers; mod crop_delete_off_background; +mod csh_import; mod current_affinity_artboards; mod duplicate_layer_comps; mod duplicate_slices; @@ -66,6 +75,8 @@ mod guide_layout_limit; mod guide_layout_preview; mod hdr_gamma_direction; mod huge_doc_flatten; +mod image_size_scale_styles; +mod image_size_scale_styles_atn; mod integration_batch; mod jpeg_exif_resolution; mod keyboard_shortcut_bulk; @@ -75,33 +86,53 @@ mod layer_delete_last; mod layer_mask_depth; mod layer_props_several; mod layer_range_panel_order; +mod live_dab_matches_replay; mod live_line_transform; +mod lut_row_cache_purge; +mod magnetic_lasso_composite; +mod mask_cache_purge; mod mask_lock_all; +mod memory_gate; +mod memory_prefs; mod merge_transparent_bounds; mod missing_layer_error; +mod multi_channel_editing; mod nonfinite_style; mod open_identity; +mod paste_style_options; mod path_blur_speed_clamp; mod path_transform_target; mod pdn; +mod pen_path_append; mod photoshop_oracles; mod pixel_lock_edits; +mod place_steps_measure; mod precheck; mod prefs_usage; mod rasterize_psd_reopen; mod rasterize_selected_layers; mod rendering_preferences; mod save_keeps_encoding; +mod scratch_disk; +mod scratch_pause; +mod scratch_release; mod selection_layer_commands; +mod shape_kernel_budget; mod shortcut_sets; mod shortcuts_headless; mod smart_clipboard_sources; mod smart_duplicates; mod smart_filter_canvas_geometry; +mod smart_filter_stages; mod smart_object_tones; mod smart_psd; +mod smart_rerender_fallback; +mod smart_source_cache; +mod smart_source_peak; +mod spot_dot_gain; mod style_and_align; mod svg_smart_object; +mod text_gamma; mod tone_target_picker; mod transform_budget_unclamped; mod type_format_targets; @@ -109,6 +140,7 @@ mod type_postscript_font; mod undo_keeps_active_layer; mod unicode_colors; mod unsupported_smart_filters; +mod vector_paste_options; mod wand_transparent_copy; mod working_rgb_profile; mod xmp_charref; diff --git a/crates/engine/tests/mask_cache_purge.rs b/crates/engine/tests/it/mask_cache_purge.rs similarity index 100% rename from crates/engine/tests/mask_cache_purge.rs rename to crates/engine/tests/it/mask_cache_purge.rs diff --git a/crates/engine/tests/memory_gate.rs b/crates/engine/tests/it/memory_gate.rs similarity index 100% rename from crates/engine/tests/memory_gate.rs rename to crates/engine/tests/it/memory_gate.rs diff --git a/crates/engine/tests/memory_prefs.rs b/crates/engine/tests/it/memory_prefs.rs similarity index 100% rename from crates/engine/tests/memory_prefs.rs rename to crates/engine/tests/it/memory_prefs.rs diff --git a/crates/engine/tests/multi_channel_editing.rs b/crates/engine/tests/it/multi_channel_editing.rs similarity index 100% rename from crates/engine/tests/multi_channel_editing.rs rename to crates/engine/tests/it/multi_channel_editing.rs diff --git a/crates/engine/tests/paste_style_options.rs b/crates/engine/tests/it/paste_style_options.rs similarity index 100% rename from crates/engine/tests/paste_style_options.rs rename to crates/engine/tests/it/paste_style_options.rs diff --git a/crates/engine/tests/pen_path_append.rs b/crates/engine/tests/it/pen_path_append.rs similarity index 100% rename from crates/engine/tests/pen_path_append.rs rename to crates/engine/tests/it/pen_path_append.rs diff --git a/crates/engine/tests/place_steps_measure.rs b/crates/engine/tests/it/place_steps_measure.rs similarity index 100% rename from crates/engine/tests/place_steps_measure.rs rename to crates/engine/tests/it/place_steps_measure.rs diff --git a/crates/engine/tests/scratch_disk.rs b/crates/engine/tests/it/scratch_disk.rs similarity index 100% rename from crates/engine/tests/scratch_disk.rs rename to crates/engine/tests/it/scratch_disk.rs diff --git a/crates/engine/tests/scratch_pause.rs b/crates/engine/tests/it/scratch_pause.rs similarity index 100% rename from crates/engine/tests/scratch_pause.rs rename to crates/engine/tests/it/scratch_pause.rs diff --git a/crates/engine/tests/scratch_release.rs b/crates/engine/tests/it/scratch_release.rs similarity index 100% rename from crates/engine/tests/scratch_release.rs rename to crates/engine/tests/it/scratch_release.rs diff --git a/crates/engine/tests/shape_kernel_budget.rs b/crates/engine/tests/it/shape_kernel_budget.rs similarity index 100% rename from crates/engine/tests/shape_kernel_budget.rs rename to crates/engine/tests/it/shape_kernel_budget.rs diff --git a/crates/engine/tests/smart_filter_stages.rs b/crates/engine/tests/it/smart_filter_stages.rs similarity index 100% rename from crates/engine/tests/smart_filter_stages.rs rename to crates/engine/tests/it/smart_filter_stages.rs diff --git a/crates/engine/tests/smart_rerender_fallback.rs b/crates/engine/tests/it/smart_rerender_fallback.rs similarity index 100% rename from crates/engine/tests/smart_rerender_fallback.rs rename to crates/engine/tests/it/smart_rerender_fallback.rs diff --git a/crates/engine/tests/smart_source_cache.rs b/crates/engine/tests/it/smart_source_cache.rs similarity index 100% rename from crates/engine/tests/smart_source_cache.rs rename to crates/engine/tests/it/smart_source_cache.rs diff --git a/crates/engine/tests/smart_source_peak.rs b/crates/engine/tests/it/smart_source_peak.rs similarity index 100% rename from crates/engine/tests/smart_source_peak.rs rename to crates/engine/tests/it/smart_source_peak.rs diff --git a/crates/engine/tests/spot_dot_gain.rs b/crates/engine/tests/it/spot_dot_gain.rs similarity index 100% rename from crates/engine/tests/spot_dot_gain.rs rename to crates/engine/tests/it/spot_dot_gain.rs diff --git a/crates/engine/tests/text_gamma.rs b/crates/engine/tests/it/text_gamma.rs similarity index 100% rename from crates/engine/tests/text_gamma.rs rename to crates/engine/tests/it/text_gamma.rs diff --git a/crates/engine/tests/vector_paste_options.rs b/crates/engine/tests/it/vector_paste_options.rs similarity index 100% rename from crates/engine/tests/vector_paste_options.rs rename to crates/engine/tests/it/vector_paste_options.rs diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs index ae17798530..057fc1e9bc 100644 --- a/crates/format/tests/it/main.rs +++ b/crates/format/tests/it/main.rs @@ -9,5 +9,6 @@ mod float_roundtrip; mod frame_stroke; mod layer_labels; mod roundtrip; +mod scratch_retry; mod smart_contents; mod triangle_live; diff --git a/crates/format/tests/scratch_retry.rs b/crates/format/tests/it/scratch_retry.rs similarity index 100% rename from crates/format/tests/scratch_retry.rs rename to crates/format/tests/it/scratch_retry.rs diff --git a/crates/io/tests/large_png_export.rs b/crates/io/tests/it/large_png_export.rs similarity index 100% rename from crates/io/tests/large_png_export.rs rename to crates/io/tests/it/large_png_export.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 0522415add..6c4dc3481b 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -34,6 +34,7 @@ mod heif_unsupported; mod krita_corpus; mod lab16; mod large_files; +mod large_png_export; mod large_psb; mod layer_labels; mod layer_xmp; diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/it/abi.rs similarity index 99% rename from crates/plugins/tests/abi.rs rename to crates/plugins/tests/it/abi.rs index 113d401dcf..320388604d 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/it/abi.rs @@ -9,7 +9,7 @@ use photocraft_plugins::{Error, Limits, Plugin}; use photocraft_raster::Surface; use serde_json::json; -const INVERT: &[u8] = include_bytes!("fixtures/invert.wasm"); +const INVERT: &[u8] = include_bytes!("../fixtures/invert.wasm"); /// A module implementing the ABI whose pieces can be swapped: `manifest` JSON, `version`, /// `filter` body (params `$buf $len $w $h $ch $fmt $pp $pl`, result i32) and extra items. diff --git a/crates/plugins/tests/it/main.rs b/crates/plugins/tests/it/main.rs new file mode 100644 index 0000000000..6a4481be73 --- /dev/null +++ b/crates/plugins/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The crate's integration tests, linked into one test binary. + +mod abi; diff --git a/crates/raster/tests/it/main.rs b/crates/raster/tests/it/main.rs new file mode 100644 index 0000000000..b8d6abca00 --- /dev/null +++ b/crates/raster/tests/it/main.rs @@ -0,0 +1,8 @@ +//! The crate's integration tests, linked into one test binary. + +mod scratch; +mod scratch_capacity; +mod scratch_recovery; +mod scratch_slow_folder; +mod scratch_translate; +mod spill; diff --git a/crates/raster/tests/scratch.rs b/crates/raster/tests/it/scratch.rs similarity index 100% rename from crates/raster/tests/scratch.rs rename to crates/raster/tests/it/scratch.rs diff --git a/crates/raster/tests/scratch_capacity.rs b/crates/raster/tests/it/scratch_capacity.rs similarity index 100% rename from crates/raster/tests/scratch_capacity.rs rename to crates/raster/tests/it/scratch_capacity.rs diff --git a/crates/raster/tests/scratch_recovery.rs b/crates/raster/tests/it/scratch_recovery.rs similarity index 100% rename from crates/raster/tests/scratch_recovery.rs rename to crates/raster/tests/it/scratch_recovery.rs diff --git a/crates/raster/tests/scratch_slow_folder.rs b/crates/raster/tests/it/scratch_slow_folder.rs similarity index 100% rename from crates/raster/tests/scratch_slow_folder.rs rename to crates/raster/tests/it/scratch_slow_folder.rs diff --git a/crates/raster/tests/scratch_translate.rs b/crates/raster/tests/it/scratch_translate.rs similarity index 100% rename from crates/raster/tests/scratch_translate.rs rename to crates/raster/tests/it/scratch_translate.rs diff --git a/crates/raster/tests/spill.rs b/crates/raster/tests/it/spill.rs similarity index 100% rename from crates/raster/tests/spill.rs rename to crates/raster/tests/it/spill.rs diff --git a/crates/ui-egui/tests/display_names.rs b/crates/ui-egui/tests/it/display_names.rs similarity index 100% rename from crates/ui-egui/tests/display_names.rs rename to crates/ui-egui/tests/it/display_names.rs diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/it/flatpak_updates.rs similarity index 82% rename from crates/ui-egui/tests/flatpak_updates.rs rename to crates/ui-egui/tests/it/flatpak_updates.rs index d9c1df0b85..d7ec1175cd 100644 --- a/crates/ui-egui/tests/flatpak_updates.rs +++ b/crates/ui-egui/tests/it/flatpak_updates.rs @@ -14,8 +14,8 @@ fn finish_args(manifest: &str) -> Vec<&str> { #[test] fn flatpak_update_permissions() { let manifests = [ - include_str!("../../../packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml"), - include_str!("../../../packaging/linux/flatpak/ai.storyteller.photocraft.yml"), + include_str!("../../../../packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml"), + include_str!("../../../../packaging/linux/flatpak/ai.storyteller.photocraft.yml"), ]; let args = manifests.map(finish_args); assert_eq!(args[0], args[1], "source and release permissions must agree"); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index e346aff3df..e4fedbecc3 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -16,9 +16,11 @@ 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; @@ -33,6 +35,7 @@ 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; diff --git a/crates/ui-egui/tests/save_memory_gate.rs b/crates/ui-egui/tests/it/save_memory_gate.rs similarity index 100% rename from crates/ui-egui/tests/save_memory_gate.rs rename to crates/ui-egui/tests/it/save_memory_gate.rs diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3fe247e33c..b9e488d47c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -13,6 +13,7 @@ mod perf; mod pinned; mod scorecard; mod stats; +mod test_binaries; mod version; use std::path::{Path, PathBuf}; @@ -28,6 +29,8 @@ commands: egui-fork fail unless Cargo.lock takes every egui package from the craft framework's egui fork panel-commands fail on a shell click handler that changes the document or session directly instead of dispatching a command id (allowlist: xtask/src/panel_commands.rs) + test-binaries fail on a single-file test binary (crates/*/tests/*.rs): integration tests are modules of tests/it/main.rs + (allowlist: xtask/src/test_binaries.rs) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call, plus one per optional web feature) test workspace tests (cargo nextest when installed, else cargo test), then doctests @@ -68,6 +71,7 @@ fn main() -> ExitCode { Some("layers") => cmd_layers(), Some("egui-fork") => cmd_egui_fork(), Some("panel-commands") => panel_commands::run(&root()), + Some("test-binaries") => test_binaries::run(&root()), Some("wasm") => cmd_wasm(), Some("test") => cmd_test().and_then(|()| cmd_doctest()), Some("ci") => cmd_ci(), @@ -298,6 +302,7 @@ fn cmd_ci() -> Result<(), String> { ), ("layers", Box::new(cmd_layers)), ("panel-commands", Box::new(|| panel_commands::run(&root()))), + ("test-binaries", Box::new(|| test_binaries::run(&root()))), ("scorecard", Box::new(|| scorecard::run(&root(), &["--check"]))), ("test", Box::new(|| cmd_gate_tests(false))), ("panic_hunt", Box::new(|| cmd_gate_tests(true))), diff --git a/xtask/src/test_binaries.rs b/xtask/src/test_binaries.rs new file mode 100644 index 0000000000..4498d362d6 --- /dev/null +++ b/xtask/src/test_binaries.rs @@ -0,0 +1,96 @@ +//! `cargo xtask test-binaries`: a crate's integration tests are modules of one binary. +//! +//! Every file directly under `crates//tests/` is compiled and linked as its own test binary, +//! which costs one link per file and one process start per binary under nextest. Integration tests +//! go in `crates//tests/it/.rs` with a `mod ;` line in `tests/it/main.rs`. +//! +//! A file that must stay its own binary is listed in [`ALLOWLIST`] with the reason. + +use std::path::Path; + +/// A single-file test binary that stays, with the reason. +#[derive(Debug, Clone, Copy)] +pub struct Allowed { + /// Path relative to the workspace root, with `/` separators. + pub file: &'static str, + pub reason: &'static str, +} + +pub const ALLOWLIST: &[Allowed] = &[ + Allowed { + file: "crates/engine/tests/panic_hunt.rs", + reason: "installs a process-wide panic hook and counts every panic in the process, so no other test may share it; `cargo xtask` selects it by binary id", + }, + Allowed { file: "crates/tablet/tests/monitor_macos.rs", reason: "`harness = false` binary with its own `main`" }, +]; + +/// Single-file test binaries under `root` that are not allow-listed, plus allow-list entries that +/// no longer match a file. +pub fn violations(root: &Path) -> Vec { + let mut found = Vec::new(); + let mut seen = Vec::new(); + let mut crates: Vec<_> = std::fs::read_dir(root.join("crates")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + crates.sort(); + for krate in crates { + let mut files: Vec<_> = std::fs::read_dir(krate.join("tests")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + files.sort(); + for file in files { + if !file.is_file() || file.extension().is_none_or(|e| e != "rs") { + continue; + } + let rel = file.strip_prefix(root).unwrap_or(&file).to_string_lossy().replace('\\', "/"); + if ALLOWLIST.iter().any(|a| a.file == rel) { + seen.push(rel); + } else { + found.push(format!( + "{rel}: a single-file test binary; move it to {}/it/ and add `mod` to its main.rs", + Path::new(&rel).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default() + )); + } + } + } + for a in ALLOWLIST { + if !seen.iter().any(|s| s == a.file) { + found.push(format!("{}: allow-list entry matches no file; delete it from xtask/src/test_binaries.rs", a.file)); + } + } + found +} + +pub fn run(root: &Path) -> Result<(), String> { + let found = violations(root); + if found.is_empty() { + println!("test-binaries: ok"); + for a in ALLOWLIST { + println!(" kept as its own binary: {} ({})", a.file, a.reason); + } + return Ok(()); + } + Err(format!("test-binaries: integration tests are modules of tests/it/main.rs:\n {}", found.join("\n "))) +} + +#[cfg(test)] +mod tests { + use super::violations; + + fn tree(files: &[&str]) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("xtask-test-binaries-{}-{}", std::process::id(), files.len())); + let _ = std::fs::remove_dir_all(&dir); + for f in files { + let p = dir.join(f); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, "").unwrap(); + } + dir + } + + #[test] + fn refuses_a_new_single_file_binary_but_not_modules() { + let root = tree(&["crates/a/tests/it/main.rs", "crates/a/tests/it/x.rs", "crates/a/tests/new.rs", "crates/a/tests/fixtures/f.rs"]); + let found = violations(&root); + let _ = std::fs::remove_dir_all(&root); + let mine: Vec<_> = found.iter().filter(|m| m.starts_with("crates/a/")).collect(); + assert_eq!(mine.len(), 1, "{found:?}"); + assert!(mine[0].starts_with("crates/a/tests/new.rs")); + } +} From 877e23f54382b43073fba147e8c3b2a63eebc692 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:19:35 +0000 Subject: [PATCH 10/25] Tests: one shared lock per process-wide global in each merged test binary The scratch pool and spill configuration, simulated free memory and the global caches are locked from tests/it/main.rs instead of a mutex per file. --- crates/automation/tests/it/scratch_save.rs | 2 +- crates/compose/tests/it/buffer_reuse.rs | 2 +- crates/compose/tests/it/spot_dot_gain.rs | 4 ++-- crates/engine/tests/it/lut_row_cache_purge.rs | 5 +++-- crates/engine/tests/it/main.rs | 15 +++++++++++++++ crates/engine/tests/it/mask_cache_purge.rs | 3 ++- crates/engine/tests/it/memory_gate.rs | 6 ++---- crates/engine/tests/it/scratch_disk.rs | 1 + crates/engine/tests/it/scratch_pause.rs | 1 + crates/engine/tests/it/scratch_release.rs | 9 +++------ crates/engine/tests/it/shape_kernel_budget.rs | 4 ++-- crates/engine/tests/it/smart_source_cache.rs | 14 +++++--------- crates/engine/tests/it/smart_source_peak.rs | 2 +- crates/engine/tests/it/spot_dot_gain.rs | 2 +- crates/engine/tests/it/text_gamma.rs | 2 +- crates/raster/tests/it/main.rs | 10 ++++++++++ crates/raster/tests/it/scratch.rs | 9 ++------- crates/raster/tests/it/scratch_capacity.rs | 1 + crates/raster/tests/it/scratch_recovery.rs | 1 + crates/raster/tests/it/scratch_slow_folder.rs | 1 + crates/raster/tests/it/scratch_translate.rs | 1 + crates/raster/tests/it/spill.rs | 1 + crates/ui-egui/tests/it/main.rs | 10 ++++++++++ crates/ui-egui/tests/it/save_memory_gate.rs | 14 +++++--------- 24 files changed, 73 insertions(+), 47 deletions(-) diff --git a/crates/automation/tests/it/scratch_save.rs b/crates/automation/tests/it/scratch_save.rs index 586be3a50d..140b916e31 100644 --- a/crates/automation/tests/it/scratch_save.rs +++ b/crates/automation/tests/it/scratch_save.rs @@ -1,5 +1,5 @@ //! A scripted `.pcraft` save refuses to write previews or a full-size composite rendered from -//! scratch tiles that could not be read. Its own test binary: the scratch store is per process. +//! scratch tiles that could not be read. The scratch store is per process, so the test needs its own (nextest runs every test in one). #![cfg(not(target_arch = "wasm32"))] use photocraft_automation::{AutomationError, files}; diff --git a/crates/compose/tests/it/buffer_reuse.rs b/crates/compose/tests/it/buffer_reuse.rs index f07bf8b69f..32acfeb1a1 100644 --- a/crates/compose/tests/it/buffer_reuse.rs +++ b/crates/compose/tests/it/buffer_reuse.rs @@ -11,7 +11,7 @@ impl Drop for IdleReleaseOff { } } -/// Runs in its own binary so other compositor tests cannot consume the pooled allocation. +/// Needs its own process (nextest runs every test in one) so other compositor tests cannot consume the pooled allocation. #[test] fn dropped_buffer_storage_is_reused() { scratch::set_idle_release(false); diff --git a/crates/compose/tests/it/spot_dot_gain.rs b/crates/compose/tests/it/spot_dot_gain.rs index 1ae474b801..c8887ca530 100644 --- a/crates/compose/tests/it/spot_dot_gain.rs +++ b/crates/compose/tests/it/spot_dot_gain.rs @@ -1,6 +1,6 @@ //! Edit › Color Settings › Spot drives the ink preview of Multichannel documents and the saved -//! thumbnail. The setting is process-wide (`multichannel::set_spot_dot_gain`), so this test has its -//! own binary, and it is one test: changing it here can't race other tests that render inks. +//! thumbnail. The setting is process-wide (`multichannel::set_spot_dot_gain`), so this test needs its +//! own process (nextest runs every test in one): changing it can't race other tests that render inks. use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_compose::multichannel::{SPOT_DOT_GAIN, dot_gain, set_spot_dot_gain, spot_dot_gain}; diff --git a/crates/engine/tests/it/lut_row_cache_purge.rs b/crates/engine/tests/it/lut_row_cache_purge.rs index 18d78c0c9f..08e3253928 100644 --- a/crates/engine/tests/it/lut_row_cache_purge.rs +++ b/crates/engine/tests/it/lut_row_cache_purge.rs @@ -1,11 +1,12 @@ -//! One integration-test process keeps its global adjustment-table cache isolated from parallel -//! unit tests. +//! The global adjustment-table cache is isolated from parallel unit tests; the tests that count +//! it take turns. use photocraft_compose::lut_rows::{self, ROW_LEN}; use photocraft_engine::Session; use serde_json::json; #[test] fn purge_all_is_enabled_by_cached_adjustment_tables_and_releases_them() { + let _caches = crate::lock(&crate::CACHES); let mut session = Session::new(); assert!(!session.is_enabled("edit.purge.all")); let rows = lut_rows::cached(7, || vec![[0.5; ROW_LEN]; 3]); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 6ab284747a..58071a8698 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -144,3 +144,18 @@ mod vector_paste_options; mod wand_transparent_copy; mod working_rgb_profile; mod xmp_charref; + +use std::sync::{Mutex, MutexGuard, PoisonError}; + +/// The scratch pool and the spill configuration are process-wide: tests that touch either take turns. +pub(crate) static SCRATCH: Mutex<()> = Mutex::new(()); +/// The simulated free memory is process-wide: tests that set it take turns. +pub(crate) static HEADROOM: Mutex<()> = Mutex::new(()); +/// The global caches (adjustment tables, masks, decoded smart-object sources) are process-wide: tests +/// that assert what Purge All finds in them, or their byte counts, take turns. +pub(crate) static CACHES: Mutex<()> = Mutex::new(()); + +/// Takes one of the locks above; a failed test that held it does not fail the next. +pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { + lock.lock().unwrap_or_else(PoisonError::into_inner) +} diff --git a/crates/engine/tests/it/mask_cache_purge.rs b/crates/engine/tests/it/mask_cache_purge.rs index 37f2de9165..504bba89c2 100644 --- a/crates/engine/tests/it/mask_cache_purge.rs +++ b/crates/engine/tests/it/mask_cache_purge.rs @@ -1,4 +1,4 @@ -//! One integration-test process keeps its global mask cache isolated from parallel unit tests. +//! The global mask cache is isolated from parallel unit tests; the tests that count it take turns. use std::sync::Arc; use photocraft_color::{ColorMode, PixelFormat, SampleType}; @@ -11,6 +11,7 @@ use serde_json::json; #[test] fn purge_all_is_enabled_by_cached_masks_and_releases_them_at_every_depth() { + let _caches = crate::lock(&crate::CACHES); let mut session = Session::new(); assert!(!session.is_enabled("edit.purge.all")); let canvas = Rect::new(0, 0, 32, 32); diff --git a/crates/engine/tests/it/memory_gate.rs b/crates/engine/tests/it/memory_gate.rs index 9f6228e4f7..cb51534a94 100644 --- a/crates/engine/tests/it/memory_gate.rs +++ b/crates/engine/tests/it/memory_gate.rs @@ -3,21 +3,19 @@ //! an error when their estimated need won't fit (#10024). The simulation switch is process-wide, //! so every test here holds `LOCK` and resets it when it ends. -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::MutexGuard; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_engine::Session; use photocraft_raster::headroom; use serde_json::json; -static LOCK: Mutex<()> = Mutex::new(()); - /// Holds the lock and the simulated room; resets the simulation when dropped. struct Room(#[allow(dead_code)] MutexGuard<'static, ()>); impl Room { fn new(bytes: Option) -> Room { - let guard = Room(LOCK.lock().unwrap_or_else(PoisonError::into_inner)); + let guard = Room(crate::lock(&crate::HEADROOM)); headroom::simulate_available(bytes); guard } diff --git a/crates/engine/tests/it/scratch_disk.rs b/crates/engine/tests/it/scratch_disk.rs index 55a361133e..312355d407 100644 --- a/crates/engine/tests/it/scratch_disk.rs +++ b/crates/engine/tests/it/scratch_disk.rs @@ -9,6 +9,7 @@ use std::sync::Arc; #[test] fn scratch_pixels_history_and_failed_save_are_transactional() { + let _scratch = crate::lock(&crate::SCRATCH); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id())); let mut session = Session::new(); session.edit_prefs(|p| { diff --git a/crates/engine/tests/it/scratch_pause.rs b/crates/engine/tests/it/scratch_pause.rs index 3b694f2da2..abdaa376ca 100644 --- a/crates/engine/tests/it/scratch_pause.rs +++ b/crates/engine/tests/it/scratch_pause.rs @@ -9,6 +9,7 @@ use serde_json::json; #[test] fn paused_scratch_disk_restores_the_history_limit() { + let _scratch = crate::lock(&crate::SCRATCH); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id())); let mut session = Session::new(); session.edit_prefs(|p| { diff --git a/crates/engine/tests/it/scratch_release.rs b/crates/engine/tests/it/scratch_release.rs index 6976f0cb7f..c0d624fba1 100644 --- a/crates/engine/tests/it/scratch_release.rs +++ b/crates/engine/tests/it/scratch_release.rs @@ -1,12 +1,9 @@ -//! One integration-test process keeps the process-wide scratch pool isolated from parallel unit -//! tests (#10479). +//! The process-wide scratch pool is isolated from parallel unit tests (#10479); these tests take +//! turns on it. use photocraft_engine::Session; use photocraft_engine::jobs::Started; use photocraft_raster::scratch; use serde_json::json; -use std::sync::{Mutex, PoisonError}; - -static SERIAL: Mutex<()> = Mutex::new(()); /// Holds the test lock with the pool's idle release off, so a slow runner can't empty the pool /// between a command and the check after it; the release comes back on when dropped. @@ -17,7 +14,7 @@ struct Quiet { impl Quiet { /// Locks the test process and disables idle pool release for this guard's lifetime. fn new() -> Self { - let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _serial = crate::lock(&crate::SCRATCH); scratch::set_idle_release(false); Quiet { _serial } } diff --git a/crates/engine/tests/it/shape_kernel_budget.rs b/crates/engine/tests/it/shape_kernel_budget.rs index e0c065fd3b..09810693dd 100644 --- a/crates/engine/tests/it/shape_kernel_budget.rs +++ b/crates/engine/tests/it/shape_kernel_budget.rs @@ -1,6 +1,6 @@ //! A custom Shape Blur kernel is admitted against the working-memory budget before its coverage -//! buffer is allocated, also when a smart filter re-renders it. Its own binary: the budget is -//! process-wide. +//! buffer is allocated, also when a smart filter re-renders it. The budget is +//! process-wide, so this test needs its own process (nextest runs every test in one). use photocraft_geom::Rect; use photocraft_raster::memory::{self, Policy}; diff --git a/crates/engine/tests/it/smart_source_cache.rs b/crates/engine/tests/it/smart_source_cache.rs index ec28b21292..1d7b7f0dcb 100644 --- a/crates/engine/tests/it/smart_source_cache.rs +++ b/crates/engine/tests/it/smart_source_cache.rs @@ -1,14 +1,10 @@ //! #10030: the decoded-source cache counts the bytes it holds, and Purge All and closing a -//! document with smart objects release them. One integration-test process keeps the global -//! cache isolated from parallel unit tests; the tests here take turns on it. -use std::sync::Mutex; - +//! document with smart objects release them. The global cache is +//! isolated from parallel unit tests; the tests here take turns on it. use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; use photocraft_engine::{Session, file_cmds, smart_cmds}; use serde_json::json; -static TURN: Mutex<()> = Mutex::new(()); - const SIDE: u32 = 256; fn png() -> Vec { @@ -39,7 +35,7 @@ fn decode(s: &Session, bytes: &[u8]) { #[test] fn the_cache_counts_real_tile_bytes() { - let _turn = TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::CACHES); empty_caches(); let bytes = png(); let s = session_with_smart_object(&bytes); @@ -53,7 +49,7 @@ fn the_cache_counts_real_tile_bytes() { #[test] fn purge_all_reports_and_empties_the_source_cache() { - let _turn = TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::CACHES); empty_caches(); let bytes = png(); let mut s = session_with_smart_object(&bytes); @@ -72,7 +68,7 @@ fn purge_all_reports_and_empties_the_source_cache() { #[test] fn closing_a_document_with_a_smart_object_empties_the_source_cache() { - let _turn = TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::CACHES); empty_caches(); let bytes = png(); let mut s = session_with_smart_object(&bytes); diff --git a/crates/engine/tests/it/smart_source_peak.rs b/crates/engine/tests/it/smart_source_peak.rs index ea74b88e0f..33d6bf7b73 100644 --- a/crates/engine/tests/it/smart_source_peak.rs +++ b/crates/engine/tests/it/smart_source_peak.rs @@ -2,7 +2,7 @@ //! tile-aligned blocks, so the peak memory growth stays a small multiple of the source's pixels, not the 32 //! bytes a pixel the full-size RGBA buffer and its f32 copy took on top of the decoded document. //! -//! The one test here runs in its own process: it reads the process's peak RSS (`VmHWM`, Linux +//! The one test here needs its own process (nextest runs every test in one): it reads the process's peak RSS (`VmHWM`, Linux //! only) and nothing else may allocate meanwhile. #![cfg(target_os = "linux")] diff --git a/crates/engine/tests/it/spot_dot_gain.rs b/crates/engine/tests/it/spot_dot_gain.rs index 24086bac23..31e7e7f441 100644 --- a/crates/engine/tests/it/spot_dot_gain.rs +++ b/crates/engine/tests/it/spot_dot_gain.rs @@ -2,7 +2,7 @@ //! (`photocraft_compose::multichannel::spot_dot_gain`), which the ink preview of Multichannel //! documents adds to every channel. //! -//! This test has its own integration-test binary (its own process) for the same reason as +//! This test needs its own process (nextest runs every test in one) for the same reason as //! `text_gamma.rs`: changing the gain changes how every Multichannel document composites, so a //! concurrent test could flatten one document under two settings. Keep any other test that //! changes the spot dot gain in this file. diff --git a/crates/engine/tests/it/text_gamma.rs b/crates/engine/tests/it/text_gamma.rs index 603dbae558..27e1af1c83 100644 --- a/crates/engine/tests/it/text_gamma.rs +++ b/crates/engine/tests/it/text_gamma.rs @@ -1,7 +1,7 @@ //! Edit › Color Settings › "Blend Text Colors Using Gamma" drives the compositor's //! application-wide text gamma (`photocraft_compose::psblend::text_gamma`). //! -//! This test lives in its own integration-test binary (its own process) on purpose: switching +//! This test needs its own process (nextest runs every test in one): switching //! the gamma away from the default changes how every type layer composites, so running it next //! to the engine's unit tests let a concurrent test flatten one document under two gammas //! (`canvas_geom::tests::turns_at_every_depth_and_mode` compares the composite before an edit diff --git a/crates/raster/tests/it/main.rs b/crates/raster/tests/it/main.rs index b8d6abca00..cda56fa4c1 100644 --- a/crates/raster/tests/it/main.rs +++ b/crates/raster/tests/it/main.rs @@ -6,3 +6,13 @@ mod scratch_recovery; mod scratch_slow_folder; mod scratch_translate; mod spill; + +use std::sync::{Mutex, MutexGuard, PoisonError}; + +/// The scratch pool and the spill configuration are process-wide: tests that touch either take turns. +pub(crate) static SCRATCH: Mutex<()> = Mutex::new(()); + +/// Takes one of the locks above; a failed test that held it does not fail the next. +pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { + lock.lock().unwrap_or_else(PoisonError::into_inner) +} diff --git a/crates/raster/tests/it/scratch.rs b/crates/raster/tests/it/scratch.rs index fbd2982320..5245978841 100644 --- a/crates/raster/tests/it/scratch.rs +++ b/crates/raster/tests/it/scratch.rs @@ -1,11 +1,6 @@ -//! The scratch pool is process-wide, so these tests live in their own binary (nothing else -//! allocates tiles here) and take a lock to run one at a time. +//! The scratch pool is process-wide, so these tests take a lock to run one at a time. use photocraft_raster::scratch::*; -use std::sync::{Mutex, PoisonError}; - -static SERIAL: Mutex<()> = Mutex::new(()); - /// Lets a miss evict every pooled byte for the test's lifetime, so sizes can be counted. struct NoFloor; impl NoFloor { @@ -22,7 +17,7 @@ impl Drop for NoFloor { } /// Locks the process-wide pool tests against concurrent access. fn lock_serial() -> std::sync::MutexGuard<'static, ()> { - SERIAL.lock().unwrap_or_else(PoisonError::into_inner) + crate::lock(&crate::SCRATCH) } /// Runs a test alone with idle release off, so the idle thread can't empty the pool between a diff --git a/crates/raster/tests/it/scratch_capacity.rs b/crates/raster/tests/it/scratch_capacity.rs index f6f0733ad5..d96008e10f 100644 --- a/crates/raster/tests/it/scratch_capacity.rs +++ b/crates/raster/tests/it/scratch_capacity.rs @@ -25,6 +25,7 @@ fn answered_capacity() -> Option { #[test] fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() { + let _scratch = crate::lock(&crate::SCRATCH); let root = std::env::temp_dir().join(format!("photocraft-scratch-capacity-{}", std::process::id())); let dir = root.join("scratch"); diff --git a/crates/raster/tests/it/scratch_recovery.rs b/crates/raster/tests/it/scratch_recovery.rs index fc4e91bfc7..f201a74002 100644 --- a/crates/raster/tests/it/scratch_recovery.rs +++ b/crates/raster/tests/it/scratch_recovery.rs @@ -44,6 +44,7 @@ fn check(s: &Surface, seed: u32, n: i32) { #[test] fn full_or_missing_scratch_disk_pauses_and_recovers() { + let _scratch = crate::lock(&crate::SCRATCH); let root = std::env::temp_dir().join(format!("photocraft-scratch-recovery-{}", std::process::id())); let dir = root.join("scratch"); let budget = 8 * TILE_BYTES; diff --git a/crates/raster/tests/it/scratch_slow_folder.rs b/crates/raster/tests/it/scratch_slow_folder.rs index 6d7350575e..459a78fcc7 100644 --- a/crates/raster/tests/it/scratch_slow_folder.rs +++ b/crates/raster/tests/it/scratch_slow_folder.rs @@ -102,6 +102,7 @@ fn surface(seed: u32, n: i32) -> Surface { #[test] fn a_folder_that_stops_answering_never_freezes_the_app() { + let _scratch = crate::lock(&crate::SCRATCH); let root = std::env::temp_dir().join(format!("photocraft-scratch-slow-{}", std::process::id())); let good = root.join("good"); let good2 = root.join("good2"); diff --git a/crates/raster/tests/it/scratch_translate.rs b/crates/raster/tests/it/scratch_translate.rs index f3e9741da7..3fabac9722 100644 --- a/crates/raster/tests/it/scratch_translate.rs +++ b/crates/raster/tests/it/scratch_translate.rs @@ -6,6 +6,7 @@ use photocraft_raster::{Surface, spill}; #[test] fn translations_and_shared_fills_preserve_spilled_pixels_at_every_depth() { + let _scratch = crate::lock(&crate::SCRATCH); let dir = std::env::temp_dir().join(format!("photocraft-translate-spill-{}", std::process::id())); for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { let format = PixelFormat::RGBA8.with_sample(depth); diff --git a/crates/raster/tests/it/spill.rs b/crates/raster/tests/it/spill.rs index 078c1c4bf6..89e84663c5 100644 --- a/crates/raster/tests/it/spill.rs +++ b/crates/raster/tests/it/spill.rs @@ -44,6 +44,7 @@ fn check(s: &Surface, seed: u32, n: i32) { #[test] fn tiles_spill_and_come_back() { + let _scratch = crate::lock(&crate::SCRATCH); let dir = std::env::temp_dir().join(format!("photocraft-spill-test-{}", std::process::id())); let budget = 8 * TILE_BYTES; spill::configure(Some(&dir), budget).unwrap(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index e4fedbecc3..279623dd09 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -41,3 +41,13 @@ mod tone_targets; mod ui_scale_canvas; mod variables_data_sets; mod workspace_presets; + +use std::sync::{Mutex, MutexGuard, PoisonError}; + +/// The simulated free memory is process-wide: tests that set it take turns. +pub(crate) static HEADROOM: Mutex<()> = Mutex::new(()); + +/// Takes one of the locks above; a failed test that held it does not fail the next. +pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { + lock.lock().unwrap_or_else(PoisonError::into_inner) +} diff --git a/crates/ui-egui/tests/it/save_memory_gate.rs b/crates/ui-egui/tests/it/save_memory_gate.rs index cc2d1b7276..b69c01197b 100644 --- a/crates/ui-egui/tests/it/save_memory_gate.rs +++ b/crates/ui-egui/tests/it/save_memory_gate.rs @@ -1,19 +1,15 @@ //! A save that won't fit in memory is refused before any encoding starts, with a message that -//! says how to free memory; the document stays open and unsaved (#10024). Its own test binary: -//! the memory simulation is process-wide. +//! says how to free memory; the document stays open and unsaved (#10024). The memory +//! simulation is process-wide, so the tests take turns. use std::cell::RefCell; use std::rc::Rc; -use std::sync::Mutex; use photocraft_engine::Session; use photocraft_raster::headroom; use photocraft_ui_egui::{PhotocraftApp, Services}; use serde_json::json; -/// The simulation is process-wide: the tests take turns. -static LOCK: Mutex<()> = Mutex::new(()); - fn app(writes: Rc>) -> Box { let mut app = PhotocraftApp::new( Session::new(), @@ -40,7 +36,7 @@ fn identity(app: &PhotocraftApp) -> (String, Option, u64, u64) { #[test] fn a_save_that_does_not_fit_fails_and_leaves_the_document_unsaved() { - let _turn = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::HEADROOM); let writes = Rc::new(RefCell::new(0)); let mut app = app(writes.clone()); let before = identity(&app); @@ -67,7 +63,7 @@ fn warnings(app: &PhotocraftApp) -> usize { /// higher threshold takes it down and arms the next warning. #[test] fn the_low_memory_warning_posts_once_and_rearms_with_hysteresis() { - let _turn = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::HEADROOM); use photocraft_ui_egui::memory_warning::{REARM_ABOVE, WARN_BELOW, tick}; let mut app = app(Rc::new(RefCell::new(0))); let mut now = 0.0; @@ -99,7 +95,7 @@ fn the_low_memory_warning_posts_once_and_rearms_with_hysteresis() { #[test] fn no_warning_without_a_document() { - let _turn = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = crate::lock(&crate::HEADROOM); let mut app = PhotocraftApp::new(Session::new(), Services::default()); headroom::simulate_available(Some(0)); photocraft_ui_egui::memory_warning::tick(&mut app, 100.0); From a015ef2934a67a9afc6bff076f606f73b1916762 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:26:28 +0000 Subject: [PATCH 11/25] Tests: engine tests on process-wide state get their own binary The modules that assert on the scratch pool, spill configuration, simulated memory, global caches or compositor settings move to tests/global_state, where one lock makes them take turns. test-binaries lists it with the reason. --- .../lut_row_cache_purge.rs | 3 +- crates/engine/tests/global_state/main.rs | 36 +++++++++++++++++++ .../{it => global_state}/mask_cache_purge.rs | 3 +- .../tests/{it => global_state}/memory_gate.rs | 2 +- .../{it => global_state}/scratch_disk.rs | 2 +- .../{it => global_state}/scratch_pause.rs | 2 +- .../{it => global_state}/scratch_release.rs | 2 +- .../shape_kernel_budget.rs | 1 + .../smart_source_cache.rs | 7 ++-- .../{it => global_state}/smart_source_peak.rs | 1 + .../{it => global_state}/spot_dot_gain.rs | 1 + .../tests/{it => global_state}/text_gamma.rs | 1 + crates/engine/tests/it/main.rs | 26 -------------- xtask/src/test_binaries.rs | 29 ++++++++++----- 14 files changed, 73 insertions(+), 43 deletions(-) rename crates/engine/tests/{it => global_state}/lut_row_cache_purge.rs (93%) create mode 100644 crates/engine/tests/global_state/main.rs rename crates/engine/tests/{it => global_state}/mask_cache_purge.rs (96%) rename crates/engine/tests/{it => global_state}/memory_gate.rs (99%) rename crates/engine/tests/{it => global_state}/scratch_disk.rs (99%) rename crates/engine/tests/{it => global_state}/scratch_pause.rs (98%) rename crates/engine/tests/{it => global_state}/scratch_release.rs (98%) rename crates/engine/tests/{it => global_state}/shape_kernel_budget.rs (96%) rename crates/engine/tests/{it => global_state}/smart_source_cache.rs (95%) rename crates/engine/tests/{it => global_state}/smart_source_peak.rs (97%) rename crates/engine/tests/{it => global_state}/spot_dot_gain.rs (98%) rename crates/engine/tests/{it => global_state}/text_gamma.rs (98%) diff --git a/crates/engine/tests/it/lut_row_cache_purge.rs b/crates/engine/tests/global_state/lut_row_cache_purge.rs similarity index 93% rename from crates/engine/tests/it/lut_row_cache_purge.rs rename to crates/engine/tests/global_state/lut_row_cache_purge.rs index 08e3253928..b4f968974a 100644 --- a/crates/engine/tests/it/lut_row_cache_purge.rs +++ b/crates/engine/tests/global_state/lut_row_cache_purge.rs @@ -6,7 +6,8 @@ use serde_json::json; #[test] fn purge_all_is_enabled_by_cached_adjustment_tables_and_releases_them() { - let _caches = crate::lock(&crate::CACHES); + let _caches = crate::lock(&crate::PROCESS); + crate::purge_all_caches(); let mut session = Session::new(); assert!(!session.is_enabled("edit.purge.all")); let rows = lut_rows::cached(7, || vec![[0.5; ROW_LEN]; 3]); diff --git a/crates/engine/tests/global_state/main.rs b/crates/engine/tests/global_state/main.rs new file mode 100644 index 0000000000..fa3f08a3d1 --- /dev/null +++ b/crates/engine/tests/global_state/main.rs @@ -0,0 +1,36 @@ +//! Tests that assert on process-wide state the rest of the engine's tests change (the scratch pool, +//! spill configuration, simulated memory, global caches, compositor settings). They live apart from +//! `it` so plain `cargo test` runs them without the rest of the suite. + +mod lut_row_cache_purge; +mod mask_cache_purge; +mod memory_gate; +mod scratch_disk; +mod scratch_pause; +mod scratch_release; +mod shape_kernel_budget; +mod smart_source_cache; +mod smart_source_peak; +mod spot_dot_gain; +mod text_gamma; + +use std::sync::{Mutex, MutexGuard, PoisonError}; + +/// Every test here changes or asserts on process-wide state (scratch pool, spill configuration, +/// simulated memory, global caches, compositor settings) that the others touch too, so the tests +/// take turns. +pub(crate) static PROCESS: Mutex<()> = Mutex::new(()); + +/// Takes the lock; a failed test that held it does not fail the next. +pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { + lock.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Empties every global cache that Purge All reports, so a test that asserts on what Purge All +/// finds starts from nothing whatever ran before it in this process. +pub(crate) fn purge_all_caches() { + let mut session = photocraft_engine::Session::new(); + if session.is_enabled("edit.purge.all") { + let _ = session.execute("edit.purge.all", serde_json::json!({})); + } +} diff --git a/crates/engine/tests/it/mask_cache_purge.rs b/crates/engine/tests/global_state/mask_cache_purge.rs similarity index 96% rename from crates/engine/tests/it/mask_cache_purge.rs rename to crates/engine/tests/global_state/mask_cache_purge.rs index 504bba89c2..06620b0e1c 100644 --- a/crates/engine/tests/it/mask_cache_purge.rs +++ b/crates/engine/tests/global_state/mask_cache_purge.rs @@ -11,7 +11,8 @@ use serde_json::json; #[test] fn purge_all_is_enabled_by_cached_masks_and_releases_them_at_every_depth() { - let _caches = crate::lock(&crate::CACHES); + let _caches = crate::lock(&crate::PROCESS); + crate::purge_all_caches(); let mut session = Session::new(); assert!(!session.is_enabled("edit.purge.all")); let canvas = Rect::new(0, 0, 32, 32); diff --git a/crates/engine/tests/it/memory_gate.rs b/crates/engine/tests/global_state/memory_gate.rs similarity index 99% rename from crates/engine/tests/it/memory_gate.rs rename to crates/engine/tests/global_state/memory_gate.rs index cb51534a94..800a37a8d6 100644 --- a/crates/engine/tests/it/memory_gate.rs +++ b/crates/engine/tests/global_state/memory_gate.rs @@ -15,7 +15,7 @@ struct Room(#[allow(dead_code)] MutexGuard<'static, ()>); impl Room { fn new(bytes: Option) -> Room { - let guard = Room(crate::lock(&crate::HEADROOM)); + let guard = Room(crate::lock(&crate::PROCESS)); headroom::simulate_available(bytes); guard } diff --git a/crates/engine/tests/it/scratch_disk.rs b/crates/engine/tests/global_state/scratch_disk.rs similarity index 99% rename from crates/engine/tests/it/scratch_disk.rs rename to crates/engine/tests/global_state/scratch_disk.rs index 312355d407..888fa4551c 100644 --- a/crates/engine/tests/it/scratch_disk.rs +++ b/crates/engine/tests/global_state/scratch_disk.rs @@ -9,7 +9,7 @@ use std::sync::Arc; #[test] fn scratch_pixels_history_and_failed_save_are_transactional() { - let _scratch = crate::lock(&crate::SCRATCH); + let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id())); let mut session = Session::new(); session.edit_prefs(|p| { diff --git a/crates/engine/tests/it/scratch_pause.rs b/crates/engine/tests/global_state/scratch_pause.rs similarity index 98% rename from crates/engine/tests/it/scratch_pause.rs rename to crates/engine/tests/global_state/scratch_pause.rs index abdaa376ca..309e69fd39 100644 --- a/crates/engine/tests/it/scratch_pause.rs +++ b/crates/engine/tests/global_state/scratch_pause.rs @@ -9,7 +9,7 @@ use serde_json::json; #[test] fn paused_scratch_disk_restores_the_history_limit() { - let _scratch = crate::lock(&crate::SCRATCH); + let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id())); let mut session = Session::new(); session.edit_prefs(|p| { diff --git a/crates/engine/tests/it/scratch_release.rs b/crates/engine/tests/global_state/scratch_release.rs similarity index 98% rename from crates/engine/tests/it/scratch_release.rs rename to crates/engine/tests/global_state/scratch_release.rs index c0d624fba1..eab7331b42 100644 --- a/crates/engine/tests/it/scratch_release.rs +++ b/crates/engine/tests/global_state/scratch_release.rs @@ -14,7 +14,7 @@ struct Quiet { impl Quiet { /// Locks the test process and disables idle pool release for this guard's lifetime. fn new() -> Self { - let _serial = crate::lock(&crate::SCRATCH); + let _serial = crate::lock(&crate::PROCESS); scratch::set_idle_release(false); Quiet { _serial } } diff --git a/crates/engine/tests/it/shape_kernel_budget.rs b/crates/engine/tests/global_state/shape_kernel_budget.rs similarity index 96% rename from crates/engine/tests/it/shape_kernel_budget.rs rename to crates/engine/tests/global_state/shape_kernel_budget.rs index 09810693dd..d22f345283 100644 --- a/crates/engine/tests/it/shape_kernel_budget.rs +++ b/crates/engine/tests/global_state/shape_kernel_budget.rs @@ -8,6 +8,7 @@ use serde_json::json; #[test] fn custom_shape_kernel_is_admitted_before_allocation() { + let _process = crate::lock(&crate::PROCESS); let knots = json!([[0, 0], [10, 0], [10, 10], [0, 10]]); let params = json!({"radius":1000,"shapePath":{"subpaths":[{"closed":true,"knots":knots}]}}); let mut surface = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); diff --git a/crates/engine/tests/it/smart_source_cache.rs b/crates/engine/tests/global_state/smart_source_cache.rs similarity index 95% rename from crates/engine/tests/it/smart_source_cache.rs rename to crates/engine/tests/global_state/smart_source_cache.rs index 1d7b7f0dcb..5ed2ef7dc1 100644 --- a/crates/engine/tests/it/smart_source_cache.rs +++ b/crates/engine/tests/global_state/smart_source_cache.rs @@ -20,6 +20,7 @@ fn empty_caches() { photocraft_compose::purge_effect_cache(); photocraft_compose::masks::purge_cache(); photocraft_compose::shape_split::purge_cache(); + crate::purge_all_caches(); } fn session_with_smart_object(bytes: &[u8]) -> Session { @@ -35,7 +36,7 @@ fn decode(s: &Session, bytes: &[u8]) { #[test] fn the_cache_counts_real_tile_bytes() { - let _turn = crate::lock(&crate::CACHES); + let _turn = crate::lock(&crate::PROCESS); empty_caches(); let bytes = png(); let s = session_with_smart_object(&bytes); @@ -49,7 +50,7 @@ fn the_cache_counts_real_tile_bytes() { #[test] fn purge_all_reports_and_empties_the_source_cache() { - let _turn = crate::lock(&crate::CACHES); + let _turn = crate::lock(&crate::PROCESS); empty_caches(); let bytes = png(); let mut s = session_with_smart_object(&bytes); @@ -68,7 +69,7 @@ fn purge_all_reports_and_empties_the_source_cache() { #[test] fn closing_a_document_with_a_smart_object_empties_the_source_cache() { - let _turn = crate::lock(&crate::CACHES); + let _turn = crate::lock(&crate::PROCESS); empty_caches(); let bytes = png(); let mut s = session_with_smart_object(&bytes); diff --git a/crates/engine/tests/it/smart_source_peak.rs b/crates/engine/tests/global_state/smart_source_peak.rs similarity index 97% rename from crates/engine/tests/it/smart_source_peak.rs rename to crates/engine/tests/global_state/smart_source_peak.rs index 33d6bf7b73..a5ac55d4a4 100644 --- a/crates/engine/tests/it/smart_source_peak.rs +++ b/crates/engine/tests/global_state/smart_source_peak.rs @@ -31,6 +31,7 @@ fn png() -> Vec { #[test] fn decoding_a_smart_object_source_stays_within_16_bytes_a_source_pixel() { + let _process = crate::lock(&crate::PROCESS); let bytes = png(); let mut s = Session::new(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); diff --git a/crates/engine/tests/it/spot_dot_gain.rs b/crates/engine/tests/global_state/spot_dot_gain.rs similarity index 98% rename from crates/engine/tests/it/spot_dot_gain.rs rename to crates/engine/tests/global_state/spot_dot_gain.rs index 31e7e7f441..88bd13a2f5 100644 --- a/crates/engine/tests/it/spot_dot_gain.rs +++ b/crates/engine/tests/global_state/spot_dot_gain.rs @@ -20,6 +20,7 @@ fn half_tint(s: &mut Session) { #[test] fn spot_dot_gain_setting() { + let _process = crate::lock(&crate::PROCESS); let mut s = Session::new(); assert_eq!(s.color.settings.spot_dot_gain, SPOT_DOT_GAIN, "Photoshop's default Spot working space: Dot Gain 20 %"); for bad in [json!(-1), json!(50), json!("20%"), json!(true)] { diff --git a/crates/engine/tests/it/text_gamma.rs b/crates/engine/tests/global_state/text_gamma.rs similarity index 98% rename from crates/engine/tests/it/text_gamma.rs rename to crates/engine/tests/global_state/text_gamma.rs index 27e1af1c83..de7c16353d 100644 --- a/crates/engine/tests/it/text_gamma.rs +++ b/crates/engine/tests/global_state/text_gamma.rs @@ -13,6 +13,7 @@ use serde_json::json; #[test] fn blend_text_gamma_setting() { + let _process = crate::lock(&crate::PROCESS); let mut s = Session::new(); assert!((s.color.settings.blend_text_gamma - 1.45).abs() < 1e-6); assert!(s.execute("edit.colorSettings", json!({"blendTextGamma": 3.0})).is_err()); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 58071a8698..3bcc48ca68 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -88,11 +88,8 @@ mod layer_props_several; mod layer_range_panel_order; mod live_dab_matches_replay; mod live_line_transform; -mod lut_row_cache_purge; mod magnetic_lasso_composite; -mod mask_cache_purge; mod mask_lock_all; -mod memory_gate; mod memory_prefs; mod merge_transparent_bounds; mod missing_layer_error; @@ -113,11 +110,7 @@ mod rasterize_psd_reopen; mod rasterize_selected_layers; mod rendering_preferences; mod save_keeps_encoding; -mod scratch_disk; -mod scratch_pause; -mod scratch_release; mod selection_layer_commands; -mod shape_kernel_budget; mod shortcut_sets; mod shortcuts_headless; mod smart_clipboard_sources; @@ -127,12 +120,8 @@ mod smart_filter_stages; mod smart_object_tones; mod smart_psd; mod smart_rerender_fallback; -mod smart_source_cache; -mod smart_source_peak; -mod spot_dot_gain; mod style_and_align; mod svg_smart_object; -mod text_gamma; mod tone_target_picker; mod transform_budget_unclamped; mod type_format_targets; @@ -144,18 +133,3 @@ mod vector_paste_options; mod wand_transparent_copy; mod working_rgb_profile; mod xmp_charref; - -use std::sync::{Mutex, MutexGuard, PoisonError}; - -/// The scratch pool and the spill configuration are process-wide: tests that touch either take turns. -pub(crate) static SCRATCH: Mutex<()> = Mutex::new(()); -/// The simulated free memory is process-wide: tests that set it take turns. -pub(crate) static HEADROOM: Mutex<()> = Mutex::new(()); -/// The global caches (adjustment tables, masks, decoded smart-object sources) are process-wide: tests -/// that assert what Purge All finds in them, or their byte counts, take turns. -pub(crate) static CACHES: Mutex<()> = Mutex::new(()); - -/// Takes one of the locks above; a failed test that held it does not fail the next. -pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { - lock.lock().unwrap_or_else(PoisonError::into_inner) -} diff --git a/xtask/src/test_binaries.rs b/xtask/src/test_binaries.rs index 4498d362d6..cb3a5ca748 100644 --- a/xtask/src/test_binaries.rs +++ b/xtask/src/test_binaries.rs @@ -1,10 +1,11 @@ //! `cargo xtask test-binaries`: a crate's integration tests are modules of one binary. //! -//! Every file directly under `crates//tests/` is compiled and linked as its own test binary, -//! which costs one link per file and one process start per binary under nextest. Integration tests -//! go in `crates//tests/it/.rs` with a `mod ;` line in `tests/it/main.rs`. +//! Every file directly under `crates//tests/`, and every `tests//main.rs` other than +//! `tests/it/main.rs`, is compiled and linked as its own test binary, which costs one link per +//! binary and one process start per binary under nextest. Integration tests go in +//! `crates//tests/it/.rs` with a `mod ;` line in `tests/it/main.rs`. //! -//! A file that must stay its own binary is listed in [`ALLOWLIST`] with the reason. +//! A test binary that must stay separate is listed in [`ALLOWLIST`] with the reason. use std::path::Path; @@ -21,6 +22,10 @@ pub const ALLOWLIST: &[Allowed] = &[ file: "crates/engine/tests/panic_hunt.rs", reason: "installs a process-wide panic hook and counts every panic in the process, so no other test may share it; `cargo xtask` selects it by binary id", }, + Allowed { + file: "crates/engine/tests/global_state/main.rs", + reason: "tests that assert on process-wide state other engine tests change; they need a process without the rest of the suite", + }, Allowed { file: "crates/tablet/tests/monitor_macos.rs", reason: "`harness = false` binary with its own `main`" }, ]; @@ -35,6 +40,7 @@ pub fn violations(root: &Path) -> Vec { let mut files: Vec<_> = std::fs::read_dir(krate.join("tests")).into_iter().flatten().flatten().map(|e| e.path()).collect(); files.sort(); for file in files { + let file = if file.is_dir() && file.file_name().is_some_and(|n| n != "it") { file.join("main.rs") } else { file }; if !file.is_file() || file.extension().is_none_or(|e| e != "rs") { continue; } @@ -43,8 +49,8 @@ pub fn violations(root: &Path) -> Vec { seen.push(rel); } else { found.push(format!( - "{rel}: a single-file test binary; move it to {}/it/ and add `mod` to its main.rs", - Path::new(&rel).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default() + "{rel}: a separate test binary; make it a module of crates/{}/tests/it/main.rs", + krate.file_name().unwrap_or_default().to_string_lossy() )); } } @@ -86,11 +92,18 @@ mod tests { #[test] fn refuses_a_new_single_file_binary_but_not_modules() { - let root = tree(&["crates/a/tests/it/main.rs", "crates/a/tests/it/x.rs", "crates/a/tests/new.rs", "crates/a/tests/fixtures/f.rs"]); + let root = tree(&[ + "crates/a/tests/it/main.rs", + "crates/a/tests/it/x.rs", + "crates/a/tests/new.rs", + "crates/a/tests/fixtures/f.rs", + "crates/a/tests/other/main.rs", + ]); let found = violations(&root); let _ = std::fs::remove_dir_all(&root); let mine: Vec<_> = found.iter().filter(|m| m.starts_with("crates/a/")).collect(); - assert_eq!(mine.len(), 1, "{found:?}"); + assert_eq!(mine.len(), 2, "{found:?}"); assert!(mine[0].starts_with("crates/a/tests/new.rs")); + assert!(mine[1].starts_with("crates/a/tests/other/main.rs")); } } From 3b62ce7cb830f57ba53cd0ca523cb5d79cdbdf62 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 20:28:03 +0100 Subject: [PATCH 12/25] Tests: trim repeated variants in ui-egui canvas integration tests (#15369) Run each variant once where the loops reached the same code, and reuse one app harness instead of building one per case: - checker_canvas pixel grid: 8-bit on every canvas and scale, plus 16-bit and 32-bit once each on the GPU canvas (the grid reads the same f32 composite at every depth; depth only changes the GPU texture). - live_stroke_canvas: one harness for the raw pointer and camera tests; camera navigation runs the Brush only (no tool branch before a press); the committed stroke runs every zoom once with every smoothing amount, plus the special cases, split over the three parts so every case runs (the step was still 4 after part 3 was removed, so four cases never ran). - adjust_preview_gpu clipped target: each kind once per mode, cycling the depth/selection pairs; the full matrix stays in the unclipped test. - drag_preview_canvas marquee: one grey document that checks both ant colours, one harness for both scales. - arbitrary_rotation_preview: drop -45 degrees (same preview size as 45). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/adjust_preview_gpu.rs | 72 +++++----- .../tests/it/arbitrary_rotation_preview.rs | 13 +- crates/ui-egui/tests/it/checker_canvas.rs | 20 ++- .../ui-egui/tests/it/drag_preview_canvas.rs | 81 +++++++---- crates/ui-egui/tests/it/live_stroke_canvas.rs | 132 ++++++++++-------- 5 files changed, 189 insertions(+), 129 deletions(-) diff --git a/crates/ui-egui/tests/it/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/adjust_preview_gpu.rs index 59dc67c550..f8f56bb371 100644 --- a/crates/ui-egui/tests/it/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/adjust_preview_gpu.rs @@ -229,40 +229,46 @@ fn clipped_target_preview_composites_on_the_gpu_like_the_command() { let Some((device, queue, mut comp)) = gpu() else { return }; let (tol_gpu, tol_cmd) = (2.0 / 255.0, 2.5 / 255.0); let mut worst = 0.0f32; - for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for selection in [false, true] { - let (doc, target) = clipped_document(mode, depth, selection); - for kind in photocraft_ui_egui::adjust_editors::KINDS { - let params = sample(kind); - let preview = match preview_document(&doc, target, kind, ¶ms) { - Ok(p) => p, - Err(e) => { - // Only grayscale kinds that make colour keep the CPU proxy preview. - assert_eq!(mode, ColorMode::Grayscale, "{kind}: {e}"); - assert!(GRAY_COLOUR.contains(&kind), "{kind} {mode:?}: unexpected preview error: {e}"); - continue; - } - }; - assert!(preview.layer(PREVIEW_LAYER).is_some()); - assert!(preview.layer(target).unwrap().is_group(), "the clipped target is isolated"); - let what = format!("{kind} {mode:?} {depth:?} selection {selection}"); - let b = preview.bounds(); - let skip = if matches!(kind, "threshold" | "posterize") && depth != SampleType::U8 { (b.width() * b.height()) as usize / 100 } else { 0 }; - let on_gpu = render_to_vec(&mut comp, &device, &queue, &preview, b).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let on_cpu = photocraft_compose::render(&preview, b).into_px(); - let d = max_diff(&on_gpu, &on_cpu, skip); - assert!(d <= tol_gpu, "{what}: GPU vs CPU {:.2}/255", d * 255.0); - let mut s = photocraft_engine::Session::new(); - s.add_document(doc.clone(), None); - s.select_layer(target).unwrap(); - s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap(); - let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px(); - let d = max_diff(&on_gpu, &cmd, skip); - worst = worst.max(d); - assert!(d <= tol_cmd, "{what}: GPU preview vs command {:.2}/255", d * 255.0); + // Each kind runs once per mode at one (depth, selection) pair, rather than kind x depth x selection: this test's + // own case is the isolating group, which `base_document` builds before it knows the kind (`with_settings` only + // swaps the preview layer's adjustment), and the GPU planner applies a clipped adjustment through the same + // `atop_any` / `adjust` passes whatever the group around it (`crates/gpu/src/plan/planner.rs`). The kind x depth x + // selection x mode matrix of those passes is `preview_layer_composites_on_the_gpu_like_the_command`. Cycling the + // pairs over the kinds still runs every depth with and without a selection in both modes (in Grayscale among the + // kinds that keep gray, too). + const PAIRS: [(SampleType, bool); 6] = + [(SampleType::U8, false), (SampleType::U16, true), (SampleType::F32, false), (SampleType::U8, true), (SampleType::U16, false), (SampleType::F32, true)]; + for (mode, offset) in [(ColorMode::Rgb, 0), (ColorMode::Grayscale, 3)] { + for (i, kind) in photocraft_ui_egui::adjust_editors::KINDS.into_iter().enumerate() { + let (depth, selection) = PAIRS[(i + offset) % PAIRS.len()]; + let (doc, target) = clipped_document(mode, depth, selection); + let params = sample(kind); + let preview = match preview_document(&doc, target, kind, ¶ms) { + Ok(p) => p, + Err(e) => { + // Only grayscale kinds that make colour keep the CPU proxy preview. + assert_eq!(mode, ColorMode::Grayscale, "{kind}: {e}"); + assert!(GRAY_COLOUR.contains(&kind), "{kind} {mode:?}: unexpected preview error: {e}"); + continue; } - } + }; + assert!(preview.layer(PREVIEW_LAYER).is_some()); + assert!(preview.layer(target).unwrap().is_group(), "the clipped target is isolated"); + let what = format!("{kind} {mode:?} {depth:?} selection {selection}"); + let b = preview.bounds(); + let skip = if matches!(kind, "threshold" | "posterize") && depth != SampleType::U8 { (b.width() * b.height()) as usize / 100 } else { 0 }; + let on_gpu = render_to_vec(&mut comp, &device, &queue, &preview, b).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let on_cpu = photocraft_compose::render(&preview, b).into_px(); + let d = max_diff(&on_gpu, &on_cpu, skip); + assert!(d <= tol_gpu, "{what}: GPU vs CPU {:.2}/255", d * 255.0); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc.clone(), None); + s.select_layer(target).unwrap(); + s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap(); + let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px(); + let d = max_diff(&on_gpu, &cmd, skip); + worst = worst.max(d); + assert!(d <= tol_cmd, "{what}: GPU preview vs command {:.2}/255", d * 255.0); } } eprintln!("worst clipped-target GPU preview vs command: {:.3}/255", worst * 255.0); diff --git a/crates/ui-egui/tests/it/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/arbitrary_rotation_preview.rs index 40eb68c227..08641b02ac 100644 --- a/crates/ui-egui/tests/it/arbitrary_rotation_preview.rs +++ b/crates/ui-egui/tests/it/arbitrary_rotation_preview.rs @@ -108,12 +108,13 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - for (width, height, zoom, center, degrees, factor) in [ - (400, 240, 1.0, [160.0, 90.0], 45.0, 1), - (400, 240, 1.0, [160.0, 90.0], -45.0, 1), - (400, 240, 1.0, [160.0, 90.0], 90.0, 1), - (3000, 1800, 0.12, [1350.0, 825.0], 45.0, 2), - ] { + // The canvas places a size-changing preview by its size alone (`canvas/gpu_picture.rs`: `growth` and + // `preview_bounds` from `preview_size`): 45° grows both sides, 90° grows one and shrinks the other, and the large + // document runs the reduced proxy. -45° gives 45°'s size, so it repeated the same placement; the direction of + // the rotation itself is the engine's (its `image.rotation.arbitrary` tests with `"direction": "ccw"`). + for (width, height, zoom, center, degrees, factor) in + [(400, 240, 1.0, [160.0, 90.0], 45.0, 1), (400, 240, 1.0, [160.0, 90.0], 90.0, 1), (3000, 1800, 0.12, [1350.0, 825.0], 45.0, 2)] + { setup(&mut h, width, height, zoom, center); assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor); let id = open(&mut h); diff --git a/crates/ui-egui/tests/it/checker_canvas.rs b/crates/ui-egui/tests/it/checker_canvas.rs index fca78a57f5..e3708e4592 100644 --- a/crates/ui-egui/tests/it/checker_canvas.rs +++ b/crates/ui-egui/tests/it/checker_canvas.rs @@ -289,15 +289,31 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() { } } +/// The depths [`pixel_grid_is_solid_and_visible_at_scale`] runs at. Both canvases draw the grid with the same +/// `PixelGrid` over a CPU composite (`PhotoComposite`: compose's f32 render, `canvas/raster_source.rs` `read`; see +/// `grid_prep` and "The grid is drawn over the picture" in `canvas/document_display.rs`), and the fills 0 and 1 are +/// exact at every depth, so the grid reads the same pixels at 8, 16 and 32 bits. Depth reaches only the picture under +/// it, which the `inside` assertion reads: on the GPU canvas its texture (`Rgba8Unorm` for 8-bit, `Rgba16Float` for +/// 16/32-bit, see `canvas_16f.rs`). So every canvas and scale runs 8-bit, and the GPU canvas adds 16-bit at 1x and +/// 32-bit at 2x. +fn grid_depths(gpu: bool, ppp: f32) -> Vec { + use photocraft_color::SampleType; + match (gpu, ppp > 1.0) { + (true, false) => vec![SampleType::U8, SampleType::U16], + (true, true) => vec![SampleType::U8, SampleType::F32], + (false, _) => vec![SampleType::U8], + } +} + fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) { let _gpu = photocraft_testkit::gpu_lock(); - use photocraft_color::{ColorMode, PixelFormat, SampleType}; + use photocraft_color::{ColorMode, PixelFormat}; use photocraft_doc::{Document, Layer, LayerContent, Size}; use photocraft_geom::Rect; use photocraft_raster::Surface; let Some(mut h) = harness_with_scale(gpu, ppp) else { return }; - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for depth in grid_depths(gpu, ppp) { for v in [0.0, 1.0] { let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth); let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true)); diff --git a/crates/ui-egui/tests/it/drag_preview_canvas.rs b/crates/ui-egui/tests/it/drag_preview_canvas.rs index 4cb13abfb4..208dac9e95 100644 --- a/crates/ui-egui/tests/it/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/it/drag_preview_canvas.rs @@ -8,7 +8,7 @@ //! //! They drive the real app offscreen on wgpu with real egui pointer events (press, then a series //! of moves past the click distance), render the frame mid-drag and look at the pixels along the -//! preview's edges on white and on black documents. They also check the preview follows every +//! preview's edges on a mid-grey document, for both colours of the ants. They also check the preview follows every //! move (each move's frame shows the new outline) and that the animated ants keep frames coming //! while the pointer is held still. Skips when no GPU adapter exists (like `live_stroke_canvas.rs`). @@ -169,11 +169,17 @@ fn coverage_along(img: &Image, ppp: f32, pts: &[Pos2], test: impl Fn(u8) -> bool hits as f32 / samples.max(1) as f32 } -/// Ink that contrasts with `background`: dark on white, light on black. The 1 px ants are half -/// antialiasing where the curve crosses pixel columns, so a quarter of the luma range suffices. -fn ink(background: &str) -> impl Fn(u8) -> bool { - let white = background == "white"; - move |l| if white { l < 192 } else { l > 63 } +/// The document the marquee tests drag over: the grey halfway between the ants' two colours (luma 102 and 255 in the +/// default theme), so both contrast with it. +const GREY: &str = "#b3b3b3"; + +/// An ink's name and whether a luma shows it. +type Ink = (&'static str, fn(u8) -> bool); + +/// The two inks of the ants over [`GREY`] (luma 179): darker and lighter. The 1 px ants are half antialiasing where +/// the curve crosses pixel columns (luma 140 and 217 there), so the thresholds sit just past the grey either way. +fn inks() -> [Ink; 2] { + [("dark", |l| l < 150), ("light", |l| l > 208)] } /// The four edges of the document rectangle `[x0, y0]`–`[x1, y1]` on screen. @@ -186,22 +192,34 @@ fn edges(h: &Harness, a: [f32; 2], b: [f32; 2]) -> [(Pos2, Pos2); 4] { #[test] fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { let _gpu = photocraft_testkit::gpu_lock(); - for ppp in [1.0, 2.0] { - let Some(mut h) = harness(ppp) else { return }; + // One mid-grey document instead of a white and a black one: the ants are a band of the marquee colour with dashes + // of the halo colour, fixed colours that never depend on the pixels under them (the framework's `marching_ants`, + // which the marquee tool paints through `ToolContext::marching_ants`). White on white (#253) hid the light ants + // and black would hide the dark ones; over grey the test sees both inks at once, so an outline missing either + // colour fails here as it failed on one of the two documents. (The name is the one CI's slow-test order lists.) + // One harness for both scales: the app derives its scale from the window's native one every frame + // (`prefs_ui/appearance.rs` `interface_zoom`), so the 2x pass sets that, as a move to a HiDPI display does. + let Some(mut h) = harness(1.0) else { return }; + h.run_steps(4); + for ppp in [1.0f32, 2.0] { + if let Some(root) = h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT) { + root.native_pixels_per_point = Some(ppp); + } h.run_steps(4); + assert_eq!(h.ctx.pixels_per_point(), ppp, "the harness runs at {ppp}x"); for tool in ["rectMarquee", "ellipseMarquee"] { - for bg in ["white", "black"] { - setup(&mut h, bg, tool); - let (a, b) = ([100.0, 80.0], [300.0, 220.0]); - let before = render(&mut h); - drag_to(&mut h, a, b); - let img = render(&mut h); + setup(&mut h, GREY, tool); + let (a, b) = ([100.0, 80.0], [300.0, 220.0]); + let before = render(&mut h); + drag_to(&mut h, a, b); + let img = render(&mut h); + for (ink, test) in inks() { if tool == "rectMarquee" { for (i, (p, q)) in edges(&h, a, b).into_iter().enumerate() { - let was = coverage(&before, ppp, p, q, ink(bg)); - let now = coverage(&img, ppp, p, q, ink(bg)); - // Ants: half the dashes contrast with the pixels under them. - assert!(was < 0.05 && now > 0.3, "{tool} on {bg} @{ppp}x, edge {i}: {was:.2} → {now:.2} contrasting"); + let was = coverage(&before, ppp, p, q, test); + let now = coverage(&img, ppp, p, q, test); + // Ants: half the dashes are each ink. + assert!(was < 0.05 && now > 0.3, "{tool} @{ppp}x, edge {i}: {was:.2} → {now:.2} {ink}"); } } else { // The ellipse touches its box at the edge midpoints. Walk the curve around @@ -220,21 +238,24 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { screen(&h, (cx as f64 + rx as f64 * t.cos()) as f32, (cy as f64 + ry as f64 * t.sin()) as f32) }) .collect(); - let now = coverage_along(&img, ppp, &pts, ink(bg)); - assert!(now > 0.3, "{tool} on {bg} @{ppp}x at ({mx}, {my}): {now:.2} contrasting"); + let was = coverage_along(&before, ppp, &pts, test); + let now = coverage_along(&img, ppp, &pts, test); + assert!(was < 0.05 && now > 0.3, "{tool} @{ppp}x at ({mx}, {my}): {was:.2} → {now:.2} {ink}"); } } - // Each move's frame shows the outline where the pointer is now (no stale frame). - pointer_move(&mut h, 340.0, 250.0); - let img = render(&mut h); - if tool == "rectMarquee" { - let [top, right, ..] = edges(&h, a, [340.0, 250.0]); - assert!(coverage(&img, ppp, top.0, top.1, ink(bg)) > 0.3, "{tool} {bg} @{ppp}x: top edge follows the pointer"); - assert!(coverage(&img, ppp, right.0, right.1, ink(bg)) > 0.3, "{tool} {bg} @{ppp}x: right edge follows the pointer"); - } - button(&mut h, 340.0, 250.0, false); - h.run_steps(2); } + // Each move's frame shows the outline where the pointer is now (no stale frame). + pointer_move(&mut h, 340.0, 250.0); + let img = render(&mut h); + if tool == "rectMarquee" { + let [top, right, ..] = edges(&h, a, [340.0, 250.0]); + for (ink, test) in inks() { + assert!(coverage(&img, ppp, top.0, top.1, test) > 0.3, "{tool} @{ppp}x: top edge follows the pointer ({ink})"); + assert!(coverage(&img, ppp, right.0, right.1, test) > 0.3, "{tool} @{ppp}x: right edge follows the pointer ({ink})"); + } + } + button(&mut h, 340.0, 250.0, false); + h.run_steps(2); } } } diff --git a/crates/ui-egui/tests/it/live_stroke_canvas.rs b/crates/ui-egui/tests/it/live_stroke_canvas.rs index 7402ba6ce2..fba4fef7a9 100644 --- a/crates/ui-egui/tests/it/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/live_stroke_canvas.rs @@ -19,10 +19,15 @@ type Pixels = Vec<[u8; 4]>; fn raw_pointer_brush_and_mixer_pixels_appear_in_the_input_frame() { use photocraft_ui_egui::state::Tool; let _gpu = photocraft_testkit::gpu_lock(); + // One harness for every case: each case closes what the last one left open and sets its own tool, view flip, + // brush and colours, so a fresh harness per case only repeated the wgpu setup. + let Some(mut h) = harness() else { return }; for flip in [false, true] { for tool in [Tool::Brush, Tool::MixerBrush] { - let Some(mut h) = harness() else { return }; let app = h.state_mut(); + while app.session.active().is_some() { + app.run("file.close", json!({"discard": true})).unwrap(); + } app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap(); app.run("edit.fill", json!({"color":"#2040df"})).unwrap(); app.run("tools.setColors", json!({"foreground":"#ef2000"})).unwrap(); @@ -202,11 +207,14 @@ fn the_canvas_shows_the_committed_stroke_part(part: usize) { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); + // Every zoom once, with every smoothing amount among them, rather than zoom x smoothing: the canvas branches on + // the zoom (reduced, 1:1 and magnified pictures) and only on whether smoothing is on (a held pointer repeats its + // point while smoothing catches up, `canvas/strokes.rs`); that the live stroke equals the commit at + // every zoom and smoothing amount is the engine's `live_stroke_equals_the_commit_at_every_zoom_with_smoothing` + // (`brush_cmds/tests.rs`). The zoom 4, smoothing 0.1 case is the base the cases after it change one thing of. let mut cases = Vec::new(); - for zoom in [0.5, 1.0, 4.0, 12.0] { - for smoothing in [0.0, 0.1, 0.5] { - cases.push(Case { zoom, smoothing, hardness: 0.0, depth: 8, pressure: false, flip: false }); - } + for (zoom, smoothing) in [(0.5, 0.5), (1.0, 0.0), (4.0, 0.1), (12.0, 0.0)] { + cases.push(Case { zoom, smoothing, hardness: 0.0, depth: 8, pressure: false, flip: false }); } cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 1.0, depth: 8, pressure: false, flip: false }); cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 16, pressure: false, flip: false }); @@ -214,7 +222,8 @@ fn the_canvas_shows_the_committed_stroke_part(part: usize) { cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 8, pressure: false, flip: true }); cases.push(Case { zoom: 12.0, smoothing: 0.5, hardness: 0.0, depth: 16, pressure: true, flip: true }); let mut gpu_seen = false; - for c in cases.into_iter().skip(part).step_by(4) { + // One step per `_part_N` test, so every case runs in exactly one of them. + for c in cases.into_iter().skip(part).step_by(3) { let (before, drawing, done, gpu) = frames(&mut h, c); gpu_seen |= gpu; // The stroke is on screen while drawing (not a blank canvas compared with a blank one)… @@ -248,60 +257,67 @@ fn the_canvas_shows_the_committed_stroke_part_2() { fn live_tool_camera_navigation_is_visible_in_the_input_frame() { use photocraft_ui_egui::state::Tool; let _gpu = photocraft_testkit::gpu_lock(); + // Brush only: no stroke is drawn, and the canvas has no branch on the live tool before a press. Since the canvas + // moved onto the framework it always runs the tools, then shows the picture with the camera of this pass + // (`canvas/document_display.rs` `show`: "The tools run after the controls … and before the picture"); the Mixer + // Brush's own paths (`canvas/paint_tool.rs`, `canvas/strokes.rs`) start at a press, which + // `raw_pointer_brush_and_mixer_pixels_appear_in_the_input_frame` covers. The flip (CPU or GPU picture) and the + // input (pinch zoom or wheel pan) do reach different code, so they stay, on one harness. + let tool = Tool::Brush; + let Some(mut h) = harness() else { return }; for flip in [false, true] { - for tool in [Tool::Brush, Tool::MixerBrush] { - for zoom in [false, true] { - let Some(mut h) = harness() else { return }; - let app = h.state_mut(); - app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap(); - app.run("paint.stroke", json!({"points":[[40,40],[240,160]],"size":30,"hardness":1.0,"color":"#2050df"})).unwrap(); - app.run("prefs.set", json!({"values":{"tools.overscroll":true,"general.animatedZoom":false,"general.zoomWithScrollWheel":false}})).unwrap(); - app.ui.tool = tool; - app.ui.view.flip_horizontal = flip; - app.sync_views(); - h.run_steps(4); - control(&mut h, "ui.set", json!({"zoom":1.0,"center":[150,100]})); - let at = h.state().last_canvas_rect.center() + egui::vec2(30.0, 10.0); - h.hover_at(at); - h.run_steps(2); - let before = h.state().ui.views[0].clone(); - h.input_mut().events.push(if zoom { - egui::Event::Zoom(1.25) - } else { - egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(30.0, 20.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - } - }); - h.step(); - let moved = h.state().ui.views[0].clone(); - assert!(if zoom { moved.zoom != before.zoom } else { moved.center != before.center }, "navigation was applied"); - let immediate = h.render().unwrap(); - let rect = h.state().last_canvas_rect.shrink(8.0); - h.step(); - let settled = h.render().unwrap(); - if tool == Tool::MixerBrush - && flip - && zoom - && let Ok(path) = std::env::var("PHOTOCRAFT_NAV_SNAPSHOT") - { - settled.save(path).unwrap(); - } - assert_eq!(h.state().ui.views[0].zoom, moved.zoom); - assert_eq!(h.state().ui.views[0].center, moved.center); - let mut diff = 0; - for y in rect.top() as u32..rect.bottom() as u32 { - for x in rect.left() as u32..rect.right() as u32 { - for (a, b) in immediate.get_pixel(x, y).0.into_iter().zip(settled.get_pixel(x, y).0) { - diff = diff.max(a.abs_diff(b)); - } - } - } - assert!(diff <= 1, "{tool:?} flip={flip} zoom={zoom}: canvas changes {diff}/255 one frame after navigation"); + for zoom in [false, true] { + let app = h.state_mut(); + while app.session.active().is_some() { + app.run("file.close", json!({"discard": true})).unwrap(); } + app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap(); + app.run("paint.stroke", json!({"points":[[40,40],[240,160]],"size":30,"hardness":1.0,"color":"#2050df"})).unwrap(); + app.run("prefs.set", json!({"values":{"tools.overscroll":true,"general.animatedZoom":false,"general.zoomWithScrollWheel":false}})).unwrap(); + app.ui.tool = tool; + app.ui.view.flip_horizontal = flip; + app.sync_views(); + h.run_steps(4); + control(&mut h, "ui.set", json!({"zoom":1.0,"center":[150,100]})); + let at = h.state().last_canvas_rect.center() + egui::vec2(30.0, 10.0); + h.hover_at(at); + h.run_steps(2); + let before = h.state().ui.views[0].clone(); + h.input_mut().events.push(if zoom { + egui::Event::Zoom(1.25) + } else { + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(30.0, 20.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + } + }); + h.step(); + let moved = h.state().ui.views[0].clone(); + assert!(if zoom { moved.zoom != before.zoom } else { moved.center != before.center }, "navigation was applied"); + let immediate = h.render().unwrap(); + let rect = h.state().last_canvas_rect.shrink(8.0); + h.step(); + let settled = h.render().unwrap(); + if flip + && zoom + && let Ok(path) = std::env::var("PHOTOCRAFT_NAV_SNAPSHOT") + { + settled.save(path).unwrap(); + } + assert_eq!(h.state().ui.views[0].zoom, moved.zoom); + assert_eq!(h.state().ui.views[0].center, moved.center); + let mut diff = 0; + for y in rect.top() as u32..rect.bottom() as u32 { + for x in rect.left() as u32..rect.right() as u32 { + for (a, b) in immediate.get_pixel(x, y).0.into_iter().zip(settled.get_pixel(x, y).0) { + diff = diff.max(a.abs_diff(b)); + } + } + } + assert!(diff <= 1, "{tool:?} flip={flip} zoom={zoom}: canvas changes {diff}/255 one frame after navigation"); } } } From e9f698d91c6e3cdc9faa26e11fb3ca7b7aa6ae25 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 20:40:20 +0100 Subject: [PATCH 13/25] Tests: trim redundant work out of slow ui-egui unit tests (#15368) Same code paths and assertions, fewer pixels, harnesses and frames: - every_adjustment_layer_edits_through_properties: one app per mode and depth instead of one per kind (all 16 kinds still run in all 6 settings), three drag moves and two frames after each new layer. - canvas_mips_preserve_opaque_pixels_and_partial_updates: 767 x 431 instead of 1791 x 1083; still odd sides and two partially redrawn mip levels. - blend_hover_* (4 of 5): the 1024 x 768 fixture and every view halved; the background-redraw case keeps its size. - every_paragraph_box_handle_resizes_the_box_with_snapping_on: zooms 25 % and 200 % only. - the wheel tests: 3 and 4 frames per notch instead of 30 and 40; the view is already settled then. - Shift-letter cycle: two frames per press instead of three. - guide and Cmd stand-in tables: drop rows whose tool shares a family and pointer kind with a row that stays. Co-Authored-By: Claude Opus 5.5 --- .../src/canvas/blend_viewport_tests.rs | 34 +++++++++++-------- .../src/canvas/gpu_canvas/mip_tests.rs | 6 +++- .../src/dialogs/adjust_editors/ui_tests.rs | 22 +++++++++--- crates/ui-egui/src/field_wheel_app_tests.rs | 8 ++++- crates/ui-egui/src/guide_cursor_tests.rs | 11 +++--- crates/ui-egui/src/input/hold_keys/tests.rs | 6 ++-- crates/ui-egui/src/input_tests.rs | 11 ++++-- .../src/tool_shift_cycle_order_tests.rs | 14 +++++++- .../src/tools/type_tool/canvas_tests.rs | 6 +++- 9 files changed, 85 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/canvas/blend_viewport_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_tests.rs index d1e066e6e5..e3297baeee 100644 --- a/crates/ui-egui/src/canvas/blend_viewport_tests.rs +++ b/crates/ui-egui/src/canvas/blend_viewport_tests.rs @@ -36,12 +36,14 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + // Half the 1024 × 768 canvas these views were first written for (see `check_blend_viewport`): `a` still runs off + // the right edge and `b` still lies apart from it. + app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); let ctx = app.ctx().clone(); - let a = DRect::new(724, 200, 1324, 500); - let b = DRect::new(0, 200, 300, 500); + let a = DRect::new(362, 100, 662, 250); + let b = DRect::new(0, 100, 150, 250); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); app.ui.view.pattern_preview = true; crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); @@ -136,7 +138,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + // Every view and count below is half of the 1024 × 768 fixture first used: the clip to the view + // (`blend_preview::clip_damage`) and the catch-up (`blend_preview::uncovered`) are rectangle arithmetic with no + // size threshold, and the canvas stays far below the background redraw's (that case is + // `blend_hover_during_background_redraw_restores_committed_pixels`). The whole-canvas pixel checks cost a quarter. + app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); if cpu_fallback { @@ -150,7 +156,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { layers.push(photocraft_doc::LayerId(other)); } let ctx = app.ctx().clone(); - let visible = DRect::new(256, 256, 512, 512); + let visible = DRect::new(128, 128, 256, 256); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); if cpu_fallback { @@ -161,23 +167,23 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let original = gpu.read_texels(id.0).unwrap(); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply)); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 256 * 256, app.perf.gpu_info); - assert_eq!(app.perf.last_refresh_px, 256 * 256, "hover must not recomposite offscreen pixels of a full-canvas layer"); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 128 * 128, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 128 * 128, "hover must not recomposite offscreen pixels of a full-canvas layer"); assert_visible_pixels(&mut app, visible); app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture"); - let zoomed_out = DRect::new(128, 128, 640, 640); + let zoomed_out = DRect::new(64, 64, 320, 320); assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None)); - assert_eq!(app.perf.last_refresh_px, 512 * 512, "zooming out catches up the larger visible area"); - let panned = DRect::new(640, 256, 896, 512); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "zooming out catches up the larger visible area"); + let panned = DRect::new(320, 128, 448, 256); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 256 * 256, "newly exposed pixels must catch up without a mode change"); + assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change"); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen)); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 256 * 256); + assert_eq!(app.perf.last_refresh_px, 128 * 128); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_eq!(app.perf.last_refresh_px, 256 * 256, "returning view must show the current mode"); + assert_eq!(app.perf.last_refresh_px, 128 * 128, "returning view must show the current mode"); assert_visible_pixels(&mut app, visible); assert_visible_pixels(&mut app, panned); crate::blend_preview::hover(&mut app, &layers, None); @@ -189,7 +195,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); let bounds = app.session.active().unwrap().doc.bounds(); assert_visible_pixels(&mut app, bounds); - app.run("file.new", json!({"width":1024,"height":768,"background":"white"})).unwrap(); + app.run("file.new", json!({"width":512,"height":384,"background":"white"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 1, visible, None)); app.session.set_active(0); app.sync_views(); diff --git a/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs index 61edb94bdb..33dca070fe 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs @@ -125,7 +125,11 @@ fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) { fn check_mips(gpu: &GpuCanvas) { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for (w, h) in [(1791, 1083), (513, 1), (1, 513)] { + // 767 × 431 is a single tile (`DEFAULT_TILE`) with odd sides down the chain (767, 383, 191, 95 and 431, + // 215, 107, 53), and its levels 1 and 2 are over `WHOLE_MIP_SIDE` (128), so the patch below redraws two + // levels by their damage (`mip_damage`) before the chain is redrawn whole: the paths 1791 × 1083 took, at + // a sixth of the pixels. The larger driver case stays in `partial_updates_match_a_full_rebuild_at_every_mip_level`. + for (w, h) in [(767, 431), (513, 1), (1, 513)] { let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]); // Reusing the key also covers replacing textures after a size or depth change. gpu.upload_buffer_full(1, &full, depth); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index bc3155e39d..a37518b779 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -97,8 +97,9 @@ fn drag(h: &mut Harness<'_, Box>, from: Pos2, to: Pos2) { h.run_steps(1); h.drag_at(from); h.run_steps(1); - for i in 1..=6 { - h.hover_at(from + (to - from) * (i as f32 / 6.0)); + // Three moves give the gesture several previews before its one commit, which is what the history check needs. + for i in 1..=3 { + h.hover_at(from + (to - from) * (i as f32 / 3.0)); h.run_steps(1); } h.drop_at(to); @@ -137,8 +138,21 @@ fn sliders(h: &Harness<'_, Box>) -> Vec { #[test] fn every_adjustment_layer_edits_through_properties() { for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("gray", 8), ("cmyk", 8), ("lab", 16)] { - for kind in ALL_KINDS { - let mut h = app_harness(kind, mode, depth); + // One app per document setting, not one per kind: each kind deletes the previous kind's layer and adds its + // own over the same two-tone background, so its editor opens on the stack a fresh app had (the Properties + // session is per layer, `PropertiesAdjust::new`). Every kind still runs in every mode and depth: the + // composite of each adjustment differs per mode and depth, and no other test runs all of them. + let mut h = app_harness(ALL_KINDS[0], mode, depth); + for (i, kind) in ALL_KINDS.into_iter().enumerate() { + if i > 0 { + let (previous, _) = layer(&h); + h.state_mut().run("layer.delete", json!({"layer": previous.0})).unwrap(); + h.state_mut().run(&format!("layer.newAdjustmentLayer.{kind}"), json!({})).unwrap(); + // The Properties panel shows the new layer's editor on the next frame; the second leaves its widgets + // laid out for the queries below. + h.run_steps(2); + } + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 2, "{kind} {mode}: the background and this kind's layer"); let (_, before) = layer(&h); let steps = history_len(&h); let slider = sliders(&h).first().copied(); diff --git a/crates/ui-egui/src/field_wheel_app_tests.rs b/crates/ui-egui/src/field_wheel_app_tests.rs index a427652afb..f45db09970 100644 --- a/crates/ui-egui/src/field_wheel_app_tests.rs +++ b/crates/ui-egui/src/field_wheel_app_tests.rs @@ -59,6 +59,12 @@ fn the_wheel_over_a_field_steps_it_without_a_click() { assert_eq!(view(&h), before, "the canvas didn't move"); } +/// Frames a wheel event gets to play out (0.25 s each, the harness's default step). egui's wheel smoothing reaches +/// 90 % in 0.1 s and takes the rest under one point at once, so the smoothed tail of a notch (about 50 points) ends +/// within three frames even at a 0.1 s step; four leave one to spare: the view after +/// them is the one the old forty left. +const TAIL_STEPS: usize = 4; + /// How far a wheel of `delta` lines with `modifiers` over the canvas moves the view, a Smoothing /// field focused or not, once egui's smoothed scroll has run out. The field isn't stepped. fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f32, [f32; 2]) { @@ -78,7 +84,7 @@ fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f3 phase: egui::TouchPhase::Move, modifiers, }); - h.run_steps(40); + h.run_steps(TAIL_STEPS); assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("10")), "focus {focus}: the field wasn't stepped"); let after = view(&h); (after.0 / before.0, [after.1[0] - before.1[0], after.1[1] - before.1[1]]) diff --git a/crates/ui-egui/src/guide_cursor_tests.rs b/crates/ui-egui/src/guide_cursor_tests.rs index 88d36f1e29..59ddeed269 100644 --- a/crates/ui-egui/src/guide_cursor_tests.rs +++ b/crates/ui-egui/src/guide_cursor_tests.rs @@ -84,16 +84,17 @@ const GUIDE: egui::CursorIcon = egui::CursorIcon::ResizeHorizontal; #[test] fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { let takes = |tool, latched| (tool, false, latched, true); + // One tool per family (`canvas::tools::family`): whether the guides take ⌘ is decided by family + // (`rulers::moves_with_command`, `tools::takes_command_stand_in`), and the painting family refuses a ⌘ press the + // same way for all its tools (`PaintTool::takes`). Within it, one tool per kind of pointer (`cursor_policy`): the + // Brush's tip with its centre mark, the Clone Stamp's and Quick Selection's tips without one, the Paint Bucket's + // click-tool pointer. The Eraser, Dodge, Spot Healing Brush and Smudge are more Brush-like tips. let rows = [ takes(Tool::Brush, false), - takes(Tool::Eraser, false), takes(Tool::Gradient, false), takes(Tool::PaintBucket, false), takes(Tool::CloneStamp, false), takes(Tool::Eyedropper, false), - takes(Tool::Dodge, false), - takes(Tool::SpotHealing, false), - takes(Tool::Smudge, false), takes(Tool::QuickSelection, false), takes(Tool::RectMarquee, false), takes(Tool::Lasso, false), @@ -102,10 +103,8 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { takes(Tool::Frame, false), takes(Tool::Artboard, false), takes(Tool::Brush, true), - takes(Tool::Eraser, true), takes(Tool::RectMarquee, true), (Tool::Brush, true, false, false), - (Tool::Eraser, true, false, false), (Tool::Frame, true, false, false), (Tool::Pen, false, false, false), (Tool::Hand, false, false, false), diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 08876cbc5f..0a2050b7b2 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -347,8 +347,10 @@ const CTRL_ALT: Modifiers = Modifiers { alt: true, ctrl: true, shift: false, mac /// The tools that keep ⌘ for themselves leave the layer alone. #[test] fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() { - let moves = - [Tool::Brush, Tool::Eraser, Tool::Gradient, Tool::CloneStamp, Tool::Eyedropper, Tool::Move, Tool::RectMarquee, Tool::EllipseMarquee, Tool::Lasso]; + // The Eraser is left out: it is in the Brush's family (`canvas::tools::family`), which refuses a ⌘ press the same + // way for every tool (`PaintTool::takes`); the Elliptical Marquee is the Rectangular one's marquee pass with + // another shape (`selection.rs`, `MarqueeKind`). + let moves = [Tool::Brush, Tool::Gradient, Tool::CloneStamp, Tool::Eyedropper, Tool::Move, Tool::RectMarquee, Tool::Lasso]; for tool in moves { let mut h = harness(tool); let id = with_layer(&mut h); diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 16dff9e025..e3de7b1e6a 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -261,9 +261,14 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { h.hover_at(p); h.run_steps(2); let d0 = doc_at(&h, p); + // Frames after each notch (0.25 s each, the harness's default step): a notch lands within two (egui's wheel + // smoothing reaches 90 % in 0.1 s and takes the rest under one point at once), and the old clamp pulled the zoom + // back on every frame, so three show it: the zoom and centre + // after them are the ones the old thirty left. + const NOTCH_STEPS: usize = 3; for _ in 0..14 { wheel(&h, 1.0, Modifiers::ALT); - h.run_steps(30); + h.run_steps(NOTCH_STEPS); } assert_eq!(zoom(&h), max_zoom(), "a notch past the limit lands on it exactly"); let d1 = doc_at(&h, p); @@ -271,13 +276,13 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { let c = h.state().ui.views[0].center; for _ in 0..4 { wheel(&h, 1.0, Modifiers::ALT); - h.run_steps(30); + h.run_steps(NOTCH_STEPS); } assert_eq!(zoom(&h), max_zoom()); assert_eq!(h.state().ui.views[0].center, c, "at the limit the image doesn't move"); // One notch back: 12800 / 1.1, still around the pointer. wheel(&h, -1.0, Modifiers::ALT); - h.run_steps(30); + h.run_steps(NOTCH_STEPS); assert!((zoom(&h) - max_zoom() / 1.1).abs() < 1e-2, "{}", zoom(&h)); let d2 = doc_at(&h, p); assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index 4c657440d9..67760664bc 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -51,13 +51,25 @@ fn sequence(letter: char, steps: usize) -> Vec { .collect() } +/// [`shift_press`] with two frames instead of three: the runtime takes the key in the first and the app picks the +/// tool it fired in the second (`shortcut_dispatch::pick_tool`); the third only drew the toolbar again. +fn quick_shift_press(h: &mut Harness<'static, Box>, key: Key) { + h.input_mut().events.extend([ + egui::Event::ModifiersChanged(Modifiers::SHIFT), + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }, + egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT }, + egui::Event::ModifiersChanged(Modifiers::NONE), + ]); + h.run_steps(2); +} + #[test] fn from_every_tool_shift_letter_lands_on_the_next_tool_in_toolbar_order() { let mut h = app(); for (letter, group) in groups() { for (i, from) in group.iter().enumerate() { h.state_mut().ui.tool = *from; - shift_press(&mut h, key_for(letter)); + quick_shift_press(&mut h, key_for(letter)); let want = group[(i + 1) % group.len()]; assert_eq!(h.state().ui.tool, want, "Shift+{letter} from {from:?}"); } diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index 6d89f04930..6bedef6125 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -2028,7 +2028,11 @@ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() { let scaled = Affine { m: [1.5, 0.0, 0.0, 0.75, 300.0, 300.0] }; let rotated = Affine { m: [1.2 * 0.94, 1.2 * 0.342, -1.2 * 0.342, 1.2 * 0.94, 300.0, 300.0] }; for ppp in [1.0, 2.0] { - for zoom in [0.25f32, 0.5, 1.0, 2.0] { + // The ends of the range only: the frame's handles and their grab area are screen-space parts of the + // framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and the snap reach is a screen distance, + // so the zoom only scales the view, with no step in between. 25 % and 200 % at 1x and 2x span 12.5 % to + // 200 % in points, which holds 50 % and 100 %. + for zoom in [0.25f32, 2.0] { for (name, tf) in [("plain", None), ("scaled", Some(scaled)), ("rotated", Some(rotated))] { let mut app = new_app(); assert!(app.ui.extras.snap, "snapping is on by default"); From 49c9327ce4a1a2f55b4d6e920248a20524bd2bbd Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:43:45 +0000 Subject: [PATCH 14/25] engine: is_enabled_with returns false for an unknown id without formatting its error An unknown id's disabled reason ranks every command id for "did you mean"; is_enabled_with dropped that string. The menu model asks it for every row that is not an engine command. --- crates/engine/src/session/execute.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index a94504da4f..b524d5a477 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -123,7 +123,8 @@ impl Session { /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { - self.disabled_reason_with(id, params).is_none() + // An unknown id is disabled; its reason would rank every command id for "did you mean". + commands::find(id).is_some_and(|spec| self.spec_disabled_reason(spec, id, params).is_none()) } /// Why the command can't run now (None = it can): its own precondition, or a background job @@ -134,8 +135,13 @@ impl Session { /// [`Self::disabled_reason`] for a call with `params`. pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - let Some(s) = commands::find(id) else { return Some(EngineError::UnknownCommand(id.into()).to_string()) }; - self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) + let Some(spec) = commands::find(id) else { return Some(EngineError::UnknownCommand(id.into()).to_string()) }; + self.spec_disabled_reason(spec, id, params) + } + + /// [`Self::disabled_reason_with`] for the catalogue entry `spec` of `id`. + fn spec_disabled_reason(&self, spec: &commands::CommandSpec, id: &str, params: &Value) -> Option { + self.precondition(spec, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, spec.journal)) } /// The command's own precondition for a call with `params` (their target filled in). From 5b4c7adf7558f26faec3a84d29a51ab467c49f25 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:43:45 +0000 Subject: [PATCH 15/25] ui: look up tool names in one table, and build only screen-mode commands in the command gate The toolbar resolves its whole layout through Tool::from_name several times a frame, and from_name formatted and lowercased every tool's names per lookup (about 12% of a whole-app frame). The command gate asks screen_mode_row for every command a pass resolves, which built a CommandRef for every runtime command row (about 5%). --- crates/ui-egui/src/input/shortcut_dispatch.rs | 3 ++- crates/ui-egui/src/state/tool.rs | 20 ++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 2ed03ef4b4..d9ec0910e6 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -177,7 +177,8 @@ pub(crate) fn is_screen_mode(id: &str) -> bool { /// The PhotoCraft row of a screen-mode command of the shell: the command gate judges the framework command as the /// menus judge that row. pub(crate) fn screen_mode_row(command: &CommandRef) -> Option<&'static str> { - bridge_of(command).filter(|(_, bridged)| matches!(bridged, Bridged::ScreenMode(_))).map(|(id, _)| id) + // The command gate asks this for every command a pass resolves: only the screen-mode rows build their command. + RUNTIME_COMMANDS.iter().find(|(_, bridged)| matches!(bridged, Bridged::ScreenMode(_)) && bridged.command() == *command).map(|(id, _)| *id) } /// The id of the command that steps a tool group to its next tool: the group is named by its key. diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 66aa7d53f6..ec6be52664 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -317,11 +317,21 @@ impl Tool { _ => "•", } } + /// The tool `s` names: its variant name, that name without "marquee", or its label, in any case and with spaces, + /// `_` and `-` ignored. The first tool of [`Tool::ALL`] a spelling names wins. pub fn from_name(s: &str) -> Option { - let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); - Tool::ALL.into_iter().find(|t| { - let a = format!("{t:?}").to_ascii_lowercase(); - n == a || n == a.replace("marquee", "") || n == t.label().to_ascii_lowercase().replace(' ', "") - }) + // The toolbar resolves its whole layout through here every frame: one table instead of formatting every tool's names per lookup. + static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); + let names = NAMES.get_or_init(|| { + let mut names = std::collections::HashMap::new(); + for t in Tool::ALL { + let a = format!("{t:?}").to_ascii_lowercase(); + for spelling in [a.replace("marquee", ""), t.label().to_ascii_lowercase().replace(' ', ""), a] { + names.entry(spelling).or_insert(t); + } + } + names + }); + names.get(&s.to_ascii_lowercase().replace([' ', '_', '-'], "")).copied() } } From b7ccf085c7a7ec603627b203f5df0c2c42af3aa4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:43:45 +0000 Subject: [PATCH 16/25] tests: tone_targets sample through the canvas and dialogs alone The picker tests drove the whole window (panels, menus, bars) for every case of their mode, depth and target matrix, and zoomed with eight Zoom In rounds. The canvas pass and the dialogs are what sampling goes through; the harness draws those, sets the zoom once, and no longer sets up the app's context a second time. --- crates/ui-egui/tests/it/tone_targets.rs | 34 +++++++++++++------------ 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index cedcb8a773..4fdd29ddd1 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -68,26 +68,28 @@ fn value(app: &PhotocraftApp, target: ChannelTarget) -> f32 { } /// Render real modal controls with accessibility enabled for input-driven assertions. +/// The app's context is set up already ([`PhotocraftApp::new`]). fn harness(app: Box) -> Harness<'static, Box> { - let h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| dialogs::run(app, ui), app); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - h + Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| dialogs::run(app, ui), app) } -/// The whole app, canvas included: the pointer requests of a picker's samples reach the canvas pass only here. -fn canvas_harness(app: Box) -> Harness<'static, Box> { - // The app keeps the context it was made on: the harness runs the frames on it, so the canvas the app reads is the one drawn. - let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1200.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); +/// The document canvas and the dialogs over it: a picker's samples are pointer requests the canvas pass takes, as in +/// the app. The rest of the window (panels, menus, bars) plays no part in sampling, so it is left out. +fn canvas_harness(mut app: Box) -> Harness<'static, Box> { + // The window's frame keeps a view per document; the canvas alone draws the views it is given. + app.sync_views(); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1200.0, 900.0)).with_max_steps(64).build_ui_state( + |ui, app| { + egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(app, ui)); + dialogs::run(app, ui); + }, + app, + ); h.run_steps(3); - // A 32 px document at 100 % sits under the dialog's centred window, which stops the picker's press: zoom to 12x so the left part of the image lies clear of the dialog (no animation, so the view is final at once). - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); - for _ in 0..8 { - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.run_steps(2); - } + // The dialog's window is centred and stops a press under it: at 12x with the view centred right of the 32 px image, + // the image's top-left part lies clear of the dialog, at the canvas's left. + let reply = control(&mut h, "ui.set", json!({"zoom": 12, "center": [38, 16]})); + assert_eq!(reply["ok"], true, "the view zooms: {reply}"); h } From d4797333de9f9d6b9cc1be3f04b33fe8ac1b9198 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 20:47:59 +0100 Subject: [PATCH 17/25] Tests: trim repeated solves and loops in engine and GPU tests (#15367) - parity.rs: the two paging tests use a 660x580 document (3x3 pages, one interior cell) instead of 1100x900, and eviction runs 2 rounds; the residency tests that share the large document keep it. 16-bit runs only where the GPU reads the 16-bit upload (one effect stack, Dissolve and pattern cases). The disjoint-damage test paints 2 distinct series of 8 strokes and isolates its layers so strokes capture checkpoints, which makes its bytes assert able to fail. many_layers_submit_inside_one_chunk_paged is removed: its stats equal the whole test's. - Coarse preview: drop an unchecked full-resolution solve; colour tests reuse solves and use Extend where Move only adds an unread fill. - Crop fill eligibility is a unit test on additional_target; the integration test keeps 3 cases. - PSD write oracle: one run with a passing and a failing case instead of two runs. Co-Authored-By: Claude Opus 5.5 --- .../tests/it/psd_write_oracle.rs | 29 ++-- .../cmd/retouch_cmds/content_aware_move.rs | 4 +- .../content_aware_move_color_tests.rs | 31 +++-- crates/engine/src/crop_fill.rs | 49 +++++++ .../tests/it/crop_content_aware_layers.rs | 32 ++--- crates/gpu/tests/it/parity.rs | 129 +++++++++++------- 6 files changed, 180 insertions(+), 94 deletions(-) diff --git a/apps/photocraft-cli/tests/it/psd_write_oracle.rs b/apps/photocraft-cli/tests/it/psd_write_oracle.rs index 524f476fa1..44e5c57e22 100644 --- a/apps/photocraft-cli/tests/it/psd_write_oracle.rs +++ b/apps/photocraft-cli/tests/it/psd_write_oracle.rs @@ -19,27 +19,30 @@ fn edited_psd_roundtrip_is_checked_and_bad_expectations_fail() { .unwrap(); assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr)); let hash = xtask::sha256::hex(&fs::read(&base).unwrap()); - let mut recipe = json!({"version":1,"corpus_revision":"synthetic","cases":[{ - "id":"style", "base":"base.psd", "base_sha256":hash, "target":{"kind":"Type","name":"Oracle"}, - "commands":[{"command":"type.antiAlias.crisp","params":{}}], - "checks":[{"op":"changed_to","path":"/text/antialias","value":"Crisp"},{"op":"unchanged","path":"/text/text"}] - }]}); + // One run with a right and a wrong expectation of the same edit: the runner hashes the CLI, + // asks git and makes its output directory once, and still has to report the first case as + // passing and the second as failing (and fail itself). + let case = |id: &str, value: &str| { + json!({ + "id":id, "base":"base.psd", "base_sha256":hash, "target":{"kind":"Type","name":"Oracle"}, + "commands":[{"command":"type.antiAlias.crisp","params":{}}], + "checks":[{"op":"changed_to","path":"/text/antialias","value":value},{"op":"unchanged","path":"/text/text"}] + }) + }; + let recipe = json!({"version":1,"corpus_revision":"synthetic","cases":[case("style", "Crisp"), case("wrong", "Sharp")]}); let recipe_path = root.join("recipes.json"); let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap(); let cli_path = Path::new(&cli).to_str().unwrap(); let corpus = root.to_str().unwrap(); let recipe_name = recipe_path.to_str().unwrap(); - let output = root.join("success"); + let output = root.join("report"); let args = [recipe_name, corpus, cli_path, output.to_str().unwrap()]; - xtask::psd_write_oracle::run(&src, &args).unwrap(); + assert!(xtask::psd_write_oracle::run(&src, &args).is_err(), "a failing case fails the run"); let report: Value = serde_json::from_slice(&fs::read(output.join("report.json")).unwrap()).unwrap(); + assert_eq!(report["cases"][0]["id"], "style"); assert_eq!(report["cases"][0]["status"], "pass"); assert_eq!(report["cases"][0]["photoshop"]["opens"], "not_run"); - recipe["cases"][0]["checks"][0]["value"] = json!("Sharp"); - fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap(); - let bad_output = root.join("failure"); - assert!(xtask::psd_write_oracle::run(&src, &[recipe_name, corpus, cli_path, bad_output.to_str().unwrap()]).is_err()); - let bad: Value = serde_json::from_slice(&fs::read(bad_output.join("report.json")).unwrap()).unwrap(); - assert_eq!(bad["cases"][0]["status"], "fail"); + assert_eq!(report["cases"][1]["id"], "wrong"); + assert_eq!(report["cases"][1]["status"], "fail"); } diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index 8d106b7bc9..181aebfd4f 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -891,7 +891,9 @@ mod tests { let b = got.bounds(); let before = s.active().unwrap().doc.layers[0].surface().unwrap().read_region(b); assert!(got.layers[0].surface().unwrap().read_region(b) != before, "the preview moves something"); - s.execute("paint.contentAwareMove", p).unwrap(); + // That the command takes this selection too is shown by `preview` above: it runs the + // command's own `plan`, which rejects an empty selection, at full resolution. The + // command's full-resolution solve is left out: nothing here checked its result. } } diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs index 55e2d306bf..ac19725de7 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -115,8 +115,10 @@ fn the_core_fit_shifts_brightness_and_leaves_a_hue_alone() { #[test] fn color_ten_on_green_leaves_the_middle_and_blends_the_edge() { // Selection 120,120 40×40 dragged (140,140) → (600,420). Row y 420 is the middle of the landing. + // Color 0 is only read at the landing, which Extend makes as Move does (`run_move` step 1), + // without Move's second fill of the old place. let mut kept = green_doc(); - select_and_move(&mut kept, [120, 120, 40, 40], [460, 280], 0, "move"); + select_and_move(&mut kept, [120, 120, 40, 40], [460, 280], 0, "extend"); let mut fitted = green_doc(); select_and_move(&mut fitted, [120, 120, 40, 40], [460, 280], 10, "move"); @@ -144,9 +146,12 @@ fn color_ten_on_green_leaves_the_middle_and_blends_the_edge() { #[test] fn a_brightness_change_shifts_the_middle_only_past_color_five() { + // Every check reads the landing, which Move and Extend make with the same code (`run_move` + // step 1); Extend skips Move's fill of the old place, which nothing here reads. The drop + // straight down below stays a Move. let row = |color: u64| { let mut s = ramp_doc(); - select_and_move(&mut s, [120, 120, 40, 40], [460, 280], color, "move"); + select_and_move(&mut s, [120, 120, 40, 40], [460, 280], color, "extend"); (levels(&s, 590, 420), levels(&s, 600, 420)) }; let (light, dark) = row(0); @@ -171,21 +176,23 @@ fn a_brightness_change_shifts_the_middle_only_past_color_five() { #[test] fn a_flat_patch_matches_the_new_surroundings_at_color_ten() { - let middle = |color: u64, mode: &str| { + let moved_with = |color: u64, mode: &str| { let mut s = flat_doc(); select_and_move(&mut s, [150, 250, 100, 100], [400, 0], color, mode); - levels(&s, 600, 300) + s }; - for mode in ["move", "extend"] { - assert_eq!(middle(0, mode), [204, 204, 204], "{mode} color 0 keeps 204"); - assert_eq!(middle(3, mode), [204, 204, 204], "{mode} color 3 leaves the middle"); - assert_eq!(middle(10, mode), [51, 51, 51], "{mode} color 10 becomes 51"); + // Move and Extend land the content with the same code (`run_move` step 1); Move only adds + // the fill of the old place, away from the landing. So Colors 0 and 3 run once (Extend, one + // fill instead of two), and Color 10 runs in both modes, whose landings are compared pixel + // by pixel below. + assert_eq!(levels(&moved_with(0, "extend"), 600, 300), [204, 204, 204], "color 0 keeps 204"); + assert_eq!(levels(&moved_with(3, "extend"), 600, 300), [204, 204, 204], "color 3 leaves the middle"); + let moved = moved_with(10, "move"); + let extended = moved_with(10, "extend"); + for (mode, s) in [("move", &moved), ("extend", &extended)] { + assert_eq!(levels(s, 600, 300), [51, 51, 51], "{mode} color 10 becomes 51"); } // The landing itself agrees; the old place is the part Move refills and Extend keeps. - let mut moved = flat_doc(); - select_and_move(&mut moved, [150, 250, 100, 100], [400, 0], 10, "move"); - let mut extended = flat_doc(); - select_and_move(&mut extended, [150, 250, 100, 100], [400, 0], 10, "extend"); for y in [256, 300, 340] { for x in [556, 600, 640] { assert_eq!(levels(&moved, x, y), levels(&extended, x, y), "move and extend agree at {x},{y}"); diff --git a/crates/engine/src/crop_fill.rs b/crates/engine/src/crop_fill.rs index f5da0de07b..d127168220 100644 --- a/crates/engine/src/crop_fill.rs +++ b/crates/engine/src/crop_fill.rs @@ -339,4 +339,53 @@ mod tests { assert!(c.covered(6, 0, m, None), "x = 4"); assert!(!c.covered(7, 0, m, None), "x = 5"); } + + /// The active layer is a second fill target only as a visible, unlocked pixel layer with + /// visible, unlocked ancestors: each unmeasured state keeps the Background alone. Every state + /// here is a pure function of the layer tree; `crop_content_aware_layers.rs` runs a few of them + /// through `image.crop`. + #[test] + fn only_a_visible_unlocked_active_raster_adds_a_target() { + use photocraft_doc::{Layer, LayerContent, TextLayer}; + let mut s = crate::Session::new(); + s.execute("file.new", serde_json::json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + let base = (*s.active().unwrap().doc).clone(); + let fmt = base.pixel_format(); + let background = base.background().unwrap().id; + // The active layer `layer`, at the root or inside a group that `ancestor` edits. + let with = |layer: Layer, ancestor: Option| { + let mut d = base.clone(); + let id = layer.id; + match ancestor { + None => d.layers.push(layer), + Some(edit) => { + let mut group = Layer::group("Ancestor", vec![layer]); + edit(&mut group); + d.layers.push(group); + } + } + (additional_target(&d, Some(id)), id) + }; + let (got, id) = with(Layer::raster("Active", fmt), None); + assert_eq!(got, Some(id), "a visible, unlocked raster"); + let plain_group: fn(&mut Layer) = |_| {}; + let (got, id) = with(Layer::raster("Active", fmt), Some(plain_group)); + assert_eq!(got, Some(id), "inside a visible, unlocked group"); + let text = Layer::new("T", LayerContent::Text(TextLayer { text: "T".into(), ..Default::default() })); + assert_eq!(with(text, None).0, None, "a type layer"); + let mut hidden = Layer::raster("Active", fmt); + hidden.visible = false; + assert_eq!(with(hidden, None).0, None, "a hidden layer"); + for lock in ["all", "pixels", "transparency", "position", "artboard"] { + let mut locked = Layer::raster("Active", fmt); + assert!(locked.locks.set(lock, true)); + assert_eq!(with(locked, None).0, None, "lock {lock}"); + } + let hidden_group: fn(&mut Layer) = |g| g.visible = false; + assert_eq!(with(Layer::raster("Active", fmt), Some(hidden_group)).0, None, "a hidden ancestor"); + let locked_group: fn(&mut Layer) = |g| assert!(g.locks.set("pixels", true)); + assert_eq!(with(Layer::raster("Active", fmt), Some(locked_group)).0, None, "a locked ancestor"); + assert_eq!(additional_target(&base, Some(background)), None, "the Background itself"); + assert_eq!(additional_target(&base, None), None, "no active layer"); + } } diff --git a/crates/engine/tests/it/crop_content_aware_layers.rs b/crates/engine/tests/it/crop_content_aware_layers.rs index bd3ee0db2c..97511fb949 100644 --- a/crates/engine/tests/it/crop_content_aware_layers.rs +++ b/crates/engine/tests/it/crop_content_aware_layers.rs @@ -236,34 +236,24 @@ fn background_active_is_not_a_second_target() { } /// Verifies Background-only fill for ineligible active layers and Delete Cropped Pixels off. +/// Which active layers are a second target is a pure function of the layer tree, checked for every +/// unmeasured state (type, hidden, each lock, hidden or locked ancestor) by `crop_fill`'s +/// `only_a_visible_unlocked_active_raster_adds_a_target`. Through the command, straight and +/// turned, run one state the layer itself rules out (type), one an ancestor rules out (a locked +/// group) and Delete Cropped Pixels off, its own branch of `fill_uncovered`. #[test] fn unmeasured_active_targets_and_delete_off_keep_the_legacy_target() { for turned in [false, true] { let (x, y) = extension_sample(turned); - for case in 0..10 { + for (text, locked_group, delete) in [(true, false, true), (false, true, true), (false, false, false)] { let (mut s, ids) = scene(turned); - let active = match case { - 0 => ids.text, - 1 => ids.hidden, - _ => ids.quads, - }; - if (2..7).contains(&case) { - s.edit("Lock active", |d, _| { - assert!(d.layer_mut(active).unwrap().locks.set(["all", "pixels", "transparency", "position", "artboard"][case - 2], true)); - Ok(()) - }) - .unwrap(); - } - if case >= 8 { + let active = if text { ids.text } else { ids.quads }; + if locked_group { s.edit("Group active", |d, _| { let i = d.layers.iter().position(|layer| layer.id == active).unwrap(); let child = d.layers.remove(i); let mut group = Layer::group("Ancestor", vec![child]); - if case == 8 { - group.visible = false; - } else { - assert!(group.locks.set("pixels", true)); - } + assert!(group.locks.set("pixels", true)); d.layers.insert(i, group); Ok(()) }) @@ -271,9 +261,7 @@ fn unmeasured_active_targets_and_delete_off_keep_the_legacy_target() { } select(&mut s, active); let mut p = frame(turned); - if case == 7 { - p["deleteCroppedPixels"] = json!(false); - } + p["deleteCroppedPixels"] = json!(delete); let plain = plain_control(&mut s, &p); crop(&mut s, p, true); pixel(doc(&s), ids.background, x, y, WHITE); diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 5301c49da7..61bd699bb2 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -474,27 +474,31 @@ fn root_checkpoints_keep_clipping_groups_and_adjustments_whole() { fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { let Some(mut g) = gpu() else { return }; let mut doc = base_doc(600, 300); - doc.layers.push(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2)); - doc.layers.push(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2)); + // Each layer in a pass of its own (`alone`): batched into one run, the stack has no + // checkpoint below the top layer, so no render would capture and the byte count could not + // grow whatever the admission did. + doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); + doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "warm"); + // Each series paints 8 rectangles. The second series' rectangles are all new (7 px across + // and 65 px down from the first's) but in the same chunk (the 600 x 300 document is one + // chunk at `CHUNK`), so a cache entry per damage rectangle would add 8 entries. (The four + // series of 24 this replaces painted the same 24 rectangles every time.) let strokes = |g: &mut Gpu, doc: &Document, pass: i32| { - for i in 0..24u32 { - let x = 40 + ((i + pass as u32 * 13) % 8) * 60; - let y = 30 + (i / 8) * 60; - diff_rect(g, doc, Rect::new(x as i32, y as i32, x as i32 + 40, y as i32 + 30), "stroke").unwrap(); + for i in 0..8 { + let (x, y) = (40 + i * 60 + pass * 7, 30 + pass * 65); + diff_rect(g, doc, Rect::new(x, y, x + 40, y + 30), "stroke").unwrap(); } }; - for pass in 0..2 { - doc.layers[2].opacity = 0.3 + pass as f32 * 0.1; - strokes(&mut g, &doc, pass); - } - // The same grid chunks hold every stroke: no entry-per-rectangle growth between passes. + doc.layers[2].opacity = 0.3; + strokes(&mut g, &doc, 0); + // The same grid chunks hold every stroke: no entry-per-rectangle growth between series. let bytes = g.comp.composite_cache_bytes(); assert!(bytes > 0); - for pass in 2..4 { - doc.layers[2].opacity = 0.3 + pass as f32 * 0.1; - strokes(&mut g, &doc, pass); - } + // 0.6, the last opacity the four series this replaces left, so what follows renders the + // same document as before. + doc.layers[2].opacity = 0.6; + strokes(&mut g, &doc, 1); assert_eq!(g.comp.composite_cache_bytes(), bytes, "partial damages must not add entries"); // A full-canvas render still populates the whole chunks, and the top edit afterwards hits. check(&mut g, &doc, "full refresh after strokes"); @@ -1425,7 +1429,12 @@ fn small_layers_composite_over_their_bounds() { check(&mut g, &big, "small layers across chunks"); } -fn many_layers_submit_inside_one_chunk_mode(paged: bool) { +/// One compositor is enough: at 16 x 12 the document is one page and one chunk under the whole +/// texture limit and under [`PAGED_LIMIT`] alike, and both draw it through the same `run_cell`. +/// The paged run this replaces reported the same `Stats`, field for field (1202 passes, 2401 +/// tiles uploaded, 1 flush, 1 chunk, 1 cell). +#[test] +fn many_layers_submit_inside_one_chunk_whole() { // P12: a refresh recorded every pass of a page cell into one command buffer, and with a few // hundred layers Metal ran out of command buffers (device lost, "pc_compose_uniforms is // invalid"). 1200 layers need well over 1000 passes in the document's only chunk: each is @@ -1443,24 +1452,13 @@ fn many_layers_submit_inside_one_chunk_mode(paged: bool) { d.layers.push(l); } let cpu = photocraft_compose::render(&d, d.bounds()); - let comp = if paged { &mut g.paged } else { &mut g.comp }; - let (out, stats) = photocraft_gpu::render_to_vec_stats(comp, &g.device, &g.queue, &d, d.bounds()).unwrap(); - assert!(worst_diff(&cpu.px, &out).0 <= TOL, "1200 layers, paged={paged}"); + let (out, stats) = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds()).unwrap(); + assert!(worst_diff(&cpu.px, &out).0 <= TOL, "1200 layers"); assert_eq!(stats.layers_batched, 0, "{stats:?}"); assert_eq!(stats.chunks, 1); assert!(stats.flushes > 0, "{stats:?}"); } -#[test] -fn many_layers_submit_inside_one_chunk_whole() { - many_layers_submit_inside_one_chunk_mode(false); -} - -#[test] -fn many_layers_submit_inside_one_chunk_paged() { - many_layers_submit_inside_one_chunk_mode(true); -} - #[test] fn runs_of_plain_layers_blend_in_one_pass() { // Consecutive plain layers are drawn several to a pass (`fs_layerbatch`). Every layer mode at @@ -1901,8 +1899,19 @@ fn fx_check(g: &mut Gpu, doc: &Document, what: &str) -> photocraft_gpu::Stats { fn layer_effects_every_kind() { let Some(mut g) = gpu() else { return }; let mut failures = Vec::new(); + // On the GPU a 16-bit document differs only in the layer upload + // (`convert::rgb_gray16_to_f16`) and in what that input does to Dissolve's threshold and to + // pattern pixels: 16 bits run every Dissolve and pattern case, and the full stack (every kind + // at once) for the rest. Every case runs at 8 bits. + let depth_sensitive = |fx: &[Effect]| { + let text = format!("{fx:?}"); + text.contains("Dissolve") || text.contains("Pattern") + }; for depth in [SampleType::U8, SampleType::U16] { for (name, fx) in effect_cases() { + if depth == SampleType::U16 && name != "full stack" && !depth_sensitive(&fx) { + continue; + } let mut d = fx_doc(96, 80, depth); d.patterns.push(checker_pattern()); let mut l = blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.9, 0.4, 0.2]); @@ -1985,6 +1994,12 @@ fn exterior_effects_merge_from_the_shape_at_any_fill() { ]; for depth in [SampleType::U8, SampleType::U16] { for (name, fx) in &stacks { + // The merge (`effect_exterior`, `fs_fxmerge`) has no depth branch on the GPU or the + // CPU: depth only changes how the layer is uploaded (`convert::rgb_gray16_to_f16`). The + // stack with both effects covers that at 16 bits; every stack runs at 8 bits. + if depth == SampleType::U16 && *name != "shadow and glow" { + continue; + } for (opacity, fill, blend) in [ (1.0, 1.0, BlendMode::Normal), (0.8, 0.6, BlendMode::Normal), @@ -3083,30 +3098,50 @@ fn unbuildable_pipelines_are_an_error_not_a_panic() { /// A document several pages wide under [`PAGED_LIMIT`]: pixel layers crossing page borders (one /// masked, one off-canvas), a big effect layer whose region exceeds the limit (maps built per -/// page cell), a type layer with a shadow, an adjustment, a clipped group and a gradient fill. +/// page cell), a type layer with a shadow across a border, an adjustment, a clipped group and a +/// gradient fill. 1100 x 900 (5 x 4 pages) for the residency and budget tests, whose views and +/// ratios are measured on it. fn big_doc() -> Document { - let (w, h) = (1100, 900); + big_doc_sized(false) +} + +/// [`big_doc`] at 660 x 580, 3 x 3 pages, with every layer moved and sized to cross the same +/// borders: the middle cell has page borders on all four sides and the four inner page corners, +/// so it holds every border and corner case of the larger document at about 40 % of its pixels. +fn small_big_doc() -> Document { + big_doc_sized(true) +} + +fn big_doc_sized(small: bool) -> Document { + // Each geometry as (1100 x 900 value, 660 x 580 value). + let pick = |large: [i32; 4], reduced: [i32; 4]| { + let [x0, y0, x1, y1] = if small { reduced } else { large }; + Rect::new(x0, y0, x1, y1) + }; + let (w, h) = if small { (660, 580) } else { (1100, 900) }; let mut d = fx_doc(w, h, SampleType::U8); // Right over the background: adjustment results round to 8 bits, which would turn sub-LSB // float differences of blends beneath into whole steps. let mut adj = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)); adj.opacity = 0.6; - adj.mask = Some(mask(Rect::new(240, 0, 800, 520), 83, 0.0)); + adj.mask = Some(mask(pick([240, 0, 800, 520], [240, 0, 560, 520]), 83, 0.0)); d.layers.push(adj); - let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(-30, 200, 700, 820), 81, 0.0); + let mut top = noise_layer("top", PixelFormat::RGBA8, pick([-30, 200, 700, 820], [-30, 200, 620, 600]), 81, 0.0); top.blend = BlendMode::Multiply; - top.mask = Some(mask(Rect::new(100, 240, 600, 700), 82, 1.0)); + top.mask = Some(mask(pick([100, 240, 600, 700], [100, 240, 500, 540]), 82, 1.0)); d.layers.push(top); let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1; - let mut big = blob("big", d.pixel_format(), 520.0, 450.0, 330.0, [0.9, 0.4, 0.2]); + let (bx, by, br) = if small { (330.0, 290.0, 200.0) } else { (520.0, 450.0, 330.0) }; + let mut big = blob("big", d.pixel_format(), bx, by, br, [0.9, 0.4, 0.2]); big.effects.items = stack; big.effects.items.push(Effect::OuterGlow(glow(FxPaint::Color(Color::rgb(0.2, 1.0, 0.6)), GlowTechnique::Softer, 40.0, 0.2, GlowSource::Edge))); d.layers.push(big); - let mut text = as_text(blob("type", d.pixel_format(), 900.0, 150.0, 90.0, [0.1, 0.2, 0.9])); + let (tx, ty, tr) = if small { (560.0, 120.0, 60.0) } else { (900.0, 150.0, 90.0) }; + let mut text = as_text(blob("type", d.pixel_format(), tx, ty, tr, [0.1, 0.2, 0.9])); text.effects.items = vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.8, 135.0, 12.0, 20.0, 0.0))]; d.layers.push(text); - let a = noise_layer("ga", PixelFormat::RGBA8, Rect::new(200, 500, 1000, 880), 84, 0.6); - let mut c = noise_layer("gc", PixelFormat::RGBA8, Rect::new(0, 600, 1100, 700), 85, 0.0); + let a = noise_layer("ga", PixelFormat::RGBA8, pick([200, 500, 1000, 880], [150, 400, 620, 570]), 84, 0.6); + let mut c = noise_layer("gc", PixelFormat::RGBA8, pick([0, 600, 1100, 700], [0, 450, 660, 520]), 85, 0.0); c.clipped = true; c.blend = BlendMode::Screen; let mut grp = Layer::group("g", vec![a, c]); @@ -3124,20 +3159,20 @@ fn big_doc() -> Document { fn documents_larger_than_the_texture_limit() { let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner()); let Some(mut g) = gpu() else { return }; - let mut d = big_doc(); + let mut d = small_big_doc(); assert!(g.paged.supports(&d).is_ok()); // Every pass sees page borders, and effect maps and blurs crossing them. check(&mut g, &d, "big document"); let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1; - assert!(s.cells >= 20 && s.chunks == s.cells, "{s:?}"); - // A viewport off the page grid covers only its cells. - let view = Rect::new(300, 330, 790, 610); + assert!(s.cells >= 9 && s.chunks == s.cells, "{s:?}"); + // A viewport off the page grid covers only its cells (3 x 2). + let view = Rect::new(200, 230, 530, 430); diff_rect(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}")); let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, view).unwrap().1; assert_eq!(s.cells, 6, "{s:?}"); // A dab across a page corner on the effect layer, and an edit elsewhere. - d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(500, 490, 530, 530), &[0.1, 0.1, 0.9, 1.0]); - d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(250, 250, 270, 270), &[0.0, 0.0, 0.0, 0.0]); + d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(240, 240, 270, 270), &[0.1, 0.1, 0.9, 1.0]); + d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(500, 250, 520, 270), &[0.0, 0.0, 0.0, 0.0]); check(&mut g, &d, "after dabs"); let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1; assert_eq!((s.tiles_uploaded, s.fx_shapes), (0, 0), "nothing changed since the last render: {s:?}"); @@ -3147,13 +3182,15 @@ fn documents_larger_than_the_texture_limit() { fn pages_are_evicted_under_the_budget() { let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner()); let Some(mut g) = gpu() else { return }; - let mut d = big_doc(); + let mut d = small_big_doc(); check(&mut g, &d, "warm"); let all = g.paged.resident_bytes(); // A budget of one page: everything but the cell being drawn is evicted as the render goes. let page = u64::from(g.paged.page_size()).pow(2) * 4; g.paged.set_resident_budget(page); - for round in 0..3 { + // Round 0 evicts from a warm, fully resident state; round 1 brings back pages evicted with + // the edits made meanwhile (a third round repeated round 1). + for round in 0..2 { let cpu = timed("eviction CPU reference", || photocraft_compose::flatten(&d)); let (out, s) = timed("eviction GPU render/readback", || photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds())).unwrap(); From 5456a5a81241f4e325a42473ce971ffc068e7f01 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 19:57:50 +0000 Subject: [PATCH 18/25] Tests: the nextest gpu group holds only the tests that build a GPU device The gpu group (at most 4 at a time) was chosen by name: every ui-egui integration test and every test whose path contained canvas, gpu, mip or type_tool. On main's gate that put about 680 ui-egui tests that never open a device on four slots. The group is now photocraft-gpu plus every test in a module named `gpu_tests` or `_gpu_tests`: - ui-egui integration tests that draw on a device move to tests/it/gpu_tests/; mixed files and unit tests keep their GPU tests in a nested `gpu_tests` module or a `*_gpu_tests` file. - photocraft-automation's GPU backend tests are `gpu_backend::gpu_tests`. - batch_export_options checks menus and exported bytes, so it runs on the CPU canvas instead of a GPU harness. No test assertion changes. The Windows priority list follows the moved test names. --- .config/nextest.toml | 20 +- crates/automation/tests/it/gpu_backend.rs | 2 +- crates/ui-egui/src/canvas.rs | 6 +- .../ui-egui/src/canvas/background_redraw.rs | 2 + .../src/canvas/background_redraw/gpu_tests.rs | 664 ++++++++++++++++ .../src/canvas/background_redraw/tests.rs | 663 +--------------- ...t_tests.rs => blend_viewport_gpu_tests.rs} | 0 ...d_tests.rs => cpu_background_gpu_tests.rs} | 0 crates/ui-egui/src/canvas/gpu_canvas.rs | 4 +- .../{mip_tests.rs => mip_gpu_tests.rs} | 0 .../{sharp_tests.rs => sharp_gpu_tests.rs} | 0 .../ui-egui/src/canvas/raster_source/tests.rs | 70 +- crates/ui-egui/src/canvas/tests.rs | 62 +- crates/ui-egui/src/dialogs/camera_raw_gpu.rs | 2 +- .../export_dialog/srgb_default_tests.rs | 18 +- crates/ui-egui/src/gpu_status.rs | 150 ++-- crates/ui-egui/src/zoom_mode_tests.rs | 140 ++-- .../ui-egui/tests/it/batch_export_options.rs | 10 +- crates/ui-egui/tests/it/gpu_device_loss.rs | 717 +++++++++--------- .../it/{ => gpu_tests}/adjust_preview_gpu.rs | 0 .../arbitrary_rotation_preview.rs | 0 .../tests/it/{ => gpu_tests}/canvas_16f.rs | 0 .../it/{ => gpu_tests}/checker_canvas.rs | 0 .../{ => gpu_tests}/color_managed_canvas.rs | 0 .../it/{ => gpu_tests}/display_shadows.rs | 0 .../it/{ => gpu_tests}/drag_preview_canvas.rs | 0 .../it/{ => gpu_tests}/full_res_preview.rs | 0 .../it/{ => gpu_tests}/live_stroke_canvas.rs | 0 .../{ => gpu_tests}/pattern_preview_canvas.rs | 0 .../it/{ => gpu_tests}/ui_scale_canvas.rs | 0 crates/ui-egui/tests/it/layout_perf.rs | 76 +- crates/ui-egui/tests/it/main.rs | 27 +- docs/development.md | 2 +- 33 files changed, 1336 insertions(+), 1299 deletions(-) create mode 100644 crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs rename crates/ui-egui/src/canvas/{blend_viewport_tests.rs => blend_viewport_gpu_tests.rs} (100%) rename crates/ui-egui/src/canvas/{cpu_background_tests.rs => cpu_background_gpu_tests.rs} (100%) rename crates/ui-egui/src/canvas/gpu_canvas/{mip_tests.rs => mip_gpu_tests.rs} (100%) rename crates/ui-egui/src/canvas/gpu_canvas/{sharp_tests.rs => sharp_gpu_tests.rs} (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/adjust_preview_gpu.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/arbitrary_rotation_preview.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/canvas_16f.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/checker_canvas.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/color_managed_canvas.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/display_shadows.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/drag_preview_canvas.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/full_res_preview.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/live_stroke_canvas.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/pattern_preview_canvas.rs (100%) rename crates/ui-egui/tests/it/{ => gpu_tests}/ui_scale_canvas.rs (100%) diff --git a/.config/nextest.toml b/.config/nextest.toml index ee1a1a5390..8fef7a696b 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -12,11 +12,17 @@ nextest-version = "0.9.150" # GPU tests: each test is its own process here, so the in-process `gpu_lock()` mutexes no longer # serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so # this group caps them at 4. scripts/ci-gpu-lavapipe.py reads this group's filters directly. +# +# 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 @@ -72,16 +78,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 e346aff3df..49a8473f33 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,24 +2,16 @@ 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_shadows; -mod drag_preview_canvas; mod eraser_reset_defaults; -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. @@ -28,13 +20,26 @@ 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 system_locale; mod tone_targets; -mod ui_scale_canvas; mod variables_data_sets; mod workspace_presets; + +// 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 3b14f7dbc2..90fe9ac3d8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -64,7 +64,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 From 2a83631d46235ec752b0d74c21c3c37aadee9450 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:19:02 +0000 Subject: [PATCH 19/25] CI: the GPU shard runs the whole gpu group, perf jobs share one cache entry, CI-only changes run Windows --- .github/workflows/ci.yml | 4 ++-- .github/workflows/perf-nightly.yml | 2 +- xtask/src/main.rs | 19 +++++++++++++++++-- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8bf8c05de8..28e9a01d88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,7 +128,7 @@ jobs: else echo "web=false" >> "$GITHUB_OUTPUT" fi - if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|craft-i18n\.rev$|(.*/)?build\.rs$|\.github/workflows/ci\.yml$)'; then + if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/|crates/(ui-egui|text|gpu|tablet|heif|format)/|Cargo\.lock$|craft-i18n\.rev$|(.*/)?build\.rs$|\.cargo/config\.toml$|\.config/nextest\.toml$|xtask/|scripts/ci-test-shard\.sh$|\.github/workflows/ci\.yml$)'; then echo "windows=true" >> "$GITHUB_OUTPUT" else echo "windows=false" >> "$GITHUB_OUTPUT" @@ -540,7 +540,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: prefix-key: v1-rust - key: perf-release + shared-key: perf-release save-if: false - name: Quick performance suite run: cargo xtask perf --quick diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index 3e1bdfd67e..c15d5d9f59 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -58,7 +58,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: prefix-key: v1-rust - key: perf-release + shared-key: perf-release - name: Run benchmarks id: perf diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1136b5e43e..9a7953dcbf 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -40,7 +40,8 @@ commands: tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the steps that need no test build; `tests` runs the tests and panic_hunt on the partition in - $NEXTEST_PARTITION (`--gpu`: only nextest's gpu test group, each test's output shown; + $NEXTEST_PARTITION (`--gpu`: all of nextest's gpu test group, whatever the partition, each + test's output shown; `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` builds (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves packages out of the test build and the doctests @@ -483,7 +484,7 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(Vec<(&'static st &[Part::Test] } Some("tests") => { - options.partition = std::env::var("NEXTEST_PARTITION").ok().filter(|p| !p.is_empty()); + options.partition = tests_partition(options.selection, std::env::var("NEXTEST_PARTITION").ok()); &[Part::Test] } Some(step) => { @@ -497,6 +498,12 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(Vec<(&'static st Ok((ci_plan(parts, options.build_only), options)) } +/// The partition `ci tests` runs. The gate sets $NEXTEST_PARTITION on every shard leg, and the shard +/// that runs the gpu group must still run all of it. +fn tests_partition(selection: Selection, env: Option) -> Option { + env.filter(|p| !p.is_empty() && selection != Selection::Gpu) +} + /// The steps of `parts`, in CI_STEPS order. When the tests are only built, the test steps become /// that one build. fn ci_plan(parts: &[Part], build_only: bool) -> Vec<(&'static str, StepFn)> { @@ -579,6 +586,14 @@ mod ci_tests { assert_eq!(test_build_args(&here.exclude).join(" "), build); } + #[test] + fn the_gpu_shard_runs_the_whole_gpu_group_whatever_the_partition() { + let env = || Some("hash:1/4".to_string()); + assert_eq!(tests_partition(Selection::Gpu, env()), None); + assert_eq!(tests_partition(Selection::NoGpu, env()).as_deref(), Some("hash:1/4")); + assert_eq!(tests_partition(Selection::All, Some(String::new())), None); + } + #[test] fn the_gpu_group_takes_every_filter_that_selects_it() { let config: toml::Table = toml::from_str( From e6a58842f36794eafa1b3fa953e580a361cf733b Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:28:54 +0000 Subject: [PATCH 20/25] ui: build the toolbar's slots once per preferences revision The toolbar, its measure and the dock's grid each resolved the stored layout (tool_layout, layout_sections, Tool::from_name per name) several times a frame. The slots depend only on the preferences' toolbar layout, so the app keeps them with the PrefsStore revision they were built at. --- crates/engine/src/prefs.rs | 4 ++-- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/lib.rs | 2 ++ crates/ui-egui/src/panels/tool_commands.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/panels/toolbar.rs | 8 ++++---- crates/ui-egui/src/state/tool.rs | 3 ++- 6 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1412f1406a..86ce38741b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1413,8 +1413,8 @@ impl ToolbarCustomization { /// works with or without "Tool". `None` for a name that isn't a tool. pub fn tool_name(name: &str) -> Option { let canonical = |key: &str| -> String { key.chars().take(1).flat_map(char::to_uppercase).chain(key.chars().skip(1)).collect() }; - // Stored layouts hold canonical names: find those without allocating (the toolbar - // resolves its layout every frame). + // Stored layouts hold canonical names: find those without allocating (every layout + // resolves each of its names here). if let Some(key) = crate::shell_commands::TOOLS.iter().filter_map(|(id, _, _)| id.strip_prefix("tools.select.")).find(|k| k.eq_ignore_ascii_case(name)) { return Some(canonical(key)); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 50e17e2a46..f65417fd5c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -69,6 +69,7 @@ impl PhotocraftApp { remove_pending_target: None, remove_trail: None, menu_model: None, + toolbar_slots: Default::default(), move_preview: None, move_hover: None, move_distance: None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 63c87c0551..ab76978eed 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -351,6 +351,8 @@ pub struct PhotocraftApp { /// The menu bar's rows and the English text of its titles, rebuilt when their inputs change /// (`menus::MenuModel`). pub(crate) menu_model: Option, + /// The toolbar's slots for the stored layout (`tool_commands::ToolbarSlots`). + pub(crate) toolbar_slots: panels::tool_commands::ToolbarSlots, /// Move tool drag shown live (`move_ui`). pub(crate) move_preview: Option, /// Move tool › Show Highlight on Rollover: the last hover answer (`move_hover`). diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index 68e63869f2..453e98fa4b 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -338,6 +338,28 @@ pub(crate) fn slots(toolbar: &ToolbarCustomization) -> Vec> { slots } +/// The rail's [`slots`] for the stored layout, built once per preferences revision ([`PrefsStore::rev`]): the toolbar, its +/// measure and the dock's grid read them several times a frame, and the layout changes only with the preferences. +/// +/// [`PrefsStore::rev`]: photocraft_engine::prefs::PrefsStore::rev +#[derive(Default)] +pub(crate) struct ToolbarSlots(std::cell::RefCell]>)>>); + +impl ToolbarSlots { + /// The slots of `prefs`' toolbar layout. + pub(crate) fn get(&self, prefs: &photocraft_engine::prefs::PrefsStore) -> std::sync::Arc<[ToolSlot]> { + let mut held = self.0.borrow_mut(); + match &*held { + Some((rev, slots)) if *rev == prefs.rev() => slots.clone(), + _ => { + let built: std::sync::Arc<[ToolSlot]> = slots(&prefs.get().toolbar).into(); + *held = Some((prefs.rev(), built.clone())); + built + } + } + } +} + /// `slots` as the group layout `edit.toolbar {"toolbar": ..}` stores: one list of `Tool` names per slot. pub(crate) fn saved_groups(slots: &[ToolSlot]) -> serde_json::Value { slots.iter().map(|slot| slot.tools.iter().map(|tool| format!("{:?}", tool.id)).collect::>()).collect() diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index acb14c1d00..b239bcf3d0 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -140,7 +140,7 @@ fn last_used(slots: &[ToolSlot], group_tools: &[Tool]) -> LastUsed { /// The cells of the toolbar's grid: its visible slots and the Edit Toolbar button. The dock column's width in steps goes /// up to this many content columns. pub(crate) fn cells(app: &PhotocraftApp) -> usize { - visible_slots(&tool_commands::slots(&app.session.prefs().toolbar), &[]).len() + 1 + visible_slots(&app.toolbar_slots.get(&app.session.prefs), &[]).len() + 1 } /// The Edit in Quick Mask Mode command, which the rail's footer shows as a rail button. @@ -181,7 +181,7 @@ fn footer(app: &mut PhotocraftApp, ui: &mut egui::Ui, rail: RailFooter) { /// The height of the toolbar's rail laid out `width` wide: as many tool columns as `width` holds, with the footer. pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 { - let slots = tool_commands::slots(&app.session.prefs().toolbar); + let slots = app.toolbar_slots.get(&app.session.prefs); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); @@ -196,7 +196,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 /// remembered tools are read again at the start of each pass, so a second pass applies only its own input. pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); - let slots = tool_commands::slots(&app.session.prefs().toolbar); + let slots = app.toolbar_slots.get(&app.session.prefs); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); @@ -217,7 +217,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { _ => {} } if let Some(next) = &out.last_used { - for slot in &slots { + for slot in slots.iter() { if let Some(tool) = next.get(slot.id) && remembered.get(slot.id) != Some(tool) { diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index ec6be52664..f68a0ece96 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -320,7 +320,8 @@ impl Tool { /// The tool `s` names: its variant name, that name without "marquee", or its label, in any case and with spaces, /// `_` and `-` ignored. The first tool of [`Tool::ALL`] a spelling names wins. pub fn from_name(s: &str) -> Option { - // The toolbar resolves its whole layout through here every frame: one table instead of formatting every tool's names per lookup. + // Panels resolve tool names per row as they draw, and the command gate per tool command: one table instead of + // formatting every tool's names per lookup. static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); let names = NAMES.get_or_init(|| { let mut names = std::collections::HashMap::new(); From 5a0ba0940884b0d5ecffbd188f6f8172f2a10744 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:30:10 +0000 Subject: [PATCH 21/25] ui: is_live tests the hash tables and prefixes before the row scans The command gate asks is_live for every command a pass resolves. The engine catalogue, the shell's commands and the prefix tests answer for most live ids; the linear scans (bridged rows, view and workspace commands, which builds a CommandRef) now run last. Same answers. --- crates/ui-egui/src/menus/items.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index fa6bb6f12a..6ed2a6741a 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -13,22 +13,24 @@ use super::state::{checked, is_enabled, reveal_label, translated_menu_label}; use super::{DOCUMENT_ITEM, PhotocraftApp, TOP_MENUS, UI_COMMANDS}; /// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and -/// the parity report ([`crate::parity`]). +/// the parity report ([`crate::parity`]). The command gate asks this for every command a pass +/// resolves, framework commands included, so the hash lookups and prefix tests come first and +/// the scans of the bridged rows and the workspace commands last. pub fn is_live(id: &str) -> bool { static UI_IDS: std::sync::OnceLock> = std::sync::OnceLock::new(); photocraft_engine::commands::find(id).is_some() - || crate::tool_shortcuts::tool(id).is_some() || UI_IDS.get_or_init(|| UI_COMMANDS.iter().map(|c| c.0).collect()).contains(id) + || id.starts_with(super::DOCUMENT_ITEM) + || id == "view.proofSetup.custom" + || crate::tool_shortcuts::tool(id).is_some() || panel_alias(id).is_some() || crate::panel_docking::toggle_panel(id).is_some() || workspace_id(id).is_some() || proof_preset(id).is_some() - || id == "view.proofSetup.custom" - || crate::view_cmds::handles(id) || crate::analysis::handles(id) + || crate::view_cmds::handles(id) || crate::shortcut_dispatch::is_bridged(id) || crate::workspace_ui::handles(id) - || id.starts_with(super::DOCUMENT_ITEM) } /// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`. From 837e19257c65bcffe7a916fc7bffc5de54f8bf9c Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:32:04 +0000 Subject: [PATCH 22/25] tests: the adjustment editors test runs one app per document every_adjustment_layer_edits_through_properties started the whole app for each of 16 kinds on each of 6 documents. It now starts one app per document and runs Undo back to the document before adding the next kind's layer, so every kind still meets the new document with its two tones. Cases and assertions are kept. --- .../src/dialogs/adjust_editors/ui_tests.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index bc3155e39d..faa944fadb 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -134,11 +134,24 @@ fn sliders(h: &Harness<'_, Box>) -> Vec { /// Issue #12: every adjustment kind, on a new document at 8/16/32 bits and in RGB, Grayscale, /// CMYK and Lab, opens its Properties editor and takes an edit through real input without /// panicking; slider kinds commit exactly one history step per gesture and end the preview with it. +/// One app per document: Undo takes back each kind's layer and edit before the next kind's layer +/// is added, so every kind meets the new document with its two tones. #[test] fn every_adjustment_layer_edits_through_properties() { for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("gray", 8), ("cmyk", 8), ("lab", 16)] { - for kind in ALL_KINDS { - let mut h = app_harness(kind, mode, depth); + let mut h = app_harness(ALL_KINDS[0], mode, depth); + // The document's history before its adjustment layer. + let base = history_len(&h) - 1; + for (i, kind) in ALL_KINDS.into_iter().enumerate() { + if i > 0 { + while history_len(&h) > base { + let steps = history_len(&h); + h.state_mut().run("edit.undo", json!({})).unwrap_or_else(|e| panic!("{kind} {mode}: undo: {e}")); + assert!(history_len(&h) < steps, "{kind} {mode}: undo to the new document"); + } + h.state_mut().run(&format!("layer.newAdjustmentLayer.{kind}"), json!({})).unwrap(); + h.run_steps(8); + } let (_, before) = layer(&h); let steps = history_len(&h); let slider = sliders(&h).first().copied(); From c1ab90aa35eb3eac34792c8bf993308352edcfea Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:33:05 +0000 Subject: [PATCH 23/25] tests: the exhaustive shortcut test sends each press as one frame's input Harness::event steps one frame per queued event, so a tap (modifiers, press, release, modifiers) plus its three steps ran six whole-app frames per shortcut. The dispatch test now queues the four events into one frame's input and runs the two frames the runtime and the app need to take the key and run its command. Every shortcut, place and assertion stays. --- .../src/input/shortcut_dispatch/tests.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 9d9dd2f319..6561866c34 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -84,6 +84,19 @@ fn press(h: &mut Harness<'_, Box>, sc: &str) { tap(h, sc.logical_key, sc.modifiers); } +/// Queue one press/release in one input frame, then let the runtime collect and the app dispatch it. +fn press_in_one_frame(h: &mut Harness<'_, Box>, sc: &str) { + let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); + let m = platform(sc.modifiers); + h.input_mut().events.extend([ + egui::Event::ModifiersChanged(m), + egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: true, repeat: false, modifiers: m }, + egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: false, repeat: false, modifiers: m }, + egui::Event::ModifiersChanged(Modifiers::NONE), + ]); + h.run_steps(2); +} + fn click(h: &mut Harness<'_, Box>, at: Pos2) { h.hover_at(at); h.run_steps(1); @@ -211,7 +224,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { // A press the focused component holds (the Layers rows' stacking and visibility keys) // is the component's and reaches no app command. let held = focus_holds(&h.ctx, chord); - press(&mut h, &sc); + press_in_one_frame(&mut h, &sc); let log = take_log(&h.ctx); if typing && !chord.has_command() && !chord.is_function_key() { // A focused text field keeps its typing / editing keys: nothing may fire. @@ -232,7 +245,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { if !typing { for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; - press(&mut h, &t.key().to_string()); + press_in_one_frame(&mut h, &t.key().to_string()); if h.state().ui.tool.key() != t.key() { failures.push(format!("{place:?}: tool key {} left {:?}", t.key(), h.state().ui.tool)); } From d83654889eb9c8535defe90c0e951402d4b43bee Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:34:40 +0000 Subject: [PATCH 24/25] tests: the slow tone_targets tests run their cases on one app The grayscale picker, filter mask and addressed mask tests started an app for every case. Each now keeps one canvas harness and opens each case's fixture document in it as a new document, after closing the last case's and clearing what a case leaves: the actions, the Layers panel's mask targets and the tone dialogs' last-used settings. Cases and assertions are kept. --- crates/ui-egui/tests/it/tone_targets.rs | 143 ++++++++++++++++-------- 1 file changed, 97 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index b1db0eaab7..7e56445c20 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -8,7 +8,7 @@ use egui_kittest::{ kittest::{NodeT, Queryable}, }; use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent, LayerMask}; +use photocraft_doc::{AlphaChannel, DocId, Document, Layer, LayerContent, LayerMask}; use photocraft_engine::{Session, actions_cmds::Action, channel_cmds::ChannelTarget}; use photocraft_geom::Size; use photocraft_raster::Surface; @@ -34,6 +34,18 @@ const DIALOG_STATE: [&str; 4] = ["preview", "picker", "channel", "clipping"]; /// Build a native-depth document with distinct colour pixels, a named alpha, a layer mask and optional Quick Mask. fn fixture(mode: ColorMode, depth: SampleType, target: ChannelTarget) -> Box { + app_of(fixture_session(mode, depth, target)) +} + +/// The app over a fixture's session, its jobs run in place. +fn app_of(session: Session) -> Box { + let mut app = PhotocraftApp::new(session, Default::default()); + app.background_jobs = false; + app +} + +/// [`fixture`]'s session. +fn fixture_session(mode: ColorMode, depth: SampleType, target: ChannelTarget) -> Session { let mut doc = Document::new("Tone targets", Size::new(32, 32), mode, depth); let mut pixels = Surface::new(PixelFormat::new(mode, depth, true)); pixels.fill_rect( @@ -59,9 +71,7 @@ fn fixture(mode: ColorMode, depth: SampleType, target: ChannelTarget) -> Box) -> Harness<'static, Box>) { + let reply = control(h, "ui.set", json!({"zoom": 12, "center": [38, 16]})); + assert_eq!(reply["ok"], true, "the view zooms: {reply}"); +} + +/// One [`canvas_harness`] for all the cases of a test: [`next_case`] puts each case's document in it. +fn bench() -> Harness<'static, Box> { + canvas_harness(fixture(ColorMode::Rgb, SampleType::U8, ChannelTarget::Composite)) +} + +/// The next case of a test on the bench `h`: the active document of `from` (a fixture's session) opens as a new +/// document in place of what `h` shows, with its active layer and channel target, and `filter_mask` is the Layers +/// panel's filter mask target. What an earlier case left goes first: the open documents, the actions, the Layers +/// panel's mask targets and the tone dialogs' last-used settings. +fn next_case(h: &mut Harness<'static, Box>, from: &Session, filter_mask: Option) { + for kind in ["levels", "curves"] { + set_saved_value(&h.ctx, &adjust_dialog::last_key(kind), None::); + } + let app = h.state_mut(); + assert_eq!(app.dialog_count(), 0, "the last case closed its dialog"); + while app.session.close(0).is_some() {} + let st = from.active().unwrap(); + let mut doc = (*st.doc).clone(); + // A document of its own, as in a case's own app: nothing the app keeps per document carries over. + doc.id = DocId::fresh(); + app.session.add_document(doc, None); + app.session.select_layer(st.active_layer.unwrap()).unwrap(); + app.session.active_mut().unwrap().channel_view = st.channel_view.clone(); + app.session.actions = from.actions.clone(); + app.ui.mask_target = false; + app.ui.vector_mask_target = false; + app.ui.filter_mask_target = filter_mask; + app.sync_views(); + h.run_steps(3); + show_left_of_dialog(h); +} + /// Open a neutral tone dialog on `h` and settle its layout before interacting with controls. fn open_in(mut h: Harness<'static, Box>, kind: &str) -> Harness<'static, Box> { + open_here(&mut h, kind); + h +} + +/// [`open_in`] on a harness kept for more cases. +fn open_here(h: &mut Harness<'static, Box>, kind: &str) { adjust_dialog::open(h.state_mut(), &format!("image.adjustments.{kind}")).unwrap(); h.run_steps(4); - h } /// Open a neutral tone dialog and settle its layout before interacting with controls. @@ -420,10 +471,12 @@ fn levels_auto_uses_the_selected_colour_channels_histogram() { /// Black/white picker controls sample the gray plane and update the visible neutral curve. #[test] fn grayscale_picker_controls_sample_the_plane_and_change_the_visible_curve() { + let mut h = bench(); for kind in ["curves", "levels"] { for (mode, depth) in GRAY_MODE_DEPTHS { for target in TARGETS { - let mut h = open_on_canvas(fixture(mode, depth, target), kind); + next_case(&mut h, &fixture_session(mode, depth, target), None); + open_here(&mut h, kind); assert!(h.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled()); assert!(!h.get_by_label("Set White Point").accesskit_node().is_disabled()); h.get_by_label("Set White Point").click(); @@ -888,30 +941,39 @@ fn last_tone_settings_on_grayscale_pixels_drop_hidden_colour_records() { /// Build a filtered smart object with a selected filter mask, optionally still the implicit reveal-all mask. fn filter_mask_fixture(mode: ColorMode, depth: SampleType, stored: bool) -> Box { - let mut app = fixture(mode, depth, ChannelTarget::Color(0)); - app.session.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius":1})).unwrap(); - let id = app.session.active().unwrap().active_layer.unwrap(); - if stored { - app.run("edit.fill", json!({"target":"filterMask","contents":"color","color":"#404040"})).unwrap(); - } + let (session, id) = filter_mask_session(mode, depth, stored); + let mut app = app_of(session); app.ui.filter_mask_target = Some(id.0); app } +/// [`filter_mask_fixture`]'s session and the smart object, whose filter mask the Layers panel targets. +fn filter_mask_session(mode: ColorMode, depth: SampleType, stored: bool) -> (Session, photocraft_doc::LayerId) { + let mut session = fixture_session(mode, depth, ChannelTarget::Color(0)); + session.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + session.execute("filter.blur.gaussianBlur", json!({"radius":1})).unwrap(); + let id = session.active().unwrap().active_layer.unwrap(); + if stored { + session.execute("edit.fill", json!({"target":"filterMask","contents":"color","color":"#404040"})).unwrap(); + } + (session, id) +} + /// New upstream filter masks use the same scalar controls, picker and preserved targeting in every document space. #[test] fn filter_mask_tone_dialogs_preserve_the_target_and_sample_its_own_levels() { + let mut h = bench(); for (mode, depth) in GRAY_MODE_DEPTHS { for kind in ["levels", "curves"] { for stored in [false, true] { - let app = filter_mask_fixture(mode, depth, stored); - let st = app.session.active().unwrap(); + let (session, id) = filter_mask_session(mode, depth, stored); + next_case(&mut h, &session, Some(id.0)); + let st = h.state().session.active().unwrap(); let layer = st.active_layer.unwrap(); let expected_name = format!("{} Filter Mask", st.doc.layer(layer).unwrap().name); let before = st.doc.clone(); - let mut h = open_on_canvas(app, kind); + open_here(&mut h, kind); assert_eq!(names(&h), [expected_name], "{mode:?} {depth:?} {kind}"); assert_eq!(params(&h)["target"], "filterMask"); let id = top(&h); @@ -1096,15 +1158,16 @@ fn review_precise_action_settings_survive_last_used_recall() { } } -/// Build distinct active and addressed masks, retaining the active layer and panel target. -fn addressed_mask_app(mode: ColorMode, depth: SampleType, filter: bool) -> (Box, photocraft_doc::LayerId) { - let mut app = if filter { filter_mask_fixture(mode, depth, true) } else { fixture(mode, depth, ChannelTarget::Alpha(0)) }; - let mut other = app.session.active().unwrap().doc.layers[0].clone(); +/// Build distinct active and addressed masks, retaining the active layer. The session holds the document, the id is +/// the addressed layer's. +fn addressed_mask_session(mode: ColorMode, depth: SampleType, filter: bool) -> (Session, photocraft_doc::LayerId) { + let mut session = if filter { filter_mask_session(mode, depth, true).0 } else { fixture_session(mode, depth, ChannelTarget::Alpha(0)) }; + let mut other = session.active().unwrap().doc.layers[0].clone(); other.id = Layer::new("id", other.content.clone()).id; other.name = "Receiver".into(); let mut mask = LayerMask::reveal_all(); mask.surface = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false)); - mask.surface.fill_rect(app.session.active().unwrap().doc.bounds(), &[0.75]); + mask.surface.fill_rect(session.active().unwrap().doc.bounds(), &[0.75]); if filter { let LayerContent::Smart(sm) = &mut other.content else { panic!("smart") }; sm.filter_mask = Some(mask); @@ -1112,36 +1175,36 @@ fn addressed_mask_app(mode: ColorMode, depth: SampleType, filter: bool) -> (Box< other.mask = Some(mask); } let id = other.id; - app.session + session .edit("Other mask", |doc, _| { doc.layers.push(other); Ok(()) }) .unwrap(); - (app, id) + (session, id) } /// Named/id mask Actions show, sample, preview and edit the addressed layer's own mask without /// switching the selected layer. The matrix includes native raster and Smart Filter masks. #[test] fn review_mask_action_context_matches_the_addressed_layer() { + let mut h = bench(); for (pair, (mode, depth)) in MODE_DEPTHS.into_iter().enumerate() { for kind in ["levels", "curves"] { for filter in [false, true] { - let (app, layer) = addressed_mask_app(mode, depth, filter); + let (source, layer) = addressed_mask_session(mode, depth, filter); // Resolving the address does not depend on the mode or depth: every selector form on the first pair. let selectors = [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})]; for selector in selectors.into_iter().take(if pair == 0 { 3 } else { 1 }) { - let mut app = fixture_for_addressed_replay(&app); + next_case(&mut h, &source, None); let command = format!("image.adjustments.{kind}"); let target = if filter { "filterMask" } else { "mask" }; let raw = json!({"layer":selector,"target":target}); - add_action(&mut app, "Other mask", command.clone(), raw, true); - let original = app.session.active().unwrap().doc.clone(); - let active = app.session.active().unwrap().active_layer; + add_action(h.state_mut(), "Other mask", command.clone(), raw, true); + let original = h.state().session.active().unwrap().doc.clone(); + let active = h.state().session.active().unwrap().active_layer; let expected = photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); - let mut h = canvas_harness(app); play(&mut h, "Other mask"); assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); let id = top(&h); @@ -1172,18 +1235,6 @@ fn review_mask_action_context_matches_the_addressed_layer() { } } -/// Copy the source document for independent Action cases without carrying modal/UI history. -fn fixture_for_addressed_replay(app: &PhotocraftApp) -> Box { - let st = app.session.active().unwrap(); - let mut s = Session::new(); - s.add_document((*st.doc).clone(), None); - s.select_layer(st.active_layer.unwrap()).unwrap(); - s.active_mut().unwrap().channel_view = st.channel_view.clone(); - let mut result = PhotocraftApp::new(s, Default::default()); - result.background_jobs = false; - result -} - /// Repairing a missing Action address re-seeds its recorded alias without losing modal context. #[test] fn review_repaired_action_target_seeds_recorded_controls() { From aa9648185a0387675917848e6dcd16c653fd5259 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 18 Nov 2026 20:36:32 +0000 Subject: [PATCH 25/25] tests: the caret font test runs its 18 cases on one app caret_font_choices_style_only_subsequent_typing_including_ime started the whole app for each font, text and caret. It now keeps one app with the fixture's document: Undo takes each case's text layer back before the next case makes its own, so every case starts from the same document. The fixture builds the same app and layer through the two steps the test shares. Cases and assertions are kept. --- .../src/tools/type_tool/font_commit_tests.rs | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index cddbe532c2..dcc72c211d 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -66,17 +66,29 @@ fn surrender_focus(h: &mut H) { /// A text layer `content` in an edit session in `FONTS[pattern % 2]`; patterns 2 and 3 style characters 2..4 in the other font. /// The full app frame, so the options bar and the Character panel both show their family fields. fn fixture(pattern: usize, content: &str) -> (H, LayerId) { - let content = content.to_owned(); - let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_max_steps(64).build_eframe(move |cc| { + let mut h = document(); + let id = text_layer(&mut h, pattern, content); + (h, id) +} + +/// [`fixture`]'s app with its document and the Type tool, before the text layer. +fn document() -> H { + Harness::builder().with_size(vec2(1600.0, 1000.0)).with_max_steps(64).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(), Services::default()); app.session.edit_prefs(|p| p.type_.font_preview = photocraft_engine::prefs::FontPreview::Off); app.run("file.new", json!({"width": 240, "height": 160})).unwrap(); app.sync_views(); app.ui.tool = crate::state::Tool::Type; - app.run("type.create", json!({"text": content, "font": FONTS[pattern % 2], "size": 18})).unwrap(); app - }); + }) +} + +/// [`fixture`]'s text layer, made on `h` and edited. +fn text_layer(h: &mut H, pattern: usize, content: &str) -> LayerId { + h.state_mut().run("type.create", json!({"text": content, "font": FONTS[pattern % 2], "size": 18})).unwrap(); + // Settle as the harness does after its first frame. + let _ = h.run_ok(); let id = h.state().session.active().unwrap().active_layer.unwrap(); let ctx = h.ctx.clone(); super::edit_active(h.state_mut(), &ctx).unwrap(); @@ -85,7 +97,22 @@ fn fixture(pattern: usize, content: &str) -> (H, LayerId) { h.state_mut().run("type.setStyle", json!({"layer": id.0, "range": [2, 4], "font": FONTS[1 - pattern % 2], "coalesce": key})).unwrap(); } h.run_steps(3); - (h, id) + id +} + +/// The past states of the document's history. +fn past_len(h: &H) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// Undo back to `steps` past states: the document before the last case's text layer. +fn undo_to(h: &mut H, steps: usize) { + while past_len(h) > steps { + let before = past_len(h); + h.state_mut().run("edit.undo", json!({})).unwrap_or_else(|e| panic!("undo: {e}")); + assert!(past_len(h) < before, "Undo takes back the last case"); + } + let _ = h.run_ok(); } /// Picks `font` in the first family field: open it, type the name, Enter, as `accept` says. @@ -111,11 +138,15 @@ fn checkmark(h: &mut H) { #[test] fn caret_font_choices_style_only_subsequent_typing_including_ime() { + // One app: each case's text layer goes with Undo before the next case makes its own. + let mut h = document(); + let base = past_len(&h); for original in 0..2 { for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { let n = text.chars().count(); for caret in [0, n / 2, n] { - let (mut h, id) = fixture(original, text); + undo_to(&mut h, base); + let id = text_layer(&mut h, original, text); select(&mut h, [caret, caret]); h.run(); let before = saved(&h, id);