diff --git a/crates/ui-egui/src/canvas/paint_tool/tests.rs b/crates/ui-egui/src/canvas/paint_tool/tests.rs index 4498653fdad..fb373370640 100644 --- a/crates/ui-egui/src/canvas/paint_tool/tests.rs +++ b/crates/ui-egui/src/canvas/paint_tool/tests.rs @@ -215,7 +215,12 @@ fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { #[test] fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { for failed in [false, true] { - let mut h = harness(mixer_app()); + let mut app = mixer_app(); + // Smoothing off: this is about which points reach the commit, and the Mixer Brush's + // first-use 10 % lag (measured, #11888) would hold the brush short of the release point. + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap(); + let mut h = harness(app); let before = h.state().session.active().unwrap().doc.clone(); let p = |h: &Harness<'static, Box>, x: f64| at(h, x, 30.0); let start = p(&h, 20.0); @@ -371,7 +376,10 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); let ctx = app.ctx().clone(); app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); - let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); + // Smoothing off: the default 10 % lag (measured, #11888) on wall-clock times would leave the + // preview's tail anywhere short of the release, so the comparison below couldn't hold. + let tilt = + json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "smoothing": {"amount": 0.0}, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); app.ui.tool = Tool::Brush; let mut seen = composite_revision(&mut app, &ctx, 0, None); @@ -390,7 +398,6 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); - // (The smoothed tail catches up to the end point only when the stroke finishes.) assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index 87d51024a68..f2f40b70206 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -159,6 +159,9 @@ pub(crate) struct SourceInit { pub(crate) ctx: egui::Context, } +#[cfg(test)] +type BeforePreviewPublish = Arc; + /// PhotoCraft's develop for the RAW Develop workspace: the proxy, the selection coverage, the GPU handle and the /// result slot the develop jobs fill. Nothing in it is kept across passes beyond those results. pub(crate) struct PcRawSource { @@ -191,6 +194,9 @@ pub(crate) struct PcRawSource { running: Arc, /// Develops started so far: the order of the results. issued: AtomicU64, + /// Tests can hold one real job after its cancellation check, before the revision guard. + #[cfg(test)] + before_preview_publish: Mutex>, /// The side of the blocks the proxy averaged: the pictures' reduction. block: u32, /// Wakes the UI when a refinement lands. @@ -237,6 +243,8 @@ impl PcRawSource { developed: Arc::default(), running: Arc::default(), issued: AtomicU64::new(0), + #[cfg(test)] + before_preview_publish: Mutex::new(None), block: block as u32, ctx, } @@ -324,6 +332,8 @@ impl RawDevelopSource for PcRawSource { let before_histogram = self.before_histogram.clone(); let (pw, ph) = (self.pw, self.ph); let block = self.block; + #[cfg(test)] + let before_preview_publish = self.before_preview_publish.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); let running = Running::start(&self.running); Job::new(move |_progress, cancel| { let _running = running; @@ -354,6 +364,10 @@ impl RawDevelopSource for PcRawSource { backend: frame.backend, scope, }; + #[cfg(test)] + if let Some(before_publish) = before_preview_publish { + before_publish(order, &result.settings); + } // A job for older settings that finishes after a newer one must not replace its result. let mut slot = developed.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if slot.as_ref().is_none_or(|current| current.revision <= result.revision) { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index d042e52d228..48cf85f0861 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -181,7 +181,11 @@ fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings assert_eq!(last["previewPending"], false); let now = shown(&app); assert_eq!((now.exposure, now.highlights, now.shadows), (1.0, -60.0, 45.0)); - // PLAN: the develop `Job` cannot be run outside the runtime, so the frame is compared with a fresh dialog's develop of the same settings, not a direct `ProxyJob::run`. + // The runtime owns the real job; its published pixels must also match the synchronous proxy calculation. + let synchronous = session(&app).source.proxy_job(&now).run(); + assert_eq!(processed(&app), synchronous.px, "the real worker develops exactly the same proxy pixels"); + assert_eq!(session(&app).source.developed().unwrap().after_histogram.channels, synchronous.histogram.channels); + assert!(craft::ui::runtime::pending::finish_jobs(&ctx, std::time::Duration::from_secs(30)), "all actual preview jobs have terminated"); assert_eq!( last["histogram"], single_develop_histogram(json!({"exposure": 1.0, "highlights": -60, "shadows": 45})), @@ -189,23 +193,125 @@ fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings ); } +/// An old job held after its real cancellation check. Drop always releases it and drains its queue, including on +/// an assertion failure; all waits have bounds. This never substitutes for the production menu or develop job. +#[cfg(not(target_arch = "wasm32"))] +struct HeldPreview { + ctx: egui::Context, + release: Arc<(std::sync::Mutex, std::sync::Condvar)>, + timed_out: Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +impl HeldPreview { + fn release_and_finish(&self) -> bool { + let (released, wake) = &*self.release; + *released.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + wake.notify_all(); + craft::ui::runtime::pending::finish_jobs(&self.ctx, std::time::Duration::from_secs(30)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for HeldPreview { + fn drop(&mut self) { + let _ = self.release_and_finish(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn hold_old_preview(app: &PhotocraftApp) -> (HeldPreview, std::sync::mpsc::Receiver) { + let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (arrived, waiting) = std::sync::mpsc::channel(); + let held = HeldPreview { ctx: app.ctx().clone(), release: release.clone(), timed_out: timed_out.clone() }; + *session(app).source.before_preview_publish.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(move |order, settings| { + if settings.highlights != -80.0 { + return; + } + let _ = arrived.send(order); + let (released, wake) = &*release; + let released = released.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (released, _) = + wake.wait_timeout_while(released, std::time::Duration::from_secs(30), |released| !*released).unwrap_or_else(std::sync::PoisonError::into_inner); + if !*released { + timed_out.store(true, std::sync::atomic::Ordering::Relaxed); + } + })); + (held, waiting) +} + +/// Observe only the newer publication: `settle` deliberately waits for the older held job too. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_newer_preview(app: &mut PhotocraftApp, order: u64) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + frame(app); + if session(app) + .source + .developed() + .is_some_and(|result| result.revision > order && result.settings.exposure == -1.0 && result.settings.highlights == 0.0) + { + return; + } + assert!(std::time::Instant::now() < deadline, "the real newer request must publish while the older job is held"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + /// An older develop that lands after a newer request must not replace the frame of the newer /// settings. #[test] fn a_stale_worker_never_replaces_a_newer_synchronous_render() { - let (mut app, ctx) = worker_app(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); - // The develop of the older request is running. - frame(&mut app); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); - settle(&mut app); - let landed = describe(&app); - std::thread::sleep(std::time::Duration::from_millis(200)); - frame(&mut app); - frame(&mut app); - let later = describe(&app); - assert_eq!((&later["previewRevision"], &later["histogram"]), (&landed["previewRevision"], &landed["histogram"]), "nothing replaced the newer frame"); - assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + #[cfg(not(target_arch = "wasm32"))] + { + let (mut app, ctx) = worker_app(); + let (held, arrived) = hold_old_preview(&app); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); + frame(&mut app); + let old_order = arrived.recv_timeout(std::time::Duration::from_secs(10)).expect("the real old request passed cancellation and reached publication"); + assert!(session(&app).source.pending(), "the old job remains live at the gate"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); + wait_for_newer_preview(&mut app, old_order); + let landed = describe(&app); + let shown_pixels = processed(&app); + assert_eq!(landed["previewPending"], true, "observing the new publication did not release the older job"); + assert!(landed["previewRevision"].as_u64().unwrap() > old_order); + assert!(held.release_and_finish(), "every actual queued or running develop has terminated"); + assert!(!held.timed_out.load(std::sync::atomic::Ordering::Relaxed), "the old result was released by the test, not its deadline"); + frame(&mut app); + frame(&mut app); + let later = describe(&app); + assert_eq!(later["previewPending"], false); + assert_eq!( + (&later["previewRevision"], &later["histogram"]), + (&landed["previewRevision"], &landed["histogram"]), + "the old result reached publication last and did not replace the newer frame" + ); + assert_eq!(processed(&app), shown_pixels, "the old result did not replace the displayed proxy pixels"); + assert_eq!( + session(&app).source.proxy_job(&shown(&app)).run().px, + shown_pixels, + "the pixels still match a synchronous develop of the control channel's settings" + ); + assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + } + #[cfg(target_arch = "wasm32")] + { + let (mut app, ctx) = worker_app(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": -80}}})).unwrap().unwrap(); + // The develop of the older request is running. + frame(&mut app); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); + settle(&mut app); + let landed = describe(&app); + assert!(craft::ui::runtime::pending::finish_jobs(&ctx, std::time::Duration::from_secs(30)), "all preview jobs have terminated"); + frame(&mut app); + frame(&mut app); + let later = describe(&app); + assert_eq!((&later["previewRevision"], &later["histogram"]), (&landed["previewRevision"], &landed["histogram"]), "nothing replaced the newer frame"); + assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); + } } #[test] diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index f7cbbc72559..95185153182 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -480,6 +480,99 @@ mod tests { assert!(loaded.is_none()); } + /// Drive the real Home source and store with one explicitly completed background lane. + #[cfg(not(target_arch = "wasm32"))] + fn recent_thumbnail_pass(app: &PhotocraftApp, frames: &mut craft::ui::testing::Frames, key: &ThumbKey) -> craft::ui::primitives::TextureState { + let ctx = app.ctx().clone(); + let mut state = None; + frames.frame(Vec::new(), |_| { + state = Some(thumbnails(&ctx).state(&ctx, &source(app, &ctx), key, &ThumbRequest::for_cell(64.0, 1.0), craft::ui::primitives::Priority::VISIBLE)); + }); + state.expect("the Home thumbnail caller ran") + } + + #[cfg(not(target_arch = "wasm32"))] + fn manual_recent_thumbnails(app: &PhotocraftApp) -> (craft::ui::testing::Frames, std::sync::Arc) { + let ctx = app.ctx().clone(); + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + // The production accessor uses this same salt; its later options keep this first-created loader. + Thumbnails::::in_context(&ctx, "home-recent", ThumbnailOptions::new().lanes(1).jobs(jobs.clone())); + let mut frames = craft::ui::testing::Frames::over(ctx); + frames.record_paint(); + (frames, jobs) + } + + #[cfg(not(target_arch = "wasm32"))] + fn assert_recent_picture(frames: &mut craft::ui::testing::Frames, state: craft::ui::primitives::TextureState, rgba: [u8; 4]) { + let craft::ui::primitives::TextureState::Ready(texture) = state else { panic!("the completed decoder must supply a ready picture") }; + assert_eq!((texture.size.width, texture.size.height), (4, 4)); + let mut paint = frames.take_paint().expect("texture uploads were recorded"); + let delta = paint.textures_delta.set.get(&texture.id).and_then(|changes| changes.last()).expect("the real decoder's texture was uploaded"); + let egui::ImageData::Color(image) = &delta.image; + assert_eq!(image.size, [4, 4]); + assert!(image.pixels.iter().all(|pixel| pixel.to_array() == rgba), "the picture contains the decoded file's pixels"); + // The headless test inspected the uploads instead of rendering them. + paint.textures_delta.clear(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn recent_thumbnail_loads_in_background_when_background_jobs_enabled() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("background.png"); + std::fs::write(&path, flat_png([20, 60, 100, 255])).unwrap(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = true; + app.push_recent(&path.to_string_lossy()); + let key = ThumbKey::Recent(path); + let (mut frames, jobs) = manual_recent_thumbnails(&app); + + assert!(matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { stand_in: None, .. })); + assert_eq!(jobs.waiting(), 1, "the real source returned a background decoder, rather than decoding inline"); + assert!(jobs.run_next(), "the queued decoder actually ran to completion"); + assert_eq!(jobs.waiting(), 0, "no worker remains deferred"); + let state = recent_thumbnail_pass(&app, &mut frames, &key); + assert_recent_picture(&mut frames, state, [20, 60, 100, 255]); + assert!(!jobs.run_next(), "the ready picture starts no duplicate job"); + assert!(thumbnails(app.ctx()).shutdown(std::time::Duration::from_secs(2)), "the completed loader has no running work"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn recent_thumbnail_discards_background_result_if_invalidated_while_loading() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("invalidated.png"); + std::fs::write(&path, flat_png([100, 20, 60, 255])).unwrap(); + let path_string = path.to_string_lossy().into_owned(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = true; + app.push_recent(&path_string); + let key = ThumbKey::Recent(path); + let (mut frames, jobs) = manual_recent_thumbnails(&app); + + assert!(matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. })); + let before = revision_of(&app, &path_string); + assert!(jobs.run_next(), "finish the actual decoder before invalidation and before its result is uploaded"); + assert_eq!(jobs.waiting(), 0); + lock(&app.thumbnail_cache).invalidate(&path_string); + assert_ne!(before, revision_of(&app, &path_string), "invalidation must change the real source's revision"); + // Check invalidation with unchanged metadata first, then make stale and fresh decoder pixels distinct. + std::fs::write(&path_string, flat_png([20, 100, 60, 255])).unwrap(); + + // The former picture may be a stand-in, but it cannot satisfy the invalidated revision as Ready. + assert!( + matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. }), + "the completed old result is not current" + ); + assert_eq!(jobs.waiting(), 1, "the production source requests a replacement decoder"); + assert!(jobs.run_next(), "the replacement decoder completes"); + let state = recent_thumbnail_pass(&app, &mut frames, &key); + assert_recent_picture(&mut frames, state, [20, 100, 60, 255]); + assert_eq!(jobs.waiting(), 0); + assert!(!jobs.run_next()); + assert!(thumbnails(app.ctx()).shutdown(std::time::Duration::from_secs(2)), "both decoder jobs have terminated"); + } + /// The thumbnail source of a fresh pass over `app`. #[cfg(not(target_arch = "wasm32"))] fn revision_of(app: &PhotocraftApp, path: &str) -> Revision { 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 dcc72c211d5..8b47bc69d3a 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 @@ -115,7 +115,8 @@ fn undo_to(h: &mut H, steps: usize) { let _ = h.run_ok(); } -/// Picks `font` in the first family field: open it, type the name, Enter, as `accept` says. +/// Picks `font` in the first family field: open it, type the name, then accept it as `accept` says +/// (Enter, ArrowDown then Enter, a click on its row, or a hover). fn choose(h: &mut H, font: &str, accept: &str) { h.query_all_by_label("Font family").next().unwrap().click(); h.run(); @@ -123,6 +124,11 @@ fn choose(h: &mut H, font: &str, accept: &str) { h.run(); match accept { "enter" => h.key_press(Key::Enter), + "arrow-enter" => { + h.key_press(Key::ArrowDown); + h.run(); + h.key_press(Key::Enter); + } "click" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).click(), "hover" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).hover(), _ => panic!("unknown acceptance"), @@ -139,22 +145,40 @@ 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. + // Every acceptance, as each reaches the caret's pending style by its own route through the + // family field (ArrowDown applies its row once per step). One original font, as it only decides + // which font is chosen, and the carets at both ends. let mut h = document(); let base = past_len(&h); - for original in 0..2 { + let original = 0; + for accept in ["enter", "click", "arrow-enter"] { for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - let n = text.chars().count(); - for caret in [0, n / 2, n] { + for caret in [0, text.chars().count()] { + let label = (accept, text, caret); 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); let steps = h.state().session.active().unwrap().history.entries().len(); - let font = FONTS[1 - original]; - choose(&mut h, font, "enter"); - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters"); - assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); + let requested = FONTS[1 - original]; + choose(&mut h, requested, accept); + // ArrowDown steps to the row below the typed match, which depends on the installed fonts + // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. + let font = h + .state() + .ui + .type_insertion_style + .as_ref() + .map(|s| s.style.font_family.clone()) + .unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); + let font = font.as_str(); + assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); + if accept != "arrow-enter" { + assert_eq!(font, requested, "{label:?}"); + } + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); crate::type_font_preview::set(h.state_mut(), font.into()); assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); // Two preedit replacements and the final commit keep the pending font. @@ -169,11 +193,15 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { h.run(); let mut expected = families(&before); expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected); + assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); + let mut expected_text: Vec = text.chars().collect(); + expected_text.splice(caret..caret, "éXZ".chars()); let typed = saved(&h, id); + assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); + assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); checkmark(&mut h); - assert_eq!(saved(&h, id), typed); - assert!(h.state().ui.type_insertion_style.is_none()); + assert_eq!(saved(&h, id), typed, "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); } } }