Skip to main content

sui_platform/
headless.rs

1use std::{collections::VecDeque, time::Instant};
2
3use sui_core::{AsyncWakeToken, Error, Event, Result, Size, WindowEvent, WindowId};
4use sui_render_wgpu::{
5    DebugCaptureArtifact, DebugCaptureRequest, FeatheringOptions, OutputStrategy, RgbaImage,
6    WgpuRenderer,
7};
8use sui_runtime::{
9    PresentationLatencyDiagnostics, Runtime, WindowRenderOptions, window_render_options,
10    window_scene_statistics_detail_mode,
11};
12
13use crate::{
14    AccessibilityBridge, AccessibilitySnapshot, WindowOutputDiagnostics, map_window_stem_darkening,
15    map_window_text_coverage_policy, map_window_text_hinting, map_window_text_subpixel_order,
16    publish_window_output_diagnostics, resolve_sdr_content_brightness_nits,
17};
18
19#[derive(Debug, Clone)]
20pub struct PlatformWindow {
21    pub id: WindowId,
22    pub title: String,
23    pub accessibility: Option<AccessibilitySnapshot>,
24}
25
26#[derive(Debug, Default)]
27pub struct HeadlessPlatform {
28    renderer: WgpuRenderer,
29    windows: Vec<WindowState>,
30    pending_events: VecDeque<QueuedEvent>,
31    frame_clock: f64,
32}
33
34impl HeadlessPlatform {
35    const DEFAULT_WINDOW_SIZE: Size = Size::new(1280.0, 720.0);
36
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    pub fn with_feather_width(mut self, feather_width: f32) -> Self {
42        self.set_feather_width(feather_width);
43        self
44    }
45
46    pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
47        self.set_feathering_enabled(enabled);
48        self
49    }
50
51    pub fn run(&mut self, runtime: &mut Runtime) -> Result<Vec<PlatformWindow>> {
52        loop {
53            if self.pump(runtime)? {
54                continue;
55            }
56            if !self.advance_to_next_wakeup(runtime)? {
57                break;
58            }
59        }
60
61        Ok(self
62            .windows
63            .iter()
64            .filter(|window| window.open)
65            .map(WindowState::snapshot)
66            .collect())
67    }
68
69    pub fn pump(&mut self, runtime: &mut Runtime) -> Result<bool> {
70        self.sync_windows(runtime)?;
71        runtime.tick(self.frame_clock);
72        self.queue_ready_events(runtime);
73        self.queue_redraw_requests(runtime)?;
74
75        let mut did_work = false;
76
77        while let Some(queued_event) = self.pending_events.pop_front() {
78            did_work = true;
79            self.process_event(runtime, queued_event)?;
80        }
81
82        Ok(did_work)
83    }
84
85    pub fn advance_time(&mut self, delta: f64) {
86        self.frame_clock += delta;
87    }
88
89    pub fn wake_async(
90        &mut self,
91        runtime: &mut Runtime,
92        window_id: WindowId,
93        token: AsyncWakeToken,
94    ) -> Result<bool> {
95        self.sync_windows(runtime)?;
96        runtime.wake_async(window_id, token)
97    }
98
99    pub fn current_time(&self) -> f64 {
100        self.frame_clock
101    }
102
103    fn advance_to_next_wakeup(&mut self, runtime: &Runtime) -> Result<bool> {
104        let mut next: Option<f64> = None;
105        for window_id in runtime.window_ids() {
106            let candidate = runtime.next_wakeup_time(window_id)?;
107            next = match (next, candidate) {
108                (Some(current), Some(candidate)) => Some(current.min(candidate)),
109                (None, Some(candidate)) => Some(candidate),
110                (current, None) => current,
111            };
112        }
113
114        let Some(next) = next else {
115            return Ok(false);
116        };
117        if next <= self.frame_clock {
118            return Ok(false);
119        }
120
121        self.frame_clock = next;
122        Ok(true)
123    }
124
125    pub fn pending_event_count(&self) -> usize {
126        self.pending_events.len()
127    }
128
129    pub fn has_pending_events(&self) -> bool {
130        !self.pending_events.is_empty()
131    }
132
133    pub fn dispatch_event(
134        &mut self,
135        runtime: &Runtime,
136        window_id: WindowId,
137        event: Event,
138    ) -> Result<()> {
139        self.sync_windows(runtime)?;
140
141        if !self
142            .windows
143            .iter()
144            .any(|window| window.id == window_id && window.open)
145        {
146            return Err(Error::new(format!(
147                "window {} is not registered with the headless platform",
148                window_id.get()
149            )));
150        }
151
152        self.pending_events
153            .push_back(QueuedEvent { window_id, event });
154        Ok(())
155    }
156
157    pub fn renderer(&self) -> &WgpuRenderer {
158        &self.renderer
159    }
160
161    pub fn feather_width(&self) -> f32 {
162        self.renderer.feather_width()
163    }
164
165    pub fn feathering_enabled(&self) -> bool {
166        self.renderer.feathering_enabled()
167    }
168
169    pub fn set_feather_width(&mut self, feather_width: f32) {
170        self.renderer.set_feather_width(feather_width);
171    }
172
173    pub fn set_feathering_enabled(&mut self, enabled: bool) {
174        self.renderer.set_feathering_enabled(enabled);
175    }
176
177    pub fn renderer_mut(&mut self) -> &mut WgpuRenderer {
178        &mut self.renderer
179    }
180
181    pub fn capture_rgba(&self, window_id: WindowId) -> Result<RgbaImage> {
182        self.renderer.capture_rgba(window_id)
183    }
184
185    pub fn capture_debug_frame(
186        &mut self,
187        window_id: WindowId,
188        request: DebugCaptureRequest,
189    ) -> Result<DebugCaptureArtifact> {
190        self.renderer.capture_last_frame_debug(window_id, request)
191    }
192
193    pub fn accessibility_snapshot(&self, window_id: WindowId) -> Option<&AccessibilitySnapshot> {
194        self.windows
195            .iter()
196            .find(|window| window.id == window_id && window.open)
197            .and_then(|window| window.accessibility.snapshot())
198    }
199
200    fn queue_ready_events(&mut self, runtime: &mut Runtime) {
201        self.pending_events.extend(
202            runtime
203                .drain_ready_events()
204                .into_iter()
205                .map(|(window_id, event)| QueuedEvent { window_id, event }),
206        );
207    }
208
209    fn sync_windows(&mut self, runtime: &Runtime) -> Result<()> {
210        let runtime_window_ids = runtime.window_ids();
211
212        let removed_ids: Vec<_> = self
213            .windows
214            .iter()
215            .map(|window| window.id)
216            .filter(|window_id| !runtime_window_ids.contains(window_id))
217            .collect();
218
219        for window_id in removed_ids {
220            self.renderer.remove_window(window_id);
221            crate::clear_window_performance(window_id);
222        }
223
224        self.windows
225            .retain(|window| runtime_window_ids.contains(&window.id));
226        self.pending_events
227            .retain(|queued_event| runtime_window_ids.contains(&queued_event.window_id));
228
229        for window_id in runtime_window_ids {
230            if self.windows.iter().any(|window| window.id == window_id) {
231                continue;
232            }
233
234            self.windows.push(WindowState {
235                id: window_id,
236                title: runtime.window_title(window_id)?.to_string(),
237                open: true,
238                awaiting_performance_bootstrap: true,
239                redraw_requested: false,
240                redraw_requested_at_ms: None,
241                frame_index: 0,
242                pending_event_time_ms: 0.0,
243                last_non_redraw_event_at_ms: None,
244                accessibility: AccessibilityBridge::default(),
245            });
246            self.pending_events.push_back(QueuedEvent {
247                window_id,
248                event: Event::Window(WindowEvent::Resized(Self::DEFAULT_WINDOW_SIZE)),
249            });
250        }
251
252        Ok(())
253    }
254
255    fn queue_redraw_requests(&mut self, runtime: &Runtime) -> Result<()> {
256        let now_ms = self.current_time() * 1000.0;
257
258        for window in &mut self.windows {
259            if !window.open || window.redraw_requested || !runtime.needs_render(window.id)? {
260                continue;
261            }
262
263            window.redraw_requested = true;
264            window.redraw_requested_at_ms = Some(now_ms);
265            self.pending_events.push_back(QueuedEvent {
266                window_id: window.id,
267                event: Event::Window(WindowEvent::RedrawRequested),
268            });
269        }
270
271        Ok(())
272    }
273
274    fn process_event(&mut self, runtime: &mut Runtime, queued_event: QueuedEvent) -> Result<()> {
275        let Some(window_index) = self
276            .windows
277            .iter()
278            .position(|window| window.id == queued_event.window_id && window.open)
279        else {
280            return Ok(());
281        };
282
283        let is_redraw = matches!(
284            queued_event.event,
285            Event::Window(WindowEvent::RedrawRequested)
286        );
287        let is_close = matches!(
288            queued_event.event,
289            Event::Window(WindowEvent::CloseRequested)
290        );
291        let window_id = queued_event.window_id;
292        let event_arrived_at_ms = self.current_time() * 1000.0;
293
294        let event_started = Instant::now();
295        runtime.handle_event(window_id, queued_event.event)?;
296        let event_time_ms = event_started.elapsed().as_secs_f64() * 1000.0;
297        if !is_redraw {
298            self.windows[window_index].pending_event_time_ms += event_time_ms;
299        }
300        if !is_redraw && !is_close {
301            self.windows[window_index].last_non_redraw_event_at_ms = Some(event_arrived_at_ms);
302        }
303
304        if is_redraw {
305            self.windows[window_index].redraw_requested = false;
306
307            if runtime.needs_render(window_id)? {
308                runtime.tick(self.frame_clock);
309
310                let render_started_at_ms = self.current_time() * 1000.0;
311                let mut presentation_latency = PresentationLatencyDiagnostics::new(
312                    self.windows[window_index]
313                        .last_non_redraw_event_at_ms
314                        .map(|timestamp| (render_started_at_ms - timestamp).max(0.0))
315                        .unwrap_or(0.0),
316                    0.0,
317                    self.windows[window_index]
318                        .redraw_requested_at_ms
319                        .map(|timestamp| (render_started_at_ms - timestamp).max(0.0))
320                        .unwrap_or(0.0),
321                );
322
323                let runtime_started = Instant::now();
324                let output = runtime.render(window_id)?;
325                let runtime_time_ms = runtime_started.elapsed().as_secs_f64() * 1000.0;
326                let renderer_started = Instant::now();
327                let diagnostics_enabled =
328                    window_scene_statistics_detail_mode(window_id).is_detailed();
329                self.renderer
330                    .set_runtime_diagnostics_enabled(diagnostics_enabled);
331                let render_options = window_render_options(window_id);
332                self.renderer
333                    .set_runtime_feathering_override(render_options.map(|options| {
334                        FeatheringOptions::new(options.feathering_enabled, options.feather_width)
335                    }));
336                self.renderer.set_runtime_text_hinting_override(
337                    render_options.map(|options| map_window_text_hinting(options.text_hinting)),
338                );
339                self.renderer.set_runtime_stem_darkening_override(
340                    render_options.map(|options| map_window_stem_darkening(options.stem_darkening)),
341                );
342                self.renderer.set_runtime_text_coverage_policy_override(
343                    render_options.map(|options| {
344                        map_window_text_coverage_policy(options.text_coverage_policy)
345                    }),
346                );
347                self.renderer
348                    .set_runtime_text_subpixel_order_override(render_options.map(|options| {
349                        map_window_text_subpixel_order(options.text_subpixel_order)
350                    }));
351                let active_render_options =
352                    render_options.unwrap_or_else(|| WindowRenderOptions::new(false, 0.0));
353                let display_capabilities_for_brightness = self
354                    .renderer
355                    .window_display_capabilities(window_id)
356                    .unwrap_or_default();
357                let sdr_content_brightness_nits = resolve_sdr_content_brightness_nits(
358                    active_render_options.sdr_content_brightness_nits,
359                    active_render_options.use_system_sdr_content_brightness,
360                    &display_capabilities_for_brightness,
361                );
362                self.renderer.render(&output.frame)?;
363                let mut display_capabilities = self
364                    .renderer
365                    .window_display_capabilities(window_id)
366                    .unwrap_or_default();
367                if !display_capabilities.notes.is_empty() {
368                    display_capabilities.notes.push(' ');
369                }
370                display_capabilities
371                    .notes
372                    .push_str("Headless offscreen renderer.");
373                let system_sdr_content_brightness_nits = display_capabilities.sdr_white_nits;
374                publish_window_output_diagnostics(
375                    window_id,
376                    WindowOutputDiagnostics {
377                        display_capabilities,
378                        requested_color_management_mode: active_render_options
379                            .color_management_mode,
380                        requested_output_primaries: active_render_options.output_color_primaries,
381                        requested_dynamic_range_mode: active_render_options.dynamic_range_mode,
382                        requested_tone_mapping_mode: active_render_options.tone_mapping_mode,
383                        requested_sdr_content_brightness_nits: sdr_content_brightness_nits,
384                        configured_sdr_content_brightness_nits: active_render_options
385                            .sdr_content_brightness_nits,
386                        system_sdr_content_brightness_nits,
387                        use_system_sdr_content_brightness: active_render_options
388                            .use_system_sdr_content_brightness,
389                        active_output_strategy: OutputStrategy::SdrSurface {
390                            format: wgpu::TextureFormat::Bgra8UnormSrgb,
391                        },
392                    },
393                );
394                let renderer_time_ms = renderer_started.elapsed().as_secs_f64() * 1000.0;
395                let presented_at_ms = self.current_time() * 1000.0;
396                presentation_latency.event_to_present_ms = self.windows[window_index]
397                    .last_non_redraw_event_at_ms
398                    .map(|timestamp| (presented_at_ms - timestamp).max(0.0))
399                    .unwrap_or(0.0);
400
401                self.windows[window_index].frame_index += 1;
402                let frame_index = self.windows[window_index].frame_index;
403                let pending_event_time_ms =
404                    std::mem::take(&mut self.windows[window_index].pending_event_time_ms);
405                self.windows[window_index].last_non_redraw_event_at_ms = None;
406                self.windows[window_index].redraw_requested_at_ms = None;
407
408                crate::publish_frame_performance(
409                    window_id,
410                    frame_index,
411                    pending_event_time_ms,
412                    event_time_ms,
413                    runtime_time_ms,
414                    presentation_latency,
415                    &output,
416                    &self.renderer,
417                    renderer_time_ms,
418                );
419
420                if self.windows[window_index].awaiting_performance_bootstrap {
421                    self.windows[window_index].awaiting_performance_bootstrap = false;
422                    if !self.windows[window_index].redraw_requested {
423                        self.windows[window_index].redraw_requested = true;
424                        self.windows[window_index].redraw_requested_at_ms =
425                            Some(self.current_time() * 1000.0);
426                        self.pending_events.push_back(QueuedEvent {
427                            window_id,
428                            event: Event::Window(WindowEvent::RedrawRequested),
429                        });
430                    }
431                }
432
433                self.windows[window_index].title = output.title;
434                self.windows[window_index]
435                    .accessibility
436                    .update(window_id, output.semantics);
437            }
438        }
439
440        if is_close {
441            runtime.remove_window(window_id)?;
442            self.renderer.remove_window(window_id);
443            crate::clear_window_performance(window_id);
444            self.pending_events
445                .retain(|pending_event| pending_event.window_id != window_id);
446            self.windows.swap_remove(window_index);
447        }
448
449        Ok(())
450    }
451}
452
453#[derive(Debug, Clone)]
454struct WindowState {
455    id: WindowId,
456    title: String,
457    open: bool,
458    awaiting_performance_bootstrap: bool,
459    redraw_requested: bool,
460    redraw_requested_at_ms: Option<f64>,
461    frame_index: u64,
462    pending_event_time_ms: f64,
463    last_non_redraw_event_at_ms: Option<f64>,
464    accessibility: AccessibilityBridge,
465}
466
467impl WindowState {
468    fn snapshot(&self) -> PlatformWindow {
469        PlatformWindow {
470            id: self.id,
471            title: self.title.clone(),
472            accessibility: self.accessibility.snapshot().cloned(),
473        }
474    }
475}
476
477#[derive(Debug, Clone)]
478struct QueuedEvent {
479    window_id: WindowId,
480    event: Event,
481}
482
483#[cfg(test)]
484mod tests {
485    use std::{cell::RefCell, f32::consts::TAU, rc::Rc};
486
487    use super::HeadlessPlatform;
488    use sui_core::{
489        AsyncWakeToken, Color, CustomEvent, Event, Rect, Result, SemanticsNode, SemanticsRole,
490        Size, TimerToken, WakeEvent, WindowEvent,
491    };
492    use sui_layout::Constraints;
493    use sui_runtime::{
494        Application, ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, Runtime,
495        SceneStatisticsDetailMode, SemanticsCtx, Widget, WindowBuilder, WindowColorManagementMode,
496        WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
497        WindowToneMappingMode, set_window_render_options, set_window_scene_statistics_detail_mode,
498        window_performance_snapshot,
499    };
500
501    #[derive(Default)]
502    struct Counters {
503        events: usize,
504        paints: usize,
505        timer_wakes: usize,
506        async_wakes: usize,
507        animation_wakes: usize,
508        pending_animation_frames: usize,
509        last_animation_delta: Option<f64>,
510        timer_token: Option<TimerToken>,
511        async_token: Option<AsyncWakeToken>,
512    }
513
514    struct TestRoot {
515        counters: Rc<RefCell<Counters>>,
516    }
517
518    impl Widget for TestRoot {
519        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
520            match event {
521                Event::Custom(custom) if custom.kind == "repaint" => {
522                    self.counters.borrow_mut().events += 1;
523                    ctx.request_paint();
524                }
525                Event::Custom(custom) if custom.kind == "arm-wakeups" => {
526                    let mut counters = self.counters.borrow_mut();
527                    counters.timer_token = Some(ctx.schedule_timer_after(3.0));
528                    counters.async_token = Some(ctx.register_async_wakeup());
529                }
530                Event::Custom(custom) if custom.kind == "arm-animation" => {
531                    let mut counters = self.counters.borrow_mut();
532                    counters.pending_animation_frames = 3;
533                    counters.last_animation_delta = None;
534                    ctx.request_animation_frame();
535                }
536                Event::Wake(WakeEvent::Timer { token, .. }) => {
537                    let mut counters = self.counters.borrow_mut();
538                    if counters.timer_token == Some(*token) {
539                        counters.timer_wakes += 1;
540                        ctx.request_paint();
541                        ctx.set_handled();
542                    }
543                }
544                Event::Wake(WakeEvent::Async { token, .. }) => {
545                    let mut counters = self.counters.borrow_mut();
546                    if counters.async_token == Some(*token) {
547                        counters.async_wakes += 1;
548                        ctx.request_paint();
549                        ctx.set_handled();
550                    }
551                }
552                Event::Wake(WakeEvent::AnimationFrame { delta, .. }) => {
553                    let mut counters = self.counters.borrow_mut();
554                    if counters.pending_animation_frames > 0 {
555                        counters.pending_animation_frames -= 1;
556                        counters.animation_wakes += 1;
557                        counters.last_animation_delta = Some(*delta);
558                        ctx.request_paint();
559                        if counters.pending_animation_frames > 0 {
560                            ctx.request_animation_frame();
561                        }
562                        ctx.set_handled();
563                    }
564                }
565                _ => {}
566            }
567        }
568
569        fn paint(&self, ctx: &mut PaintCtx) {
570            self.counters.borrow_mut().paints += 1;
571            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
572            ctx.fill_rect(
573                Rect::new(24.0, 24.0, 120.0, 48.0),
574                Color::rgba(0.16, 0.19, 0.25, 1.0),
575            );
576        }
577
578        fn semantics(&self, ctx: &mut SemanticsCtx) {
579            ctx.push(SemanticsNode::new(
580                ctx.widget_id(),
581                SemanticsRole::Window,
582                ctx.bounds(),
583            ));
584        }
585    }
586
587    fn build_runtime(counters: Rc<RefCell<Counters>>) -> (Runtime, sui_core::WindowId) {
588        let runtime = Application::new()
589            .window(
590                WindowBuilder::new()
591                    .title("Test")
592                    .root(TestRoot { counters }),
593            )
594            .build()
595            .unwrap();
596        let window_id = runtime.window_ids()[0];
597        (runtime, window_id)
598    }
599
600    #[test]
601    fn queued_events_reenter_the_platform_render_loop() -> Result<()> {
602        let counters = Rc::new(RefCell::new(Counters::default()));
603        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
604        let mut platform = HeadlessPlatform::new();
605
606        let windows = platform.run(&mut runtime)?;
607        let accessibility = platform.accessibility_snapshot(window_id).unwrap();
608
609        assert_eq!(windows.len(), 1);
610        assert_eq!(windows[0].title, "Test");
611        assert_eq!(windows[0].accessibility.as_ref(), Some(accessibility));
612        assert_eq!(accessibility.nodes.len(), 1);
613        assert_eq!(accessibility.nodes[0].role, SemanticsRole::Window);
614        assert_eq!(platform.renderer().frames_rendered(), 2);
615        assert_eq!(counters.borrow().paints, 1);
616        assert!(!platform.has_pending_events());
617
618        platform.dispatch_event(
619            &runtime,
620            window_id,
621            Event::Custom(CustomEvent::new("repaint")),
622        )?;
623        let _ = platform.run(&mut runtime)?;
624
625        assert_eq!(counters.borrow().events, 1);
626        assert_eq!(counters.borrow().paints, 2);
627        assert_eq!(platform.renderer().frames_rendered(), 3);
628        assert!(!platform.has_pending_events());
629        assert!(!runtime.needs_render(window_id)?);
630
631        Ok(())
632    }
633
634    #[test]
635    fn close_requested_removes_window_from_platform_and_runtime() -> Result<()> {
636        let counters = Rc::new(RefCell::new(Counters::default()));
637        let (mut runtime, window_id) = build_runtime(counters);
638        let mut platform = HeadlessPlatform::new();
639
640        let _ = platform.run(&mut runtime)?;
641
642        platform.dispatch_event(
643            &runtime,
644            window_id,
645            Event::Window(WindowEvent::CloseRequested),
646        )?;
647        let windows = platform.run(&mut runtime)?;
648
649        assert!(windows.is_empty());
650        assert!(runtime.window_ids().is_empty());
651        assert!(runtime.needs_render(window_id).is_err());
652
653        Ok(())
654    }
655
656    #[test]
657    fn wakeups_reenter_the_platform_pump_and_trigger_repaint() -> Result<()> {
658        let counters = Rc::new(RefCell::new(Counters::default()));
659        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
660        let mut platform = HeadlessPlatform::new();
661
662        let _ = platform.run(&mut runtime)?;
663
664        platform.dispatch_event(
665            &runtime,
666            window_id,
667            Event::Custom(CustomEvent::new("arm-wakeups")),
668        )?;
669        assert!(platform.pump(&mut runtime)?);
670
671        let async_token = counters.borrow().async_token.unwrap();
672        assert_eq!(counters.borrow().paints, 1);
673        assert_eq!(counters.borrow().timer_wakes, 0);
674
675        assert!(platform.wake_async(&mut runtime, window_id, async_token)?);
676        assert!(platform.pump(&mut runtime)?);
677
678        assert_eq!(counters.borrow().async_wakes, 1);
679        assert_eq!(counters.borrow().paints, 1);
680        assert!(platform.pump(&mut runtime)?);
681        assert_eq!(counters.borrow().paints, 2);
682
683        platform.advance_time(3.0);
684        assert!(platform.pump(&mut runtime)?);
685
686        assert_eq!(counters.borrow().timer_wakes, 1);
687        assert_eq!(counters.borrow().paints, 2);
688        assert!(platform.pump(&mut runtime)?);
689        assert_eq!(counters.borrow().paints, 3);
690
691        Ok(())
692    }
693
694    #[test]
695    fn animation_frame_request_keeps_headless_pumping_until_completion() -> Result<()> {
696        let counters = Rc::new(RefCell::new(Counters::default()));
697        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
698        let mut platform = HeadlessPlatform::new();
699
700        let _ = platform.run(&mut runtime)?;
701        assert_eq!(counters.borrow().paints, 1);
702
703        platform.dispatch_event(
704            &runtime,
705            window_id,
706            Event::Custom(CustomEvent::new("arm-animation")),
707        )?;
708        let _ = platform.run(&mut runtime)?;
709
710        let counters = counters.borrow();
711        assert_eq!(counters.animation_wakes, 3);
712        assert_eq!(counters.pending_animation_frames, 0);
713        assert_eq!(counters.paints, 4);
714        assert_eq!(counters.last_animation_delta, Some(1.0 / 120.0));
715        assert!((platform.current_time() - (2.0 / 120.0)).abs() < 1e-9);
716
717        Ok(())
718    }
719
720    #[test]
721    fn feather_width_is_configurable_without_renderer_access() {
722        let mut platform = HeadlessPlatform::new()
723            .with_feathering_enabled(false)
724            .with_feather_width(2.5);
725
726        assert!(!platform.feathering_enabled());
727        assert_eq!(platform.feather_width(), 2.5);
728
729        platform.set_feather_width(-4.0);
730        platform.set_feathering_enabled(true);
731
732        assert!(platform.feathering_enabled());
733        assert_eq!(platform.feather_width(), 0.0);
734    }
735
736    const HDR_BENCH_STEP_S: f64 = 1.0 / 120.0;
737    const HDR_BENCH_FRAMES: usize = 120;
738    const HDR_BENCH_WIDTH: f32 = 1280.0;
739    const HDR_BENCH_HEIGHT: f32 = 720.0;
740    const HDR_BENCH_COLS: usize = 48;
741    const HDR_BENCH_ROWS: usize = 27;
742
743    struct AnimatedHdrGrid {
744        phase: f32,
745        timer: Option<TimerToken>,
746    }
747
748    impl AnimatedHdrGrid {
749        fn new() -> Self {
750            Self {
751                phase: 0.0,
752                timer: None,
753            }
754        }
755
756        fn arm(&mut self, ctx: &mut EventCtx) {
757            if self.timer.is_none() {
758                self.timer = Some(ctx.schedule_timer_after(HDR_BENCH_STEP_S));
759            }
760        }
761    }
762
763    impl Widget for AnimatedHdrGrid {
764        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
765            match event {
766                Event::Window(WindowEvent::Resized(_)) => {
767                    self.arm(ctx);
768                    ctx.request_paint();
769                }
770                Event::Wake(WakeEvent::Timer { token, .. }) if self.timer == Some(*token) => {
771                    self.phase = (self.phase + 0.035) % TAU;
772                    self.timer = Some(ctx.schedule_timer_after(HDR_BENCH_STEP_S));
773                    ctx.request_paint();
774                    ctx.set_handled();
775                }
776                _ => {}
777            }
778        }
779
780        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
781            constraints.clamp(Size::new(HDR_BENCH_WIDTH, HDR_BENCH_HEIGHT))
782        }
783
784        fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
785
786        fn paint(&self, ctx: &mut PaintCtx) {
787            ctx.clear(Color::linear_rgba(0.08, 0.09, 0.11, 1.0));
788            let cell_w = HDR_BENCH_WIDTH / HDR_BENCH_COLS as f32;
789            let cell_h = HDR_BENCH_HEIGHT / HDR_BENCH_ROWS as f32;
790            for row in 0..HDR_BENCH_ROWS {
791                for col in 0..HDR_BENCH_COLS {
792                    let x = col as f32 * cell_w;
793                    let y = row as f32 * cell_h;
794                    let t = self.phase + row as f32 * 0.19 + col as f32 * 0.11;
795                    let r = 0.5 + 3.5 * (0.5 + 0.5 * t.sin());
796                    let g = 0.25 + 2.25 * (0.5 + 0.5 * (t * 1.3).cos());
797                    let b = 0.15 + 1.85 * (0.5 + 0.5 * (t * 0.7 + 1.2).sin());
798                    ctx.fill_rect(
799                        Rect::new(x, y, cell_w + 1.0, cell_h + 1.0),
800                        Color::linear_rgba(r, g, b, 1.0),
801                    );
802                }
803            }
804        }
805
806        fn semantics(&self, ctx: &mut SemanticsCtx) {
807            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
808            node.name = Some("Animated HDR Grid".to_string());
809            ctx.push(node);
810        }
811    }
812
813    fn mean(values: &[f64]) -> f64 {
814        if values.is_empty() {
815            0.0
816        } else {
817            values.iter().sum::<f64>() / values.len() as f64
818        }
819    }
820
821    fn percentile(sorted: &[f64], p: f64) -> f64 {
822        if sorted.is_empty() {
823            return 0.0;
824        }
825        let rank = ((sorted.len() - 1) as f64 * p).round() as usize;
826        sorted[rank]
827    }
828
829    #[test]
830    #[ignore = "hardware Vulkan benchmark; run explicitly on a machine with a working headless GPU path"]
831    fn steady_state_headless_hdr_grid_benchmark_emits_advancing_frames() -> Result<()> {
832        let options = WindowRenderOptions::new(true, 1.0)
833            .with_color_management_mode(WindowColorManagementMode::PreferHdr)
834            .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
835            .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
836            .with_tone_mapping_mode(WindowToneMappingMode::Automatic);
837
838        let runtime = Application::new()
839            .window(
840                WindowBuilder::new()
841                    .title("Animated HDR Grid")
842                    .root(AnimatedHdrGrid::new()),
843            )
844            .build()
845            .unwrap();
846        let window_id = runtime.window_ids()[0];
847        set_window_render_options(window_id, options);
848        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
849
850        let mut runtime = runtime;
851        let mut platform = HeadlessPlatform::new();
852        let mut totals = Vec::with_capacity(HDR_BENCH_FRAMES);
853        let mut commands = Vec::with_capacity(HDR_BENCH_FRAMES);
854        let mut dirty = Vec::with_capacity(HDR_BENCH_FRAMES);
855        let mut last_frame = 0u64;
856        let mut iterations = 0usize;
857        let max_iterations = 20_000usize;
858
859        while totals.len() < HDR_BENCH_FRAMES && iterations < max_iterations {
860            let _ = platform.pump(&mut runtime)?;
861            if let Some(snapshot) = window_performance_snapshot(window_id)
862                && snapshot.frame_index != last_frame
863            {
864                last_frame = snapshot.frame_index;
865                totals.push(snapshot.total_time_ms);
866                commands.push(snapshot.scene.command_count as f64);
867                dirty.push(snapshot.scene.dirty_coverage as f64);
868            }
869            platform.advance_time(HDR_BENCH_STEP_S);
870            iterations += 1;
871        }
872
873        let mut totals_sorted = totals.clone();
874        totals_sorted.sort_by(|a, b| a.total_cmp(b));
875
876        println!("benchmark=steady-state-headless-hdr-grid");
877        println!("iterations={iterations}");
878        println!("frames={}", totals.len());
879        println!("nominal_fps={:.2}", 1.0 / HDR_BENCH_STEP_S);
880        println!("frame_total_ms_avg={:.3}", mean(&totals));
881        println!("frame_total_ms_p50={:.3}", percentile(&totals_sorted, 0.50));
882        println!("frame_total_ms_p95={:.3}", percentile(&totals_sorted, 0.95));
883        println!(
884            "frame_total_ms_max={:.3}",
885            totals_sorted.last().copied().unwrap_or(0.0)
886        );
887        println!("command_count_avg={:.1}", mean(&commands));
888        println!("dirty_coverage_avg={:.2}", mean(&dirty));
889
890        assert_eq!(
891            totals.len(),
892            HDR_BENCH_FRAMES,
893            "expected {} benchmark frames, got {} after {} iterations",
894            HDR_BENCH_FRAMES,
895            totals.len(),
896            iterations
897        );
898        assert!(mean(&totals) > 0.0, "expected positive frame timings");
899
900        Ok(())
901    }
902}