Merge pull request #9833 from dotCooCoo/fix/canvas-worker-test-handshake

Canvas: render worker tests no longer depend on wall-clock time
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-27 22:20:40 -08:00
commit 206b513d58
3 files changed
+102 -18

No files matched your search

+10 -5
View File
@@ -1,5 +1,4 @@
use std::collections::BTreeSet;
use std::time::Duration;
use craft::behavior::CanvasView;
use craft::ui::primitives::textures::{CachedTexture, TextureState};
@@ -140,7 +139,8 @@ fn has_picture(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, uid: u64)
/// Run frames with `run` until window `w`'s pane has its picture and the upload of it was seen,
/// starting from the uploads `seed` holds → the picture and its pixels and size as uploaded. The uploads are handled
/// once read.
/// once read. The test context runs the pictures' renders in line ([`crate::testing::ui_context`]), so a picture asked
/// for in one frame is ready and uploaded within [`READY_FRAMES`] frames on every run.
fn wait_ready(
app: &mut VectorcraftApp,
ctx: &egui::Context,
@@ -150,7 +150,7 @@ fn wait_ready(
) -> (CachedTexture, (Vec<Color32>, [usize; 2])) {
let uid = app.session.documents()[w.0].uid;
let mut uploads = seed;
for _ in 0..400 {
for frames in 0..=READY_FRAMES {
if let TextureState::Ready(texture) = picture_of(app, ctx, w, uid)
&& (uploads.iter().flat_map(|d| d.set.iter()).any(|e| *e.0 == texture.id) || UPLOADED.with(|u| u.borrow().contains_key(&texture.id)))
{
@@ -159,13 +159,18 @@ fn wait_ready(
uploads.iter_mut().for_each(note_uploads);
return (texture, picture);
}
if frames == READY_FRAMES {
break;
}
let mut out = run(app);
uploads.push(std::mem::take(&mut out.textures_delta));
std::thread::sleep(Duration::from_millis(5));
}
panic!("the pane of window {w:?} never got its picture");
panic!("the pane of window {w:?} did not get its picture within {READY_FRAMES} frames");
}
/// The frames [`wait_ready`] runs for a pane's picture at most.
const READY_FRAMES: usize = 4;
/// The picture `id` as `uploads` uploaded it, else as a frame of [`frame_in`] did: its pixels and size.
fn uploaded(uploads: &[egui::TexturesDelta], id: egui::TextureId) -> (Vec<Color32>, [usize; 2]) {
let image = uploads.iter().rev().flat_map(|d| d.set.iter()).find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| d.image.clone());
+44 -5
View File
@@ -584,11 +584,14 @@ fn report_deferred(app: &mut VectorcraftApp, effects: &vectorcraft_plugins::defe
}
}
/// Start the render worker, and upload the frame it finished.
/// Start the render worker, and upload the frame it finished. In unit tests no worker thread
/// starts and every frame renders on this thread, as with `VECTORCRAFT_SYNC_RENDER` set: a test
/// that needs a worker gives the canvas one whose frames it finishes itself
/// ([`crate::render_worker::Worker::test_channel`]).
pub(super) fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) {
if !app.canvas.worker_started {
app.canvas.worker_started = true;
if std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() {
if !cfg!(test) && std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() {
app.canvas.worker = crate::render_worker::Worker::spawn(ui.ctx().clone());
app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone());
}
@@ -710,6 +713,42 @@ struct Frame<'a> {
/// shows the document's paper without the art: about a frame at 60 Hz.
pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16);
/// How long a render on this thread that began at `t0` ([`monotonic_ms`]) took, in milliseconds.
#[cfg(not(test))]
fn render_ms(t0: f64) -> f64 {
monotonic_ms() - t0
}
/// How long the UI thread waits for a document's first frame: [`FIRST_FRAME_GRACE`].
#[cfg(not(test))]
fn first_frame_grace() -> std::time::Duration {
FIRST_FRAME_GRACE
}
#[cfg(test)]
thread_local! {
/// The time a render on the UI thread takes in unit tests, in milliseconds: what a frame's
/// time decides (whether the next frame is slow) is the same on every run. A test
/// can set it to make the canvas's renders slow or fast.
pub(crate) static TEST_RENDER_MS: std::cell::Cell<f64> = const { std::cell::Cell::new(1.0) };
/// How long the UI thread waits for a document's first frame in unit tests: none, so only a
/// frame the test finished before it lands in the wait. A test that answers the job from
/// another thread sets [`std::time::Duration::MAX`] to wait for that answer.
pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell<std::time::Duration> = const { std::cell::Cell::new(std::time::Duration::ZERO) };
}
/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds.
#[cfg(test)]
fn render_ms(_t0: f64) -> f64 {
TEST_RENDER_MS.with(std::cell::Cell::get)
}
/// [`first_frame_grace`] in unit tests: the time [`TEST_FIRST_FRAME_GRACE`] holds.
#[cfg(test)]
fn first_frame_grace() -> std::time::Duration {
TEST_FIRST_FRAME_GRACE.with(std::cell::Cell::get)
}
/// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s
/// key: only the document changed since the frame shown, in that part of it
/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's.
@@ -760,7 +799,7 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
}
app.canvas.key = Some((*key).clone());
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
app.perf.render_ms = monotonic_ms() - t0;
app.perf.render_ms = render_ms(t0);
true
}
@@ -855,7 +894,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
// A light document's first frame is ready within the grace and shows in this frame,
// with no frame of bare paper. Waited for once, when the frame is queued.
if first && queued {
landed = worker.wait(FIRST_FRAME_GRACE);
landed = worker.wait(first_frame_grace());
}
}
_ => {
@@ -868,7 +907,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
upload(app, ui.ctx(), img, pixel.is_some());
app.canvas.key = Some(key.clone());
app.canvas.shown = Some((doc.clone(), opts.clone()));
app.perf.render_ms = monotonic_ms() - t0;
app.perf.render_ms = render_ms(t0);
app.canvas.last_ms = app.perf.render_ms;
app.canvas.moved = app.canvas.renderer.stats.moved > 0;
let stats = app.canvas.renderer.stats;
+48 -8
View File
@@ -6481,24 +6481,64 @@ fn the_render_worker_waits_for_a_frame_only_as_long_as_asked() {
let job = jobs.try_recv().expect("a job to finish");
let (mut w, _, done_tx) = crate::render_worker::Worker::test_channel();
let t0 = std::time::Instant::now();
assert!(w.wait(std::time::Duration::from_millis(20)).is_none());
assert!(t0.elapsed() >= std::time::Duration::from_millis(20), "waited the time asked");
// No frame finishes: the time is up at once.
assert!(w.wait(std::time::Duration::ZERO).is_none(), "nothing once the time is up");
w.pending = Some(job.key.clone());
done_tx.send(finished(&job)).unwrap();
assert_eq!(w.wait(std::time::Duration::from_secs(5)).map(|d| d.key), Some(job.key.clone()), "finished before the wait");
assert_eq!(w.wait(super::raster::FIRST_FRAME_GRACE).map(|d| d.key), Some(job.key.clone()), "finished before the wait");
assert!(w.pending.is_none());
// The frame is sent once both sides reach the barrier; with no time limit, the wait returns
// it whether it arrives before or during the wait.
let late = finished(&job);
let sender = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(30));
done_tx.send(late).unwrap();
let ready = std::sync::Arc::new(std::sync::Barrier::new(2));
let sender = std::thread::spawn({
let ready = ready.clone();
move || {
ready.wait();
done_tx.send(late).unwrap();
}
});
assert!(w.wait(std::time::Duration::from_secs(5)).is_some(), "finished during the wait");
ready.wait();
assert!(w.wait(std::time::Duration::MAX).is_some(), "finished during the wait");
sender.join().unwrap();
}
/// A document's first frame that the worker finishes within the wait (`FIRST_FRAME_GRACE`) shows
/// in the frame that queued it, with no frame of bare paper; one that is not finished in time shows
/// once it lands ([`a_documents_first_frame_renders_on_the_worker`]).
#[test]
fn a_first_frame_finished_within_the_wait_shows_in_the_frame_that_queued_it() {
keeping_color_settings(a_first_frame_finished_within_the_wait);
}
fn a_first_frame_finished_within_the_wait() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true;
let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel();
app.canvas.worker = Some(worker);
// The worker finishes the job as soon as it receives it, and the canvas waits for it.
super::raster::TEST_FIRST_FRAME_GRACE.with(|g| g.set(std::time::Duration::MAX));
let answer = std::thread::spawn(move || {
let job = jobs.recv().expect("the first frame is queued on the worker");
done_tx.send(finished(&job)).unwrap();
job.key
});
let ctx = crate::testing::ui_context();
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0))), ..Default::default() };
ctx.run_ui(raw, |ui| show(&mut app, ui)).textures_delta.clear();
assert!(app.canvas.texture.is_some(), "shown in the frame that queued it");
assert!(app.canvas.from_worker);
// Dropping the worker ends the answering thread's wait for a job if none was queued.
let worker = app.canvas.worker.take().expect("the worker");
assert!(worker.pending.is_none(), "the job is done");
drop(worker);
let key = answer.join().expect("the first frame was queued on the worker");
assert_eq!(app.canvas.key.as_ref(), Some(&key));
}
/// An edit to a 3D effect renders the part it changed on this thread, measured by the renderer
/// that drew the frame shown ([`vectorcraft_render::Renderer::changed`]): it draws the part with
/// the 3D art it made to measure it.