hydrolysis 0.3.0

GPU-required self-drawn backend for WaterUI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Pump-based headless runtime for tests, snapshots and offscreen rendering.

use super::*;

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
pub(super) struct HeadlessPlatformWindow {
    inner: OffscreenWindow,
    pending_events: VecDeque<InputEvent>,
    redraw_requested: Cell<bool>,
}

#[cfg(not(target_arch = "wasm32"))]
impl HeadlessPlatformWindow {
    #[cfg(test)]
    pub(super) fn new_for_tests(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        Self::on_context(
            OffscreenGpuContext::new_for_tests_blocking(),
            width,
            height,
            format,
        )
    }

    pub(super) fn on_context(
        gpu: OffscreenGpuContext,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
    ) -> Self {
        Self {
            inner: OffscreenWindow::on_context(gpu, width, height, format),
            pending_events: VecDeque::new(),
            redraw_requested: Cell::new(false),
        }
    }

    pub(super) fn set_scale_factor(&mut self, scale_factor: f64) {
        self.inner.set_scale_factor(scale_factor);
    }

    pub(super) fn push_event(&mut self, event: InputEvent) {
        self.pending_events.push_back(event);
    }

    pub(super) fn has_pending_events(&self) -> bool {
        !self.pending_events.is_empty()
    }

