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    WgpuExternalTextureRegistry, 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        let mut did_work = runtime.has_pending_commands();
72        runtime.process_commands();
73        runtime.tick(self.frame_clock);
74        self.queue_ready_events(runtime);
75        self.queue_redraw_requests(runtime)?;
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    /// Attach the registry used to resolve app-owned WGPU textures.
178    pub fn set_external_texture_registry(&mut self, registry: WgpuExternalTextureRegistry) {
179        self.renderer.set_external_texture_registry(registry);
180    }
181
182    pub fn renderer_mut(&mut self) -> &mut WgpuRenderer {
183        &mut self.renderer
184    }
185
186    pub fn capture_rgba(&self, window_id: WindowId) -> Result<RgbaImage> {
187        self.renderer.capture_rgba(window_id)
188    }
189
190    pub fn capture_debug_frame(
191        &mut self,
192        window_id: WindowId,
193        request: DebugCaptureRequest,
194    ) -> Result<DebugCaptureArtifact> {
195        self.renderer.capture_last_frame_debug(window_id, request)
196    }
197
198    pub fn accessibility_snapshot(&self, window_id: WindowId) -> Option<&AccessibilitySnapshot> {
199        self.windows
200            .iter()
201            .find(|window| window.id == window_id && window.open)
202            .and_then(|window| window.accessibility.snapshot())
203    }
204
205    fn queue_ready_events(&mut self, runtime: &mut Runtime) {
206        self.pending_events.extend(
207            runtime
208                .drain_ready_events()
209                .into_iter()
210                .map(|(window_id, event)| QueuedEvent { window_id, event }),
211        );
212    }
213
214    fn sync_windows(&mut self, runtime: &Runtime) -> Result<()> {
215        let runtime_window_ids = runtime.window_ids();
216
217        let removed_ids: Vec<_> = self
218            .windows
219            .iter()
220            .map(|window| window.id)
221            .filter(|window_id| !runtime_window_ids.contains(window_id))
222            .collect();
223
224        for window_id in removed_ids {
225            self.renderer.remove_window(window_id);
226            crate::clear_window_performance(window_id);
227        }
228
229        self.windows
230            .retain(|window| runtime_window_ids.contains(&window.id));
231        self.pending_events
232            .retain(|queued_event| runtime_window_ids.contains(&queued_event.window_id));
233
234        for window_id in runtime_window_ids {
235            if self.windows.iter().any(|window| window.id == window_id) {
236                continue;
237            }
238
239            self.windows.push(WindowState {
240                id: window_id,
241                title: runtime.window_title(window_id)?.to_string(),
242                open: true,
243                awaiting_performance_bootstrap: true,
244                redraw_requested: false,
245                redraw_requested_at_ms: None,
246                frame_index: 0,
247                pending_event_time_ms: 0.0,
248                last_non_redraw_event_at_ms: None,
249                accessibility: AccessibilityBridge::default(),
250            });
251            self.pending_events.push_back(QueuedEvent {
252                window_id,
253                event: Event::Window(WindowEvent::Resized(Self::DEFAULT_WINDOW_SIZE)),
254            });
255        }
256
257        Ok(())
258    }
259
260    fn queue_redraw_requests(&mut self, runtime: &Runtime) -> Result<()> {
261        let now_ms = self.current_time() * 1000.0;
262
263        for window in &mut self.windows {
264            if !window.open || window.redraw_requested || !runtime.needs_render(window.id)? {
265                continue;
266            }
267
268            window.redraw_requested = true;
269            window.redraw_requested_at_ms = Some(now_ms);
270            self.pending_events.push_back(QueuedEvent {
271                window_id: window.id,
272                event: Event::Window(WindowEvent::RedrawRequested),
273            });
274        }
275
276        Ok(())
277    }
278
279    fn process_event(&mut self, runtime: &mut Runtime, queued_event: QueuedEvent) -> Result<()> {
280        let Some(window_index) = self
281            .windows
282            .iter()
283            .position(|window| window.id == queued_event.window_id && window.open)
284        else {
285            return Ok(());
286        };
287
288        let is_redraw = matches!(
289            queued_event.event,
290            Event::Window(WindowEvent::RedrawRequested)
291        );
292        let is_close = matches!(
293            queued_event.event,
294            Event::Window(WindowEvent::CloseRequested)
295        );
296        let window_id = queued_event.window_id;
297        let event_arrived_at_ms = self.current_time() * 1000.0;
298
299        let event_started = Instant::now();
300        runtime.handle_event(window_id, queued_event.event)?;
301        let event_time_ms = event_started.elapsed().as_secs_f64() * 1000.0;
302        // Match the desktop host: input with no pending redraw belongs to idle
303        // processing, not to the timing or latency of a future frame.
304        if !is_redraw && !is_close && runtime.needs_render(window_id)? {
305            self.windows[window_index].pending_event_time_ms += event_time_ms;
306            self.windows[window_index].last_non_redraw_event_at_ms = Some(event_arrived_at_ms);
307        }
308
309        if is_redraw {
310            self.windows[window_index].redraw_requested = false;
311
312            if runtime.needs_render(window_id)? {
313                runtime.tick(self.frame_clock);
314
315                let render_started_at_ms = self.current_time() * 1000.0;
316                let mut presentation_latency = PresentationLatencyDiagnostics::new(
317                    self.windows[window_index]
318                        .last_non_redraw_event_at_ms
319                        .map(|timestamp| (render_started_at_ms - timestamp).max(0.0))
320                        .unwrap_or(0.0),
321                    0.0,
322                    self.windows[window_index]
323                        .redraw_requested_at_ms
324                        .map(|timestamp| (render_started_at_ms - timestamp).max(0.0))
325                        .unwrap_or(0.0),
326                );
327
328                let runtime_started = Instant::now();
329                let output = runtime.render(window_id)?;
330                let runtime_time_ms = runtime_started.elapsed().as_secs_f64() * 1000.0;
331                let renderer_started = Instant::now();
332                let diagnostics_enabled =
333                    window_scene_statistics_detail_mode(window_id).is_detailed();
334                self.renderer
335                    .set_runtime_diagnostics_enabled(diagnostics_enabled);
336                let render_options = window_render_options(window_id);
337                self.renderer
338                    .set_runtime_feathering_override(render_options.map(|options| {
339                        FeatheringOptions::new(options.feathering_enabled, options.feather_width)
340                    }));
341                self.renderer.set_runtime_text_hinting_override(
342                    render_options.map(|options| map_window_text_hinting(options.text_hinting)),
343                );
344                self.renderer.set_runtime_stem_darkening_override(
345                    render_options.map(|options| map_window_stem_darkening(options.stem_darkening)),
346                );
347                self.renderer.set_runtime_text_coverage_policy_override(
348                    render_options.map(|options| {
349                        map_window_text_coverage_policy(options.text_coverage_policy)
350                    }),
351                );
352                self.renderer
353                    .set_runtime_text_subpixel_order_override(render_options.map(|options| {
354                        map_window_text_subpixel_order(options.text_subpixel_order)
355                    }));
356                let active_render_options =
357                    render_options.unwrap_or_else(|| WindowRenderOptions::new(false, 0.0));
358                let display_capabilities_for_brightness = self
359                    .renderer
360                    .window_display_capabilities(window_id)
361                    .unwrap_or_default();
362                let sdr_content_brightness_nits = resolve_sdr_content_brightness_nits(
363                    active_render_options.sdr_content_brightness_nits,
364                    active_render_options.use_system_sdr_content_brightness,
365                    &display_capabilities_for_brightness,
366                );
367                self.renderer.render(&output.frame)?;
368                let mut display_capabilities = self
369                    .renderer
370                    .window_display_capabilities(window_id)
371                    .unwrap_or_default();
372                if !display_capabilities.notes.is_empty() {
373                    display_capabilities.notes.push(' ');
374                }
375                display_capabilities
376                    .notes
377                    .push_str("Headless offscreen renderer.");
378                let system_sdr_content_brightness_nits = display_capabilities.sdr_white_nits;
379                publish_window_output_diagnostics(
380                    window_id,
381                    WindowOutputDiagnostics {
382                        display_capabilities,
383                        requested_color_management_mode: active_render_options
384                            .color_management_mode,
385                        requested_output_primaries: active_render_options.output_color_primaries,
386                        requested_dynamic_range_mode: active_render_options.dynamic_range_mode,
387                        requested_tone_mapping_mode: active_render_options.tone_mapping_mode,
388                        requested_sdr_content_brightness_nits: sdr_content_brightness_nits,
389                        configured_sdr_content_brightness_nits: active_render_options
390                            .sdr_content_brightness_nits,
391                        system_sdr_content_brightness_nits,
392                        use_system_sdr_content_brightness: active_render_options
393                            .use_system_sdr_content_brightness,
394                        active_output_strategy: OutputStrategy::SdrSurface {
395                            format: wgpu::TextureFormat::Bgra8UnormSrgb,
396                        },
397                    },
398                );
399                let renderer_time_ms = renderer_started.elapsed().as_secs_f64() * 1000.0;
400                let presented_at_ms = self.current_time() * 1000.0;
401                presentation_latency.event_to_present_ms = self.windows[window_index]
402                    .last_non_redraw_event_at_ms
403                    .map(|timestamp| (presented_at_ms - timestamp).max(0.0))
404                    .unwrap_or(0.0);
405
406                self.windows[window_index].frame_index += 1;
407                let frame_index = self.windows[window_index].frame_index;
408                let pending_event_time_ms =
409                    std::mem::take(&mut self.windows[window_index].pending_event_time_ms);
410                self.windows[window_index].last_non_redraw_event_at_ms = None;
411                self.windows[window_index].redraw_requested_at_ms = None;
412
413                crate::publish_frame_performance(
414                    window_id,
415                    frame_index,
416                    pending_event_time_ms,
417                    event_time_ms,
418                    runtime_time_ms,
419                    presentation_latency,
420                    &output,
421                    &self.renderer,
422                    renderer_time_ms,
423                );
424
425                if self.windows[window_index].awaiting_performance_bootstrap {
426                    self.windows[window_index].awaiting_performance_bootstrap = false;
427                    if !self.windows[window_index].redraw_requested {
428                        self.windows[window_index].redraw_requested = true;
429                        self.windows[window_index].redraw_requested_at_ms =
430                            Some(self.current_time() * 1000.0);
431                        self.pending_events.push_back(QueuedEvent {
432                            window_id,
433                            event: Event::Window(WindowEvent::RedrawRequested),
434                        });
435                    }
436                }
437
438                self.windows[window_index].title = output.title;
439                self.windows[window_index]
440                    .accessibility
441                    .update(window_id, output.semantics);
442            }
443        }
444
445        if is_close {
446            runtime.remove_window(window_id)?;
447            self.renderer.remove_window(window_id);
448            crate::clear_window_performance(window_id);
449            self.pending_events
450                .retain(|pending_event| pending_event.window_id != window_id);
451            self.windows.swap_remove(window_index);
452        }
453
454        Ok(())
455    }
456}
457
458#[derive(Debug, Clone)]
459struct WindowState {
460    id: WindowId,
461    title: String,
462    open: bool,
463    awaiting_performance_bootstrap: bool,
464    redraw_requested: bool,
465    redraw_requested_at_ms: Option<f64>,
466    frame_index: u64,
467    pending_event_time_ms: f64,
468    last_non_redraw_event_at_ms: Option<f64>,
469    accessibility: AccessibilityBridge,
470}
471
472impl WindowState {
473    fn snapshot(&self) -> PlatformWindow {
474        PlatformWindow {
475            id: self.id,
476            title: self.title.clone(),
477            accessibility: self.accessibility.snapshot().cloned(),
478        }
479    }
480}
481
482#[derive(Debug, Clone)]
483struct QueuedEvent {
484    window_id: WindowId,
485    event: Event,
486}
487
488#[cfg(test)]
489mod tests {
490    use std::{cell::RefCell, f32::consts::TAU, rc::Rc};
491
492    use super::HeadlessPlatform;
493    use sui_core::{
494        AsyncWakeToken, Color, CustomEvent, Event, Rect, Result, SemanticsNode, SemanticsRole,
495        Size, TimerToken, WakeEvent, WindowEvent,
496    };
497    use sui_layout::Constraints;
498    use sui_runtime::{
499        Application, ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, Runtime,
500        SceneStatisticsDetailMode, SemanticsCtx, Widget, WindowBuilder, WindowColorManagementMode,
501        WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
502        WindowToneMappingMode, set_window_render_options, set_window_scene_statistics_detail_mode,
503        window_performance_snapshot,
504    };
505
506    #[derive(Default)]
507    struct Counters {
508        events: usize,
509        paints: usize,
510        timer_wakes: usize,
511        async_wakes: usize,
512        animation_wakes: usize,
513        pending_animation_frames: usize,
514        last_animation_delta: Option<f64>,
515        timer_token: Option<TimerToken>,
516        async_token: Option<AsyncWakeToken>,
517    }
518
519    struct TestRoot {
520        counters: Rc<RefCell<Counters>>,
521    }
522
523    impl Widget for TestRoot {
524        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
525            match event {
526                Event::Custom(custom) if custom.kind == "repaint" => {
527                    self.counters.borrow_mut().events += 1;
528                    ctx.request_paint();
529                }
530                Event::Custom(custom) if custom.kind == "arm-wakeups" => {
531                    let mut counters = self.counters.borrow_mut();
532                    counters.timer_token = Some(ctx.schedule_timer_after(3.0));
533                    counters.async_token = Some(ctx.register_async_wakeup());
534                }
535                Event::Custom(custom) if custom.kind == "arm-animation" => {
536                    let mut counters = self.counters.borrow_mut();
537                    counters.pending_animation_frames = 3;
538                    counters.last_animation_delta = None;
539                    ctx.request_animation_frame();
540                }
541                Event::Wake(WakeEvent::Timer { token, .. }) => {
542                    let mut counters = self.counters.borrow_mut();
543                    if counters.timer_token == Some(*token) {
544                        counters.timer_wakes += 1;
545                        ctx.request_paint();
546                        ctx.set_handled();
547                    }
548                }
549                Event::Wake(WakeEvent::Async { token, .. }) => {
550                    let mut counters = self.counters.borrow_mut();
551                    if counters.async_token == Some(*token) {
552                        counters.async_wakes += 1;
553                        ctx.request_paint();
554                        ctx.set_handled();
555                    }
556                }
557                Event::Wake(WakeEvent::AnimationFrame { delta, .. }) => {
558                    let mut counters = self.counters.borrow_mut();
559                    if counters.pending_animation_frames > 0 {
560                        counters.pending_animation_frames -= 1;
561                        counters.animation_wakes += 1;
562                        counters.last_animation_delta = Some(*delta);
563                        ctx.request_paint();
564                        if counters.pending_animation_frames > 0 {
565                            ctx.request_animation_frame();
566                        }
567                        ctx.set_handled();
568                    }
569                }
570                _ => {}
571            }
572        }
573
574        fn paint(&self, ctx: &mut PaintCtx) {
575            self.counters.borrow_mut().paints += 1;
576            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
577            ctx.fill_rect(
578                Rect::new(24.0, 24.0, 120.0, 48.0),
579                Color::rgba(0.16, 0.19, 0.25, 1.0),
580            );
581        }
582
583        fn semantics(&self, ctx: &mut SemanticsCtx) {
584            ctx.push(SemanticsNode::new(
585                ctx.widget_id(),
586                SemanticsRole::Window,
587                ctx.bounds(),
588            ));
589        }
590    }
591
592    fn build_runtime(counters: Rc<RefCell<Counters>>) -> (Runtime, sui_core::WindowId) {
593        let runtime = Application::new()
594            .window(
595                WindowBuilder::new()
596                    .title("Test")
597                    .root(TestRoot { counters }),
598            )
599            .build()
600            .unwrap();
601        let window_id = runtime.window_ids()[0];
602        (runtime, window_id)
603    }
604
605    #[test]
606    fn input_without_a_redraw_does_not_accumulate_in_the_next_frames_timing() -> Result<()> {
607        let counters = Rc::new(RefCell::new(Counters::default()));
608        let (mut runtime, window_id) = build_runtime(counters);
609        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
610        let mut platform = HeadlessPlatform::new();
611        platform.run(&mut runtime)?;
612        let original_frame = platform.renderer().frames_rendered();
613
614        for _ in 0..1000 {
615            platform.dispatch_event(
616                &runtime,
617                window_id,
618                Event::Custom(CustomEvent::new("idle-input")),
619            )?;
620        }
621        platform.run(&mut runtime)?;
622        assert_eq!(platform.renderer().frames_rendered(), original_frame);
623        assert_eq!(
624            platform.windows[0].pending_event_time_ms, 0.0,
625            "input processed while no frame is pending must not be charged to a later frame"
626        );
627        assert_eq!(platform.windows[0].last_non_redraw_event_at_ms, None);
628
629        // A real repaint still includes the event that requested it, plus any
630        // other events processed before that frame is rendered.
631        platform.advance_time(1.0);
632        platform.process_event(
633            &mut runtime,
634            super::QueuedEvent {
635                window_id,
636                event: Event::Custom(CustomEvent::new("repaint")),
637            },
638        )?;
639        let repaint_cost = platform.windows[0].pending_event_time_ms;
640        assert!(repaint_cost > 0.0);
641        assert_eq!(
642            platform.windows[0].last_non_redraw_event_at_ms,
643            Some(1000.0)
644        );
645        platform.process_event(
646            &mut runtime,
647            super::QueuedEvent {
648                window_id,
649                event: Event::Custom(CustomEvent::new("more-input")),
650            },
651        )?;
652        assert!(platform.windows[0].pending_event_time_ms >= repaint_cost);
653        let expected_event_cost = platform.windows[0].pending_event_time_ms;
654        platform.run(&mut runtime)?;
655        let snapshot = window_performance_snapshot(window_id).expect("repaint timing");
656        let reported_event_cost = snapshot
657            .phase_timings
658            .iter()
659            .find(|sample| sample.phase == sui_runtime::FramePhase::Event)
660            .expect("events that contribute to a frame must still be reported")
661            .duration_ms;
662        assert_eq!(reported_event_cost, expected_event_cost);
663        assert_eq!(platform.windows[0].pending_event_time_ms, 0.0);
664        assert_eq!(platform.windows[0].last_non_redraw_event_at_ms, None);
665        Ok(())
666    }
667
668    #[test]
669    fn queued_events_reenter_the_platform_render_loop() -> Result<()> {
670        let counters = Rc::new(RefCell::new(Counters::default()));
671        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
672        let mut platform = HeadlessPlatform::new();
673
674        let windows = platform.run(&mut runtime)?;
675        let accessibility = platform.accessibility_snapshot(window_id).unwrap();
676
677        assert_eq!(windows.len(), 1);
678        assert_eq!(windows[0].title, "Test");
679        assert_eq!(windows[0].accessibility.as_ref(), Some(accessibility));
680        assert_eq!(accessibility.nodes.len(), 1);
681        assert_eq!(accessibility.nodes[0].role, SemanticsRole::Window);
682        assert_eq!(platform.renderer().frames_rendered(), 2);
683        assert_eq!(counters.borrow().paints, 1);
684        assert!(!platform.has_pending_events());
685
686        platform.dispatch_event(
687            &runtime,
688            window_id,
689            Event::Custom(CustomEvent::new("repaint")),
690        )?;
691        let _ = platform.run(&mut runtime)?;
692
693        assert_eq!(counters.borrow().events, 1);
694        assert_eq!(counters.borrow().paints, 2);
695        assert_eq!(platform.renderer().frames_rendered(), 3);
696        assert!(!platform.has_pending_events());
697        assert!(!runtime.needs_render(window_id)?);
698
699        Ok(())
700    }
701
702    #[test]
703    fn close_requested_removes_window_from_platform_and_runtime() -> Result<()> {
704        let counters = Rc::new(RefCell::new(Counters::default()));
705        let (mut runtime, window_id) = build_runtime(counters);
706        let mut platform = HeadlessPlatform::new();
707
708        let _ = platform.run(&mut runtime)?;
709
710        platform.dispatch_event(
711            &runtime,
712            window_id,
713            Event::Window(WindowEvent::CloseRequested),
714        )?;
715        let windows = platform.run(&mut runtime)?;
716
717        assert!(windows.is_empty());
718        assert!(runtime.window_ids().is_empty());
719        assert!(runtime.needs_render(window_id).is_err());
720
721        Ok(())
722    }
723
724    #[test]
725    fn wakeups_reenter_the_platform_pump_and_trigger_repaint() -> Result<()> {
726        let counters = Rc::new(RefCell::new(Counters::default()));
727        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
728        let mut platform = HeadlessPlatform::new();
729
730        let _ = platform.run(&mut runtime)?;
731
732        platform.dispatch_event(
733            &runtime,
734            window_id,
735            Event::Custom(CustomEvent::new("arm-wakeups")),
736        )?;
737        assert!(platform.pump(&mut runtime)?);
738
739        let async_token = counters.borrow().async_token.unwrap();
740        assert_eq!(counters.borrow().paints, 1);
741        assert_eq!(counters.borrow().timer_wakes, 0);
742
743        assert!(platform.wake_async(&mut runtime, window_id, async_token)?);
744        assert!(platform.pump(&mut runtime)?);
745
746        assert_eq!(counters.borrow().async_wakes, 1);
747        assert_eq!(counters.borrow().paints, 1);
748        assert!(platform.pump(&mut runtime)?);
749        assert_eq!(counters.borrow().paints, 2);
750
751        platform.advance_time(3.0);
752        assert!(platform.pump(&mut runtime)?);
753
754        assert_eq!(counters.borrow().timer_wakes, 1);
755        assert_eq!(counters.borrow().paints, 2);
756        assert!(platform.pump(&mut runtime)?);
757        assert_eq!(counters.borrow().paints, 3);
758
759        Ok(())
760    }
761
762    #[test]
763    fn animation_frame_request_keeps_headless_pumping_until_completion() -> Result<()> {
764        let counters = Rc::new(RefCell::new(Counters::default()));
765        let (mut runtime, window_id) = build_runtime(Rc::clone(&counters));
766        let mut platform = HeadlessPlatform::new();
767
768        let _ = platform.run(&mut runtime)?;
769        assert_eq!(counters.borrow().paints, 1);
770
771        platform.dispatch_event(
772            &runtime,
773            window_id,
774            Event::Custom(CustomEvent::new("arm-animation")),
775        )?;
776        let _ = platform.run(&mut runtime)?;
777
778        let counters = counters.borrow();
779        assert_eq!(counters.animation_wakes, 3);
780        assert_eq!(counters.pending_animation_frames, 0);
781        assert_eq!(counters.paints, 4);
782        assert_eq!(counters.last_animation_delta, Some(1.0 / 120.0));
783        assert!((platform.current_time() - (2.0 / 120.0)).abs() < 1e-9);
784
785        Ok(())
786    }
787
788    #[test]
789    fn feather_width_is_configurable_without_renderer_access() {
790        let mut platform = HeadlessPlatform::new()
791            .with_feathering_enabled(false)
792            .with_feather_width(2.5);
793
794        assert!(!platform.feathering_enabled());
795        assert_eq!(platform.feather_width(), 2.5);
796
797        platform.set_feather_width(-4.0);
798        platform.set_feathering_enabled(true);
799
800        assert!(platform.feathering_enabled());
801        assert_eq!(platform.feather_width(), 0.0);
802    }
803
804    const HDR_BENCH_STEP_S: f64 = 1.0 / 120.0;
805    const HDR_BENCH_FRAMES: usize = 120;
806    const HDR_BENCH_WIDTH: f32 = 1280.0;
807    const HDR_BENCH_HEIGHT: f32 = 720.0;
808    const HDR_BENCH_COLS: usize = 48;
809    const HDR_BENCH_ROWS: usize = 27;
810
811    struct AnimatedHdrGrid {
812        phase: f32,
813        timer: Option<TimerToken>,
814    }
815
816    impl AnimatedHdrGrid {
817        fn new() -> Self {
818            Self {
819                phase: 0.0,
820                timer: None,
821            }
822        }
823
824        fn arm(&mut self, ctx: &mut EventCtx) {
825            if self.timer.is_none() {
826                self.timer = Some(ctx.schedule_timer_after(HDR_BENCH_STEP_S));
827            }
828        }
829    }
830
831    impl Widget for AnimatedHdrGrid {
832        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
833            match event {
834                Event::Window(WindowEvent::Resized(_)) => {
835                    self.arm(ctx);
836                    ctx.request_paint();
837                }
838                Event::Wake(WakeEvent::Timer { token, .. }) if self.timer == Some(*token) => {
839                    self.phase = (self.phase + 0.035) % TAU;
840                    self.timer = Some(ctx.schedule_timer_after(HDR_BENCH_STEP_S));
841                    ctx.request_paint();
842                    ctx.set_handled();
843                }
844                _ => {}
845            }
846        }
847
848        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
849            constraints.clamp(Size::new(HDR_BENCH_WIDTH, HDR_BENCH_HEIGHT))
850        }
851
852        fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
853
854        fn paint(&self, ctx: &mut PaintCtx) {
855            ctx.clear(Color::linear_rgba(0.08, 0.09, 0.11, 1.0));
856            let cell_w = HDR_BENCH_WIDTH / HDR_BENCH_COLS as f32;
857            let cell_h = HDR_BENCH_HEIGHT / HDR_BENCH_ROWS as f32;
858            for row in 0..HDR_BENCH_ROWS {
859                for col in 0..HDR_BENCH_COLS {
860                    let x = col as f32 * cell_w;
861                    let y = row as f32 * cell_h;
862                    let t = self.phase + row as f32 * 0.19 + col as f32 * 0.11;
863                    let r = 0.5 + 3.5 * (0.5 + 0.5 * t.sin());
864                    let g = 0.25 + 2.25 * (0.5 + 0.5 * (t * 1.3).cos());
865                    let b = 0.15 + 1.85 * (0.5 + 0.5 * (t * 0.7 + 1.2).sin());
866                    ctx.fill_rect(
867                        Rect::new(x, y, cell_w + 1.0, cell_h + 1.0),
868                        Color::linear_rgba(r, g, b, 1.0),
869                    );
870                }
871            }
872        }
873
874        fn semantics(&self, ctx: &mut SemanticsCtx) {
875            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
876            node.name = Some("Animated HDR Grid".to_string());
877            ctx.push(node);
878        }
879    }
880
881    fn mean(values: &[f64]) -> f64 {
882        if values.is_empty() {
883            0.0
884        } else {
885            values.iter().sum::<f64>() / values.len() as f64
886        }
887    }
888
889    fn percentile(sorted: &[f64], p: f64) -> f64 {
890        if sorted.is_empty() {
891            return 0.0;
892        }
893        let rank = ((sorted.len() - 1) as f64 * p).round() as usize;
894        sorted[rank]
895    }
896
897    #[test]
898    #[ignore = "hardware Vulkan benchmark; run explicitly on a machine with a working headless GPU path"]
899    fn steady_state_headless_hdr_grid_benchmark_emits_advancing_frames() -> Result<()> {
900        let options = WindowRenderOptions::new(true, 1.0)
901            .with_color_management_mode(WindowColorManagementMode::PreferHdr)
902            .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
903            .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
904            .with_tone_mapping_mode(WindowToneMappingMode::Automatic);
905
906        let runtime = Application::new()
907            .window(
908                WindowBuilder::new()
909                    .title("Animated HDR Grid")
910                    .root(AnimatedHdrGrid::new()),
911            )
912            .build()
913            .unwrap();
914        let window_id = runtime.window_ids()[0];
915        set_window_render_options(window_id, options);
916        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
917
918        let mut runtime = runtime;
919        let mut platform = HeadlessPlatform::new();
920        let mut totals = Vec::with_capacity(HDR_BENCH_FRAMES);
921        let mut commands = Vec::with_capacity(HDR_BENCH_FRAMES);
922        let mut dirty = Vec::with_capacity(HDR_BENCH_FRAMES);
923        let mut last_frame = 0u64;
924        let mut iterations = 0usize;
925        let max_iterations = 20_000usize;
926
927        while totals.len() < HDR_BENCH_FRAMES && iterations < max_iterations {
928            let _ = platform.pump(&mut runtime)?;
929            if let Some(snapshot) = window_performance_snapshot(window_id)
930                && snapshot.frame_index != last_frame
931            {
932                last_frame = snapshot.frame_index;
933                totals.push(snapshot.total_time_ms);
934                commands.push(snapshot.scene.command_count as f64);
935                dirty.push(snapshot.scene.dirty_coverage as f64);
936            }
937            platform.advance_time(HDR_BENCH_STEP_S);
938            iterations += 1;
939        }
940
941        let mut totals_sorted = totals.clone();
942        totals_sorted.sort_by(|a, b| a.total_cmp(b));
943
944        println!("benchmark=steady-state-headless-hdr-grid");
945        println!("iterations={iterations}");
946        println!("frames={}", totals.len());
947        println!("nominal_fps={:.2}", 1.0 / HDR_BENCH_STEP_S);
948        println!("frame_total_ms_avg={:.3}", mean(&totals));
949        println!("frame_total_ms_p50={:.3}", percentile(&totals_sorted, 0.50));
950        println!("frame_total_ms_p95={:.3}", percentile(&totals_sorted, 0.95));
951        println!(
952            "frame_total_ms_max={:.3}",
953            totals_sorted.last().copied().unwrap_or(0.0)
954        );
955        println!("command_count_avg={:.1}", mean(&commands));
956        println!("dirty_coverage_avg={:.2}", mean(&dirty));
957
958        assert_eq!(
959            totals.len(),
960            HDR_BENCH_FRAMES,
961            "expected {} benchmark frames, got {} after {} iterations",
962            HDR_BENCH_FRAMES,
963            totals.len(),
964            iterations
965        );
966        assert!(mean(&totals) > 0.0, "expected positive frame timings");
967
968        Ok(())
969    }
970}