    pub(super) fn take_redraw_request(&self) -> bool {
        self.redraw_requested.replace(false)
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl PlatformWindow for HeadlessPlatformWindow {
    fn surface(&mut self) -> &mut dyn crate::platform::SurfaceProvider {
        self.inner.surface()
    }

    fn apply_properties(&mut self, window: &Window) {
        self.inner.apply_properties(window);
    }

    fn set_size_limits(
        &mut self,
        min: Option<waterui_core::layout::Size>,
        max: Option<waterui_core::layout::Size>,
    ) {
        self.inner.set_size_limits(min, max);
    }

    fn applies_size_limits(&self) -> bool {
        self.inner.applies_size_limits()
    }

    fn drain_events(&mut self) -> Vec<InputEvent> {
        self.pending_events.drain(..).collect()
    }

    fn request_redraw(&self) {
        self.redraw_requested.set(true);
    }

    fn scale_factor(&self) -> f64 {
        self.inner.scale_factor()
    }

    fn sync_text_input_state(&mut self, state: Option<crate::platform::TextInputState>) {
        self.inner.sync_text_input_state(state);
    }

    fn set_cursor_style(&mut self, style: waterui::cursor::CursorStyle) {
        self.inner.set_cursor_style(style);
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
impl HeadlessPlatformWindow {
    /// The last (min, max) content-size limits the runner applied, for tests.
    pub(super) fn applied_size_limits(
        &self,
    ) -> Option<(
        Option<waterui_core::layout::Size>,
        Option<waterui_core::layout::Size>,
    )> {
        self.inner.applied_size_limits()
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
pub struct HeadlessPumpResult {
    pub rebuilt: bool,
    pub profile: FrameProfile,
    #[cfg(feature = "accessibility")]
    pub tree_update: Option<AccessibilityTreeUpdate>,
    pub snapshot: Option<HeadlessSnapshot>,
    #[cfg(feature = "accessibility")]
    pub ui_focus: Option<accesskit::NodeId>,
}

#[cfg(not(target_arch = "wasm32"))]
pub struct HeadlessRuntime {
    env: Environment,
    runtime: RuntimeWindow<HeadlessPlatformWindow>,
    pending_window_queue: Rc<RefCell<Vec<Window>>>,
    popup_windows: Vec<RuntimeWindow<HeadlessPlatformWindow>>,
    /// The style the runtime was launched with, kept so popup windows'
    /// renderers measure and encode with the same widget theme.
    theme: Rc<dyn crate::engine::WidgetTheme>,
    /// Every window this runtime opens renders on this one device: the main
    /// window, and each popup it later vends. Requesting a device per window
    /// made a runtime that opens a popup pay for two.
    gpu: OffscreenGpuContext,
    /// The application's font collection, the same one the environment carries.
    /// Popup windows get their own renderer, which is seeded from this so it
    /// shapes with the same faces as the main one — deterministic bundled fonts
    /// under a test host, the app's resource fonts everywhere else.
    fonts: FontCollection,
    local_executor: HeadlessMainThreadExecutor,
    /// Declared last so it drops after the runtime state above: consumes any
    /// still-queued spawned work while this thread's locals are intact, so no
    /// runnable is ever dropped during thread-local teardown.
    _executor_teardown: DrainExecutorOnDrop,
    /// Declared after everything that owns GPU resources, for the same reason.
    /// Fields drop in declaration order and `RuntimeWindow` holds its platform
    /// window before its renderer, so a reclaim run from the surface's own drop
    /// happens while the renderer still holds its pipelines and buffers — which
    /// is why a probe building hundreds of runtimes on one device still ran the
    /// machine out of memory. From here, both are already gone.
    _gpu_reclaim: ReclaimGpuOnDrop,
}

/// Lets the device release a runtime's GPU resources once the runtime is gone.
#[cfg(not(target_arch = "wasm32"))]
struct ReclaimGpuOnDrop(OffscreenGpuContext);

#[cfg(not(target_arch = "wasm32"))]
impl Drop for ReclaimGpuOnDrop {
    fn drop(&mut self) {
        self.0.reclaim();
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl HeadlessRuntime {
    #[must_use]
    pub fn new(
        env: Environment,
        content: AnyViewBuilder<AnyView>,
        width: u32,
        height: u32,
        style: impl crate::Style,
    ) -> Self {
        Self::on_gpu_context(
            pollster::block_on(OffscreenGpuContext::new()),
            env,
            content,
            width,
            height,
            style,
            native_resource_fonts,
        )
    }

    /// Renders at `scale_factor` physical pixels per logical pixel.
    ///
    /// The layout is unchanged — it stays in logical units — so this only makes
    /// the captured image sharper. A preview meant to be viewed on a HiDPI
    /// display should raise this above 1.
    #[must_use]
    pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
        self.runtime.platform.set_scale_factor(scale_factor);
        self
    }

    /// Creates a headless runtime for WaterUI test hosts.
    ///
    /// This constructor allows compute-capable software adapters for CI-only
    /// semantic testing while keeping [`Self::new`] on production adapter
    /// selection, and shapes text with the bundled deterministic fonts so
    /// layout assertions and snapshot goldens hold on every platform's runner.
    #[cfg(any(test, feature = "testing"))]
    #[must_use]
    pub fn new_for_tests(
        env: Environment,
        content: AnyViewBuilder<AnyView>,
        width: u32,
        height: u32,
        style: impl crate::Style,
    ) -> Self {
        Self::on_gpu_context(
            OffscreenGpuContext::new_for_tests_blocking(),
            env,
            content,
            width,
            height,
            style,
            super::fonts::deterministic_test_fonts,
        )
    }

    /// Creates a test runtime on an already-requested [`OffscreenGpuContext`].
    ///
    /// A wgpu device is expensive to request and, on a runner whose only
    /// adapter is a software rasterizer, expensive to hold: a probe that builds
    /// a fresh runtime per sample exhausted the machine requesting one device
    /// per sample. Such a probe requests one context and passes it to every
    /// runtime. The device is all that is shared — the view tree, the renderer
    /// and the retained scene are still built from scratch per runtime, so what
    /// a measurement observes is unchanged.
    #[cfg(any(test, feature = "testing"))]
    #[must_use]
    pub fn new_for_tests_on_context(
        gpu: OffscreenGpuContext,
        env: Environment,
        content: AnyViewBuilder<AnyView>,
        width: u32,
        height: u32,
        style: impl crate::Style,
    ) -> Self {
        Self::on_gpu_context(
            gpu,
            env,
            content,
            width,
            height,
            style,
            super::fonts::deterministic_test_fonts,
        )
    }

    fn on_gpu_context(
        gpu: OffscreenGpuContext,
        env: Environment,
        content: AnyViewBuilder<AnyView>,
        width: u32,
        height: u32,
        style: impl crate::Style,
        build_fonts: fn() -> parley::FontContext,
    ) -> Self {
        let inspector = init_main_thread_executors();
        let inspector_probe = inspector
            .as_ref()
            .map(waterui::inspector::InspectorRuntime::runtime_probe);
        let mut env = env.extending(waterui_graphics::SceneViewMergeToParent);
        waterui::inspector::install(&mut env, inspector);
        let pending_window_queue = Rc::new(RefCell::new(Vec::new()));
        install_native_component_hooks(&mut env);
        install_headless_window_managers(&mut env, Rc::clone(&pending_window_queue));
        env.insert(HydrolysisTextContextMenuMode::Overlay);
        crate::theme::install_default_tokens(&mut env);
        style.install_tokens(&mut env);
        let theme: Rc<dyn crate::engine::WidgetTheme> = Rc::new(style);
        env.insert(waterui_core::ViewRenderer::new(
            crate::view_renderer::HydrolysisViewRenderer::new(Rc::clone(&theme)),
        ));
        // The application's fonts, built once. Every window's renderer is
        // seeded from this collection, and a self-drawn component that typesets
        // text itself reads it out of the environment instead of enumerating
        // the system's fonts for itself.
        let fonts = FontCollection::new(build_fonts());
        fonts.clone().install(&mut env);

        // Headless binaries (preview, tests) have no platform runner to install
        // a tracing subscriber; honor `RUST_LOG` here so they stay debuggable.
        let _ = tracing_subscriber::fmt()
            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
            .with_writer(std::io::stderr)
            .try_init();
        let local_executor = HeadlessMainThreadExecutor::thread_shared();
        let _ = try_init_local_executor(waterui::task::monitored_local_executor_with_probes(
            local_executor.clone(),
            inspector_probe,
        ));

        // The headless window uses the same default background as platform
        // windows (the theme `Background` slot), so offscreen captures match
        // what `water run` renders from the very first frame.
        let content_builder = content.clone();
        let window = Window::new(
            "",
            waterui_core::binding(waterui::window::WindowState::Normal),
            move || content_builder.build(),
        );
        window.frame.set(waterui_core::layout::Rect::new(
            waterui_core::layout::Point::zero(),
            waterui_core::layout::Size::new(width.max(1) as f32, height.max(1) as f32),
        ));

        let mut platform = HeadlessPlatformWindow::on_context(
            gpu.clone(),
            width.max(1),
            height.max(1),
            wgpu::TextureFormat::Rgba8Unorm,
        );
        platform.apply_properties(&window);
        let mut renderer = {
            let surface = platform.surface();
            HydrolysisRenderer::new(surface.adapter(), surface.device(), Rc::clone(&theme))
        };
        super::seed_core(&mut renderer, &fonts);

        Self {
            env,
            runtime: RuntimeWindow::new(
                window,
                platform,
                renderer,
                RenderDiagnosticsConfig {
                    enabled: false,
                    interval: Duration::from_secs(1),
                    slow_frame_threshold_override: None,
                },
            ),
            pending_window_queue,
            popup_windows: Vec::new(),
            theme,
            fonts,
            _executor_teardown: DrainExecutorOnDrop(local_executor.clone()),
            _gpu_reclaim: ReclaimGpuOnDrop(gpu.clone()),
            gpu,
            local_executor,
        }
    }

    fn create_popup_runtime(&self, window: Window) -> RuntimeWindow<HeadlessPlatformWindow> {
        let frame = window.frame.get();
        let width = frame.width().max(1.0) as u32;
        let height = frame.height().max(1.0) as u32;
        let mut platform = HeadlessPlatformWindow::on_context(
            self.gpu.clone(),
            width,
            height,
            wgpu::TextureFormat::Rgba8Unorm,
        );
        platform.apply_properties(&window);
        let mut renderer = {
            let surface = platform.surface();
            HydrolysisRenderer::new(surface.adapter(), surface.device(), Rc::clone(&self.theme))
        };
        super::seed_core(&mut renderer, &self.fonts);
        RuntimeWindow::new(
            window,
            platform,
            renderer,
            RenderDiagnosticsConfig {
                enabled: false,
                interval: Duration::from_secs(1),
                slow_frame_threshold_override: None,
            },
        )
    }

    fn mount_pending_popup_windows(&mut self) {
        let pending = self
            .pending_window_queue
            .borrow_mut()
            .drain(..)
            .collect::<Vec<_>>();
        for window in pending {
            self.popup_windows.push(self.create_popup_runtime(window));
        }
    }

    pub fn push_input_event(&mut self, event: InputEvent) {
        self.runtime.platform.push_event(event);
    }

    pub fn request_redraw(&mut self) {
        self.runtime.platform.request_redraw();
    }

    /// Performs an accessibility action against the merged tree.
    ///
    /// Popup-window node ids are shifted into their own stride in the merged
    /// update (see [`SemanticCore::take_merged_accessibility_tree_update`]),
    /// so a request whose target lands in a popup's range demuxes back to that
    /// window's core — the action targets (a menu item's activation, a picker
    /// row's selection) live there. Returns whether the action changed state,
    /// in which case the next pump re-emits.
    #[cfg(feature = "accessibility")]
    pub fn perform_accessibility_action(&mut self, request: AccessibilityActionRequest) -> bool {
        /// The same id range
        /// [`SemanticCore::take_merged_accessibility_tree_update`] assigns
        /// each popup.
        const WINDOW_ID_STRIDE: u64 = 1 << 32;

        let target = request.target_node.0;
        let (window, request) = if target >= WINDOW_ID_STRIDE {
            let index = target / WINDOW_ID_STRIDE - 1;
            let popup = self
                .popup_windows
                .get_mut(index as usize)
                .unwrap_or_else(|| {
                    panic!(
                        "hydrolysis headless runtime: accessibility action {:?} targets closed popup \
                         node {target}",
                        request.action
                    )
                });
            let mut request = request;
            request.target_node = accesskit::NodeId(target % WINDOW_ID_STRIDE);
            (popup, request)
        } else {
            (&mut self.runtime, request)
        };
        let action_env = self.env.extending(runtime_window_origin(window));
        let changed = window
            .renderer
            .handle_accessibility_action(request, &action_env);
        if changed {
            window.request_refresh();
            window.platform.request_redraw();
        }
        changed
    }

    /// Where the runner would anchor the platform's input-method panel.
    ///
    /// This is the value the runner hands to
    /// [`PlatformWindow::sync_text_input_state`](crate::PlatformWindow::sync_text_input_state)
    /// every frame; a headless host has no panel to place, so tests read it
    /// from here.
    #[cfg(any(test, feature = "testing"))]
    #[must_use]
    pub fn focused_text_input_state(&self) -> Option<crate::platform::TextInputState> {
        self.runtime.renderer.focused_text_input_state()
    }

    #[cfg(feature = "accessibility")]
    pub fn clear_ui_focus(&mut self) -> bool {
        let changed = self.runtime.renderer.clear_ui_focus();
        if changed {
            self.runtime.request_refresh();
            self.runtime.platform.request_redraw();
        }
        changed
    }

    #[cfg(feature = "accessibility")]
    #[must_use]
    pub fn focused_ui_node(&self) -> Option<accesskit::NodeId> {
        self.runtime.renderer.focused_ui_node()
    }

    /// Whether the runtime is quiescent: no queued input, no spawned work
    /// awaiting a drain, no pending popup mounts, no window — the main window
    /// or a popup — with a frame still pending, and no renderer-scheduled
    /// semantic work (patches, rebuilds, animations, gesture deadlines,
    /// gliding scrolls) in this window or any popup.
    ///
    /// Visual-only repaint requests (caret blink, the visible-window present
    /// cadence) do not count: they never move semantic state. Work scheduled
    /// entirely outside the runtime — an app future sleeping on a wall-clock
    /// timer, a worker thread that has not yet woken its task — is invisible
    /// here until it wakes, so callers waiting on such work must keep polling
    /// with their own timeout rather than trusting one settled probe.
    #[must_use]
    pub fn is_settled(&self) -> bool {
        !self.runtime.platform.has_pending_events()
            && !self.local_executor.has_pending()
            && self.pending_window_queue.borrow().is_empty()
            && !self.runtime.mode.is_pending()
            && !self.runtime.renderer.has_scheduled_semantic_work()
            && self.popup_windows.iter().all(|popup| {
                !popup.mode.is_pending()
                    && !popup.platform.has_pending_events()
                    && !popup.renderer.has_scheduled_semantic_work()
            })
    }

    /// Whether a state change has been requested but not yet flushed, so the
    /// semantics this runtime last produced are stale.
    ///
    /// Unlike [`Self::is_settled`] this says nothing about work that keeps
    /// going of its own accord — an animation, a gliding scroll, an armed
    /// gesture deadline. It answers only "is what I last observed still
    /// current?", which is what an observer needs before reading the tree: an
    /// app with a perpetual animation is never settled, but it is very often
    /// up to date.
    #[must_use]
    pub fn has_pending_semantic_update(&self) -> bool {
        self.runtime.mode.is_unapplied_change()
            || self.runtime.renderer.has_pending_semantic_update()
            || self.popup_windows.iter().any(|popup| {
                popup.mode.is_unapplied_change() || popup.renderer.has_pending_semantic_update()
            })
    }

    pub fn pump(&mut self, capture_snapshot: bool) -> HeadlessPumpResult {
        self.pump_at(capture_snapshot, Instant::now())
    }

    pub fn pump_offscreen(&mut self) -> HeadlessPumpResult {
        self.pump_at(false, Instant::now())
    }

    pub fn pump_snapshot(&mut self) -> HeadlessPumpResult {
        self.pump_at(true, Instant::now())
    }

    /// The main window's renderer, for tests that assert on frame internals.
    #[cfg(test)]
    pub(crate) fn renderer(&self) -> &HydrolysisRenderer {
        &self.runtime.renderer
    }

    pub fn pump_at(&mut self, capture_snapshot: bool, at: Instant) -> HeadlessPumpResult {
        let frame_started_at = Instant::now();
        self.runtime.renderer.set_frame_instant(at);
        let executor_before_started_at = Instant::now();
        let drained_before = self.local_executor.drain();
        let executor_before = executor_before_started_at.elapsed();
        let input_started_at = Instant::now();
        let _ = handle_input_events(&mut self.runtime, &self.env);
        let input = input_started_at.elapsed();
        let animation_started_at = Instant::now();
        let _ = advance_runtime(&mut self.runtime, &self.env, at);
        let animation = animation_started_at.elapsed();
        self.mount_pending_popup_windows();
        for popup in &mut self.popup_windows {
            popup.renderer.set_frame_instant(at);
            let _ = handle_input_events(popup, &self.env);
            let _ = advance_runtime(popup, &self.env, at);
        }
        // A popup whose state flipped `Closed` — its menu group dismissed it
        // or a close request arrived — leaves the merged tree. Flag the main
        // window so the update re-emits without it.
        if self
            .popup_windows
            .iter()
            .any(|popup| popup.window.state.get() == waterui::window::WindowState::Closed)
        {
            self.popup_windows
                .retain(|popup| popup.window.state.get() != waterui::window::WindowState::Closed);
            self.runtime.request_refresh();
            self.runtime.platform.request_redraw();
        }
        let should_render = capture_snapshot
            || self.runtime.mode.is_pending()
            || self.runtime.platform.take_redraw_request();
        let mut render_result = should_render.then(|| {
            render_window_with_capture(&mut self.runtime, &self.env, capture_snapshot, &mut || {
                self.local_executor.drain()
            })
        });
        // A popup window pumps its scene the way the main window does: the
        // scene pump is where its retained tree — and with it the window's
        // accessibility update — is built. A popup that only ever rendered on
        // capture frames would composite into snapshots yet never reach the
        // merged tree, so an open popup gets a frame whenever its own work is
        // pending, while readback stays limited to the frames that composite
        // it into a snapshot.
        let mut popups_rebuilt = false;
        for popup in &mut self.popup_windows {
            let composite = capture_snapshot
                && render_result
                    .as_ref()
                    .is_some_and(|result| result.snapshot.is_some());
            let redraw_requested = popup.platform.take_redraw_request();
            if !(composite || popup.mode.is_pending() || redraw_requested) {
                continue;
            }
            let popup_result = render_window_with_capture(popup, &self.env, composite, &mut || {
                self.local_executor.drain()
            });
            popups_rebuilt |= popup_result.rebuilt;
            if let (Some(snapshot), Some(popup_snapshot)) = (
                render_result
                    .as_mut()
                    .and_then(|result| result.snapshot.as_mut()),
                popup_result.snapshot,
            ) {
                composite_popup_snapshot(snapshot, &popup_snapshot, popup.window.frame.get());
            }
        }
        let executor_after_started_at = Instant::now();
        let drained_after = self.local_executor.drain();
        let executor_after = executor_after_started_at.elapsed();

        let mut profile = render_result
            .as_ref()
            .map_or_else(FrameProfile::default, |result| result.profile);
        profile.phases.executor_before = executor_before;
        profile.phases.input = input;
        profile.phases.animation = animation;
        profile.phases.executor_after = executor_after;

        HeadlessPumpResult {
            rebuilt: render_result.as_ref().is_some_and(|result| result.rebuilt)
                || popups_rebuilt
                || drained_before
                || drained_after,
            profile: profile.with_total(frame_started_at.elapsed()),
            #[cfg(feature = "accessibility")]
            tree_update: self.runtime.renderer.take_merged_accessibility_tree_update(
                self.popup_windows
                    .iter_mut()
                    .map(|popup| &mut *popup.renderer),
            ),
            snapshot: render_result.and_then(|result| result.snapshot),
            #[cfg(feature = "accessibility")]
            ui_focus: self.runtime.renderer.focused_ui_node(),
        }
    }
}

fn composite_popup_snapshot(
    target: &mut HeadlessSnapshot,
    source: &HeadlessSnapshot,
    frame: waterui_core::layout::Rect,
) {
    let offset_x = frame.x().round() as i32;
    let offset_y = frame.y().round() as i32;
    for source_y in 0..source.height {
        let target_y = offset_y + i32::try_from(source_y).expect("source y should fit i32");
        if target_y < 0 || target_y >= i32::try_from(target.height).expect("height should fit i32")
        {
            continue;
        }
        for source_x in 0..source.width {
            let target_x = offset_x + i32::try_from(source_x).expect("source x should fit i32");
            if target_x < 0
                || target_x >= i32::try_from(target.width).expect("width should fit i32")
            {
                continue;
            }
            let source_index = ((source_y * source.width + source_x) * 4) as usize;
            let target_index = ((u32::try_from(target_y).expect("target y should be non-negative")
                * target.width
                + u32::try_from(target_x).expect("target x should be non-negative"))
                * 4) as usize;
            composite_pixel(
                &mut target.rgba8[target_index..target_index + 4],
                &source.rgba8[source_index..source_index + 4],
            );
        }
    }
}

fn composite_pixel(target: &mut [u8], source: &[u8]) {
    let source_alpha = f32::from(source[3]) / 255.0;
    if source_alpha <= 0.0 {
        return;
    }
    let target_alpha = f32::from(target[3]) / 255.0;
    let out_alpha = source_alpha + target_alpha * (1.0 - source_alpha);
    for channel in 0..3 {
        let source_channel = f32::from(source[channel]) / 255.0;
        let target_channel = f32::from(target[channel]) / 255.0;
        let out = (source_channel * source_alpha
            + target_channel * target_alpha * (1.0 - source_alpha))
            / out_alpha;
        target[channel] = (out * 255.0).round().clamp(0.0, 255.0) as u8;
    }
    target[3] = (out_alpha * 255.0).round().clamp(0.0, 255.0) as u8;
}