ailloli_ui_winit/
ui_app.rs

1//! Retained multi-window UI state serviced by the winit host adapter.
2//!
3//! Owns one runtime and [`ailloli_ui_render_wgpu::Renderer`] per window, routes
4//! pointer/keyboard/IME events, and runs `layout → paint → render` on each redraw.
5//! [`crate::WinitHost`] is the sole `ApplicationHandler` on the high-level path.
6
7#[cfg(feature = "devtools")]
8use std::collections::BTreeSet;
9use std::collections::{HashMap, HashSet};
10use std::error::Error;
11use std::fmt;
12use std::ops::{Deref, DerefMut};
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
16
17use ailloli_ui_app_storage::{LogicalWindowPosition, LogicalWindowSize, WindowSnapshot};
18use ailloli_ui_core::event::keyboard::{Key, KeyEvent, KeyState, NamedKey};
19use ailloli_ui_core::event::pointer::{
20    MouseButton, PointerEvent, PointerId, PointerSample, PointerSource,
21};
22use ailloli_ui_core::event::{Event, FileEvent, ImeEvent, ImePreedit, Modifiers};
23use ailloli_ui_core::geometry::Constraints;
24use ailloli_ui_core::math::{snap_rect_to_physical, to_logical_f32, PhysicalRectI32, Scale};
25use ailloli_ui_core::Color;
26use ailloli_ui_core::ElementId;
27use ailloli_ui_core::Point;
28use ailloli_ui_core::Rect;
29use ailloli_ui_core::Size;
30use ailloli_ui_render_wgpu::{
31    CaptureParams, LayerPass, Renderer, RendererError, RendererOptions, SurfaceReattachOutcome,
32};
33#[cfg(feature = "devtools")]
34use ailloli_ui_runtime::app::UiWakeError;
35use ailloli_ui_runtime::app::{
36    FrameWorkPlan, PendingPresentationIntents, PresentationCursor, PresentationEvent,
37    PresentationGeneration, PresentationIntent, PresentationLifecycle, PresentationState,
38    PresentationUnavailableReason, Runtime, RuntimeHandle, UiWake, WindowChromeOp,
39};
40use ailloli_ui_runtime::component::{IntoView, View};
41use ailloli_ui_runtime::element::ViewKeyResolveError;
42use ailloli_ui_runtime::element::{ElementKind, ElementTree};
43use ailloli_ui_runtime::input::{
44    absolute_paint_bounds, hit_test_target, EventEnvelope, EventId, EventMeta, EventTimestamp,
45    FocusPolicy, HoverCursorRole, InputRole, InputRouter, ResizeEdge,
46};
47use ailloli_ui_runtime::popup_mount::PopupOverlayMounts;
48use ailloli_ui_text::TextSystem;
49use ailloli_ui_widgets::chrome::{hit_resize_frame, hit_window_drag_region};
50#[cfg(any(test, feature = "test_support"))]
51use winit::dpi::PhysicalSize;
52use winit::dpi::{LogicalPosition, LogicalSize, PhysicalPosition};
53use winit::event::{ElementState, Ime, MouseScrollDelta, TouchPhase, WindowEvent};
54use winit::event_loop::{ActiveEventLoop, ControlFlow};
55use winit::keyboard::{Key as WinitKey, ModifiersState, NamedKey as WinitNamedKey};
56use winit::window::{CursorIcon, Window, WindowId};
57
58use crate::clipboard::NativeClipboard;
59#[cfg(feature = "devtools")]
60use crate::devtools::DevToolsWindowState;
61use crate::event_loop::shutdown_signal;
62use crate::external_url::SystemExternalUrlOpener;
63#[cfg(all(target_os = "linux", feature = "native_overlay"))]
64use crate::native_overlay::wayland::{
65    CreatedWaylandOverlay, WaylandOverlayConfigured, WaylandOverlayEvent, WaylandOverlaySurface,
66};
67use crate::resize::{ResizeController, ResizeRedrawAction, SurfaceRecoveryAction};
68use crate::wgpu_bootstrap::{
69    detach_renderer_surface, reattach_renderer_to_window, renderer_from_window_with_options,
70};
71use crate::window::{create_window, WindowOptions};
72use crate::window_chrome_resize::{resize_edge_to_winit, CLIENT_RESIZE_BORDER_LOGICAL_PX};
73#[cfg(feature = "native_overlay")]
74use crate::{
75    NativeOverlayBackend, NativeOverlayCapabilities, NativeOverlayInputMode, NativeOverlayOptions,
76};
77
78use crate::capture::{
79    crop_captured_frame, strip_png_if_disabled, CaptureError, CaptureHandle, CaptureRequest,
80    CaptureResult, CaptureTarget,
81};
82
83/// Errors surfaced while creating windows, renderers, or during render.
84///
85/// The host retains only the first fatal error until [`UiApp::take_error`].
86/// Platform and renderer source errors are flattened to diagnostic strings.
87///
88/// # Examples
89///
90/// ```
91/// let error = ailloli_ui_winit::UiAppError::Render("device lost".into());
92/// assert!(error.to_string().contains("render failed"));
93/// ```
94#[derive(Debug)]
95pub enum UiAppError {
96    /// Native window creation failed with platform diagnostic text.
97    WindowCreate(String),
98    /// Renderer/device/surface initialization failed.
99    RendererCreate(String),
100    /// A fatal frame render or capture operation failed.
101    Render(String),
102}
103
104/// Prefixes each category with the winit adapter identity.
105impl fmt::Display for UiAppError {
106    /// Formats the originating window, renderer, runtime, capture, or storage failure.
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::WindowCreate(err) => write!(f, "ailloli_ui_winit: create window failed: {err}"),
110            Self::RendererCreate(err) => {
111                write!(f, "ailloli_ui_winit: create renderer failed: {err}")
112            }
113            Self::Render(err) => write!(f, "ailloli_ui_winit: render failed: {err}"),
114        }
115    }
116}
117
118/// Marks fatal UI host failures as standard errors without a chained source.
119impl Error for UiAppError {}
120
121/// Presentation failure injected on the event-loop thread by native tests.
122///
123/// Faults are queued by logical window and run at the next safe host boundary;
124/// they never execute synchronously in the caller.
125///
126/// # Examples
127///
128/// ```
129/// use ailloli_ui_winit::PresentationTestFault;
130/// assert_ne!(PresentationTestFault::Lost, PresentationTestFault::Outdated);
131/// ```
132#[cfg(feature = "test_support")]
133#[non_exhaustive]
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum PresentationTestFault {
136    /// Detach and immediately reattach the native presentation.
137    DetachReattach,
138    /// Exercise the recovery path used after `SurfaceError::Lost`.
139    Lost,
140    /// Exercise the recovery path used after `SurfaceError::Outdated`.
141    Outdated,
142    /// Exercise a dormant zero extent followed by a non-zero surface apply.
143    ///
144    /// This fault is injected on the event-loop thread without asking the
145    /// compositor to create a physically zero-sized native window. It covers
146    /// the same provider-neutral resize/lifecycle path as a winit `Resized`
147    /// callback and waits for the restored extent to be configured.
148    ZeroExtentRoundTrip,
149}
150
151/// Observable lifecycle state for deterministic native tests.
152///
153/// All counters are cumulative and saturating within the lifetime of the
154/// retained logical window. `attached` distinguishes live native presentation
155/// state from suspended retained state.
156///
157/// # Examples
158///
159/// ```
160/// use ailloli_ui_winit::PresentationTestState;
161/// fn inspect(state: &PresentationTestState) {
162///     let generation: u64 = state.generation.get();
163///     let _ = (state.attached, generation, state.state);
164/// }
165/// ```
166#[cfg(feature = "test_support")]
167#[non_exhaustive]
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct PresentationTestState {
170    /// Stable logical window identity.
171    pub logical_window_id: ailloli_ui_core::LogicalWindowId,
172    /// Provider-neutral presentation lifecycle state.
173    pub state: PresentationState,
174    /// Current attachment generation; stale envelopes use older values.
175    pub generation: PresentationGeneration,
176    /// Whether a native presentation currently owns this retained state.
177    pub attached: bool,
178    /// Number of completed native detach operations.
179    pub detach_count: u64,
180    /// Number of acquisition-recovery sequences requested.
181    pub recovery_count: u64,
182    /// Reattachments that retained the existing GPU context and caches.
183    pub gpu_context_reuse_count: u64,
184    /// Reattachments that required a new adapter/device/pipeline context.
185    pub gpu_context_rebuild_count: u64,
186    /// Number of injected or observed lost-surface paths.
187    pub lost_count: u64,
188    /// Number of injected or observed outdated-surface paths.
189    pub outdated_count: u64,
190    /// Number of injected zero-extent round trips.
191    pub zero_extent_count: u64,
192    /// Number of generation-mismatched injected envelopes rejected.
193    pub rejected_stale_event_count: u64,
194    /// Number of queued faults not yet serviced for this logical window.
195    pub pending_fault_count: usize,
196    /// Successful native frames rendered for this retained presentation.
197    ///
198    /// Unlike `rendered_once`, this counter is not reset by a test fault. It
199    /// lets native capture tests wait for a geometry-publishing warmup frame
200    /// and a subsequent layout frame before issuing a one-shot capture.
201    pub rendered_frame_count: u64,
202}
203
204#[cfg(feature = "test_support")]
205#[derive(Debug, Default, Clone, Copy)]
206/// Saturating internal counters copied into [`PresentationTestState`].
207struct PresentationTestCounters {
208    /// Completed native detach operations.
209    detach_count: u64,
210    /// Requested recovery sequences.
211    recovery_count: u64,
212    /// Compatible-surface reattachments.
213    gpu_context_reuse_count: u64,
214    /// Full GPU context rebuilds.
215    gpu_context_rebuild_count: u64,
216    /// Lost-surface paths.
217    lost_count: u64,
218    /// Outdated-surface paths.
219    outdated_count: u64,
220    /// Zero-extent round trips.
221    zero_extent_count: u64,
222    /// Rejected stale-generation events.
223    rejected_stale_event_count: u64,
224}
225
226/// Returns the concrete winit backend name used in diagnostics/bench metadata.
227fn observed_winit_backend(event_loop: &ActiveEventLoop) -> &'static str {
228    #[cfg(target_os = "linux")]
229    {
230        use winit::platform::wayland::ActiveEventLoopExtWayland;
231        use winit::platform::x11::ActiveEventLoopExtX11;
232
233        if event_loop.is_wayland() {
234            "wayland"
235        } else if event_loop.is_x11() {
236            "x11"
237        } else {
238            "linux-native"
239        }
240    }
241
242    #[cfg(not(target_os = "linux"))]
243    {
244        let _ = event_loop;
245        std::env::consts::OS
246    }
247}
248
249#[cfg(feature = "native_overlay")]
250/// Establishes and verifies X11 overlay invariants after winit window creation.
251///
252/// Exact physical placement and size are derived from the target logical rect
253/// and current scale. Wayland is rejected because it requires layer-shell.
254///
255/// # Errors
256///
257/// Returns a string error for invalid target geometry, a non-X11 backend,
258/// cursor-hit-test configuration failure, coordinate/size overflow, or a native
259/// position/extent mismatch after applying the overlay request.
260fn configure_x11_overlay(
261    event_loop: &ActiveEventLoop,
262    window: &Window,
263    options: Option<&NativeOverlayOptions>,
264) -> Result<Option<NativeOverlayCapabilities>, String> {
265    let Some(options) = options else {
266        return Ok(None);
267    };
268    options
269        .target
270        .logical_rect
271        .validate()
272        .map_err(|err| err.to_string())?;
273
274    #[cfg(target_os = "linux")]
275    {
276        use winit::platform::x11::ActiveEventLoopExtX11;
277
278        if !event_loop.is_x11() {
279            return Err("Wayland native overlays require the layer-shell surface path".to_string());
280        }
281        if matches!(options.input_mode, NativeOverlayInputMode::PassThrough) {
282            window
283                .set_cursor_hittest(false)
284                .map_err(|err| format!("could not disable X11 overlay hit-testing: {err}"))?;
285        }
286        window.set_ime_allowed(false);
287        let scale_factor = window.scale_factor();
288        let expected_position = winit::dpi::LogicalPosition::new(
289            options.target.logical_rect.x,
290            options.target.logical_rect.y,
291        )
292        .to_physical::<i32>(scale_factor);
293        let actual_position = window
294            .outer_position()
295            .map_err(|err| format!("could not verify X11 overlay placement: {err}"))?;
296        if actual_position != expected_position {
297            return Err(format!(
298                "X11 overlay placement mismatch: expected {expected_position:?}, got {actual_position:?}"
299            ));
300        }
301        let expected_size = winit::dpi::LogicalSize::new(
302            options.target.logical_rect.width,
303            options.target.logical_rect.height,
304        )
305        .to_physical::<u32>(scale_factor);
306        if window.inner_size() != expected_size {
307            return Err(format!(
308                "X11 overlay size mismatch: expected {expected_size:?}, got {:?}",
309                window.inner_size()
310            ));
311        }
312        Ok(Some(NativeOverlayCapabilities::established(
313            NativeOverlayBackend::X11,
314            options.input_mode,
315        )))
316    }
317
318    #[cfg(not(target_os = "linux"))]
319    {
320        let _ = (event_loop, window);
321        Err("native overlays are unsupported on this platform".to_string())
322    }
323}
324
325/// Declarative window registration awaiting conversion to retained state on resume.
326struct PendingWindow<A> {
327    /// Native and logical window configuration.
328    options: WindowOptions,
329    /// Unreconciled retained root view.
330    root: View<A>,
331    /// Exact per-window render clear color.
332    clear: Color,
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336/// Native file-hover batch kind; only consecutive same-window/same-kind events merge.
337enum PendingFileBatchKind {
338    /// One or more files entered the window.
339    Entered,
340    /// Hover was cancelled; carries no files.
341    Left,
342    /// One or more files were dropped.
343    Dropped,
344}
345
346/// Consecutive native file callbacks coalesced until the next host boundary.
347struct PendingFileBatch {
348    /// Ephemeral native destination window.
349    window_id: WindowId,
350    /// Enter, leave, or drop category.
351    kind: PendingFileBatchKind,
352    /// Files in native callback order; empty for leave.
353    files: Vec<ailloli_ui_core::UploadFile>,
354}
355
356/// Tracks the first contact in one active touch sequence.
357///
358/// winit 0.30 exposes stable touch IDs but no primary flag. The adapter can
359/// still classify the first `Started` contact deterministically. If that
360/// contact ends while secondary contacts remain, none of those existing
361/// contacts is promoted; the next sequence begins once all contacts end.
362#[derive(Debug, Default)]
363struct TouchPrimaryTracker {
364    /// Active native touch ids.
365    active_ids: HashSet<u64>,
366    /// First id in the current sequence, cleared when it ends.
367    primary_id: Option<u64>,
368}
369
370/// Deterministic primary-contact classification and lifecycle reset.
371impl TouchPrimaryTracker {
372    /// Updates the active set and returns whether this event belongs to the first contact.
373    ///
374    /// Duplicate `Started` ids do not begin a new sequence. Ending the primary
375    /// never promotes an already-active secondary contact.
376    fn classify(&mut self, id: u64, phase: TouchPhase) -> bool {
377        match phase {
378            TouchPhase::Started => {
379                let begins_sequence = self.active_ids.is_empty();
380                let inserted = self.active_ids.insert(id);
381                if begins_sequence && inserted {
382                    self.primary_id = Some(id);
383                }
384                self.primary_id == Some(id)
385            }
386            TouchPhase::Moved => self.primary_id == Some(id),
387            TouchPhase::Ended | TouchPhase::Cancelled => {
388                let is_primary = self.primary_id == Some(id);
389                self.active_ids.remove(&id);
390                if is_primary || self.active_ids.is_empty() {
391                    self.primary_id = None;
392                }
393                is_primary
394            }
395        }
396    }
397
398    /// Forgets all contacts when a native presentation detaches.
399    fn clear(&mut self) {
400        self.active_ids.clear();
401        self.primary_id = None;
402    }
403}
404
405/// Provider-neutral UI state that survives destruction of a native presentation.
406///
407/// No winit window, WGPU surface, resize controller, or other native attachment is
408/// stored here. A renderer may retain its detached instance/adapter/device/queue and
409/// caches. Keeping this value alive across `suspended` preserves both that reusable
410/// GPU context and the element tree, signals, focus/input router, text system, and
411/// pending presentation intents.
412struct RetainedWindowState<A> {
413    /// Declarative/native configuration updated by replayed presentation intents.
414    options: WindowOptions,
415    /// Stable logical id, possibly empty when the caller omitted one.
416    logical_window_id: String,
417    /// Provider-neutral attachment state machine.
418    lifecycle: PresentationLifecycle,
419    /// Generation copied into every accepted event envelope.
420    presentation_generation: PresentationGeneration,
421    /// Coalescing intents accumulated while no native presentation exists.
422    presentation_intents: PendingPresentationIntents,
423    /// Detached GPU context/caches available for surface reattachment.
424    renderer: Option<Renderer>,
425    /// Whether client-side edge-resize hit testing is active.
426    client_edge_resize: bool,
427    /// Whether client title-row drag gestures are permitted.
428    client_titlebar_drag: bool,
429    /// Optional exact view key delimiting the title row.
430    client_titlebar_key: Option<String>,
431    /// Renderer clear color.
432    clear: Color,
433    /// Per-window shaping/font state retained across presentation loss.
434    text_system: TextSystem,
435    /// Retained element tree and per-window runtime.
436    runtime: Runtime<A>,
437    /// Current device-pixel ratio, normalized by [`Scale`].
438    scale: Scale,
439    /// Latest logical mouse position; touch does not overwrite it.
440    cursor_pos: Option<Point>,
441    /// Active-touch primary classification.
442    touch_primary: TouchPrimaryTracker,
443    /// Last provider-neutral cursor intent.
444    current_cursor: PresentationCursor,
445    /// Latest keyboard modifier state.
446    modifiers: Modifiers,
447    /// Focus, hover, capture, click, and text-input router.
448    input: InputRouter,
449    /// Mounted popup runtimes and focus ownership.
450    popup_mounts: PopupOverlayMounts<A>,
451    /// Whether native IME is currently allowed for the focus target.
452    ime_allowed: bool,
453    /// Last integer physical IME cursor area sent to winit.
454    last_ime_cursor_area: Option<PhysicalRectI32>,
455    /// Earliest text-caret/animation wake deadline.
456    next_text_blink: Option<Instant>,
457    /// Earliest retry after a transient render timeout.
458    render_retry_at: Option<Instant>,
459    /// Consecutive timeout count used for bounded exponential backoff.
460    render_timeout_streak: u32,
461    /// Optional one-second input benchmark aggregation.
462    input_bench: InputBenchCounters,
463    /// Whether the first successful frame has already been presented.
464    rendered_once: bool,
465    #[cfg(feature = "test_support")]
466    /// Cumulative successful native frame count, saturating.
467    rendered_frame_count: u64,
468    /// Whether the native window starts hidden and must reveal after first frame.
469    reveal_after_first_frame: bool,
470    #[cfg(feature = "devtools")]
471    /// Window-local developer-tools overlay and remote state.
472    devtools: DevToolsWindowState,
473}
474
475/// Live winit presentation attached to retained logical state.
476///
477/// Field order is safety-relevant: the renderer/surface drops before the
478/// `Arc<Window>` that owns its raw handles.
479struct WindowState<A> {
480    // `renderer` holds a strong ref to the window via the wgpu `Surface`; declare it
481    // before `window` so drop order releases the surface first, then the window.
482    /// Attached renderer whose surface strongly owns the window.
483    renderer: Renderer,
484    /// Shared native window owner.
485    window: Arc<Window>,
486    /// Coalesced physical resize and recovery state.
487    resize: ResizeController,
488    #[cfg(feature = "native_overlay")]
489    /// Verified X11 overlay invariants, absent for normal windows.
490    native_overlay_capabilities: Option<NativeOverlayCapabilities>,
491    /// Provider-neutral state surviving this attachment.
492    retained: RetainedWindowState<A>,
493}
494
495/// Makes retained state fields available to live-window helpers.
496impl<A> Deref for WindowState<A> {
497    /// Retained state target.
498    type Target = RetainedWindowState<A>;
499
500    /// Borrows provider-neutral retained state.
501    fn deref(&self) -> &Self::Target {
502        &self.retained
503    }
504}
505
506/// Makes retained state fields mutably available to live-window helpers.
507impl<A> DerefMut for WindowState<A> {
508    /// Mutably borrows provider-neutral retained state.
509    fn deref_mut(&mut self) -> &mut Self::Target {
510        &mut self.retained
511    }
512}
513
514/// Platform-specific successful attachment waiting to enter the live collections.
515enum AttachedWindow<A> {
516    /// Ordinary winit/X11 presentation keyed by ephemeral native id.
517    Native(WindowId, WindowState<A>),
518    #[cfg(all(target_os = "linux", feature = "native_overlay"))]
519    /// Direct Wayland layer-shell presentation without a winit window.
520    WaylandOverlay(WaylandOverlayState<A>),
521}
522
523/// Allocation-boxed retained state paired with a failed attachment error.
524///
525/// Boxing keeps the result's error variant small while returning ownership for retry.
526type AttachmentError<A> = Box<(RetainedWindowState<A>, UiAppError)>;
527
528#[cfg(all(target_os = "linux", feature = "native_overlay"))]
529/// Live direct Wayland layer-shell presentation attached to retained state.
530///
531/// Field order drops the renderer surface before the raw-handle owner.
532struct WaylandOverlayState<A> {
533    // Drop the WGPU surface before the layer-shell surface.
534    /// Attached renderer and Wayland surface.
535    renderer: Renderer,
536    /// Raw-window-handle owner retained until after renderer drop/detach.
537    _surface: Arc<WaylandOverlaySurface>,
538    /// Unbounded configure/closed event receiver.
539    events: std::sync::mpsc::Receiver<WaylandOverlayEvent>,
540    /// Most recent positive logical configure and integer scale.
541    configured: WaylandOverlayConfigured,
542    /// Verified layer-shell invariants.
543    capabilities: NativeOverlayCapabilities,
544    /// Interior-mutable redraw latch set from shared host APIs.
545    needs_redraw: std::cell::Cell<bool>,
546    /// Provider-neutral state surviving overlay recreation.
547    retained: RetainedWindowState<A>,
548}
549
550#[cfg(all(target_os = "linux", feature = "native_overlay"))]
551/// Makes retained state fields available to live Wayland-overlay helpers.
552impl<A> Deref for WaylandOverlayState<A> {
553    /// Retained state target.
554    type Target = RetainedWindowState<A>;
555
556    /// Borrows provider-neutral retained state.
557    fn deref(&self) -> &Self::Target {
558        &self.retained
559    }
560}
561
562#[cfg(all(target_os = "linux", feature = "native_overlay"))]
563/// Makes retained state fields mutably available to live Wayland-overlay helpers.
564impl<A> DerefMut for WaylandOverlayState<A> {
565    /// Mutably borrows provider-neutral retained state.
566    fn deref_mut(&mut self) -> &mut Self::Target {
567        &mut self.retained
568    }
569}
570
571/// Initial delay for transient surface-timeout retries.
572const RENDER_TIMEOUT_RETRY_BASE_DELAY: Duration = Duration::from_millis(16);
573/// Inclusive cap for exponential surface-timeout retry delay.
574const RENDER_TIMEOUT_RETRY_MAX_DELAY: Duration = Duration::from_millis(250);
575
576#[derive(Clone, Copy, Debug, PartialEq, Eq)]
577/// Host response selected for a renderer error category.
578enum RenderErrorAction {
579    /// Retain presentation and retry the frame after the supplied delay.
580    RetryFrame(Duration),
581    /// Force configure, then escalate to full attachment recreation if repeated.
582    ReconfigureSurface,
583    /// Store a fatal [`UiAppError`] and exit the native loop.
584    Fatal,
585}
586
587#[derive(Clone, Copy, Debug, PartialEq, Eq)]
588/// Diagnostic reason recorded when a native presentation must be recreated.
589enum PresentationRecreationCause {
590    /// Surface acquisition reported lost.
591    Lost,
592    /// Surface acquisition reported outdated.
593    Outdated,
594    /// Forced reconfiguration failed or repeated.
595    ReconfigureFailed,
596}
597
598#[derive(Debug)]
599/// One-second optional input/IME counters and accumulated microsecond durations.
600///
601/// Collection is completely bypassed unless benchmark mode is enabled. Counts
602/// use ordinary `u64` increments; duration sums saturate at `u128::MAX`.
603struct InputBenchCounters {
604    /// Raw winit empty-preedit callback count.
605    ime_preedit_empty: u64,
606    /// Raw winit non-empty-preedit callback count.
607    ime_preedit_nonempty: u64,
608    /// Raw winit commit callback count.
609    ime_commit: u64,
610    /// Raw winit disabled/end callback count.
611    ime_end: u64,
612    /// Routed provider-neutral keyboard event count.
613    event_keyboard: u64,
614    /// Routed empty-preedit event count.
615    event_ime_preedit_empty: u64,
616    /// Routed non-empty-preedit event count.
617    event_ime_preedit_nonempty: u64,
618    /// Routed IME commit event count.
619    event_ime_commit: u64,
620    /// Routed IME end event count.
621    event_ime_end: u64,
622    /// Native IME cursor rectangles actually changed/set.
623    ime_cursor_area_set: u64,
624    /// Native IME cursor updates skipped because quantized state was unchanged.
625    ime_cursor_area_skipped: u64,
626    /// Routed events explicitly requesting redraw.
627    route_redraw: u64,
628    /// Routed events followed by dirty retained elements.
629    dirty_redraw: u64,
630    /// Sum of input routing time in whole microseconds.
631    route_event_us: u128,
632    /// Sum of IME cursor quantize/native-update time in whole microseconds.
633    ime_cursor_rect_us: u128,
634    /// Sum of layout-before-input time in whole microseconds.
635    layout_before_event_us: u128,
636    /// Timestamp of construction or last reset.
637    last_flush: Instant,
638}
639
640/// Gated recording and one-second/reset-boundary metric emission.
641impl InputBenchCounters {
642    /// Creates zeroed counters with `last_flush = now`.
643    fn new(now: Instant) -> Self {
644        Self {
645            ime_preedit_empty: 0,
646            ime_preedit_nonempty: 0,
647            ime_commit: 0,
648            ime_end: 0,
649            event_keyboard: 0,
650            event_ime_preedit_empty: 0,
651            event_ime_preedit_nonempty: 0,
652            event_ime_commit: 0,
653            event_ime_end: 0,
654            ime_cursor_area_set: 0,
655            ime_cursor_area_skipped: 0,
656            route_redraw: 0,
657            dirty_redraw: 0,
658            route_event_us: 0,
659            ime_cursor_rect_us: 0,
660            layout_before_event_us: 0,
661            last_flush: now,
662        }
663    }
664
665    /// Matches [`ailloli_ui_bench::init_from_env`]: no counters or flush unless bench mode is on.
666    fn metrics_enabled() -> bool {
667        ailloli_ui_bench::bench_enabled()
668    }
669
670    /// Classifies a raw winit IME callback into raw and routed-event buckets.
671    ///
672    /// `Enabled` has no counter; empty preedit remains distinct from end/disabled.
673    fn record_ime(&mut self, ime: &Ime) {
674        if !Self::metrics_enabled() {
675            return;
676        }
677        match ime {
678            Ime::Preedit(text, _) if text.is_empty() => {
679                self.ime_preedit_empty += 1;
680                self.event_ime_preedit_empty += 1;
681            }
682            Ime::Preedit(_, _) => {
683                self.ime_preedit_nonempty += 1;
684                self.event_ime_preedit_nonempty += 1;
685            }
686            Ime::Commit(_) => {
687                self.ime_commit += 1;
688                self.event_ime_commit += 1;
689            }
690            Ime::Disabled => {
691                self.ime_end += 1;
692                self.event_ime_end += 1;
693            }
694            Ime::Enabled => {}
695        }
696    }
697
698    /// Increments the routed keyboard-event count when metrics are enabled.
699    fn record_keyboard(&mut self) {
700        if Self::metrics_enabled() {
701            self.event_keyboard += 1;
702        }
703    }
704
705    /// Saturating-adds one whole-microsecond route duration sample.
706    fn record_route_event_us(&mut self, value: u128) {
707        if Self::metrics_enabled() {
708            self.route_event_us = self.route_event_us.saturating_add(value);
709        }
710    }
711
712    /// Saturating-adds one whole-microsecond IME cursor update sample.
713    fn record_ime_cursor_rect_us(&mut self, value: u128) {
714        if Self::metrics_enabled() {
715            self.ime_cursor_rect_us = self.ime_cursor_rect_us.saturating_add(value);
716        }
717    }
718
719    /// Saturating-adds one whole-microsecond pre-input layout sample.
720    fn record_layout_before_event_us(&mut self, value: u128) {
721        if Self::metrics_enabled() {
722            self.layout_before_event_us = self.layout_before_event_us.saturating_add(value);
723        }
724    }
725
726    /// Increments the route-requested-redraw count when enabled.
727    fn record_route_redraw(&mut self) {
728        if Self::metrics_enabled() {
729            self.route_redraw += 1;
730        }
731    }
732
733    /// Increments the dirty-after-routing redraw count when enabled.
734    fn record_dirty_redraw(&mut self) {
735        if Self::metrics_enabled() {
736            self.dirty_redraw += 1;
737        }
738    }
739
740    /// Emits and resets counters once at least one second elapsed.
741    ///
742    /// A `now` earlier than `last_flush` behaves as zero elapsed.
743    fn flush_if_due(&mut self, now: Instant) {
744        if !Self::metrics_enabled() {
745            return;
746        }
747        if now.duration_since(self.last_flush) < Duration::from_secs(1) {
748            return;
749        }
750        self.flush_values(now);
751    }
752
753    /// Flushes pending input counters at a lifecycle boundary without waiting
754    /// for the periodic one-second interval.
755    fn flush(&mut self) {
756        if Self::metrics_enabled() {
757            self.flush_values(Instant::now());
758        }
759    }
760
761    /// Emits each non-zero value and resets every counter and the flush origin.
762    ///
763    /// Conversion to `f64` may lose integer precision above `2^53`, which is
764    /// unreachable for ordinary one-second event counts but possible in theory.
765    fn flush_values(&mut self, now: Instant) {
766        Self::metric_count("input.ime_preedit_empty", self.ime_preedit_empty);
767        Self::metric_count("input.ime_preedit_nonempty", self.ime_preedit_nonempty);
768        Self::metric_count("input.ime_commit", self.ime_commit);
769        Self::metric_count("input.ime_end", self.ime_end);
770        Self::metric_count("input.event_keyboard", self.event_keyboard);
771        Self::metric_count(
772            "input.event_ime_preedit_empty",
773            self.event_ime_preedit_empty,
774        );
775        Self::metric_count(
776            "input.event_ime_preedit_nonempty",
777            self.event_ime_preedit_nonempty,
778        );
779        Self::metric_count("input.event_ime_commit", self.event_ime_commit);
780        Self::metric_count("input.event_ime_end", self.event_ime_end);
781        Self::metric_count("input.ime_cursor_area_set", self.ime_cursor_area_set);
782        Self::metric_count(
783            "input.ime_cursor_area_skipped",
784            self.ime_cursor_area_skipped,
785        );
786        Self::metric_count("input.route_redraw", self.route_redraw);
787        Self::metric_count("input.dirty_redraw", self.dirty_redraw);
788        Self::metric_duration("input.route_event_us", self.route_event_us);
789        Self::metric_duration("input.ime_cursor_rect_us", self.ime_cursor_rect_us);
790        Self::metric_duration("input.layout_before_event_us", self.layout_before_event_us);
791        self.ime_preedit_empty = 0;
792        self.ime_preedit_nonempty = 0;
793        self.ime_commit = 0;
794        self.ime_end = 0;
795        self.event_keyboard = 0;
796        self.event_ime_preedit_empty = 0;
797        self.event_ime_preedit_nonempty = 0;
798        self.event_ime_commit = 0;
799        self.event_ime_end = 0;
800        self.ime_cursor_area_set = 0;
801        self.ime_cursor_area_skipped = 0;
802        self.route_redraw = 0;
803        self.dirty_redraw = 0;
804        self.route_event_us = 0;
805        self.ime_cursor_rect_us = 0;
806        self.layout_before_event_us = 0;
807        self.last_flush = now;
808    }
809
810    /// Emits a non-zero integer counter as one benchmark metric.
811    fn metric_count(name: &'static str, value: u64) {
812        if value > 0 {
813            ailloli_ui_bench::metric(name, value as f64);
814        }
815    }
816
817    /// Emits a non-zero whole-microsecond duration sum as one benchmark metric.
818    fn metric_duration(name: &'static str, value: u128) {
819        if value > 0 {
820            ailloli_ui_bench::metric(name, value as f64);
821        }
822    }
823}
824
825/// Multi-window winit application (one runtime + one renderer per window).
826///
827/// Retained rendering flow:
828/// - reconcile runs once at startup per window,
829/// - each redraw: `layout → paint → ailloli_ui_render_wgpu`.
830///
831/// The application starts with no windows and uses [`ControlFlow::Wait`]. Each
832/// registered logical window retains its runtime, input, popup, text, and
833/// presentation intents across native suspend/resume cycles.
834///
835/// # Examples
836///
837/// ```
838/// let app = ailloli_ui_winit::UiApp::<()>::new();
839/// assert!(app.window_snapshots().is_empty());
840/// assert!(app.error().is_none());
841/// ```
842pub struct UiApp<A> {
843    /// Shared application action, clipboard, URL, scheduling, and chrome handle.
844    runtime: RuntimeHandle<A>,
845    /// Declared windows awaiting the first creation-authorized resume.
846    pending: Vec<PendingWindow<A>>,
847    /// Native winit presentations keyed by ephemeral platform window id.
848    windows: HashMap<WindowId, WindowState<A>>,
849    /// Logical window state detached across host suspension/recovery.
850    retained_windows: Vec<RetainedWindowState<A>>,
851    /// Consecutive native file-hover/drop callbacks awaiting batch flush.
852    pending_file_batches: Vec<PendingFileBatch>,
853    #[cfg(all(target_os = "linux", feature = "native_overlay"))]
854    /// Direct layer-shell presentations that do not own a winit window.
855    wayland_overlays: Vec<WaylandOverlayState<A>>,
856    /// Last known persisted snapshot per logical window id.
857    window_snapshots: HashMap<String, WindowSnapshot>,
858    /// Monotonic origin for provider-neutral event timestamps.
859    event_origin: Instant,
860    /// Saturating event-id counter; initialized to one.
861    next_event_id: u64,
862    /// Default native loop policy applied during construction.
863    control_flow: ControlFlow,
864    /// First fatal host error retained until taken.
865    error: Option<UiAppError>,
866    /// Optional declarative capture queue.
867    capture: Option<crate::capture::CaptureHandle>,
868    /// Shared late-bound wake for non-winit presentation sources.
869    host_wake: Option<Arc<dyn UiWake>>,
870    #[cfg(feature = "test_support")]
871    /// FIFO deterministic faults keyed by logical window.
872    presentation_test_faults: Vec<(ailloli_ui_core::LogicalWindowId, PresentationTestFault)>,
873    #[cfg(feature = "test_support")]
874    /// Deduplicated native presentation closes applied at a safe loop boundary.
875    presentation_test_closes: Vec<ailloli_ui_core::LogicalWindowId>,
876    #[cfg(feature = "test_support")]
877    /// Cumulative counters retained after detach/recreation.
878    presentation_test_counters: HashMap<ailloli_ui_core::LogicalWindowId, PresentationTestCounters>,
879    #[cfg(feature = "devtools")]
880    /// Explicit remote address copied into each newly retained window.
881    devtools_remote_addr: Option<std::net::SocketAddr>,
882    #[cfg(feature = "devtools")]
883    /// First devtools wake error across all presentations.
884    devtools_wake_error: Option<UiWakeError>,
885}
886
887/// Creates an empty wait-mode application with native clipboard and URL providers.
888impl<A: 'static> Default for UiApp<A> {
889    /// Delegates to [`UiApp::new`].
890    fn default() -> Self {
891        Self::new()
892    }
893}
894
895/// Declarative configuration, host wake wiring, diagnostics, and retained state access.
896impl<A: 'static> UiApp<A> {
897    /// Creates an empty application using [`ControlFlow::Wait`].
898    ///
899    /// Installs lazy native clipboard and validated system URL providers. No
900    /// native event loop, window, renderer, or remote server is created yet.
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// let app = ailloli_ui_winit::UiApp::<u32>::new();
906    /// assert!(app.error().is_none());
907    /// ```
908    pub fn new() -> Self {
909        Self::with_control_flow(ControlFlow::Wait)
910    }
911
912    /// Creates an empty application with an explicit winit control-flow policy.
913    ///
914    /// The policy is copied into the event loop during presentation creation;
915    /// host wait service may temporarily choose a deadline needed by resize,
916    /// text, render-retry, or scheduled-repaint work.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// use winit::event_loop::ControlFlow;
922    /// let app = ailloli_ui_winit::UiApp::<()>::with_control_flow(ControlFlow::Poll);
923    /// assert!(app.window_snapshots().is_empty());
924    /// ```
925    pub fn with_control_flow(control_flow: ControlFlow) -> Self {
926        let runtime = RuntimeHandle::new();
927        runtime.set_clipboard_provider(Rc::new(NativeClipboard::new()));
928        runtime.set_external_url_opener(Rc::new(SystemExternalUrlOpener::new()));
929        Self {
930            runtime,
931            pending: Vec::new(),
932            windows: HashMap::new(),
933            retained_windows: Vec::new(),
934            pending_file_batches: Vec::new(),
935            #[cfg(all(target_os = "linux", feature = "native_overlay"))]
936            wayland_overlays: Vec::new(),
937            window_snapshots: HashMap::new(),
938            event_origin: Instant::now(),
939            next_event_id: 1,
940            control_flow,
941            error: None,
942            capture: None,
943            host_wake: None,
944            #[cfg(feature = "test_support")]
945            presentation_test_faults: Vec::new(),
946            #[cfg(feature = "test_support")]
947            presentation_test_closes: Vec::new(),
948            #[cfg(feature = "test_support")]
949            presentation_test_counters: HashMap::new(),
950            #[cfg(feature = "devtools")]
951            devtools_remote_addr: None,
952            #[cfg(feature = "devtools")]
953            devtools_wake_error: None,
954        }
955    }
956
957    /// Attaches a capture handle processed during redraw.
958    ///
959    /// Repeated builder calls replace the previous handle. Clones held by the
960    /// caller continue to share the newly attached queue state.
961    ///
962    /// # Examples
963    ///
964    /// ```
965    /// use ailloli_ui_winit::{CaptureHandle, UiApp};
966    /// let captures = CaptureHandle::new();
967    /// let app = UiApp::<()>::new().capture_handle(captures.clone());
968    /// captures.request_window("main");
969    /// let _ = app;
970    /// ```
971    pub fn capture_handle(mut self, handle: crate::capture::CaptureHandle) -> Self {
972        self.capture = Some(handle);
973        self
974    }
975
976    /// Capture queue attached to this host, when configured.
977    ///
978    /// The returned clone shares request and result state.
979    ///
980    /// # Examples
981    ///
982    /// ```
983    /// // Public configuration uses `capture_handle`; the host clones it internally.
984    /// let app = ailloli_ui_winit::UiApp::<()>::new();
985    /// assert!(app.window_snapshots().is_empty());
986    /// ```
987    pub(crate) fn capture_handle_for_host(&self) -> Option<crate::capture::CaptureHandle> {
988        self.capture.clone()
989    }
990
991    /// Installs one shared host wake into runtime and every current devtools state.
992    ///
993    /// Devtools installation failures are latched without preventing other
994    /// presentations from receiving the callback.
995    ///
996    /// # Examples
997    ///
998    /// ```
999    /// // `run_winit_host` performs this wiring immediately before loop entry.
1000    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1001    /// assert!(app.error().is_none());
1002    /// ```
1003    pub(crate) fn install_host_wake(&mut self, wake: Arc<dyn UiWake>) {
1004        self.host_wake = Some(wake.clone());
1005        self.runtime.install_ui_wake(wake.clone());
1006        #[cfg(feature = "devtools")]
1007        {
1008            let mut first_error = None;
1009            for state in self.windows.values_mut() {
1010                if let Err(error) = state.devtools.install_host_wake(wake.clone()) {
1011                    first_error.get_or_insert(error);
1012                }
1013            }
1014            for retained in &mut self.retained_windows {
1015                if let Err(error) = retained.devtools.install_host_wake(wake.clone()) {
1016                    first_error.get_or_insert(error);
1017                }
1018            }
1019            #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1020            for state in &mut self.wayland_overlays {
1021                if let Err(error) = state.devtools.install_host_wake(wake.clone()) {
1022                    first_error.get_or_insert(error);
1023                }
1024            }
1025            if let Some(error) = first_error {
1026                self.devtools_wake_error.get_or_insert(error);
1027            }
1028        }
1029    }
1030
1031    #[cfg(feature = "devtools")]
1032    /// Rearms devtools wake latches and returns exact presentations with commands.
1033    ///
1034    /// The first observed per-window wake error is promoted to the application slot.
1035    ///
1036    /// # Examples
1037    ///
1038    /// ```
1039    /// // The host uses the result to request redraw before sleeping.
1040    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1041    /// assert!(app.error().is_none());
1042    /// ```
1043    pub(crate) fn begin_devtools_host_service(
1044        &mut self,
1045    ) -> Vec<(ailloli_ui_core::LogicalWindowId, PresentationGeneration)> {
1046        let mut pending = BTreeSet::new();
1047        let mut first_error = None;
1048        for state in self.windows.values() {
1049            if state.devtools.begin_host_service() {
1050                pending.insert((
1051                    ailloli_ui_core::LogicalWindowId::new(state.logical_window_id.clone()),
1052                    state.presentation_generation,
1053                ));
1054            }
1055            if let Some(error) = state.devtools.take_wake_error() {
1056                first_error.get_or_insert(error);
1057            }
1058        }
1059        for retained in &self.retained_windows {
1060            if retained.devtools.begin_host_service() {
1061                pending.insert((
1062                    ailloli_ui_core::LogicalWindowId::new(retained.logical_window_id.clone()),
1063                    retained.presentation_generation,
1064                ));
1065            }
1066            if let Some(error) = retained.devtools.take_wake_error() {
1067                first_error.get_or_insert(error);
1068            }
1069        }
1070        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1071        for state in &self.wayland_overlays {
1072            if state.devtools.begin_host_service() {
1073                pending.insert((
1074                    ailloli_ui_core::LogicalWindowId::new(state.logical_window_id.clone()),
1075                    state.presentation_generation,
1076                ));
1077            }
1078            if let Some(error) = state.devtools.take_wake_error() {
1079                first_error.get_or_insert(error);
1080            }
1081        }
1082        if let Some(error) = first_error {
1083            self.devtools_wake_error.get_or_insert(error);
1084        }
1085        pending.into_iter().collect()
1086    }
1087
1088    #[cfg(feature = "devtools")]
1089    /// Consumes the first devtools wake failure across all presentations.
1090    ///
1091    /// # Examples
1092    ///
1093    /// ```
1094    /// // A fresh application has no latched remote wake failure.
1095    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1096    /// assert!(app.error().is_none());
1097    /// ```
1098    pub(crate) fn take_devtools_wake_error(&mut self) -> Option<UiWakeError> {
1099        self.devtools_wake_error.take()
1100    }
1101
1102    /// Queues a deterministic presentation failure for the next safe
1103    /// event-loop boundary.
1104    ///
1105    /// Returns `true` and appends the fault when the id is pending, attached,
1106    /// retained, or a live Wayland overlay; unknown ids return `false` without
1107    /// mutation. Faults for one id retain FIFO order.
1108    ///
1109    /// # Examples
1110    ///
1111    /// ```
1112    /// use ailloli_ui_core::LogicalWindowId;
1113    /// use ailloli_ui_winit::{PresentationTestFault, UiApp};
1114    /// let mut app = UiApp::<()>::new();
1115    /// assert!(!app.inject_presentation_fault(
1116    ///     &LogicalWindowId::new("missing"), PresentationTestFault::Lost));
1117    /// ```
1118    #[cfg(feature = "test_support")]
1119    pub fn inject_presentation_fault(
1120        &mut self,
1121        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1122        fault: PresentationTestFault,
1123    ) -> bool {
1124        let known = self
1125            .windows
1126            .values()
1127            .any(|state| state.logical_window_id == logical_window_id.as_str())
1128            || self
1129                .retained_windows
1130                .iter()
1131                .any(|state| state.logical_window_id == logical_window_id.as_str())
1132            || {
1133                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1134                {
1135                    self.wayland_overlays
1136                        .iter()
1137                        .any(|state| state.logical_window_id == logical_window_id.as_str())
1138                }
1139                #[cfg(not(all(target_os = "linux", feature = "native_overlay")))]
1140                {
1141                    false
1142                }
1143            }
1144            || self
1145                .pending
1146                .iter()
1147                .any(|state| state.options.logical_window_id == logical_window_id.as_str());
1148        if known {
1149            self.presentation_test_faults
1150                .push((logical_window_id.clone(), fault));
1151        }
1152        known
1153    }
1154
1155    /// Queues destruction of one attached native presentation for a host test.
1156    ///
1157    /// The request is deduplicated and applied only at the next safe event-loop
1158    /// boundary. It exists solely to prove that reactive work stops targeting a
1159    /// presentation after its runtime tree has been destroyed.
1160    #[cfg(feature = "test_support")]
1161    #[doc(hidden)]
1162    pub fn request_presentation_test_close(
1163        &mut self,
1164        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1165    ) -> bool {
1166        let attached = self
1167            .windows
1168            .values()
1169            .any(|state| state.logical_window_id == logical_window_id.as_str());
1170        if attached && !self.presentation_test_closes.contains(logical_window_id) {
1171            self.presentation_test_closes
1172                .push(logical_window_id.clone());
1173        }
1174        attached
1175    }
1176
1177    /// Routes one provider-neutral event through a currently attached and
1178    /// generation-matching presentation.
1179    ///
1180    /// Returns `false` for an unknown logical window or stale generation. A
1181    /// stale known envelope increments the saturating rejection counter. An
1182    /// accepted event ensures initial layout, routes input, and schedules redraw
1183    /// when routing or retained dirtiness requires it.
1184    ///
1185    /// # Panics
1186    ///
1187    /// Panics only if the internal window map loses the resolved entry between
1188    /// the immutable lookup and subsequent mutable lookup.
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```no_run
1193    /// fn inject(app: &mut ailloli_ui_winit::UiApp<()>,
1194    ///     envelope: ailloli_ui_runtime::input::EventEnvelope) {
1195    ///     let accepted: bool = app.inject_event_envelope(envelope);
1196    ///     let _ = accepted;
1197    /// }
1198    /// ```
1199    #[cfg(feature = "test_support")]
1200    pub fn inject_event_envelope(&mut self, envelope: EventEnvelope) -> bool {
1201        let logical_window_id = envelope.meta().logical_window_id().clone();
1202        let Some(window_id) = self.windows.iter().find_map(|(window_id, state)| {
1203            (state.logical_window_id == logical_window_id.as_str()).then_some(*window_id)
1204        }) else {
1205            return false;
1206        };
1207        let accepted = self.windows.get(&window_id).is_some_and(|state| {
1208            state
1209                .lifecycle
1210                .accepts(envelope.meta().presentation_generation())
1211        });
1212        if !accepted {
1213            self.presentation_test_counters
1214                .entry(logical_window_id)
1215                .or_default()
1216                .rejected_stale_event_count += 1;
1217            return false;
1218        }
1219
1220        let state = self
1221            .windows
1222            .get_mut(&window_id)
1223            .expect("window id was resolved above");
1224        if !runtime_has_root_layout(&state.runtime) {
1225            layout_window(state);
1226        }
1227        let outcome = route_retained_envelope(&mut state.retained, &envelope);
1228        if outcome.needs_redraw() || state.runtime.runtime.has_dirty_elements() {
1229            state.window.request_redraw();
1230        }
1231        true
1232    }
1233
1234    /// Returns deterministic presentation state/counters for native tests.
1235    ///
1236    /// Returns `None` for unknown and still-pending windows. Live winit and
1237    /// Wayland presentations set `attached`; suspended retained windows do not.
1238    /// Missing counter history is reported as all zeros.
1239    ///
1240    /// # Examples
1241    ///
1242    /// ```
1243    /// use ailloli_ui_core::LogicalWindowId;
1244    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1245    /// assert!(app.presentation_test_state(&LogicalWindowId::new("missing")).is_none());
1246    /// ```
1247    #[cfg(feature = "test_support")]
1248    pub fn presentation_test_state(
1249        &self,
1250        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1251    ) -> Option<PresentationTestState> {
1252        let live = self
1253            .windows
1254            .values()
1255            .find(|state| state.logical_window_id == logical_window_id.as_str())
1256            .map(|state| {
1257                (
1258                    state.lifecycle.state(),
1259                    state.lifecycle.generation(),
1260                    true,
1261                    state.rendered_frame_count,
1262                )
1263            });
1264        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1265        let live = live.or_else(|| {
1266            self.wayland_overlays
1267                .iter()
1268                .find(|state| state.logical_window_id == logical_window_id.as_str())
1269                .map(|state| {
1270                    (
1271                        state.lifecycle.state(),
1272                        state.lifecycle.generation(),
1273                        true,
1274                        state.rendered_frame_count,
1275                    )
1276                })
1277        });
1278        let lifecycle = live.or_else(|| {
1279            self.retained_windows
1280                .iter()
1281                .find(|state| state.logical_window_id == logical_window_id.as_str())
1282                .map(|state| {
1283                    (
1284                        state.lifecycle.state(),
1285                        state.lifecycle.generation(),
1286                        false,
1287                        state.rendered_frame_count,
1288                    )
1289                })
1290        })?;
1291        let counters = self
1292            .presentation_test_counters
1293            .get(logical_window_id)
1294            .copied()
1295            .unwrap_or_default();
1296        Some(PresentationTestState {
1297            logical_window_id: logical_window_id.clone(),
1298            state: lifecycle.0,
1299            generation: lifecycle.1,
1300            attached: lifecycle.2,
1301            detach_count: counters.detach_count,
1302            recovery_count: counters.recovery_count,
1303            gpu_context_reuse_count: counters.gpu_context_reuse_count,
1304            gpu_context_rebuild_count: counters.gpu_context_rebuild_count,
1305            lost_count: counters.lost_count,
1306            outdated_count: counters.outdated_count,
1307            zero_extent_count: counters.zero_extent_count,
1308            rejected_stale_event_count: counters.rejected_stale_event_count,
1309            pending_fault_count: self
1310                .presentation_test_faults
1311                .iter()
1312                .filter(|(id, _)| id == logical_window_id)
1313                .count(),
1314            rendered_frame_count: lifecycle.3,
1315        })
1316    }
1317
1318    /// Reports whether the native host currently considers this test window focused.
1319    ///
1320    /// Native input benchmarks use this readiness signal before injecting a
1321    /// focus-sensitive sequence. In particular, X11 can deliver its initial
1322    /// `Focused(false)`/`Focused(true)` pair after the first rendered frame.
1323    /// `None` means no attached winit window with that logical id; direct
1324    /// Wayland overlays deliberately do not report native focus here.
1325    ///
1326    /// # Examples
1327    ///
1328    /// ```
1329    /// use ailloli_ui_core::LogicalWindowId;
1330    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1331    /// assert_eq!(app.presentation_test_window_has_native_focus(
1332    ///     &LogicalWindowId::new("missing")), None);
1333    /// ```
1334    #[cfg(feature = "test_support")]
1335    pub fn presentation_test_window_has_native_focus(
1336        &self,
1337        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1338    ) -> Option<bool> {
1339        self.windows
1340            .values()
1341            .find(|state| state.logical_window_id == logical_window_id.as_str())
1342            .map(|state| state.window.has_focus())
1343    }
1344
1345    /// Reports whether a retained popup registration is mounted in the
1346    /// requested live presentation and whether that popup tree owns focus.
1347    ///
1348    /// Returns `None` for non-live/unknown winit windows, otherwise
1349    /// `Some((mounted, owns_focus))`. Focus ownership implies the same popup id.
1350    ///
1351    /// # Examples
1352    ///
1353    /// ```no_run
1354    /// fn inspect(app: &ailloli_ui_winit::UiApp<()>,
1355    ///     id: &ailloli_ui_core::LogicalWindowId,
1356    ///     popup: ailloli_ui_runtime::popup::PopupId) {
1357    ///     let state: Option<(bool, bool)> = app.presentation_test_popup_mount_state(id, popup);
1358    ///     let _ = state;
1359    /// }
1360    /// ```
1361    #[cfg(feature = "test_support")]
1362    pub fn presentation_test_popup_mount_state(
1363        &self,
1364        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1365        popup_id: ailloli_ui_runtime::popup::PopupId,
1366    ) -> Option<(bool, bool)> {
1367        self.windows
1368            .values()
1369            .find(|state| state.logical_window_id == logical_window_id.as_str())
1370            .map(|state| {
1371                (
1372                    state.retained.popup_mounts.contains(popup_id),
1373                    state
1374                        .retained
1375                        .popup_mounts
1376                        .focus_owner()
1377                        .is_some_and(|focus| focus.popup_id() == popup_id),
1378                )
1379            })
1380    }
1381
1382    /// Returns the absolute layout bounds of one keyed view in a live native
1383    /// presentation. This is available only to the event-loop test driver.
1384    ///
1385    /// Bounds use logical window coordinates. Unknown windows, missing or
1386    /// ambiguous keys, and elements without absolute paint bounds return `None`.
1387    ///
1388    /// # Examples
1389    ///
1390    /// ```
1391    /// use ailloli_ui_core::LogicalWindowId;
1392    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1393    /// assert!(app.presentation_test_element_bounds(
1394    ///     &LogicalWindowId::new("missing"), "button").is_none());
1395    /// ```
1396    #[cfg(feature = "test_support")]
1397    pub fn presentation_test_element_bounds(
1398        &self,
1399        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1400        key: &str,
1401    ) -> Option<Rect> {
1402        let state = self
1403            .windows
1404            .values()
1405            .find(|state| state.logical_window_id == logical_window_id.as_str())?;
1406        let element_id = state.runtime.tree.resolve_element_by_view_key(key).ok()?;
1407        absolute_paint_bounds(&state.runtime.tree, element_id)
1408    }
1409
1410    /// Reports whether a keyed view contains the current focus target in one
1411    /// live native presentation.
1412    ///
1413    /// `Some(false)` means the window and unique key exist but focus is absent
1414    /// or outside that subtree. Unknown windows and unresolved keys return `None`.
1415    ///
1416    /// # Examples
1417    ///
1418    /// ```
1419    /// use ailloli_ui_core::LogicalWindowId;
1420    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1421    /// assert!(app.presentation_test_focus_within_key(
1422    ///     &LogicalWindowId::new("missing"), "editor").is_none());
1423    /// ```
1424    #[cfg(feature = "test_support")]
1425    pub fn presentation_test_focus_within_key(
1426        &self,
1427        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1428        key: &str,
1429    ) -> Option<bool> {
1430        let state = self
1431            .windows
1432            .values()
1433            .find(|state| state.logical_window_id == logical_window_id.as_str())?;
1434        let element_id = state.runtime.tree.resolve_element_by_view_key(key).ok()?;
1435        Some(
1436            state
1437                .input
1438                .focused()
1439                .is_some_and(|focused| state.runtime.tree.is_ancestor_of(element_id, focused)),
1440        )
1441    }
1442
1443    #[cfg(feature = "devtools")]
1444    /// Configures the loopback devtools address for subsequently created windows.
1445    ///
1446    /// This builder stores the address but does not bind immediately. Each
1447    /// window attempts its own remote server when retained state is created.
1448    ///
1449    /// # Examples
1450    ///
1451    /// ```
1452    /// let address = "127.0.0.1:9229".parse().unwrap();
1453    /// let app = ailloli_ui_winit::UiApp::<()>::new().devtools_remote_addr(address);
1454    /// assert!(app.error().is_none());
1455    /// ```
1456    pub fn devtools_remote_addr(mut self, addr: std::net::SocketAddr) -> Self {
1457        self.devtools_remote_addr = Some(addr);
1458        self
1459    }
1460
1461    /// Shared runtime handle (windows, focus, clipboard, chrome ops).
1462    ///
1463    /// Clones share the same action queue and providers; this does not clone
1464    /// per-window retained trees or renderers.
1465    ///
1466    /// # Examples
1467    ///
1468    /// ```
1469    /// let app = ailloli_ui_winit::UiApp::<u32>::new();
1470    /// let runtime: ailloli_ui_runtime::app::RuntimeHandle<u32> = app.runtime();
1471    /// assert!(runtime.take_actions().is_empty());
1472    /// ```
1473    pub fn runtime(&self) -> RuntimeHandle<A> {
1474        self.runtime.clone()
1475    }
1476
1477    /// Registers a window to open on `resumed` (hidden until first frame is drawn).
1478    ///
1479    /// The clear color defaults to transparent for transparent windows and
1480    /// `#1a1a1f` otherwise. Registration is append-only and performs no native
1481    /// work. The caller-provided visibility flag is overridden to hidden.
1482    ///
1483    /// # Panics
1484    ///
1485    /// Panics only if the fixed internal `#1a1a1f` color literal is changed to an
1486    /// invalid hexadecimal color.
1487    ///
1488    /// # Examples
1489    ///
1490    /// ```
1491    /// use ailloli_ui_widgets::text::Text;
1492    /// use ailloli_ui_winit::{UiApp, WindowOptions};
1493    /// let app = UiApp::<()>::new().window(WindowOptions::default(), Text::new("Hello"));
1494    /// assert!(app.window_snapshots().is_empty());
1495    /// ```
1496    pub fn window(mut self, mut options: WindowOptions, root: impl IntoView<A>) -> Self {
1497        options.start_hidden_until_first_frame = true;
1498        let clear = if options.transparent {
1499            Color::TRANSPARENT
1500        } else {
1501            Color::hex("#1a1a1f").expect("hex")
1502        };
1503        self.pending.push(PendingWindow {
1504            options,
1505            root: root.into_view(),
1506            clear,
1507        });
1508        self
1509    }
1510
1511    /// Registers a hidden-until-first-frame window with an explicit clear color.
1512    ///
1513    /// Unlike [`Self::window`], transparency does not replace `clear`; the exact
1514    /// supplied color is retained. Native work remains deferred until resume.
1515    ///
1516    /// # Examples
1517    ///
1518    /// ```
1519    /// use ailloli_ui_core::Color;
1520    /// use ailloli_ui_widgets::text::Text;
1521    /// use ailloli_ui_winit::{UiApp, WindowOptions};
1522    /// let app = UiApp::<()>::new().window_with_clear(
1523    ///     WindowOptions::default(), Color::TRANSPARENT, Text::new("Overlay"));
1524    /// assert!(app.error().is_none());
1525    /// ```
1526    pub fn window_with_clear(
1527        mut self,
1528        mut options: WindowOptions,
1529        clear: Color,
1530        root: impl IntoView<A>,
1531    ) -> Self {
1532        options.start_hidden_until_first_frame = true;
1533        self.pending.push(PendingWindow {
1534            options,
1535            root: root.into_view(),
1536            clear,
1537        });
1538        self
1539    }
1540
1541    /// Requests redraw for every live or retained presentation.
1542    ///
1543    /// Live winit windows receive native redraw requests; retained windows queue
1544    /// a coalescible presentation intent. Direct Wayland overlays mark their
1545    /// redraw bit and best-effort wake the host. An empty application is a no-op.
1546    ///
1547    /// # Examples
1548    ///
1549    /// ```
1550    /// let mut app = ailloli_ui_winit::UiApp::<()>::new();
1551    /// app.request_redraw_all();
1552    /// assert!(app.error().is_none());
1553    /// ```
1554    pub fn request_redraw_all(&mut self) {
1555        for state in self.windows.values() {
1556            state.window.request_redraw();
1557        }
1558        for retained in &mut self.retained_windows {
1559            retained
1560                .presentation_intents
1561                .push(PresentationIntent::Redraw);
1562        }
1563        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1564        if !self.wayland_overlays.is_empty() {
1565            for state in &self.wayland_overlays {
1566                state.needs_redraw.set(true);
1567            }
1568            if let Some(wake) = self.host_wake.as_ref() {
1569                let _ = wake.wake();
1570            }
1571        }
1572    }
1573
1574    /// Requests a redraw for one stable logical window when it is attached.
1575    ///
1576    /// Suspended retained windows queue the intent for replay after attachment.
1577    /// Returns `false` only when no live or retained presentation has the id.
1578    ///
1579    /// # Examples
1580    ///
1581    /// ```
1582    /// use ailloli_ui_core::LogicalWindowId;
1583    /// let mut app = ailloli_ui_winit::UiApp::<()>::new();
1584    /// assert!(!app.request_window_redraw(&LogicalWindowId::new("missing")));
1585    /// ```
1586    pub fn request_window_redraw(
1587        &mut self,
1588        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1589    ) -> bool {
1590        if let Some(state) = self
1591            .windows
1592            .values()
1593            .find(|state| state.logical_window_id == logical_window_id.as_str())
1594        {
1595            state.window.request_redraw();
1596            return true;
1597        }
1598        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1599        if let Some(state) = self
1600            .wayland_overlays
1601            .iter()
1602            .find(|state| state.logical_window_id == logical_window_id.as_str())
1603        {
1604            state.needs_redraw.set(true);
1605            if let Some(wake) = self.host_wake.as_ref() {
1606                let _ = wake.wake();
1607            }
1608            return true;
1609        }
1610        if let Some(retained) = self
1611            .retained_windows
1612            .iter_mut()
1613            .find(|state| state.logical_window_id == logical_window_id.as_str())
1614        {
1615            retained
1616                .presentation_intents
1617                .push(PresentationIntent::Redraw);
1618            return true;
1619        }
1620        false
1621    }
1622
1623    /// Requests redraw only when the exact presentation generation still exists.
1624    ///
1625    /// Dirty work from a detached or superseded tree must never wake a newer
1626    /// native attachment that happens to reuse the same logical window ID.
1627    /// Suspended retained state accepts its last generation and coalesces a
1628    /// redraw intent for replay after attachment.
1629    pub(crate) fn request_presentation_redraw(
1630        &mut self,
1631        logical_window_id: &ailloli_ui_core::LogicalWindowId,
1632        presentation_generation: PresentationGeneration,
1633    ) -> bool {
1634        if let Some(state) = self.windows.values().find(|state| {
1635            state.logical_window_id == logical_window_id.as_str()
1636                && state.presentation_generation == presentation_generation
1637        }) {
1638            if native_presentation_accepts_retained_redraw(
1639                state.lifecycle.state(),
1640                &state.resize,
1641                state.render_retry_at,
1642            ) {
1643                state.window.request_redraw();
1644                return true;
1645            }
1646            return false;
1647        }
1648        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1649        if let Some(state) = self.wayland_overlays.iter().find(|state| {
1650            state.logical_window_id == logical_window_id.as_str()
1651                && state.presentation_generation == presentation_generation
1652        }) {
1653            if state.lifecycle.state() != PresentationState::Ready
1654                || state.render_retry_at.is_some()
1655                || !state.capabilities.placed
1656            {
1657                return false;
1658            }
1659            state.needs_redraw.set(true);
1660            if let Some(wake) = self.host_wake.as_ref() {
1661                let _ = wake.wake();
1662            }
1663            return true;
1664        }
1665        if let Some(retained) = self.retained_windows.iter_mut().find(|state| {
1666            state.logical_window_id == logical_window_id.as_str()
1667                && state.presentation_generation == presentation_generation
1668        }) {
1669            retained
1670                .presentation_intents
1671                .push(PresentationIntent::Redraw);
1672            return true;
1673        }
1674        false
1675    }
1676
1677    /// Requests one redraw for every exact presentation with retained work.
1678    ///
1679    /// Runtime tree IDs and dirty roots remain encapsulated by the provider-
1680    /// neutral runtime. Stale generations and headless trees are ignored while
1681    /// their retained work remains pending for an explicit future scope.
1682    pub(crate) fn request_pending_presentation_redraws(&mut self) -> usize {
1683        let pending = self.runtime.pending_presentation_work();
1684        pending
1685            .into_iter()
1686            .filter(|work| {
1687                work.frame_work_plan().needs_paint()
1688                    && self.request_presentation_redraw(
1689                        work.logical_window_id(),
1690                        work.presentation_generation(),
1691                    )
1692            })
1693            .count()
1694    }
1695
1696    /// Drains global chrome operations and applies or retains them by logical id.
1697    ///
1698    /// Live operations target the first matching window and request redraw.
1699    /// Suspended targets retain the chrome operation plus redraw; unknown ids are dropped.
1700    fn drain_window_chrome_ops(&mut self) {
1701        let ops = self.runtime.take_window_chrome_ops();
1702        if ops.is_empty() {
1703            return;
1704        }
1705        for (lid, op) in ops {
1706            let mut applied = false;
1707            for state in self.windows.values_mut() {
1708                if state.logical_window_id != lid.as_str() {
1709                    continue;
1710                }
1711                match op {
1712                    WindowChromeOp::Minimize => state.window.set_minimized(true),
1713                    WindowChromeOp::ToggleMaximize => {
1714                        let next = !state.window.is_maximized();
1715                        state.window.set_maximized(next);
1716                    }
1717                }
1718                state.window.request_redraw();
1719                applied = true;
1720                break;
1721            }
1722            if !applied {
1723                if let Some(retained) = self
1724                    .retained_windows
1725                    .iter_mut()
1726                    .find(|state| state.logical_window_id == lid.as_str())
1727                {
1728                    retained
1729                        .presentation_intents
1730                        .push(PresentationIntent::WindowChrome(op));
1731                    retained
1732                        .presentation_intents
1733                        .push(PresentationIntent::Redraw);
1734                }
1735            }
1736        }
1737    }
1738
1739    /// Appends one native file callback, merging only the immediately preceding
1740    /// batch when both ephemeral window id and event kind match.
1741    fn queue_file_batch(
1742        &mut self,
1743        window_id: WindowId,
1744        kind: PendingFileBatchKind,
1745        file: Option<ailloli_ui_core::UploadFile>,
1746    ) {
1747        if let Some(batch) = self.pending_file_batches.last_mut() {
1748            if batch.window_id == window_id && batch.kind == kind {
1749                if let Some(file) = file {
1750                    batch.files.push(file);
1751                }
1752                return;
1753            }
1754        }
1755        self.pending_file_batches.push(PendingFileBatch {
1756            window_id,
1757            kind,
1758            files: file.into_iter().collect(),
1759        });
1760    }
1761
1762    /// Converts queued native file batches to generation-stamped runtime envelopes.
1763    ///
1764    /// Batches for vanished windows are dropped. Event ids saturate; missing
1765    /// initial layout is performed before routing and redraw follows route/dirty state.
1766    fn flush_pending_file_batches(&mut self) {
1767        let batches = std::mem::take(&mut self.pending_file_batches);
1768        for batch in batches {
1769            let Some(state) = self.windows.get_mut(&batch.window_id) else {
1770                continue;
1771            };
1772            let event = match batch.kind {
1773                PendingFileBatchKind::Entered => Event::File(FileEvent::Entered {
1774                    pos: None,
1775                    files: batch.files,
1776                }),
1777                PendingFileBatchKind::Left => Event::File(FileEvent::Left),
1778                PendingFileBatchKind::Dropped => Event::File(FileEvent::Dropped {
1779                    pos: None,
1780                    files: batch.files,
1781                }),
1782            };
1783            let meta = EventMeta::new(
1784                EventId::new(self.next_event_id),
1785                EventTimestamp::new(self.event_origin.elapsed()),
1786                state.logical_window_id.as_str(),
1787                state.presentation_generation,
1788            );
1789            self.next_event_id = self.next_event_id.saturating_add(1);
1790            if !runtime_has_root_layout(&state.runtime) {
1791                layout_window(state);
1792            }
1793            let envelope = EventEnvelope::new(meta, event);
1794            let outcome = route_retained_envelope(&mut state.retained, &envelope);
1795            if outcome.needs_redraw() || state.runtime.runtime.has_dirty_elements() {
1796                state.window.request_redraw();
1797            }
1798        }
1799    }
1800
1801    /// Consumes the first fatal host error.
1802    ///
1803    /// A second call returns `None` unless a later fatal error was recorded.
1804    ///
1805    /// # Examples
1806    ///
1807    /// ```
1808    /// let mut app = ailloli_ui_winit::UiApp::<()>::new();
1809    /// assert!(app.take_error().is_none());
1810    /// ```
1811    pub fn take_error(&mut self) -> Option<UiAppError> {
1812        self.error.take()
1813    }
1814
1815    /// Borrows the first fatal host error without consuming it.
1816    ///
1817    /// # Examples
1818    ///
1819    /// ```
1820    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1821    /// assert!(app.error().is_none());
1822    /// ```
1823    pub fn error(&self) -> Option<&UiAppError> {
1824        self.error.as_ref()
1825    }
1826
1827    /// Returns the latest persisted/logical snapshot for every known window id.
1828    ///
1829    /// Live attached state overrides an older retained snapshot with the same
1830    /// logical id. The returned `HashMap` values have unspecified order.
1831    ///
1832    /// # Examples
1833    ///
1834    /// ```
1835    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1836    /// let snapshots: Vec<ailloli_ui_app_storage::WindowSnapshot> = app.window_snapshots();
1837    /// assert!(snapshots.is_empty());
1838    /// ```
1839    pub fn window_snapshots(&self) -> Vec<WindowSnapshot> {
1840        let mut snapshots = self.window_snapshots.clone();
1841        for state in self.windows.values() {
1842            snapshots.insert(state.logical_window_id.clone(), window_snapshot(state));
1843        }
1844        snapshots.into_values().collect()
1845    }
1846
1847    /// Effective overlay capabilities for a live logical window.
1848    ///
1849    /// Returns `None` for normal windows, unknown ids, retained/detached
1850    /// overlays, or native overlay setup that did not establish every invariant.
1851    ///
1852    /// # Examples
1853    ///
1854    /// ```
1855    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1856    /// assert!(app.native_overlay_capabilities("missing").is_none());
1857    /// ```
1858    #[cfg(feature = "native_overlay")]
1859    pub fn native_overlay_capabilities(
1860        &self,
1861        logical_window_id: &str,
1862    ) -> Option<NativeOverlayCapabilities> {
1863        self.windows
1864            .values()
1865            .find(|state| state.logical_window_id == logical_window_id)
1866            .and_then(|state| state.native_overlay_capabilities)
1867            .or_else(|| {
1868                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1869                {
1870                    return self
1871                        .wayland_overlays
1872                        .iter()
1873                        .find(|state| state.logical_window_id == logical_window_id)
1874                        .map(|state| state.capabilities);
1875                }
1876                #[allow(unreachable_code)]
1877                None
1878            })
1879    }
1880
1881    /// Services deferred UI work before the native loop sleeps.
1882    ///
1883    /// Flushes file batches and test/Wayland work, consumes Linux shutdown,
1884    /// promotes scheduled repaints, arms due resize/text/render retries, applies
1885    /// chrome operations, then chooses the earliest internal or external wake
1886    /// deadline. Immediate work prevents sleeping.
1887    ///
1888    /// # Examples
1889    ///
1890    /// ```no_run
1891    /// // `WinitHost::about_to_wait` supplies the active event loop and driver deadline.
1892    /// let app = ailloli_ui_winit::UiApp::<()>::new();
1893    /// assert!(app.window_snapshots().is_empty());
1894    /// ```
1895    pub(crate) fn host_about_to_wait(
1896        &mut self,
1897        event_loop: &ActiveEventLoop,
1898        external_wakeup: Option<Instant>,
1899    ) {
1900        self.flush_pending_file_batches();
1901        #[cfg(feature = "test_support")]
1902        self.service_presentation_test_closes(event_loop);
1903        #[cfg(feature = "test_support")]
1904        self.service_presentation_test_faults(event_loop);
1905        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1906        self.service_wayland_overlays(event_loop);
1907        if shutdown_signal::take_requested() {
1908            Self::trace_startup("shutdown signal requested");
1909            event_loop.exit();
1910            return;
1911        }
1912
1913        let mut next_resize_wakeup = None;
1914        let mut pending_resize_redraw = false;
1915        let mut next_text_wakeup = None;
1916        let mut pending_text_redraw = false;
1917        let mut next_render_wakeup = None;
1918        let mut pending_render_redraw = false;
1919        let now = Instant::now();
1920        let pending_scheduled_redraw = self.runtime.promote_due_scheduled_repaints(now) != 0;
1921        self.request_pending_presentation_redraws();
1922        let next_scheduled_wakeup = self.runtime.next_scheduled_repaint_due_global();
1923        for state in self.windows.values_mut() {
1924            if state.resize.take_due_redraw_request() {
1925                state.window.request_redraw();
1926                pending_resize_redraw = true;
1927            } else if let Some(ready_at) = state.resize.retry_at() {
1928                next_resize_wakeup = Some(
1929                    next_resize_wakeup.map_or(ready_at, |current| std::cmp::min(current, ready_at)),
1930                );
1931            }
1932
1933            if let Some(ready_at) = state.render_retry_at {
1934                if ready_at <= now {
1935                    state.render_retry_at = None;
1936                    state.window.request_redraw();
1937                    pending_render_redraw = true;
1938                } else {
1939                    next_render_wakeup = Some(
1940                        next_render_wakeup
1941                            .map_or(ready_at, |current| std::cmp::min(current, ready_at)),
1942                    );
1943                }
1944            }
1945
1946            if matches!(
1947                state.input.focused_input_role(&state.runtime.tree),
1948                InputRole::TextSingleLine | InputRole::TextMultiLine
1949            ) {
1950                let (text_redraw_due, due) = {
1951                    let due = state.retained.next_text_blink.get_or_insert(now);
1952                    let redraw_due = *due <= now;
1953                    if redraw_due {
1954                        *due = now + Duration::from_millis(500);
1955                    }
1956                    (redraw_due, *due)
1957                };
1958                if text_redraw_due {
1959                    state.window.request_redraw();
1960                    pending_text_redraw = true;
1961                }
1962                next_text_wakeup =
1963                    Some(next_text_wakeup.map_or(due, |current| std::cmp::min(current, due)));
1964            } else {
1965                state.next_text_blink = None;
1966            }
1967
1968            state.input_bench.flush_if_due(now);
1969        }
1970
1971        let startup_redraw_pending = (!self.windows.is_empty()
1972            && self
1973                .windows
1974                .values()
1975                .any(|state| !state.rendered_once && !state.resize.zero_extent_unavailable()))
1976            || {
1977                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
1978                {
1979                    self.wayland_overlays
1980                        .iter()
1981                        .any(|state| !state.rendered_once)
1982                }
1983                #[cfg(not(all(target_os = "linux", feature = "native_overlay")))]
1984                {
1985                    false
1986                }
1987            };
1988        if startup_redraw_pending {
1989            self.request_redraw_all();
1990            ailloli_ui_bench::record(ailloli_ui_bench::Event::AboutToWaitRedraw {
1991                ts_ms: now_ms(),
1992                awaiting_resize: false,
1993            });
1994            event_loop.set_control_flow(ControlFlow::Poll);
1995        } else if pending_resize_redraw
1996            || pending_text_redraw
1997            || pending_scheduled_redraw
1998            || pending_render_redraw
1999        {
2000            ailloli_ui_bench::record(ailloli_ui_bench::Event::AboutToWaitRedraw {
2001                ts_ms: now_ms(),
2002                awaiting_resize: pending_resize_redraw,
2003            });
2004            event_loop.set_control_flow(ControlFlow::Wait);
2005        } else if let Some(wakeup) = [
2006            next_resize_wakeup,
2007            next_text_wakeup,
2008            next_render_wakeup,
2009            next_scheduled_wakeup,
2010            external_wakeup,
2011        ]
2012        .into_iter()
2013        .flatten()
2014        .min()
2015        {
2016            let awaiting_resize = next_resize_wakeup.is_some();
2017            ailloli_ui_bench::record(ailloli_ui_bench::Event::AboutToWaitRedraw {
2018                ts_ms: now_ms(),
2019                awaiting_resize,
2020            });
2021            event_loop.set_control_flow(ControlFlow::WaitUntil(wakeup));
2022        } else {
2023            event_loop.set_control_flow(self.control_flow);
2024        }
2025    }
2026
2027    #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2028    /// Drains direct Wayland overlay events and renders each latched redraw once.
2029    ///
2030    /// Configure changes update integer scale and resize the surface. Closed
2031    /// overlays clear presentation scope and are removed. Capture replaces the
2032    /// ordinary render for that frame; fatal renderer errors exit the loop.
2033    fn service_wayland_overlays(&mut self, event_loop: &ActiveEventLoop) {
2034        let capture = self.capture.clone();
2035        let mut failure = None;
2036
2037        for state in &mut self.wayland_overlays {
2038            while let Ok(event) = state.events.try_recv() {
2039                match event {
2040                    WaylandOverlayEvent::Configured(configured) => {
2041                        if configured != state.configured {
2042                            state.configured = configured;
2043                            state.scale = Scale::new(configured.scale_factor.max(1) as f32);
2044                            let size = configured.physical_size();
2045                            if let Err(err) = state.renderer.try_resize(
2046                                ailloli_ui_render_wgpu::PhysicalExtent::new(
2047                                    size.width,
2048                                    size.height,
2049                                ),
2050                            ) {
2051                                failure = Some(UiAppError::Render(err.to_string()));
2052                                break;
2053                            }
2054                            state.needs_redraw.set(true);
2055                        }
2056                    }
2057                    WaylandOverlayEvent::Closed => {
2058                        state.capabilities.placed = false;
2059                    }
2060                }
2061            }
2062            if failure.is_some() || !state.capabilities.placed || !state.needs_redraw.replace(false)
2063            {
2064                continue;
2065            }
2066
2067            let logical_width = state.configured.logical_width as f32;
2068            let logical_height = state.configured.logical_height as f32;
2069            {
2070                let retained = &mut state.retained;
2071                let scale = retained.scale;
2072                retained.runtime.layout(
2073                    Constraints::tight(logical_width, logical_height),
2074                    scale,
2075                    &mut retained.text_system,
2076                );
2077            }
2078            let popup_viewport = Rect::new(0.0, 0.0, logical_width, logical_height);
2079            let scene = paint_retained_window(&mut state.retained, popup_viewport, now_ms());
2080            state
2081                .renderer
2082                .set_text_face_blobs(state.text_system.face_blobs_snapshot());
2083            let passes = scene_to_layer_passes(&scene);
2084            let mut did_capture = false;
2085            if let Some(cap) = &capture {
2086                if cap.has_pending_for_window(&state.logical_window_id) {
2087                    let pending = cap.take_pending_for_window(&state.logical_window_id);
2088                    did_capture =
2089                        process_wayland_overlay_capture_requests(state, cap, pending, &passes);
2090                }
2091            }
2092            let result = if did_capture {
2093                Ok(())
2094            } else {
2095                state
2096                    .renderer
2097                    .render_layered_scaled(state.clear, &passes, state.scale)
2098            };
2099            match result {
2100                Ok(()) => {
2101                    state.rendered_once = true;
2102                    #[cfg(feature = "test_support")]
2103                    {
2104                        state.rendered_frame_count = state.rendered_frame_count.saturating_add(1);
2105                    }
2106                }
2107                Err(err) => failure = Some(UiAppError::Render(err.to_string())),
2108            }
2109        }
2110
2111        self.wayland_overlays.retain(|state| {
2112            if !state.capabilities.placed {
2113                state.runtime.runtime.clear_presentation_scope();
2114            }
2115            state.capabilities.placed
2116        });
2117        if let Some(cap) = &capture {
2118            if cap.exit_after_all_captures() && cap.is_complete() {
2119                event_loop.exit();
2120            }
2121        }
2122        if self.wayland_overlays.is_empty()
2123            && self.windows.is_empty()
2124            && self.retained_windows.is_empty()
2125            && self.pending.is_empty()
2126        {
2127            event_loop.exit();
2128        }
2129        if let Some(error) = failure {
2130            self.fail(event_loop, error);
2131        }
2132    }
2133
2134    /// Reconciles one pending root and initializes provider-neutral retained state.
2135    ///
2136    /// Client edge/title gestures are disabled for native overlays. Scale starts
2137    /// at one until attachment; renderer is absent; generation is initial.
2138    fn retain_pending_window(&mut self, pending: PendingWindow<A>) -> RetainedWindowState<A> {
2139        #[cfg(feature = "native_overlay")]
2140        let is_native_overlay = pending.options.native_overlay.is_some();
2141        #[cfg(not(feature = "native_overlay"))]
2142        let is_native_overlay = false;
2143
2144        let logical_window_id = pending.options.logical_window_id.clone();
2145        let mut runtime = Runtime::new(self.runtime.clone());
2146        runtime.reconcile(pending.root);
2147        let popup_mounts = PopupOverlayMounts::new(runtime.runtime.clone());
2148
2149        #[cfg(feature = "devtools")]
2150        let mut devtools = DevToolsWindowState::new();
2151        #[cfg(feature = "devtools")]
2152        if let Some(addr) = self.devtools_remote_addr {
2153            devtools.set_remote_addr(Some(addr));
2154        }
2155        #[cfg(feature = "devtools")]
2156        if let Some(wake) = self.host_wake.as_ref() {
2157            if let Err(error) = devtools.install_host_wake(wake.clone()) {
2158                self.devtools_wake_error.get_or_insert(error);
2159            }
2160        }
2161
2162        RetainedWindowState {
2163            lifecycle: PresentationLifecycle::new(logical_window_id.clone()),
2164            presentation_generation: PresentationGeneration::INITIAL,
2165            presentation_intents: PendingPresentationIntents::default(),
2166            renderer: None,
2167            client_edge_resize: !is_native_overlay
2168                && !pending.options.decorations
2169                && pending.options.resizable,
2170            client_titlebar_drag: !is_native_overlay
2171                && client_titlebar_drag_enabled(&pending.options),
2172            client_titlebar_key: pending.options.client_titlebar_key.clone(),
2173            reveal_after_first_frame: pending.options.start_hidden_until_first_frame,
2174            options: pending.options,
2175            logical_window_id,
2176            clear: pending.clear,
2177            text_system: TextSystem::new(),
2178            runtime,
2179            scale: Scale::new(1.0),
2180            cursor_pos: None,
2181            touch_primary: TouchPrimaryTracker::default(),
2182            current_cursor: PresentationCursor::Default,
2183            modifiers: Modifiers::default(),
2184            input: InputRouter::default(),
2185            popup_mounts,
2186            ime_allowed: false,
2187            last_ime_cursor_area: None,
2188            next_text_blink: None,
2189            render_retry_at: None,
2190            render_timeout_streak: 0,
2191            input_bench: InputBenchCounters::new(Instant::now()),
2192            rendered_once: false,
2193            #[cfg(feature = "test_support")]
2194            rendered_frame_count: 0,
2195            #[cfg(feature = "devtools")]
2196            devtools,
2197        }
2198    }
2199
2200    /// Advances declared/suspended/unavailable lifecycle state to creation-allowed.
2201    ///
2202    /// Already-ready, destroyed, and future unsupported states become typed
2203    /// window-creation errors; an already-allowed state is unchanged.
2204    ///
2205    /// # Errors
2206    ///
2207    /// Returns [`UiAppError::WindowCreate`] for an attached/destroyed/unsupported
2208    /// state or when the presentation lifecycle rejects the required transition.
2209    fn allow_presentation_creation(
2210        retained: &mut RetainedWindowState<A>,
2211    ) -> Result<(), UiAppError> {
2212        let transition = match retained.lifecycle.state() {
2213            PresentationState::Declared | PresentationState::Suspended => {
2214                Some(PresentationEvent::AllowCreation)
2215            }
2216            PresentationState::Unavailable(_) => Some(PresentationEvent::Retry),
2217            PresentationState::CreationAllowed => None,
2218            PresentationState::Ready => {
2219                return Err(UiAppError::WindowCreate(format!(
2220                    "logical window `{}` is already attached",
2221                    retained.logical_window_id
2222                )))
2223            }
2224            PresentationState::Destroyed => {
2225                return Err(UiAppError::WindowCreate(format!(
2226                    "logical window `{}` was destroyed",
2227                    retained.logical_window_id
2228                )))
2229            }
2230            _ => {
2231                return Err(UiAppError::WindowCreate(format!(
2232                    "logical window `{}` has an unsupported lifecycle state",
2233                    retained.logical_window_id
2234                )))
2235            }
2236        };
2237        if let Some(transition) = transition {
2238            retained.lifecycle.apply(transition).map_err(|error| {
2239                UiAppError::WindowCreate(format!(
2240                    "logical window `{}` rejected lifecycle transition: {error}",
2241                    retained.logical_window_id
2242                ))
2243            })?;
2244        }
2245        Ok(())
2246    }
2247
2248    /// Best-effort lifecycle transition to an unavailable reason.
2249    ///
2250    /// Rejection is intentionally ignored because the original attachment error
2251    /// remains the actionable diagnostic.
2252    fn mark_attachment_unavailable(
2253        retained: &mut RetainedWindowState<A>,
2254        reason: PresentationUnavailableReason,
2255    ) {
2256        let _ = retained
2257            .lifecycle
2258            .apply(PresentationEvent::Unavailable(reason));
2259    }
2260
2261    /// Marks an attached zero-sized presentation ready only after its surface
2262    /// accepted a later non-zero extent. This advances the generation so any
2263    /// event retained across the unavailable interval is rejected as stale.
2264    ///
2265    /// # Errors
2266    ///
2267    /// Returns [`UiAppError::WindowCreate`] when retry or attached transition is
2268    /// rejected. States other than zero-extent unavailable are successful no-ops.
2269    fn complete_zero_extent_recovery(
2270        retained: &mut RetainedWindowState<A>,
2271    ) -> Result<(), UiAppError> {
2272        if retained.lifecycle.state()
2273            != PresentationState::Unavailable(PresentationUnavailableReason::ZeroExtent)
2274        {
2275            return Ok(());
2276        }
2277
2278        retained
2279            .lifecycle
2280            .apply(PresentationEvent::Retry)
2281            .and_then(|_| retained.lifecycle.apply(PresentationEvent::Attached))
2282            .map(|reduction| {
2283                retained.presentation_generation = reduction.generation;
2284            })
2285            .map_err(|error| {
2286                UiAppError::WindowCreate(format!(
2287                    "logical window `{}` could not recover from a zero physical extent: {error}",
2288                    retained.logical_window_id
2289                ))
2290            })
2291    }
2292
2293    /// Applies attachment, copies its new generation, and resets native-only state.
2294    ///
2295    /// Every new attachment must render once before reveal, even if retained GPU
2296    /// context and element state were reused.
2297    ///
2298    /// # Errors
2299    ///
2300    /// Returns [`UiAppError::WindowCreate`] when the lifecycle rejects the
2301    /// attached transition; native-only state is reset only after success.
2302    fn complete_attachment(retained: &mut RetainedWindowState<A>) -> Result<(), UiAppError> {
2303        let reduction = retained
2304            .lifecycle
2305            .apply(PresentationEvent::Attached)
2306            .map_err(|error| {
2307                UiAppError::WindowCreate(format!(
2308                    "logical window `{}` could not attach: {error}",
2309                    retained.logical_window_id
2310                ))
2311            })?;
2312        retained.presentation_generation = reduction.generation;
2313        retained.ime_allowed = false;
2314        retained.last_ime_cursor_area = None;
2315        retained.render_retry_at = None;
2316        retained.render_timeout_streak = 0;
2317        retained.rendered_once = false;
2318        retained.reveal_after_first_frame = true;
2319        Ok(())
2320    }
2321
2322    /// Traces a surface reattachment and updates saturating test counters.
2323    fn record_gpu_reattach_outcome(
2324        &mut self,
2325        logical_window_id: &str,
2326        outcome: SurfaceReattachOutcome,
2327    ) {
2328        Self::trace_startup(format_args!(
2329            "reattached GPU presentation for {logical_window_id}: {outcome:?}"
2330        ));
2331        #[cfg(feature = "test_support")]
2332        {
2333            let counters = self
2334                .presentation_test_counters
2335                .entry(ailloli_ui_core::LogicalWindowId::new(logical_window_id))
2336                .or_default();
2337            match outcome {
2338                SurfaceReattachOutcome::ReusedGpuContext => {
2339                    counters.gpu_context_reuse_count =
2340                        counters.gpu_context_reuse_count.saturating_add(1);
2341                }
2342                SurfaceReattachOutcome::RebuiltGpuContext { .. } => {
2343                    counters.gpu_context_rebuild_count =
2344                        counters.gpu_context_rebuild_count.saturating_add(1);
2345                }
2346                _ => {}
2347            }
2348        }
2349    }
2350
2351    /// Attaches retained state through Wayland layer-shell or winit plus WGPU.
2352    ///
2353    /// A detached renderer is reattached when compatible and fully rebuilt by
2354    /// renderer fallback when necessary. Every failure returns ownership of the
2355    /// retained state inside [`AttachmentError`] after marking why it is
2356    /// unavailable. Successful intent replay precedes insertion into live state.
2357    ///
2358    /// # Errors
2359    ///
2360    /// Returns [`AttachmentError`] containing the original retained state for
2361    /// lifecycle, host-wake, native-overlay/window creation, renderer attachment,
2362    /// intent replay, or final lifecycle-transition failure.
2363    fn attach_retained_window(
2364        &mut self,
2365        event_loop: &ActiveEventLoop,
2366        mut retained: RetainedWindowState<A>,
2367    ) -> Result<AttachedWindow<A>, AttachmentError<A>> {
2368        if let Err(error) = Self::allow_presentation_creation(&mut retained) {
2369            return Err(Box::new((retained, error)));
2370        }
2371
2372        #[cfg(feature = "native_overlay")]
2373        let native_overlay = retained.options.native_overlay.clone();
2374        #[cfg(feature = "native_overlay")]
2375        let is_native_overlay = native_overlay.is_some();
2376        #[cfg(not(feature = "native_overlay"))]
2377        let is_native_overlay = false;
2378
2379        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2380        if let Some(options) = native_overlay.as_ref() {
2381            use winit::platform::wayland::ActiveEventLoopExtWayland;
2382
2383            if event_loop.is_wayland() {
2384                let Some(wake) = self.host_wake.clone() else {
2385                    Self::mark_attachment_unavailable(
2386                        &mut retained,
2387                        PresentationUnavailableReason::HostUnavailable,
2388                    );
2389                    return Err(Box::new((
2390                        retained,
2391                        UiAppError::WindowCreate(
2392                            "native overlay host wake is unavailable".to_string(),
2393                        ),
2394                    )));
2395                };
2396                let created = match crate::native_overlay::wayland::create(options, wake) {
2397                    Ok(created) => created,
2398                    Err(error) => {
2399                        Self::mark_attachment_unavailable(
2400                            &mut retained,
2401                            PresentationUnavailableReason::HostUnavailable,
2402                        );
2403                        return Err(Box::new((
2404                            retained,
2405                            UiAppError::WindowCreate(error.to_string()),
2406                        )));
2407                    }
2408                };
2409                let CreatedWaylandOverlay {
2410                    surface,
2411                    configured,
2412                    events,
2413                    capabilities,
2414                } = created;
2415                let renderer_options = RendererOptions {
2416                    transparent: true,
2417                    ..Default::default()
2418                };
2419                let physical_size = configured.physical_size();
2420                let physical_extent = ailloli_ui_render_wgpu::PhysicalExtent::new(
2421                    physical_size.width,
2422                    physical_size.height,
2423                );
2424                let (mut renderer, reattach_outcome) = if let Some(mut renderer) =
2425                    retained.renderer.take()
2426                {
2427                    match renderer.reattach_surface_target(surface.clone(), physical_extent, None) {
2428                        Ok(outcome) => (renderer, Some(outcome)),
2429                        Err(error) => {
2430                            retained.renderer = Some(renderer);
2431                            Self::mark_attachment_unavailable(
2432                                &mut retained,
2433                                PresentationUnavailableReason::NoCompatibleSurface,
2434                            );
2435                            return Err(Box::new((
2436                                retained,
2437                                UiAppError::RendererCreate(error.to_string()),
2438                            )));
2439                        }
2440                    }
2441                } else {
2442                    match Renderer::new_with_surface_target(
2443                        surface.clone(),
2444                        physical_extent,
2445                        renderer_options,
2446                        None,
2447                    ) {
2448                        Ok(renderer) => (renderer, None),
2449                        Err(error) => {
2450                            Self::mark_attachment_unavailable(
2451                                &mut retained,
2452                                PresentationUnavailableReason::NoCompatibleSurface,
2453                            );
2454                            return Err(Box::new((
2455                                retained,
2456                                UiAppError::RendererCreate(error.to_string()),
2457                            )));
2458                        }
2459                    }
2460                };
2461                retained.scale = Scale::new(configured.scale_factor.max(1) as f32);
2462                if let Err(error) = Self::complete_attachment(&mut retained) {
2463                    renderer.detach_surface();
2464                    retained.renderer = Some(renderer);
2465                    return Err(Box::new((retained, error)));
2466                }
2467                if let Some(outcome) = reattach_outcome {
2468                    self.record_gpu_reattach_outcome(&retained.logical_window_id, outcome);
2469                }
2470                let redraw = replay_retained_intents(&mut retained, None);
2471                return Ok(AttachedWindow::WaylandOverlay(WaylandOverlayState {
2472                    renderer,
2473                    _surface: surface,
2474                    events,
2475                    configured,
2476                    capabilities,
2477                    needs_redraw: std::cell::Cell::new(redraw),
2478                    retained,
2479                }));
2480            }
2481        }
2482
2483        let renderer_options = RendererOptions {
2484            transparent: retained.options.transparent || is_native_overlay,
2485            ..Default::default()
2486        };
2487        // `create_window` consumes its options, while the retained copy is needed
2488        // for a later resume.
2489        let window = match create_window(event_loop, retained.options.clone()) {
2490            Ok(window) => Arc::new(window),
2491            Err(error) => {
2492                Self::mark_attachment_unavailable(
2493                    &mut retained,
2494                    PresentationUnavailableReason::HostUnavailable,
2495                );
2496                return Err(Box::new((
2497                    retained,
2498                    UiAppError::WindowCreate(error.to_string()),
2499                )));
2500            }
2501        };
2502        #[cfg(feature = "native_overlay")]
2503        let native_overlay_capabilities =
2504            match configure_x11_overlay(event_loop, window.as_ref(), native_overlay.as_ref()) {
2505                Ok(capabilities) => capabilities,
2506                Err(error) => {
2507                    Self::mark_attachment_unavailable(
2508                        &mut retained,
2509                        PresentationUnavailableReason::HostUnavailable,
2510                    );
2511                    return Err(Box::new((retained, UiAppError::WindowCreate(error))));
2512                }
2513            };
2514        Self::trace_startup(format_args!("created window {:?}", window.id()));
2515        retained.scale = Scale::new(window.scale_factor() as f32);
2516        if let Err(error) = ailloli_ui_bench::try_update_window_observation(
2517            observed_winit_backend(event_loop),
2518            window.scale_factor(),
2519        ) {
2520            eprintln!(
2521                "ailloli_ui_winit: benchmark window observation could not be recorded: {error}"
2522            );
2523        }
2524        let (mut renderer, reattach_outcome) = if let Some(mut renderer) = retained.renderer.take()
2525        {
2526            match reattach_renderer_to_window(&mut renderer, window.clone()) {
2527                Ok(outcome) => (renderer, Some(outcome)),
2528                Err(error) => {
2529                    retained.renderer = Some(renderer);
2530                    Self::mark_attachment_unavailable(
2531                        &mut retained,
2532                        PresentationUnavailableReason::NoCompatibleSurface,
2533                    );
2534                    return Err(Box::new((
2535                        retained,
2536                        UiAppError::RendererCreate(error.to_string()),
2537                    )));
2538                }
2539            }
2540        } else {
2541            match renderer_from_window_with_options(window.clone(), renderer_options) {
2542                Ok(renderer) => (renderer, None),
2543                Err(error) => {
2544                    Self::mark_attachment_unavailable(
2545                        &mut retained,
2546                        PresentationUnavailableReason::NoCompatibleSurface,
2547                    );
2548                    return Err(Box::new((
2549                        retained,
2550                        UiAppError::RendererCreate(error.to_string()),
2551                    )));
2552                }
2553            }
2554        };
2555        record_renderer_bench_metadata(&renderer);
2556        Self::trace_startup(format_args!("created renderer for {:?}", window.id()));
2557        if let Err(error) = Self::complete_attachment(&mut retained) {
2558            detach_renderer_surface(&mut renderer);
2559            retained.renderer = Some(renderer);
2560            return Err(Box::new((retained, error)));
2561        }
2562        if let Some(outcome) = reattach_outcome {
2563            self.record_gpu_reattach_outcome(&retained.logical_window_id, outcome);
2564        }
2565        let redraw = replay_retained_intents(&mut retained, Some(window.as_ref()));
2566        let id = window.id();
2567        let mut resize = ResizeController::default();
2568        let resize_requested = resize.request_window_size(window.as_ref());
2569        if !resize_requested {
2570            Self::mark_attachment_unavailable(
2571                &mut retained,
2572                PresentationUnavailableReason::ZeroExtent,
2573            );
2574        }
2575        if redraw && resize_requested {
2576            window.request_redraw();
2577        }
2578        Ok(AttachedWindow::Native(
2579            id,
2580            WindowState {
2581                renderer,
2582                window,
2583                resize,
2584                #[cfg(feature = "native_overlay")]
2585                native_overlay_capabilities,
2586                retained,
2587            },
2588        ))
2589    }
2590
2591    /// Inserts a successful attachment into its platform-specific live collection.
2592    fn store_attached_window(&mut self, attached: AttachedWindow<A>) {
2593        match attached {
2594            AttachedWindow::Native(id, state) => {
2595                self.windows.insert(id, state);
2596            }
2597            #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2598            AttachedWindow::WaylandOverlay(state) => self.wayland_overlays.push(state),
2599        }
2600    }
2601
2602    #[cfg(feature = "test_support")]
2603    /// Drains deterministic test faults at a safe event-loop boundary.
2604    ///
2605    /// Detached zero-extent faults are requeued. Other faults detach and attempt
2606    /// immediate reattachment, preserving retained state on failure and updating
2607    /// only counters corresponding to completed lifecycle operations.
2608    fn service_presentation_test_faults(&mut self, event_loop: &ActiveEventLoop) {
2609        let faults = std::mem::take(&mut self.presentation_test_faults);
2610        for (logical_window_id, fault) in faults {
2611            let native_window_id = self.windows.iter().find_map(|(window_id, state)| {
2612                (state.logical_window_id == logical_window_id.as_str()).then_some(*window_id)
2613            });
2614
2615            if fault == PresentationTestFault::ZeroExtentRoundTrip {
2616                let Some(window_id) = native_window_id else {
2617                    // A detached presentation has no surface to resize. Keep
2618                    // the fault observable as pending work for the next
2619                    // event-loop boundary after a successful attachment.
2620                    self.presentation_test_faults
2621                        .push((logical_window_id, fault));
2622                    continue;
2623                };
2624                let state = self
2625                    .windows
2626                    .get_mut(&window_id)
2627                    .expect("zero-extent fault target was resolved above");
2628                let current = state.window.inner_size();
2629                let restored = PhysicalSize::new(current.width.max(1), current.height.max(1));
2630
2631                ailloli_ui_bench::record(ailloli_ui_bench::Event::ResizePending {
2632                    ts_ms: now_ms(),
2633                    w: 0,
2634                    h: 0,
2635                });
2636                let zero_redraw_requested = state.resize.request(PhysicalSize::new(0, 0));
2637                debug_assert!(!zero_redraw_requested);
2638                Self::mark_attachment_unavailable(
2639                    &mut state.retained,
2640                    PresentationUnavailableReason::ZeroExtent,
2641                );
2642                state.render_retry_at = None;
2643                state.render_timeout_streak = 0;
2644
2645                ailloli_ui_bench::record(ailloli_ui_bench::Event::ResizePending {
2646                    ts_ms: now_ms(),
2647                    w: restored.width,
2648                    h: restored.height,
2649                });
2650                let restore_redraw_requested = state.resize.request(restored);
2651                debug_assert!(restore_redraw_requested);
2652                state.window.request_redraw();
2653                let counters = self
2654                    .presentation_test_counters
2655                    .entry(logical_window_id)
2656                    .or_default();
2657                counters.zero_extent_count = counters.zero_extent_count.saturating_add(1);
2658                continue;
2659            }
2660
2661            let mut detached = native_window_id.and_then(|window_id| {
2662                self.windows.remove(&window_id).map(|state| {
2663                    self.window_snapshots
2664                        .insert(state.logical_window_id.clone(), window_snapshot(&state));
2665                    detach_native_window(state)
2666                })
2667            });
2668
2669            #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2670            if detached.is_none() {
2671                if let Some(index) = self
2672                    .wayland_overlays
2673                    .iter()
2674                    .position(|state| state.logical_window_id == logical_window_id.as_str())
2675                {
2676                    detached = Some(detach_wayland_overlay(self.wayland_overlays.remove(index)));
2677                }
2678            }
2679
2680            let was_attached = detached.is_some();
2681            if detached.is_none() {
2682                if let Some(index) = self
2683                    .retained_windows
2684                    .iter()
2685                    .position(|state| state.logical_window_id == logical_window_id.as_str())
2686                {
2687                    detached = Some(self.retained_windows.remove(index));
2688                }
2689            }
2690            let Some(mut retained) = detached else {
2691                continue;
2692            };
2693            let previous_generation = retained.lifecycle.generation();
2694            let counters = self
2695                .presentation_test_counters
2696                .entry(logical_window_id.clone())
2697                .or_default();
2698            if was_attached {
2699                counters.detach_count = counters.detach_count.saturating_add(1);
2700            }
2701            match fault {
2702                PresentationTestFault::DetachReattach => {}
2703                PresentationTestFault::Lost => {
2704                    counters.lost_count = counters.lost_count.saturating_add(1);
2705                    Self::mark_attachment_unavailable(
2706                        &mut retained,
2707                        PresentationUnavailableReason::SurfaceLost,
2708                    );
2709                }
2710                PresentationTestFault::Outdated => {
2711                    counters.outdated_count = counters.outdated_count.saturating_add(1);
2712                    Self::mark_attachment_unavailable(
2713                        &mut retained,
2714                        PresentationUnavailableReason::SurfaceLost,
2715                    );
2716                }
2717                PresentationTestFault::ZeroExtentRoundTrip => {
2718                    unreachable!("zero-extent faults are handled without detaching above")
2719                }
2720            }
2721
2722            match self.attach_retained_window(event_loop, retained) {
2723                Ok(attached) => {
2724                    let next_generation = match &attached {
2725                        AttachedWindow::Native(_, state) => state.lifecycle.generation(),
2726                        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2727                        AttachedWindow::WaylandOverlay(state) => state.lifecycle.generation(),
2728                    };
2729                    if next_generation > previous_generation {
2730                        self.presentation_test_counters
2731                            .entry(logical_window_id)
2732                            .or_default()
2733                            .recovery_count += 1;
2734                    }
2735                    self.store_attached_window(attached);
2736                }
2737                Err(attachment_error) => {
2738                    let (retained, error) = *attachment_error;
2739                    eprintln!(
2740                        "ailloli_ui_winit: injected presentation recovery remains unavailable: {error}"
2741                    );
2742                    self.retained_windows.push(retained);
2743                }
2744            }
2745        }
2746    }
2747
2748    #[cfg(feature = "test_support")]
2749    /// Applies queued test-only presentation destruction at a safe boundary.
2750    fn service_presentation_test_closes(&mut self, event_loop: &ActiveEventLoop) {
2751        let logical_window_ids = std::mem::take(&mut self.presentation_test_closes);
2752        for logical_window_id in logical_window_ids {
2753            let Some(window_id) = self.windows.iter().find_map(|(window_id, state)| {
2754                (state.logical_window_id == logical_window_id.as_str()).then_some(*window_id)
2755            }) else {
2756                continue;
2757            };
2758            let Some(mut state) = self.windows.remove(&window_id) else {
2759                continue;
2760            };
2761            self.window_snapshots
2762                .insert(state.logical_window_id.clone(), window_snapshot(&state));
2763            state.input_bench.flush();
2764            let _ = state.lifecycle.apply(PresentationEvent::Destroy);
2765            state.runtime.runtime.clear_presentation_scope();
2766            drop(state);
2767        }
2768
2769        if self.windows.is_empty()
2770            && self.retained_windows.is_empty()
2771            && self.pending.is_empty()
2772            && {
2773                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
2774                {
2775                    self.wayland_overlays.is_empty()
2776                }
2777                #[cfg(not(all(target_os = "linux", feature = "native_overlay")))]
2778                {
2779                    true
2780                }
2781            }
2782        {
2783            event_loop.exit();
2784        }
2785    }
2786
2787    /// Emits one startup/lifecycle diagnostic only when winit tracing is present.
2788    fn trace_startup(message: impl fmt::Display) {
2789        if crate::winit_trace_enabled() {
2790            eprintln!("ailloli_ui_winit: {message}");
2791        }
2792    }
2793
2794    /// Prints/stores a fatal error and requests native loop exit.
2795    fn fail(&mut self, event_loop: &ActiveEventLoop, error: UiAppError) {
2796        eprintln!("{error}");
2797        self.error = Some(error);
2798        event_loop.exit();
2799    }
2800}
2801
2802/// Maps supported provider-neutral cursors to winit, defaulting future variants.
2803fn cursor_icon_from_presentation_cursor(cursor: PresentationCursor) -> CursorIcon {
2804    match cursor {
2805        PresentationCursor::Default => CursorIcon::Default,
2806        PresentationCursor::Pointer => CursorIcon::Pointer,
2807        PresentationCursor::Text => CursorIcon::Text,
2808        PresentationCursor::ResizeX => CursorIcon::from(resize_edge_to_winit(ResizeEdge::E)),
2809        PresentationCursor::ResizeY => CursorIcon::from(resize_edge_to_winit(ResizeEdge::S)),
2810        _ => CursorIcon::Default,
2811    }
2812}
2813
2814/// Drains coalesced presentation intents into retained options and an optional window.
2815///
2816/// Size components clamp to one logical pixel. Chrome operations remain queued
2817/// when no native window exists. The return value requests at least one redraw;
2818/// it currently defaults to `true` even when the drained queue is empty.
2819fn replay_retained_intents<A>(
2820    retained: &mut RetainedWindowState<A>,
2821    window: Option<&Window>,
2822) -> bool {
2823    let mut redraw = true;
2824    for intent in retained.presentation_intents.drain() {
2825        match intent {
2826            PresentationIntent::SetTitle(title) => {
2827                retained.options.title.clone_from(&title);
2828                if let Some(window) = window {
2829                    window.set_title(&title);
2830                }
2831            }
2832            PresentationIntent::SetInnerSize(size) => {
2833                let size = LogicalSize::new(size.w.max(1.0) as f64, size.h.max(1.0) as f64);
2834                retained.options.inner_size = Some(size);
2835                if let Some(window) = window {
2836                    let _ = window.request_inner_size(size);
2837                }
2838            }
2839            PresentationIntent::SetCursor(cursor) => {
2840                retained.current_cursor = cursor;
2841                if let Some(window) = window {
2842                    window.set_cursor(cursor_icon_from_presentation_cursor(cursor));
2843                }
2844            }
2845            PresentationIntent::WindowChrome(operation) => {
2846                if let Some(window) = window {
2847                    match operation {
2848                        WindowChromeOp::Minimize => window.set_minimized(true),
2849                        WindowChromeOp::ToggleMaximize => {
2850                            window.set_maximized(!window.is_maximized());
2851                        }
2852                    }
2853                } else {
2854                    retained
2855                        .presentation_intents
2856                        .push(PresentationIntent::WindowChrome(operation));
2857                }
2858            }
2859            PresentationIntent::Redraw => redraw = true,
2860            _ => {}
2861        }
2862    }
2863    if let Some(window) = window {
2864        window.set_cursor(cursor_icon_from_presentation_cursor(
2865            retained.current_cursor,
2866        ));
2867    }
2868    redraw
2869}
2870
2871/// Best-effort records fixed winit version and current adapter/driver metadata.
2872fn record_renderer_bench_metadata(renderer: &Renderer) {
2873    let adapter_info = renderer.adapter_info();
2874    let mut bench_metadata = ailloli_ui_bench::RunMetadata::default();
2875    bench_metadata.winit_version = Some("0.30.13".to_string());
2876    bench_metadata.backend = Some(adapter_info.backend.to_str().to_string());
2877    bench_metadata.gpu = Some(adapter_info.name.clone());
2878    bench_metadata.driver = Some(if adapter_info.driver_info.is_empty() {
2879        adapter_info.driver.clone()
2880    } else {
2881        format!("{} ({})", adapter_info.driver, adapter_info.driver_info)
2882    });
2883    let _ = ailloli_ui_bench::try_update_metadata(bench_metadata);
2884}
2885
2886/// Flushes metrics, retains current intents, and cancels native pointer state.
2887///
2888/// Logical size components clamp to one; lifecycle suspension rejection is
2889/// ignored because callers already own a live attachment.
2890fn prepare_retained_for_detach<A: 'static>(
2891    retained: &mut RetainedWindowState<A>,
2892    logical_size: Size,
2893) {
2894    retained.input_bench.flush();
2895    retained.options.inner_size = Some(LogicalSize::new(
2896        logical_size.w.max(1.0) as f64,
2897        logical_size.h.max(1.0) as f64,
2898    ));
2899    retained
2900        .presentation_intents
2901        .push(PresentationIntent::SetInnerSize(logical_size));
2902    retained
2903        .presentation_intents
2904        .push(PresentationIntent::SetCursor(retained.current_cursor));
2905    retained
2906        .presentation_intents
2907        .push(PresentationIntent::Redraw);
2908    retained
2909        .input
2910        .cancel_pointer_state(&retained.runtime.tree, retained.runtime.runtime.clone());
2911    retained.cursor_pos = None;
2912    retained.touch_primary.clear();
2913    retained.ime_allowed = false;
2914    retained.last_ime_cursor_area = None;
2915    retained.render_retry_at = None;
2916    retained.render_timeout_streak = 0;
2917    let _ = retained.lifecycle.apply(PresentationEvent::Suspend);
2918}
2919
2920/// Detaches a winit surface before dropping its raw-handle owner and retains GPU context.
2921fn detach_native_window<A: 'static>(state: WindowState<A>) -> RetainedWindowState<A> {
2922    let physical_size = state.window.inner_size();
2923    let logical_size = Size::new(
2924        to_logical_f32(physical_size.width as f32, state.scale),
2925        to_logical_f32(physical_size.height as f32, state.scale),
2926    );
2927    let WindowState {
2928        mut renderer,
2929        window,
2930        resize: _,
2931        #[cfg(feature = "native_overlay")]
2932            native_overlay_capabilities: _,
2933        mut retained,
2934    } = state;
2935    prepare_retained_for_detach(&mut retained, logical_size);
2936    // Release the surface and its strong raw-handle owner before dropping the
2937    // native window. The remaining GPU context and caches are retained.
2938    detach_renderer_surface(&mut renderer);
2939    retained.renderer = Some(renderer);
2940    drop(window);
2941    retained
2942}
2943
2944#[cfg(all(target_os = "linux", feature = "native_overlay"))]
2945/// Detaches a direct Wayland surface before dropping its raw-handle owner.
2946fn detach_wayland_overlay<A: 'static>(state: WaylandOverlayState<A>) -> RetainedWindowState<A> {
2947    let logical_size = Size::new(
2948        state.configured.logical_width as f32,
2949        state.configured.logical_height as f32,
2950    );
2951    let WaylandOverlayState {
2952        mut renderer,
2953        _surface: surface,
2954        events: _,
2955        configured: _,
2956        capabilities: _,
2957        needs_redraw: _,
2958        mut retained,
2959    } = state;
2960    prepare_retained_for_detach(&mut retained, logical_size);
2961    renderer.detach_surface();
2962    retained.renderer = Some(renderer);
2963    drop(surface);
2964    retained
2965}
2966
2967/// Native callback implementation used exclusively by [`crate::WinitHost`].
2968impl<A: 'static> UiApp<A> {
2969    /// Handles the native resume callback delegated by [`crate::WinitHost`].
2970    ///
2971    /// Converts pending declarations to retained state, attempts attachment of
2972    /// every retained presentation, preserves previously attached state on a
2973    /// reattach failure, treats first attachment failure as fatal, services test
2974    /// faults, and requests initial redraw.
2975    ///
2976    /// # Examples
2977    ///
2978    /// ```no_run
2979    /// // `WinitHost::resumed` delegates the active loop to this internal callback.
2980    /// let app = ailloli_ui_winit::UiApp::<()>::new();
2981    /// assert!(app.window_snapshots().is_empty());
2982    /// ```
2983    pub(crate) fn host_resumed(&mut self, event_loop: &ActiveEventLoop) {
2984        Self::trace_startup(format_args!(
2985            "resumed with {} new and {} retained window(s)",
2986            self.pending.len(),
2987            self.retained_windows.len()
2988        ));
2989
2990        let pending_windows = std::mem::take(&mut self.pending);
2991        for pending in pending_windows {
2992            let retained = self.retain_pending_window(pending);
2993            self.retained_windows.push(retained);
2994        }
2995
2996        let retained_windows = std::mem::take(&mut self.retained_windows);
2997        for retained in retained_windows {
2998            let was_previously_attached =
2999                retained.presentation_generation != PresentationGeneration::INITIAL;
3000            match self.attach_retained_window(event_loop, retained) {
3001                Ok(attached) => self.store_attached_window(attached),
3002                Err(attachment_error) => {
3003                    let (retained, error) = *attachment_error;
3004                    self.retained_windows.push(retained);
3005                    if was_previously_attached {
3006                        eprintln!(
3007                            "ailloli_ui_winit: presentation reattach deferred; retained UI state remains available: {error}"
3008                        );
3009                    } else {
3010                        self.fail(event_loop, error);
3011                        return;
3012                    }
3013                }
3014            }
3015        }
3016
3017        #[cfg(feature = "test_support")]
3018        self.service_presentation_test_faults(event_loop);
3019        // Win32 only: winit routes `request_redraw()` through `WM_PAINT`, which
3020        // hidden windows do not receive. Reveal windows waiting for their first
3021        // frame before the initial redraw request to break that visibility/redraw cycle.
3022        // See: https://github.com/rust-windowing/winit/blob/v0.30.13/src/platform_impl/windows/event_loop.rs#L957-L960
3023        #[cfg(target_os = "windows")]
3024        for state in self.windows.values() {
3025            if state.reveal_after_first_frame {
3026                state.window.set_visible(true);
3027            }
3028        }
3029        Self::trace_startup("requesting initial redraw");
3030        self.request_redraw_all();
3031    }
3032
3033    /// Handles the native suspend callback delegated by [`crate::WinitHost`].
3034    ///
3035    /// Flushes pending file batches, snapshots each live winit window, detaches
3036    /// renderer surfaces before native handles, preserves retained runtime/GPU
3037    /// state, and resets control flow to wait. Direct Wayland overlays follow
3038    /// the same retained lifecycle.
3039    ///
3040    /// # Examples
3041    ///
3042    /// ```no_run
3043    /// // Suspension may leave a logical application alive with no native windows.
3044    /// let app = ailloli_ui_winit::UiApp::<()>::new();
3045    /// assert!(app.error().is_none());
3046    /// ```
3047    pub(crate) fn host_suspended(&mut self, _event_loop: &ActiveEventLoop) {
3048        Self::trace_startup(format_args!(
3049            "suspending {} native window(s)",
3050            self.windows.len()
3051        ));
3052
3053        self.flush_pending_file_batches();
3054        let windows = std::mem::take(&mut self.windows);
3055        for (_, state) in windows {
3056            self.window_snapshots
3057                .insert(state.logical_window_id.clone(), window_snapshot(&state));
3058            self.retained_windows.push(detach_native_window(state));
3059        }
3060
3061        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
3062        {
3063            let overlays = std::mem::take(&mut self.wayland_overlays);
3064            for state in overlays {
3065                self.retained_windows.push(detach_wayland_overlay(state));
3066            }
3067        }
3068
3069        // A suspended host can legitimately own no native window. The logical
3070        // application remains alive and will reattach presentations on resumed.
3071        self.control_flow = ControlFlow::Wait;
3072    }
3073
3074    /// Handles one native window callback delegated by [`crate::WinitHost`].
3075    ///
3076    /// File hover/drop callbacks are batched; resize and scale update lifecycle;
3077    /// redraw applies resize/retry, layout, focus, paint, devtools, capture, and
3078    /// render in order; input is translated to generation-stamped envelopes.
3079    /// Unknown ephemeral window ids are ignored after chrome operations drain.
3080    ///
3081    /// # Examples
3082    ///
3083    /// ```no_run
3084    /// // The public host owns ephemeral `WindowId` routing.
3085    /// let app = ailloli_ui_winit::UiApp::<()>::new();
3086    /// assert!(app.error().is_none());
3087    /// ```
3088    pub(crate) fn host_window_event(
3089        &mut self,
3090        event_loop: &ActiveEventLoop,
3091        id: WindowId,
3092        event: WindowEvent,
3093    ) {
3094        let capture = self.capture.clone();
3095        let known_window_ids: Vec<String> = self
3096            .windows
3097            .values()
3098            .map(|s| s.logical_window_id.clone())
3099            .chain({
3100                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
3101                {
3102                    self.wayland_overlays
3103                        .iter()
3104                        .map(|state| state.logical_window_id.clone())
3105                        .collect::<Vec<_>>()
3106                }
3107                #[cfg(not(all(target_os = "linux", feature = "native_overlay")))]
3108                {
3109                    Vec::new()
3110                }
3111            })
3112            .collect();
3113        if let Some(ref c) = &capture {
3114            c.fail_unknown_windows(known_window_ids.iter().map(|s| s.as_str()));
3115        }
3116
3117        let event_id = EventId::new(self.next_event_id);
3118        self.next_event_id = self.next_event_id.saturating_add(1);
3119        let event_timestamp = EventTimestamp::new(self.event_origin.elapsed());
3120
3121        let queued_file_event = match &event {
3122            WindowEvent::HoveredFile(path) => {
3123                self.queue_file_batch(
3124                    id,
3125                    PendingFileBatchKind::Entered,
3126                    Some(ailloli_ui_core::UploadFile::from_path(path.clone())),
3127                );
3128                true
3129            }
3130            WindowEvent::HoveredFileCancelled => {
3131                self.queue_file_batch(id, PendingFileBatchKind::Left, None);
3132                true
3133            }
3134            WindowEvent::DroppedFile(path) => {
3135                self.queue_file_batch(
3136                    id,
3137                    PendingFileBatchKind::Dropped,
3138                    Some(ailloli_ui_core::UploadFile::from_path(path.clone())),
3139                );
3140                true
3141            }
3142            _ => false,
3143        };
3144        if queued_file_event {
3145            self.drain_window_chrome_ops();
3146            return;
3147        }
3148
3149        let Some(state) = self.windows.get_mut(&id) else {
3150            self.drain_window_chrome_ops();
3151            return;
3152        };
3153
3154        let mut failure = None;
3155        let mut recreate_surface = None;
3156
3157        match event {
3158            WindowEvent::CloseRequested => {
3159                if let Some(mut state) = self.windows.remove(&id) {
3160                    self.window_snapshots
3161                        .insert(state.logical_window_id.clone(), window_snapshot(&state));
3162                    state.input_bench.flush();
3163                    let _ = state.lifecycle.apply(PresentationEvent::Destroy);
3164                    state.runtime.runtime.clear_presentation_scope();
3165                    // Struct field order releases renderer/surface before window.
3166                    drop(state);
3167                }
3168                if self.windows.is_empty()
3169                    && self.retained_windows.is_empty()
3170                    && self.pending.is_empty()
3171                    && {
3172                        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
3173                        {
3174                            self.wayland_overlays.is_empty()
3175                        }
3176                        #[cfg(not(all(target_os = "linux", feature = "native_overlay")))]
3177                        {
3178                            true
3179                        }
3180                    }
3181                {
3182                    event_loop.exit();
3183                }
3184            }
3185            WindowEvent::Resized(size) => {
3186                ailloli_ui_bench::record(ailloli_ui_bench::Event::ResizePending {
3187                    ts_ms: now_ms(),
3188                    w: size.width,
3189                    h: size.height,
3190                });
3191                let request_redraw = state.resize.request(size);
3192                if let Some(root) = state.runtime.root {
3193                    state.runtime.runtime.request_layout(root);
3194                }
3195                if !request_redraw {
3196                    Self::mark_attachment_unavailable(
3197                        &mut state.retained,
3198                        PresentationUnavailableReason::ZeroExtent,
3199                    );
3200                    state.render_retry_at = None;
3201                    state.render_timeout_streak = 0;
3202                }
3203                self.window_snapshots
3204                    .insert(state.logical_window_id.clone(), window_snapshot(state));
3205                if request_redraw {
3206                    state.window.request_redraw();
3207                }
3208            }
3209            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
3210                state.scale = Scale::new(scale_factor as f32);
3211                state.last_ime_cursor_area = None;
3212                let size = state.window.inner_size();
3213                ailloli_ui_bench::record(ailloli_ui_bench::Event::ResizePending {
3214                    ts_ms: now_ms(),
3215                    w: size.width,
3216                    h: size.height,
3217                });
3218                let request_redraw = state.resize.request(size);
3219                if let Some(root) = state.runtime.root {
3220                    state.runtime.runtime.request_layout(root);
3221                }
3222                if !request_redraw {
3223                    Self::mark_attachment_unavailable(
3224                        &mut state.retained,
3225                        PresentationUnavailableReason::ZeroExtent,
3226                    );
3227                    state.render_retry_at = None;
3228                    state.render_timeout_streak = 0;
3229                }
3230                self.window_snapshots
3231                    .insert(state.logical_window_id.clone(), window_snapshot(state));
3232                if request_redraw {
3233                    state.window.request_redraw();
3234                }
3235            }
3236            WindowEvent::RedrawRequested => {
3237                Self::trace_startup(format_args!("redraw requested for {id:?}"));
3238                let mut skip_render = false;
3239                let mut presentation_requires_layout = false;
3240                match state
3241                    .resize
3242                    .prepare_redraw(state.window.as_ref(), &mut state.renderer)
3243                {
3244                    Ok(ResizeRedrawAction::Ready) => {}
3245                    Ok(ResizeRedrawAction::Waiting) => skip_render = true,
3246                    Ok(ResizeRedrawAction::Deferred { reason, .. }) => {
3247                        skip_render = true;
3248                        Self::trace_startup(format_args!(
3249                            "deferred resize for {id:?}: {}",
3250                            reason.as_str()
3251                        ));
3252                    }
3253                    Ok(ResizeRedrawAction::SkippedZero) => {
3254                        skip_render = true;
3255                        Self::mark_attachment_unavailable(
3256                            &mut state.retained,
3257                            PresentationUnavailableReason::ZeroExtent,
3258                        );
3259                        state.render_retry_at = None;
3260                        state.render_timeout_streak = 0;
3261                        Self::trace_startup(format_args!("skipped zero-sized resize for {id:?}"));
3262                    }
3263                    Ok(ResizeRedrawAction::Applied(applied)) => {
3264                        presentation_requires_layout = true;
3265                        ailloli_ui_bench::record(ailloli_ui_bench::Event::ResizeApply {
3266                            ts_ms: now_ms(),
3267                            w: applied.size.width,
3268                            h: applied.size.height,
3269                            dur_us: applied.dur_us,
3270                        });
3271                        Self::trace_startup(format_args!(
3272                            "resize outcome for {id:?}: {:?}",
3273                            applied.outcome
3274                        ));
3275                        if let Err(error) = Self::complete_zero_extent_recovery(&mut state.retained)
3276                        {
3277                            failure = Some(error);
3278                            skip_render = true;
3279                        }
3280                    }
3281                    Err(err) => match render_error_action(&err) {
3282                        RenderErrorAction::RetryFrame(delay) => {
3283                            schedule_render_retry(state, delay);
3284                            skip_render = true;
3285                        }
3286                        RenderErrorAction::ReconfigureSurface => {
3287                            recreate_surface = Some(presentation_recreation_cause(&err));
3288                            skip_render = true;
3289                        }
3290                        RenderErrorAction::Fatal => {
3291                            failure = Some(UiAppError::Render(err.to_string()));
3292                        }
3293                    },
3294                }
3295
3296                if state.lifecycle.state() != PresentationState::Ready {
3297                    skip_render = true;
3298                }
3299
3300                if failure.is_none() && !skip_render {
3301                    if let Some(reason) = state.renderer.surface_config_deferred_reason() {
3302                        state.resize.defer_for_surface(state.window.as_ref());
3303                        Self::trace_startup(format_args!(
3304                            "skipping render for {id:?}: {}",
3305                            reason.as_str()
3306                        ));
3307                        return;
3308                    }
3309
3310                    let root_has_layout = runtime_has_root_layout(&state.runtime);
3311                    let frame_work_plan = state.runtime.prepare_frame();
3312                    let layout_start = Instant::now();
3313                    if frame_requires_layout(
3314                        frame_work_plan,
3315                        presentation_requires_layout,
3316                        root_has_layout,
3317                    ) {
3318                        layout_window(state);
3319                    }
3320                    let layout_us = layout_start.elapsed().as_micros();
3321                    {
3322                        let retained = &mut state.retained;
3323                        let runtime_handle = retained.runtime.runtime.clone();
3324                        retained
3325                            .input
3326                            .apply_pending_focus_request(&retained.runtime.tree, runtime_handle);
3327                    }
3328
3329                    let paint_start = Instant::now();
3330                    let popup_viewport = window_viewport_logical(state);
3331                    let scene =
3332                        paint_retained_window(&mut state.retained, popup_viewport, now_ms());
3333                    update_ime_state(state);
3334                    #[cfg(feature = "devtools")]
3335                    let mut scene = scene;
3336                    #[cfg(feature = "devtools")]
3337                    if let Some(root) = state.runtime.root {
3338                        let viewport = window_viewport_logical(state);
3339                        let retained = &mut state.retained;
3340                        let scale = retained.scale;
3341                        if let Some(devtools_scene) = retained.devtools.build_scene(
3342                            &retained.runtime.tree,
3343                            root,
3344                            viewport,
3345                            scale,
3346                            &mut retained.text_system,
3347                        ) {
3348                            scene.layers.extend(devtools_scene.layers);
3349                        }
3350                    }
3351                    let paint_us = paint_start.elapsed().as_micros();
3352                    let draw_text_cmds = count_draw_text_cmds(&scene);
3353
3354                    state
3355                        .renderer
3356                        .set_text_face_blobs(state.text_system.face_blobs_snapshot());
3357
3358                    let passes = scene_to_layer_passes(&scene);
3359
3360                    let logical_id = state.logical_window_id.clone();
3361                    let mut did_gpu_capture = false;
3362                    if let Some(ref cap) = capture {
3363                        if cap.has_pending_for_window(&logical_id) {
3364                            let pending = cap.take_pending_for_window(&logical_id);
3365                            did_gpu_capture =
3366                                process_capture_requests(state, cap, pending, &passes);
3367                        }
3368                    }
3369
3370                    let render_start = Instant::now();
3371                    let render_outcome = if did_gpu_capture {
3372                        Ok(())
3373                    } else {
3374                        state
3375                            .renderer
3376                            .render_layered_scaled(state.clear, &passes, state.scale)
3377                    };
3378                    let render_us = render_start.elapsed().as_micros();
3379                    record_ui_frame_metrics(
3380                        &state.logical_window_id,
3381                        state.presentation_generation,
3382                        layout_us,
3383                        paint_us,
3384                        render_us,
3385                        draw_text_cmds,
3386                    );
3387
3388                    match render_outcome {
3389                        Ok(()) => {
3390                            state.resize.mark_render_succeeded();
3391                            state.render_retry_at = None;
3392                            state.render_timeout_streak = 0;
3393                            #[cfg(feature = "test_support")]
3394                            {
3395                                state.rendered_frame_count =
3396                                    state.rendered_frame_count.saturating_add(1);
3397                            }
3398                            if let Some(ref cap) = capture {
3399                                if cap.exit_after_all_captures() && cap.is_complete() {
3400                                    event_loop.exit();
3401                                }
3402                            }
3403                            if !state.rendered_once {
3404                                if state.reveal_after_first_frame {
3405                                    state.window.set_visible(true);
3406                                }
3407                                state.rendered_once = true;
3408                                Self::trace_startup(format_args!(
3409                                    "rendered first frame for {id:?}"
3410                                ));
3411                            }
3412                        }
3413                        Err(err) => match render_error_action(&err) {
3414                            RenderErrorAction::RetryFrame(delay) => {
3415                                schedule_render_retry(state, delay);
3416                                Self::trace_startup(format_args!(
3417                                    "skipping render for {id:?}: transient {err}"
3418                                ));
3419                            }
3420                            RenderErrorAction::ReconfigureSurface => {
3421                                state.render_retry_at = None;
3422                                state.render_timeout_streak = 0;
3423                                match state.resize.request_surface_recovery(state.window.as_ref()) {
3424                                    SurfaceRecoveryAction::ReconfigureScheduled => {
3425                                        if state.resize.zero_extent_unavailable() {
3426                                            Self::mark_attachment_unavailable(
3427                                                &mut state.retained,
3428                                                PresentationUnavailableReason::ZeroExtent,
3429                                            );
3430                                        }
3431                                        Self::trace_startup(format_args!(
3432                                            "skipping render for {id:?}: forcing surface reconfigure ({err})"
3433                                        ));
3434                                    }
3435                                    SurfaceRecoveryAction::RecreatePresentation => {
3436                                        recreate_surface =
3437                                            Some(presentation_recreation_cause(&err));
3438                                        Self::trace_startup(format_args!(
3439                                            "recreating presentation for {id:?}: surface remained invalid after forced reconfigure ({err})"
3440                                        ));
3441                                    }
3442                                }
3443                            }
3444                            RenderErrorAction::Fatal => {
3445                                failure = Some(UiAppError::Render(err.to_string()));
3446                            }
3447                        },
3448                    }
3449                }
3450            }
3451            event => {
3452                let redraw = route_window_event(state, &event, event_id, event_timestamp);
3453                if redraw.request {
3454                    if redraw.from_route {
3455                        state.input_bench.record_route_redraw();
3456                    }
3457                    if redraw.from_dirty {
3458                        state.input_bench.record_dirty_redraw();
3459                    }
3460                    state.window.request_redraw();
3461                }
3462            }
3463        }
3464
3465        if let Some(recreation_cause) = recreate_surface {
3466            Self::trace_startup(format_args!(
3467                "rebuilding native presentation for {id:?} after {recreation_cause:?}"
3468            ));
3469            if let Some(state) = self.windows.remove(&id) {
3470                // The retained-state boundary drops the invalid surface before
3471                // the native window. Reattachment first reuses the GPU context
3472                // and rebuilds device-bound caches only when compatibility fails.
3473                #[cfg(feature = "test_support")]
3474                let logical_window_id =
3475                    ailloli_ui_core::LogicalWindowId::new(state.logical_window_id.clone());
3476                self.window_snapshots
3477                    .insert(state.logical_window_id.clone(), window_snapshot(&state));
3478                #[cfg(feature = "test_support")]
3479                let previous_generation = state.lifecycle.generation();
3480                let mut retained = detach_native_window(state);
3481                Self::mark_attachment_unavailable(
3482                    &mut retained,
3483                    PresentationUnavailableReason::SurfaceLost,
3484                );
3485                #[cfg(feature = "test_support")]
3486                {
3487                    let counters = self
3488                        .presentation_test_counters
3489                        .entry(logical_window_id.clone())
3490                        .or_default();
3491                    counters.detach_count = counters.detach_count.saturating_add(1);
3492                    match recreation_cause {
3493                        PresentationRecreationCause::Lost => {
3494                            counters.lost_count = counters.lost_count.saturating_add(1);
3495                        }
3496                        PresentationRecreationCause::Outdated => {
3497                            counters.outdated_count = counters.outdated_count.saturating_add(1);
3498                        }
3499                        PresentationRecreationCause::ReconfigureFailed => {}
3500                    }
3501                }
3502                match self.attach_retained_window(event_loop, retained) {
3503                    Ok(attached) => {
3504                        #[cfg(feature = "test_support")]
3505                        {
3506                            let next_generation = match &attached {
3507                                AttachedWindow::Native(_, state) => state.lifecycle.generation(),
3508                                #[cfg(all(target_os = "linux", feature = "native_overlay"))]
3509                                AttachedWindow::WaylandOverlay(state) => {
3510                                    state.lifecycle.generation()
3511                                }
3512                            };
3513                            if next_generation > previous_generation {
3514                                self.presentation_test_counters
3515                                    .entry(logical_window_id)
3516                                    .or_default()
3517                                    .recovery_count += 1;
3518                            }
3519                        }
3520                        self.store_attached_window(attached);
3521                    }
3522                    Err(attachment_error) => {
3523                        let (retained, error) = *attachment_error;
3524                        eprintln!(
3525                            "ailloli_ui_winit: surface recovery deferred; retained UI state remains available: {error}"
3526                        );
3527                        self.retained_windows.push(retained);
3528                    }
3529                }
3530            }
3531        }
3532
3533        self.drain_window_chrome_ops();
3534
3535        if let Some(error) = failure {
3536            self.fail(event_loop, error);
3537        }
3538    }
3539
3540    /// Handles the payload-free native wake callback delegated by [`crate::WinitHost`].
3541    ///
3542    /// The unit payload carries no work itself. On Linux Wayland it drains
3543    /// overlay configure/close/redraw state; other queued subsystems are serviced
3544    /// by the host immediately after this callback.
3545    ///
3546    /// # Examples
3547    ///
3548    /// ```
3549    /// let app = ailloli_ui_winit::UiApp::<()>::new();
3550    /// assert!(app.error().is_none());
3551    /// ```
3552    pub(crate) fn host_user_event(&mut self, _event_loop: &ActiveEventLoop, _event: ()) {
3553        #[cfg(all(target_os = "linux", feature = "native_overlay"))]
3554        self.service_wayland_overlays(_event_loop);
3555    }
3556}
3557
3558/// Runs one GPU capture pass; returns `true` if capture render succeeded (already presented).
3559///
3560/// All same-window requests share one full-frame GPU readback; PNG generation is
3561/// enabled if any request needs it, then stripped per request. Element bounds
3562/// snap outward to physical pixels. A readback failure fails every request and
3563/// returns `false`, allowing the ordinary render path to run.
3564fn process_capture_requests<A: 'static>(
3565    state: &mut WindowState<A>,
3566    cap: &CaptureHandle,
3567    pending: Vec<CaptureRequest>,
3568    passes: &[LayerPass<'_>],
3569) -> bool {
3570    if pending.is_empty() {
3571        return false;
3572    }
3573    let merged = CaptureParams {
3574        encode_png: pending.iter().any(|r| r.params.encode_png),
3575    };
3576    let full_frame = match state.renderer.render_layered_capture_once_scaled(
3577        state.clear,
3578        passes,
3579        state.scale,
3580        merged,
3581    ) {
3582        Ok(f) => f,
3583        Err(e) => {
3584            let err = CaptureError::Render(e.to_string());
3585            for req in pending {
3586                cap.fail(req, err.clone());
3587            }
3588            return false;
3589        }
3590    };
3591
3592    for req in pending {
3593        match &req.target {
3594            CaptureTarget::Window { .. } => {
3595                let mut frame = full_frame.clone();
3596                frame = strip_png_if_disabled(frame, req.params.encode_png);
3597                cap.complete(CaptureResult {
3598                    request: req,
3599                    frame,
3600                    bounds_px: None,
3601                });
3602            }
3603            CaptureTarget::Element {
3604                window_id,
3605                key: key_owned,
3606            } => {
3607                let window_id = window_id.clone();
3608                let key_owned = key_owned.clone();
3609                match state
3610                    .runtime
3611                    .tree
3612                    .resolve_element_by_view_key(key_owned.as_str())
3613                {
3614                    Ok(el_id) => {
3615                        if let Some(log_r) = absolute_paint_bounds(&state.runtime.tree, el_id) {
3616                            let pr = snap_rect_to_physical(log_r, state.scale);
3617                            let rect_px =
3618                                Rect::new(pr.x as f32, pr.y as f32, pr.w as f32, pr.h as f32);
3619                            match crop_captured_frame(&full_frame, rect_px, req.params.encode_png) {
3620                                Ok(frame) => {
3621                                    cap.complete(CaptureResult {
3622                                        request: req,
3623                                        frame,
3624                                        bounds_px: Some(rect_px),
3625                                    });
3626                                }
3627                                Err(e) => cap.fail(req, e),
3628                            }
3629                        } else {
3630                            cap.fail(
3631                                req,
3632                                CaptureError::ElementNotFound {
3633                                    window_id: window_id.clone(),
3634                                    key: key_owned,
3635                                },
3636                            );
3637                        }
3638                    }
3639                    Err(ViewKeyResolveError::Missing { key }) => {
3640                        cap.fail(
3641                            req,
3642                            CaptureError::ElementNotFound {
3643                                window_id: window_id.clone(),
3644                                key,
3645                            },
3646                        );
3647                    }
3648                    Err(ViewKeyResolveError::Duplicate { key, count }) => {
3649                        cap.fail(
3650                            req,
3651                            CaptureError::DuplicateElementKey {
3652                                window_id: window_id.clone(),
3653                                key,
3654                                count,
3655                            },
3656                        );
3657                    }
3658                }
3659            }
3660        }
3661    }
3662
3663    true
3664}
3665
3666#[cfg(all(target_os = "linux", feature = "native_overlay"))]
3667/// Direct-Wayland counterpart of [`process_capture_requests`].
3668///
3669/// One scaled full-frame readback serves all pending full/element requests with
3670/// identical lookup, crop, PNG, listener, and failure semantics.
3671fn process_wayland_overlay_capture_requests<A: 'static>(
3672    state: &mut WaylandOverlayState<A>,
3673    cap: &CaptureHandle,
3674    pending: Vec<CaptureRequest>,
3675    passes: &[LayerPass<'_>],
3676) -> bool {
3677    if pending.is_empty() {
3678        return false;
3679    }
3680    let merged = CaptureParams {
3681        encode_png: pending.iter().any(|request| request.params.encode_png),
3682    };
3683    let full_frame = match state.renderer.render_layered_capture_once_scaled(
3684        state.clear,
3685        passes,
3686        state.scale,
3687        merged,
3688    ) {
3689        Ok(frame) => frame,
3690        Err(error) => {
3691            let error = CaptureError::Render(error.to_string());
3692            for request in pending {
3693                cap.fail(request, error.clone());
3694            }
3695            return false;
3696        }
3697    };
3698
3699    for request in pending {
3700        let target = request.target.clone();
3701        match target {
3702            CaptureTarget::Window { .. } => {
3703                let frame = strip_png_if_disabled(full_frame.clone(), request.params.encode_png);
3704                cap.complete(CaptureResult {
3705                    request,
3706                    frame,
3707                    bounds_px: None,
3708                });
3709            }
3710            CaptureTarget::Element { window_id, key } => {
3711                match state.runtime.tree.resolve_element_by_view_key(key.as_str()) {
3712                    Ok(element_id) => {
3713                        if let Some(logical_bounds) =
3714                            absolute_paint_bounds(&state.runtime.tree, element_id)
3715                        {
3716                            let physical_bounds =
3717                                snap_rect_to_physical(logical_bounds, state.scale);
3718                            let rect_px = Rect::new(
3719                                physical_bounds.x as f32,
3720                                physical_bounds.y as f32,
3721                                physical_bounds.w as f32,
3722                                physical_bounds.h as f32,
3723                            );
3724                            match crop_captured_frame(
3725                                &full_frame,
3726                                rect_px,
3727                                request.params.encode_png,
3728                            ) {
3729                                Ok(frame) => cap.complete(CaptureResult {
3730                                    request,
3731                                    frame,
3732                                    bounds_px: Some(rect_px),
3733                                }),
3734                                Err(error) => cap.fail(request, error),
3735                            }
3736                        } else {
3737                            cap.fail(
3738                                request,
3739                                CaptureError::ElementNotFound {
3740                                    window_id: window_id.clone(),
3741                                    key,
3742                                },
3743                            );
3744                        }
3745                    }
3746                    Err(ViewKeyResolveError::Missing { key }) => {
3747                        cap.fail(request, CaptureError::ElementNotFound { window_id, key })
3748                    }
3749                    Err(ViewKeyResolveError::Duplicate { key, count }) => cap.fail(
3750                        request,
3751                        CaptureError::DuplicateElementKey {
3752                            window_id,
3753                            key,
3754                            count,
3755                        },
3756                    ),
3757                }
3758            }
3759        }
3760    }
3761    true
3762}
3763
3764/// Lays out the retained tree against the current non-zero logical client extent.
3765///
3766/// Zero or negative logical dimensions skip layout without clearing prior geometry.
3767fn layout_window<A: 'static>(state: &mut WindowState<A>) {
3768    let physical = state.window.inner_size();
3769    let logical_w = to_logical_f32(physical.width as f32, state.scale);
3770    let logical_h = to_logical_f32(physical.height as f32, state.scale);
3771    if logical_w <= 0.0 || logical_h <= 0.0 {
3772        return;
3773    }
3774    let constraints = Constraints::tight(logical_w, logical_h);
3775
3776    let retained = &mut state.retained;
3777    let scale = retained.scale;
3778    retained
3779        .runtime
3780        .layout(constraints, scale, &mut retained.text_system);
3781}
3782
3783/// Paints owner and popup trees for one presentation-scoped frame.
3784///
3785/// Pending popup/input intents are applied before owner paint, procedural popup
3786/// geometry is resolved afterward, and owner paint repeats only when resulting
3787/// focus/mount changes require it. Popup layers are appended last.
3788fn paint_retained_window<A: 'static>(
3789    retained: &mut RetainedWindowState<A>,
3790    popup_viewport: Rect,
3791    frame_time_ms: u128,
3792) -> ailloli_ui_runtime::Scene {
3793    let logical_window_id =
3794        ailloli_ui_core::LogicalWindowId::new(retained.logical_window_id.clone());
3795    let presentation_generation = retained.presentation_generation;
3796    let runtime_handle = retained.runtime.runtime.clone();
3797    runtime_handle.set_presentation_scope(logical_window_id.clone(), presentation_generation);
3798    runtime_handle.close_stale_popup_presentations(&logical_window_id, presentation_generation);
3799    retained.popup_mounts.apply_pending_popup_intents();
3800    retained.input.apply_pending_popup_intents_for_presentation(
3801        &retained.runtime.tree,
3802        runtime_handle.clone(),
3803        &logical_window_id,
3804        presentation_generation,
3805    );
3806    blur_owner_for_focused_popup(retained);
3807
3808    let input = retained.input.snapshot();
3809    let mut scene =
3810        retained
3811            .runtime
3812            .paint_with_input(&mut retained.text_system, input, frame_time_ms);
3813
3814    // Procedural widgets publish their authoritative popup geometry while the
3815    // owner tree paints. Retained popup requests can then reconcile, layout,
3816    // and append their own persistent overlay trees in the same frame.
3817    retained.popup_mounts.resolve_and_sync(
3818        &logical_window_id,
3819        presentation_generation,
3820        popup_viewport,
3821        crate::popup_backend_capabilities(),
3822    );
3823    retained
3824        .popup_mounts
3825        .layout(retained.scale, &mut retained.text_system);
3826    let popup_intents_changed = retained.popup_mounts.apply_pending_popup_intents();
3827    let owner_intents_changed = retained.input.apply_pending_popup_intents_for_presentation(
3828        &retained.runtime.tree,
3829        runtime_handle,
3830        &logical_window_id,
3831        presentation_generation,
3832    );
3833    let owner_blurred = blur_owner_for_focused_popup(retained);
3834    if popup_intents_changed || owner_intents_changed || owner_blurred {
3835        let input = retained.input.snapshot();
3836        scene = retained
3837            .runtime
3838            .paint_with_input(&mut retained.text_system, input, frame_time_ms);
3839    }
3840    retained
3841        .popup_mounts
3842        .append_to_scene(&mut scene, &mut retained.text_system, frame_time_ms);
3843    scene
3844}
3845
3846/// Blurs owner-tree focus when a mounted popup owns focus; returns whether state changed.
3847fn blur_owner_for_focused_popup<A: 'static>(retained: &mut RetainedWindowState<A>) -> bool {
3848    if !retained.popup_mounts.has_focus() {
3849        return false;
3850    }
3851    retained
3852        .input
3853        .blur_tree(&retained.runtime.tree, retained.runtime.runtime.clone())
3854}
3855
3856/// Converts the current physical client extent to a zero-origin logical viewport.
3857fn window_viewport_logical<A>(state: &WindowState<A>) -> Rect {
3858    let physical = state.window.inner_size();
3859    Rect::new(
3860        0.0,
3861        0.0,
3862        to_logical_f32(physical.width as f32, state.scale),
3863        to_logical_f32(physical.height as f32, state.scale),
3864    )
3865}
3866
3867/// Samples a persistable logical window snapshot from native state.
3868///
3869/// Scale factor is floored to one. Unsupported outer-position queries yield
3870/// `None`; client size is always present, including zero dimensions.
3871fn window_snapshot<A>(state: &WindowState<A>) -> WindowSnapshot {
3872    let physical = state.window.inner_size();
3873    let scale_factor = state.window.scale_factor().max(1.0);
3874    let inner_size = Some(LogicalWindowSize::new(
3875        physical.width as f64 / scale_factor,
3876        physical.height as f64 / scale_factor,
3877    ));
3878    let position = state
3879        .window
3880        .outer_position()
3881        .ok()
3882        .map(|position: PhysicalPosition<i32>| {
3883            LogicalWindowPosition::new(
3884                position.x as f64 / scale_factor,
3885                position.y as f64 / scale_factor,
3886            )
3887        });
3888    WindowSnapshot {
3889        window_id: state.logical_window_id.clone(),
3890        inner_size,
3891        maximized: state.window.is_maximized(),
3892        fullscreen: state.window.fullscreen().is_some(),
3893        position,
3894    }
3895}
3896
3897/// Counts text commands across all layers for benchmark metadata.
3898///
3899/// Per-layer `usize` counts truncate to `u32` and the final debug sum may
3900/// overflow only for infeasibly large scenes.
3901fn count_draw_text_cmds(scene: &ailloli_ui_runtime::Scene) -> u32 {
3902    scene
3903        .layers
3904        .iter()
3905        .map(|layer| {
3906            layer
3907                .cmds
3908                .iter()
3909                .filter(|cmd| matches!(cmd, ailloli_ui_runtime::DrawCmd::Text(_)))
3910                .count() as u32
3911        })
3912        .sum()
3913}
3914
3915/// Borrows every scene layer into renderer passes while preserving order and effects.
3916fn scene_to_layer_passes(scene: &ailloli_ui_runtime::Scene) -> Vec<LayerPass<'_>> {
3917    scene
3918        .layers
3919        .iter()
3920        .map(|layer| {
3921            LayerPass::from_scene_layer(
3922                layer.cmds.as_slice(),
3923                layer.clip.clone(),
3924                layer.isolated,
3925                layer.isolated_depth,
3926                layer.effects,
3927            )
3928        })
3929        .collect()
3930}
3931
3932/// Decides whether a retained-work sweep may ask a live native window to draw.
3933///
3934/// Dirty runtime work stays queued while a zero extent or timed retry prevents
3935/// rendering. A non-zero resize waiting after zero extent is allowed through so
3936/// the normal redraw path can reconfigure the surface and advance lifecycle.
3937fn native_presentation_accepts_retained_redraw(
3938    lifecycle: PresentationState,
3939    resize: &ResizeController,
3940    render_retry_at: Option<Instant>,
3941) -> bool {
3942    if render_retry_at.is_some() || !resize.accepts_retained_redraw_request() {
3943        return false;
3944    }
3945    match lifecycle {
3946        PresentationState::Ready => true,
3947        PresentationState::Unavailable(PresentationUnavailableReason::ZeroExtent) => {
3948            resize.has_pending_nonzero_request()
3949        }
3950        _ => false,
3951    }
3952}
3953
3954/// Classifies timeout as retry, recoverable surface errors as reconfigure, and all else fatal.
3955fn render_error_action(error: &RendererError) -> RenderErrorAction {
3956    match error {
3957        RendererError::SurfaceAcquireTimeout => {
3958            RenderErrorAction::RetryFrame(RENDER_TIMEOUT_RETRY_BASE_DELAY)
3959        }
3960        RendererError::SurfaceAcquireLost | RendererError::SurfaceAcquireOutdated => {
3961            RenderErrorAction::ReconfigureSurface
3962        }
3963        RendererError::SurfaceConfigFailed | RendererError::SurfaceRecreationRequired(_) => {
3964            RenderErrorAction::ReconfigureSurface
3965        }
3966        RendererError::SurfaceAcquireOutOfMemory => RenderErrorAction::Fatal,
3967        _ => RenderErrorAction::Fatal,
3968    }
3969}
3970
3971/// Preserves lost/outdated diagnosis and groups every other recreate path as configure failure.
3972fn presentation_recreation_cause(error: &RendererError) -> PresentationRecreationCause {
3973    match error {
3974        RendererError::SurfaceAcquireLost => PresentationRecreationCause::Lost,
3975        RendererError::SurfaceAcquireOutdated => PresentationRecreationCause::Outdated,
3976        _ => PresentationRecreationCause::ReconfigureFailed,
3977    }
3978}
3979
3980/// Saturating-increments the timeout streak and arms a bounded retry from now.
3981fn schedule_render_retry<A>(state: &mut WindowState<A>, min_delay: Duration) {
3982    state.render_timeout_streak = state.render_timeout_streak.saturating_add(1);
3983    let delay = render_timeout_retry_delay(state.render_timeout_streak, min_delay);
3984    state.render_retry_at = Some(Instant::now() + delay);
3985}
3986
3987/// Computes `min_delay * 2^(min(streak-1, 4))`, capped at 250 ms.
3988///
3989/// A zero streak uses factor one; [`Duration::saturating_mul`] prevents overflow.
3990fn render_timeout_retry_delay(streak: u32, min_delay: Duration) -> Duration {
3991    let shift = streak.saturating_sub(1).min(4);
3992    let factor = 1u32 << shift;
3993    let delay = min_delay.saturating_mul(factor);
3994    delay.min(RENDER_TIMEOUT_RETRY_MAX_DELAY)
3995}
3996
3997/// Best-effort emits one frame timing event with window/surface/generation context.
3998///
3999/// Disabled benchmarking, frame-id exhaustion, and writer failures silently skip
4000/// recording so instrumentation never changes presentation behavior.
4001fn record_ui_frame_metrics(
4002    logical_window_id: &str,
4003    presentation_generation: PresentationGeneration,
4004    layout_us: u128,
4005    paint_us: u128,
4006    render_us: u128,
4007    draw_text_cmds: u32,
4008) {
4009    if !InputBenchCounters::metrics_enabled() {
4010        return;
4011    }
4012    let Ok(Some(frame_id)) = ailloli_ui_bench::try_allocate_frame_id() else {
4013        return;
4014    };
4015    let context = ailloli_ui_bench::EventContext::default()
4016        .with_frame(frame_id)
4017        .with_window(ailloli_ui_bench::BenchWindowId::new(logical_window_id))
4018        .with_surface(
4019            ailloli_ui_bench::BenchSurfaceId::new(logical_window_id),
4020            presentation_generation.get(),
4021        );
4022    let _ = ailloli_ui_bench::try_record(
4023        ailloli_ui_bench::Event::TextPipelineFrame {
4024            ts_ms: now_ms(),
4025            layout_us,
4026            paint_us,
4027            render_us,
4028            draw_text_cmds,
4029        },
4030        context,
4031    );
4032}
4033
4034/// Returns whether the current root exists and has committed layout geometry.
4035fn runtime_has_root_layout<A>(runtime: &Runtime<A>) -> bool {
4036    runtime
4037        .root
4038        .and_then(|id| runtime.tree.get(id))
4039        .and_then(|el| el.layout.as_ref())
4040        .is_some()
4041}
4042
4043/// Combines presentation invalidation, missing initial layout, and runtime work plan.
4044fn frame_requires_layout(
4045    plan: FrameWorkPlan,
4046    presentation_requires_layout: bool,
4047    root_has_layout: bool,
4048) -> bool {
4049    presentation_requires_layout || !root_has_layout || plan.needs_layout()
4050}
4051
4052/// Snaps the IME cursor rect to physical pixels for stable frame-to-frame comparison (DPR included).
4053fn quantize_ime_cursor_area(rect: Rect, scale: Scale) -> PhysicalRectI32 {
4054    snap_rect_to_physical(rect, scale)
4055}
4056
4057#[derive(Clone, Copy, Default)]
4058/// Aggregates redraw need and its route-versus-dirty benchmark attribution.
4059struct RouteWindowRedraw {
4060    /// Whether native redraw should be requested.
4061    request: bool,
4062    /// Whether routing explicitly requested redraw.
4063    from_route: bool,
4064    /// Whether retained dirtiness required redraw.
4065    from_dirty: bool,
4066}
4067
4068/// Returns laid-out root paint bounds or the full logical client rectangle fallback.
4069fn root_client_bounds_logical<A>(state: &WindowState<A>) -> Rect {
4070    let physical = state.window.inner_size();
4071    let logical_w = to_logical_f32(physical.width as f32, state.scale);
4072    let logical_h = to_logical_f32(physical.height as f32, state.scale);
4073    let fallback = Rect::new(0.0, 0.0, logical_w, logical_h);
4074    state
4075        .runtime
4076        .root
4077        .and_then(|id| absolute_paint_bounds(&state.runtime.tree, id))
4078        .unwrap_or(fallback)
4079}
4080
4081/// Maps retained hover roles to winit cursors; inherit/default share native default.
4082fn cursor_icon_for_hover_role(role: HoverCursorRole) -> CursorIcon {
4083    match role {
4084        HoverCursorRole::Pointer => CursorIcon::Pointer,
4085        HoverCursorRole::Text => CursorIcon::Text,
4086        HoverCursorRole::ResizeX => CursorIcon::from(resize_edge_to_winit(ResizeEdge::E)),
4087        HoverCursorRole::ResizeY => CursorIcon::from(resize_edge_to_winit(ResizeEdge::S)),
4088        HoverCursorRole::Inherit | HoverCursorRole::Default => CursorIcon::Default,
4089    }
4090}
4091
4092/// Chooses a client resize-edge cursor before the retained hovered role.
4093fn cursor_icon_for_hover_state(
4094    resize_edge: Option<ResizeEdge>,
4095    hovered_role: HoverCursorRole,
4096) -> CursorIcon {
4097    resize_edge
4098        .map(resize_edge_to_winit)
4099        .map(CursorIcon::from)
4100        .unwrap_or_else(|| cursor_icon_for_hover_role(hovered_role))
4101}
4102
4103/// Resolves native cursor priority: popup, client resize frame, then owner tree.
4104fn cursor_icon_for_pointer_state<A: 'static>(state: &WindowState<A>, pos: Point) -> CursorIcon {
4105    if let Some(role) = state
4106        .retained
4107        .popup_mounts
4108        .hovered_cursor_role_at_global(pos)
4109    {
4110        return cursor_icon_for_hover_role(role);
4111    }
4112    let resize_edge = if state.client_edge_resize {
4113        let bounds = root_client_bounds_logical(state);
4114        hit_resize_frame(bounds, CLIENT_RESIZE_BORDER_LOGICAL_PX, pos, true)
4115    } else {
4116        None
4117    };
4118    cursor_icon_for_hover_state(
4119        resize_edge,
4120        state.input.hovered_cursor_role_at(&state.runtime.tree, pos),
4121    )
4122}
4123
4124/// Resolves retained cursor intent with the same popup/resize/owner priority.
4125///
4126/// Provider-neutral v1 has no diagonal resize cursor, so diagonals become default.
4127fn presentation_cursor_for_pointer_state<A: 'static>(
4128    state: &WindowState<A>,
4129    pos: Point,
4130) -> PresentationCursor {
4131    if let Some(role) = state
4132        .retained
4133        .popup_mounts
4134        .hovered_cursor_role_at_global(pos)
4135    {
4136        return presentation_cursor_for_hover_role(role);
4137    }
4138    if state.client_edge_resize {
4139        let bounds = root_client_bounds_logical(state);
4140        match hit_resize_frame(bounds, CLIENT_RESIZE_BORDER_LOGICAL_PX, pos, true) {
4141            Some(ResizeEdge::E | ResizeEdge::W) => return PresentationCursor::ResizeX,
4142            Some(ResizeEdge::N | ResizeEdge::S) => return PresentationCursor::ResizeY,
4143            Some(ResizeEdge::NE | ResizeEdge::NW | ResizeEdge::SE | ResizeEdge::SW) => {
4144                // The provider-neutral v1 cursor contract has no diagonal role.
4145                return PresentationCursor::Default;
4146            }
4147            None => {}
4148        }
4149    }
4150    presentation_cursor_for_hover_role(state.input.hovered_cursor_role_at(&state.runtime.tree, pos))
4151}
4152
4153/// Maps a retained hover role into the provider-neutral cursor contract.
4154fn presentation_cursor_for_hover_role(role: HoverCursorRole) -> PresentationCursor {
4155    match role {
4156        HoverCursorRole::Pointer => PresentationCursor::Pointer,
4157        HoverCursorRole::Text => PresentationCursor::Text,
4158        HoverCursorRole::ResizeX => PresentationCursor::ResizeX,
4159        HoverCursorRole::ResizeY => PresentationCursor::ResizeY,
4160        HoverCursorRole::Inherit | HoverCursorRole::Default => PresentationCursor::Default,
4161    }
4162}
4163
4164/// Returns whether an open popup must see this pointer press before native
4165/// titlebar/resize gestures are considered.
4166///
4167/// Native chrome handling runs outside the element router. Without this gate,
4168/// an outside press intended to dismiss a menu could start moving or resizing
4169/// the window before the popup portal consumes the gesture.
4170fn popup_blocks_native_window_gesture<A: 'static>(state: &WindowState<A>, event: &Event) -> bool {
4171    if !matches!(
4172        event,
4173        Event::Pointer(PointerEvent::Button { pressed: true, .. })
4174    ) {
4175        return false;
4176    }
4177
4178    let logical_window_id =
4179        ailloli_ui_core::LogicalWindowId::new(state.retained.logical_window_id.clone());
4180    let portal = state.runtime.runtime.popup_portal();
4181    let portal = portal.borrow();
4182    let blocked = portal.open_ids().rev().any(|popup_id| {
4183        portal.request(popup_id).is_some_and(|request| {
4184            request
4185                .owner()
4186                .belongs_to(&logical_window_id, state.presentation_generation)
4187                && (request.semantics().consumes_pointer_input()
4188                    || request.semantics().dismisses_on_outside_press())
4189        })
4190    });
4191    blocked
4192}
4193
4194/// Starts native client-edge resize for a primary press in the five-pixel frame.
4195///
4196/// Popup-owning presses are filtered by the caller. Native gesture errors are
4197/// trace-only; the event is considered handled once an edge matched.
4198fn handle_client_edge_resize_input<A: 'static>(
4199    state: &mut WindowState<A>,
4200    event: &Event,
4201) -> Option<RouteWindowRedraw> {
4202    match event {
4203        Event::Pointer(PointerEvent::Moved { .. }) => None,
4204        Event::Pointer(PointerEvent::Button {
4205            pos,
4206            button: MouseButton::Left,
4207            pressed: true,
4208            ..
4209        }) => {
4210            let bounds = root_client_bounds_logical(state);
4211            if let Some(edge) =
4212                hit_resize_frame(bounds, CLIENT_RESIZE_BORDER_LOGICAL_PX, *pos, true)
4213            {
4214                if let Err(e) = state.window.drag_resize_window(resize_edge_to_winit(edge)) {
4215                    if crate::winit_trace_enabled() {
4216                        eprintln!("ailloli_ui_winit: drag_resize_window: {e}");
4217                    }
4218                }
4219                let from_dirty = state.runtime.runtime.has_dirty_elements();
4220                return Some(RouteWindowRedraw {
4221                    request: from_dirty,
4222                    from_route: false,
4223                    from_dirty,
4224                });
4225            }
4226            None
4227        }
4228        _ => None,
4229    }
4230}
4231
4232/// Requires undecorated client title row and explicit draggable policy.
4233fn client_titlebar_drag_enabled(options: &WindowOptions) -> bool {
4234    !options.decorations && options.has_client_title_row && options.titlebar_draggable
4235}
4236
4237/// Resolves configured/legacy title-row bounds for one live window.
4238fn titlebar_row_bounds_logical<A>(state: &WindowState<A>) -> Option<Rect> {
4239    client_titlebar_bounds_logical(
4240        &state.runtime.tree,
4241        state.runtime.root,
4242        state.client_titlebar_key.as_deref(),
4243    )
4244}
4245
4246/// Resolves an exact keyed title row, falling back to legacy structure only when missing.
4247///
4248/// Duplicate configured keys disable dragging rather than choosing ambiguously.
4249fn client_titlebar_bounds_logical<A>(
4250    tree: &ElementTree<A>,
4251    root_id: Option<ElementId>,
4252    client_titlebar_key: Option<&str>,
4253) -> Option<Rect> {
4254    if let Some(key) = client_titlebar_key {
4255        match tree.resolve_element_by_view_key(key) {
4256            Ok(title_id) => return absolute_paint_bounds(tree, title_id),
4257            Err(ViewKeyResolveError::Missing { .. }) => {}
4258            Err(ViewKeyResolveError::Duplicate { .. }) => return None,
4259        }
4260    }
4261
4262    let title_id = legacy_client_titlebar_id(tree, root_id?)?;
4263    absolute_paint_bounds(tree, title_id)
4264}
4265
4266/// Finds the first title child, skipping a single-child window-root clip wrapper.
4267fn legacy_client_titlebar_id<A>(tree: &ElementTree<A>, root_id: ElementId) -> Option<ElementId> {
4268    let root = tree.get(root_id)?;
4269    if root
4270        .layout
4271        .as_ref()
4272        .is_some_and(|layout| layout.is_window_root_clip)
4273        && root.children.len() == 1
4274    {
4275        let inner = tree.get(root.children[0])?;
4276        return inner.children.first().copied();
4277    }
4278    root.children.first().copied()
4279}
4280
4281/// Returns whether the hit or any ancestor is focusable or owns a non-empty input role.
4282fn hit_ancestor_blocks_titlebar_drag<A: 'static>(
4283    tree: &ailloli_ui_runtime::element::ElementTree<A>,
4284    mut id: ElementId,
4285) -> bool {
4286    loop {
4287        if let Some(el) = tree.get(id) {
4288            if let ElementKind::Widget(w) = &el.kind {
4289                if w.focus_policy() == FocusPolicy::Focusable || w.input_role() != InputRole::None {
4290                    return true;
4291                }
4292            }
4293        }
4294        match tree.parent_of(id) {
4295            Some(p) => id = p,
4296            None => return false,
4297        }
4298    }
4299}
4300
4301/// Starts a native window drag for an unobstructed primary title-row press.
4302///
4303/// Interactive descendants block the gesture. Native drag failure is trace-only;
4304/// once eligible, the event returns a redraw decision based on retained dirtiness.
4305fn handle_client_titlebar_drag_press<A: 'static>(
4306    state: &mut WindowState<A>,
4307    event: &Event,
4308) -> Option<RouteWindowRedraw> {
4309    if !state.client_titlebar_drag {
4310        return None;
4311    }
4312    let Event::Pointer(PointerEvent::Button {
4313        pos,
4314        button: MouseButton::Left,
4315        pressed: true,
4316        ..
4317    }) = event
4318    else {
4319        return None;
4320    };
4321
4322    let title_bounds = titlebar_row_bounds_logical(state)?;
4323    if !hit_window_drag_region(title_bounds, *pos, true) {
4324        return None;
4325    }
4326    let hit = hit_test_target(&state.runtime.tree, &state.input.hit_test, *pos, None);
4327    if let Some(h) = hit {
4328        if hit_ancestor_blocks_titlebar_drag(&state.runtime.tree, h) {
4329            return None;
4330        }
4331    }
4332    if let Err(e) = state.window.drag_window() {
4333        if crate::winit_trace_enabled() {
4334            eprintln!("ailloli_ui_winit: drag_window: {e}");
4335        }
4336    }
4337    let from_dirty = state.runtime.runtime.has_dirty_elements();
4338    Some(RouteWindowRedraw {
4339        request: from_dirty,
4340        from_route: false,
4341        from_dirty,
4342    })
4343}
4344
4345/// Routes a generation-scoped event through popup portals before the owner tree.
4346///
4347/// Popup mounts and focus intents synchronize both before and after routing.
4348/// Popup consumption suppresses owner routing while preserving interaction and
4349/// dispatch flags. Any mount/focus change contributes to `interaction_changed`.
4350fn route_retained_envelope<A: 'static>(
4351    retained: &mut RetainedWindowState<A>,
4352    envelope: &EventEnvelope,
4353) -> ailloli_ui_runtime::input::RouteOutcome {
4354    let logical_window_id =
4355        ailloli_ui_core::LogicalWindowId::new(retained.logical_window_id.clone());
4356    let presentation_generation = retained.presentation_generation;
4357    let runtime_handle = retained.runtime.runtime.clone();
4358    runtime_handle.set_presentation_scope(logical_window_id.clone(), presentation_generation);
4359    runtime_handle.close_stale_popup_presentations(&logical_window_id, presentation_generation);
4360    let sync_before = retained
4361        .popup_mounts
4362        .sync(&logical_window_id, presentation_generation);
4363    let popup_intents_before = retained.popup_mounts.apply_pending_popup_intents();
4364    let owner_intents_before = retained.input.apply_pending_popup_intents_for_presentation(
4365        &retained.runtime.tree,
4366        runtime_handle.clone(),
4367        &logical_window_id,
4368        presentation_generation,
4369    );
4370    let owner_blurred_before = blur_owner_for_focused_popup(retained);
4371    let popup_outcome = retained.popup_mounts.route_envelope(envelope);
4372    let mut outcome = if popup_outcome.consumed() {
4373        popup_outcome.route().clone()
4374    } else {
4375        let mut outcome =
4376            retained
4377                .input
4378                .route_envelope(&retained.runtime.tree, runtime_handle.clone(), envelope);
4379        outcome.interaction_changed |= popup_outcome.route().interaction_changed;
4380        outcome.event_dispatched |= popup_outcome.route().event_dispatched;
4381        outcome
4382    };
4383    let sync_after = retained
4384        .popup_mounts
4385        .sync(&logical_window_id, presentation_generation);
4386    let popup_intents_after = retained.popup_mounts.apply_pending_popup_intents();
4387    let owner_intents_after = retained.input.apply_pending_popup_intents_for_presentation(
4388        &retained.runtime.tree,
4389        runtime_handle,
4390        &logical_window_id,
4391        presentation_generation,
4392    );
4393    let owner_blurred_after = blur_owner_for_focused_popup(retained);
4394    outcome.interaction_changed |= sync_before.changed()
4395        || sync_after.changed()
4396        || popup_intents_before
4397        || owner_intents_before
4398        || owner_blurred_before
4399        || popup_intents_after
4400        || owner_intents_after
4401        || owner_blurred_after;
4402    outcome
4403}
4404
4405/// Translates and routes one supported winit input event, returning redraw attribution.
4406///
4407/// Devtools has first refusal. Initial layout precedes hit testing; popup gestures
4408/// precede native resize/title drag; IME and cursor state update after retained routing.
4409fn route_window_event<A: 'static>(
4410    state: &mut WindowState<A>,
4411    event: &WindowEvent,
4412    event_id: EventId,
4413    event_timestamp: EventTimestamp,
4414) -> RouteWindowRedraw {
4415    if matches!(event, WindowEvent::KeyboardInput { .. }) {
4416        state.input_bench.record_keyboard();
4417    }
4418    if let WindowEvent::Ime(ime) = event {
4419        state.input_bench.record_ime(ime);
4420    }
4421
4422    let Some((event, pointer_sample)) = translate_window_event(state, event) else {
4423        return RouteWindowRedraw::default();
4424    };
4425
4426    let mut event_meta = EventMeta::new(
4427        event_id,
4428        event_timestamp,
4429        state.logical_window_id.as_str(),
4430        state.presentation_generation,
4431    );
4432    if let Some(pointer_sample) = pointer_sample {
4433        event_meta = event_meta.with_pointer(pointer_sample);
4434    }
4435    let envelope = EventEnvelope::new(event_meta, event.clone());
4436
4437    #[cfg(feature = "devtools")]
4438    if state.devtools.handle_event(&event) {
4439        return RouteWindowRedraw {
4440            request: true,
4441            from_route: true,
4442            from_dirty: false,
4443        };
4444    }
4445
4446    if !runtime_has_root_layout(&state.runtime) {
4447        let layout_start = Instant::now();
4448        layout_window(state);
4449        state
4450            .input_bench
4451            .record_layout_before_event_us(layout_start.elapsed().as_micros());
4452    }
4453
4454    let popup_owns_press = popup_blocks_native_window_gesture(state, &event);
4455    if state.client_edge_resize && !popup_owns_press {
4456        if let Some(r) = handle_client_edge_resize_input(state, &event) {
4457            return r;
4458        }
4459    }
4460
4461    if !popup_owns_press {
4462        if let Some(r) = handle_client_titlebar_drag_press(state, &event) {
4463            return r;
4464        }
4465    }
4466
4467    let route_start = Instant::now();
4468    let outcome = route_retained_envelope(&mut state.retained, &envelope);
4469    state
4470        .input_bench
4471        .record_route_event_us(route_start.elapsed().as_micros());
4472
4473    if should_update_ime_after_event(&event, &outcome) {
4474        update_ime_state(state);
4475    }
4476    if let Event::Pointer(PointerEvent::Moved { pos, .. }) = &event {
4477        let cursor = cursor_icon_for_pointer_state(state, *pos);
4478        let retained_cursor = presentation_cursor_for_pointer_state(state, *pos);
4479        state.retained.current_cursor = retained_cursor;
4480        state.window.set_cursor(cursor);
4481    }
4482
4483    let from_route = outcome.needs_redraw();
4484    let from_dirty = state.runtime.runtime.has_dirty_elements();
4485    RouteWindowRedraw {
4486        request: from_route || from_dirty,
4487        from_route,
4488        from_dirty,
4489    }
4490}
4491
4492/// Updates IME after interaction changes or non-keyboard/non-IME events.
4493///
4494/// Keyboard and IME events without focus/interaction changes defer cursor-area
4495/// work, avoiding redundant native calls on every keystroke.
4496fn should_update_ime_after_event(
4497    event: &Event,
4498    outcome: &ailloli_ui_runtime::input::RouteOutcome,
4499) -> bool {
4500    if outcome.interaction_changed {
4501        return true;
4502    }
4503    !matches!(event, Event::Keyboard(_) | Event::Ime(_))
4504}
4505
4506/// Converts supported winit input/file/focus events to provider-neutral form.
4507///
4508/// Modifier updates mutate state but emit no event. Mouse button/wheel events
4509/// before any cursor position are dropped. Unsupported window events return `None`.
4510fn translate_window_event<A>(
4511    state: &mut WindowState<A>,
4512    event: &WindowEvent,
4513) -> Option<(Event, Option<PointerSample>)> {
4514    match event {
4515        WindowEvent::ModifiersChanged(modifiers) => {
4516            state.modifiers = convert_modifiers(modifiers.state());
4517            None
4518        }
4519        WindowEvent::CursorMoved { position, .. } => {
4520            let pos = physical_position_to_logical(*position, state.scale);
4521            state.cursor_pos = Some(pos);
4522            Some((
4523                Event::Pointer(PointerEvent::Moved {
4524                    pos,
4525                    modifiers: state.modifiers,
4526                }),
4527                mouse_pointer_sample(pos),
4528            ))
4529        }
4530        WindowEvent::MouseInput {
4531            state: input,
4532            button,
4533            ..
4534        } => {
4535            let pos = state.cursor_pos?;
4536            Some((
4537                Event::Pointer(PointerEvent::Button {
4538                    pos,
4539                    button: convert_mouse_button(*button),
4540                    pressed: *input == ElementState::Pressed,
4541                    modifiers: state.modifiers,
4542                }),
4543                mouse_pointer_sample(pos),
4544            ))
4545        }
4546        WindowEvent::MouseWheel { delta, .. } => {
4547            let pos = state.cursor_pos?;
4548            Some((
4549                Event::Pointer(convert_wheel_event(
4550                    pos,
4551                    delta,
4552                    state.scale,
4553                    state.modifiers,
4554                )),
4555                mouse_pointer_sample(pos),
4556            ))
4557        }
4558        WindowEvent::Touch(touch) => translate_touch_event(
4559            touch,
4560            state.scale,
4561            state.modifiers,
4562            &mut state.touch_primary,
4563        )
4564        .map(|(event, sample)| (event, Some(sample))),
4565        WindowEvent::KeyboardInput { event, .. } => Some((
4566            Event::Keyboard(convert_key_event(event, state.modifiers, state.cursor_pos)),
4567            None,
4568        )),
4569        WindowEvent::Ime(ime) => convert_ime_event(ime).map(|event| (event, None)),
4570        WindowEvent::Focused(focused) => {
4571            if !*focused {
4572                state.touch_primary.clear();
4573            }
4574            Some((
4575                Event::Window(ailloli_ui_core::event::WindowEvent::Focused { focused: *focused }),
4576                None,
4577            ))
4578        }
4579        WindowEvent::HoveredFile(path) => Some((
4580            Event::File(FileEvent::Entered {
4581                pos: None,
4582                files: vec![ailloli_ui_core::UploadFile::from_path(path.clone())],
4583            }),
4584            None,
4585        )),
4586        WindowEvent::HoveredFileCancelled => Some((Event::File(FileEvent::Left), None)),
4587        WindowEvent::DroppedFile(path) => Some((
4588            Event::File(FileEvent::Dropped {
4589                pos: None,
4590                files: vec![ailloli_ui_core::UploadFile::from_path(path.clone())],
4591            }),
4592            None,
4593        )),
4594        _ => None,
4595    }
4596}
4597
4598/// Builds the always-primary reserved mouse pointer sample.
4599fn mouse_pointer_sample(pos: Point) -> Option<PointerSample> {
4600    PointerSample::new_with_primary(PointerId::MOUSE, PointerSource::Mouse, pos, true).ok()
4601}
4602
4603/// Converts one native touch to a left-button/move/cancel event plus touch sample.
4604///
4605/// Touch ids are offset by one with saturation to avoid the reserved mouse id;
4606/// the two largest native ids therefore collide at `u64::MAX`. Finite normalized
4607/// pressure clamps to `[0, 1]`; invalid pointer/sample data drops the event.
4608fn translate_touch_event(
4609    touch: &winit::event::Touch,
4610    scale: Scale,
4611    modifiers: Modifiers,
4612    primary: &mut TouchPrimaryTracker,
4613) -> Option<(Event, PointerSample)> {
4614    let pos = physical_position_to_logical(touch.location, scale);
4615    let pointer_id = PointerId::new(touch.id.saturating_add(1));
4616    let mut sample =
4617        PointerSample::new_with_primary(pointer_id, PointerSource::Touch, pos, false).ok()?;
4618    sample = sample.with_primary(primary.classify(touch.id, touch.phase));
4619    if let Some(force) = touch.force {
4620        let pressure = force.normalized() as f32;
4621        if pressure.is_finite() {
4622            sample = sample.with_pressure(pressure.clamp(0.0, 1.0)).ok()?;
4623        }
4624    }
4625    let pointer = match touch.phase {
4626        TouchPhase::Started => PointerEvent::Button {
4627            pos,
4628            button: MouseButton::Left,
4629            pressed: true,
4630            modifiers,
4631        },
4632        TouchPhase::Moved => PointerEvent::Moved { pos, modifiers },
4633        TouchPhase::Ended => PointerEvent::Button {
4634            pos,
4635            button: MouseButton::Left,
4636            pressed: false,
4637            modifiers,
4638        },
4639        TouchPhase::Cancelled => PointerEvent::Cancelled { pos, modifiers },
4640    };
4641    Some((Event::Pointer(pointer), sample))
4642}
4643
4644/// Converts physical `f64` coordinates through lossy `f32` and the normalized scale.
4645fn physical_position_to_logical(position: PhysicalPosition<f64>, scale: Scale) -> Point {
4646    Point::new(
4647        to_logical_f32(position.x as f32, scale),
4648        to_logical_f32(position.y as f32, scale),
4649    )
4650}
4651
4652/// Maps control, alt, shift, and platform super to provider-neutral booleans.
4653fn convert_modifiers(modifiers: ModifiersState) -> Modifiers {
4654    Modifiers {
4655        ctrl: modifiers.control_key(),
4656        alt: modifiers.alt_key(),
4657        shift: modifiers.shift_key(),
4658        meta: modifiers.super_key(),
4659    }
4660}
4661
4662/// Preserves logical key, press/release, repeat, text, modifiers, and last mouse position.
4663fn convert_key_event(
4664    event: &winit::event::KeyEvent,
4665    modifiers: Modifiers,
4666    pointer_pos: Option<Point>,
4667) -> KeyEvent {
4668    KeyEvent {
4669        state: if event.state == ElementState::Pressed {
4670            KeyState::Pressed
4671        } else {
4672            KeyState::Released
4673        },
4674        key: convert_key(&event.logical_key),
4675        modifiers,
4676        repeat: event.repeat,
4677        pointer_pos,
4678        text: event.text.as_ref().map(|text| text.to_string()),
4679    }
4680}
4681
4682/// Converts named, character, dead, and unidentified logical keys without physical codes.
4683fn convert_key(key: &WinitKey) -> Key {
4684    match key {
4685        WinitKey::Named(named) => Key::Named(convert_named_key(named)),
4686        WinitKey::Character(ch) => Key::Character(ch.to_string()),
4687        WinitKey::Dead(dead) => Key::Dead(dead.as_ref().map(|text| text.to_string())),
4688        WinitKey::Unidentified(_) => Key::Unidentified,
4689    }
4690}
4691
4692/// Maps editing/navigation and F1-F24 keys; all other names use debug-text `Other`.
4693fn convert_named_key(key: &WinitNamedKey) -> NamedKey {
4694    match key {
4695        WinitNamedKey::Backspace => NamedKey::Backspace,
4696        WinitNamedKey::Delete => NamedKey::Delete,
4697        WinitNamedKey::Enter => NamedKey::Enter,
4698        WinitNamedKey::Tab => NamedKey::Tab,
4699        WinitNamedKey::Space => NamedKey::Space,
4700        WinitNamedKey::ArrowLeft => NamedKey::ArrowLeft,
4701        WinitNamedKey::ArrowRight => NamedKey::ArrowRight,
4702        WinitNamedKey::ArrowUp => NamedKey::ArrowUp,
4703        WinitNamedKey::ArrowDown => NamedKey::ArrowDown,
4704        WinitNamedKey::Home => NamedKey::Home,
4705        WinitNamedKey::End => NamedKey::End,
4706        WinitNamedKey::PageUp => NamedKey::PageUp,
4707        WinitNamedKey::PageDown => NamedKey::PageDown,
4708        WinitNamedKey::Escape => NamedKey::Escape,
4709        WinitNamedKey::Insert => NamedKey::Insert,
4710        WinitNamedKey::F1 => NamedKey::F(1),
4711        WinitNamedKey::F2 => NamedKey::F(2),
4712        WinitNamedKey::F3 => NamedKey::F(3),
4713        WinitNamedKey::F4 => NamedKey::F(4),
4714        WinitNamedKey::F5 => NamedKey::F(5),
4715        WinitNamedKey::F6 => NamedKey::F(6),
4716        WinitNamedKey::F7 => NamedKey::F(7),
4717        WinitNamedKey::F8 => NamedKey::F(8),
4718        WinitNamedKey::F9 => NamedKey::F(9),
4719        WinitNamedKey::F10 => NamedKey::F(10),
4720        WinitNamedKey::F11 => NamedKey::F(11),
4721        WinitNamedKey::F12 => NamedKey::F(12),
4722        WinitNamedKey::F13 => NamedKey::F(13),
4723        WinitNamedKey::F14 => NamedKey::F(14),
4724        WinitNamedKey::F15 => NamedKey::F(15),
4725        WinitNamedKey::F16 => NamedKey::F(16),
4726        WinitNamedKey::F17 => NamedKey::F(17),
4727        WinitNamedKey::F18 => NamedKey::F(18),
4728        WinitNamedKey::F19 => NamedKey::F(19),
4729        WinitNamedKey::F20 => NamedKey::F(20),
4730        WinitNamedKey::F21 => NamedKey::F(21),
4731        WinitNamedKey::F22 => NamedKey::F(22),
4732        WinitNamedKey::F23 => NamedKey::F(23),
4733        WinitNamedKey::F24 => NamedKey::F(24),
4734        other => NamedKey::Other(format!("{other:?}")),
4735    }
4736}
4737
4738/// Preserves explicit IME lifecycle, empty preedit, commit text, and UTF-8 selection.
4739///
4740/// A preedit with an invalid UTF-8 byte selection is dropped rather than repaired.
4741fn convert_ime_event(ime: &Ime) -> Option<Event> {
4742    match ime {
4743        Ime::Enabled => Some(Event::Ime(ImeEvent::Enabled)),
4744        Ime::Preedit(text, selection) => {
4745            let preedit = ImePreedit::try_new(text.clone(), *selection).ok()?;
4746            Some(Event::Ime(ImeEvent::Preedit { preedit, pos: None }))
4747        }
4748        Ime::Commit(text) => Some(Event::Ime(ImeEvent::Commit { text: text.clone() })),
4749        Ime::Disabled => Some(Event::Ime(ImeEvent::Disabled)),
4750    }
4751}
4752
4753/// Preserves line deltas and converts physical pixel deltas to logical pixels.
4754fn convert_wheel_delta(
4755    delta: &MouseScrollDelta,
4756    scale: Scale,
4757) -> ailloli_ui_core::event::WheelDelta {
4758    match delta {
4759        MouseScrollDelta::LineDelta(x, y) => {
4760            ailloli_ui_core::event::WheelDelta::LineDelta { x: *x, y: *y }
4761        }
4762        MouseScrollDelta::PixelDelta(pos) => ailloli_ui_core::event::WheelDelta::PixelDelta {
4763            x: to_logical_f32(pos.x as f32, scale),
4764            y: to_logical_f32(pos.y as f32, scale),
4765        },
4766    }
4767}
4768
4769/// Builds a logical wheel event without discarding provider precision or modifiers.
4770fn convert_wheel_event(
4771    pos: Point,
4772    delta: &MouseScrollDelta,
4773    scale: Scale,
4774    modifiers: Modifiers,
4775) -> PointerEvent {
4776    PointerEvent::Wheel {
4777        pos,
4778        delta: convert_wheel_delta(delta, scale),
4779        modifiers,
4780        precise: matches!(delta, MouseScrollDelta::PixelDelta(_)),
4781    }
4782}
4783
4784/// Synchronizes native IME permission and quantized cursor area with focused input.
4785///
4786/// Popup focus takes precedence over owner focus. Permission changes reset blink
4787/// and cached cursor geometry. Missing cursor geometry clears the cache; identical
4788/// physical quantization skips native update. Native logical width/height clamp to one.
4789fn update_ime_state<A: 'static>(state: &mut WindowState<A>) {
4790    let popup_has_focus = state.retained.popup_mounts.has_focus();
4791    let role = if popup_has_focus {
4792        state.retained.popup_mounts.focused_input_role()
4793    } else {
4794        state.input.focused_input_role(&state.runtime.tree)
4795    };
4796    let should_allow = matches!(role, InputRole::TextSingleLine | InputRole::TextMultiLine);
4797    if state.ime_allowed != should_allow {
4798        state.window.set_ime_allowed(should_allow);
4799        state.ime_allowed = should_allow;
4800        state.next_text_blink = should_allow.then(Instant::now);
4801        state.last_ime_cursor_area = None;
4802    }
4803
4804    if !should_allow {
4805        return;
4806    }
4807
4808    let cursor_start = Instant::now();
4809    let rect = if popup_has_focus {
4810        state.retained.popup_mounts.focused_ime_cursor_rect_global()
4811    } else {
4812        state.input.focused_ime_cursor_rect(&state.runtime.tree)
4813    };
4814    state
4815        .input_bench
4816        .record_ime_cursor_rect_us(cursor_start.elapsed().as_micros());
4817    let Some(rect) = rect else {
4818        state.last_ime_cursor_area = None;
4819        return;
4820    };
4821
4822    let next_px = quantize_ime_cursor_area(rect, state.scale);
4823    if state.last_ime_cursor_area == Some(next_px) {
4824        if InputBenchCounters::metrics_enabled() {
4825            state.input_bench.ime_cursor_area_skipped += 1;
4826        }
4827        return;
4828    }
4829
4830    state.window.set_ime_cursor_area(
4831        LogicalPosition::new(rect.x as f64, rect.y as f64),
4832        LogicalSize::new(rect.w.max(1.0) as f64, rect.h.max(1.0) as f64),
4833    );
4834    state.last_ime_cursor_area = Some(next_px);
4835    if InputBenchCounters::metrics_enabled() {
4836        state.input_bench.ime_cursor_area_set += 1;
4837    }
4838}
4839
4840/// Returns Unix epoch time truncated to whole milliseconds, or zero before the epoch.
4841fn now_ms() -> u128 {
4842    SystemTime::now()
4843        .duration_since(UNIX_EPOCH)
4844        .unwrap_or_default()
4845        .as_millis()
4846}
4847
4848/// Maps standard buttons, assigning back/forward conventional other ids 4/5.
4849fn convert_mouse_button(button: winit::event::MouseButton) -> MouseButton {
4850    match button {
4851        winit::event::MouseButton::Left => MouseButton::Left,
4852        winit::event::MouseButton::Middle => MouseButton::Middle,
4853        winit::event::MouseButton::Right => MouseButton::Right,
4854        winit::event::MouseButton::Back => MouseButton::Other(4),
4855        winit::event::MouseButton::Forward => MouseButton::Other(5),
4856        winit::event::MouseButton::Other(value) => MouseButton::Other(value),
4857    }
4858}
4859
4860#[cfg(test)]
4861/// Input conversion, IME, retry, cursor/chrome, scene, persistence, and lifecycle scenarios.
4862mod tests {
4863    use super::*;
4864
4865    #[test]
4866    fn frame_work_plan_skips_layout_for_paint_but_not_layout_build_or_resize() {
4867        assert!(!frame_requires_layout(
4868            FrameWorkPlan::from_invalidation(ailloli_ui_runtime::Invalidation::Paint),
4869            false,
4870            true,
4871        ));
4872        assert!(frame_requires_layout(
4873            FrameWorkPlan::from_invalidation(ailloli_ui_runtime::Invalidation::Layout),
4874            false,
4875            true,
4876        ));
4877        assert!(frame_requires_layout(
4878            FrameWorkPlan::from_invalidation(ailloli_ui_runtime::Invalidation::Build),
4879            false,
4880            true,
4881        ));
4882        assert!(frame_requires_layout(FrameWorkPlan::none(), true, true));
4883        assert!(frame_requires_layout(FrameWorkPlan::none(), false, false));
4884    }
4885
4886    /// Creates a pressure-free physical touch fixture with a dummy device id.
4887    fn touch(id: u64, phase: TouchPhase, x: f64, y: f64) -> winit::event::Touch {
4888        winit::event::Touch {
4889            device_id: winit::event::DeviceId::dummy(),
4890            phase,
4891            location: PhysicalPosition::new(x, y),
4892            force: None,
4893            id,
4894        }
4895    }
4896
4897    #[test]
4898    fn pointer_physical_position_is_converted_to_logical() {
4899        let pos =
4900            physical_position_to_logical(PhysicalPosition::new(200.0, 100.0), Scale::new(2.0));
4901
4902        assert_eq!(pos, Point::new(100.0, 50.0));
4903    }
4904
4905    #[test]
4906    fn wheel_conversion_preserves_axes_and_logical_pixel_scale() {
4907        assert_eq!(
4908            convert_wheel_delta(&MouseScrollDelta::LineDelta(-1.5, 2.0), Scale::new(3.0)),
4909            ailloli_ui_core::event::WheelDelta::LineDelta { x: -1.5, y: 2.0 }
4910        );
4911        assert_eq!(
4912            convert_wheel_delta(
4913                &MouseScrollDelta::PixelDelta(PhysicalPosition::new(18.0, -9.0)),
4914                Scale::new(1.5),
4915            ),
4916            ailloli_ui_core::event::WheelDelta::PixelDelta { x: 12.0, y: -6.0 }
4917        );
4918    }
4919
4920    #[test]
4921    fn wheel_event_preserves_modifiers_and_marks_only_pixel_input_precise() {
4922        let modifiers = Modifiers {
4923            shift: true,
4924            ctrl: true,
4925            ..Modifiers::default()
4926        };
4927        let pos = Point::new(12.0, 34.0);
4928
4929        assert!(matches!(
4930            convert_wheel_event(
4931                pos,
4932                &MouseScrollDelta::LineDelta(1.0, -2.0),
4933                Scale::new(2.0),
4934                modifiers,
4935            ),
4936            PointerEvent::Wheel {
4937                pos: event_pos,
4938                delta: ailloli_ui_core::event::WheelDelta::LineDelta { x: 1.0, y: -2.0 },
4939                modifiers: event_modifiers,
4940                precise: false,
4941            } if event_pos == pos && event_modifiers == modifiers
4942        ));
4943        assert!(matches!(
4944            convert_wheel_event(
4945                pos,
4946                &MouseScrollDelta::PixelDelta(PhysicalPosition::new(8.0, -4.0)),
4947                Scale::new(2.0),
4948                modifiers,
4949            ),
4950            PointerEvent::Wheel {
4951                delta: ailloli_ui_core::event::WheelDelta::PixelDelta { x: 4.0, y: -2.0 },
4952                modifiers: event_modifiers,
4953                precise: true,
4954                ..
4955            } if event_modifiers == modifiers
4956        ));
4957    }
4958
4959    #[test]
4960    fn mouse_translation_is_explicitly_primary() {
4961        let sample = mouse_pointer_sample(Point::new(4.0, 8.0)).expect("mouse sample");
4962
4963        assert_eq!(sample.id(), PointerId::MOUSE);
4964        assert_eq!(sample.source(), PointerSource::Mouse);
4965        assert!(sample.is_primary());
4966    }
4967
4968    #[test]
4969    fn touch_translation_marks_only_the_first_contact_primary() {
4970        let mut primary = TouchPrimaryTracker::default();
4971        let modifiers = Modifiers::default();
4972
4973        let (_, first) = translate_touch_event(
4974            &touch(7, TouchPhase::Started, 20.0, 10.0),
4975            Scale::new(2.0),
4976            modifiers,
4977            &mut primary,
4978        )
4979        .expect("first touch");
4980        let (_, second) = translate_touch_event(
4981            &touch(9, TouchPhase::Started, 40.0, 20.0),
4982            Scale::new(2.0),
4983            modifiers,
4984            &mut primary,
4985        )
4986        .expect("second touch");
4987        let (_, first_end) = translate_touch_event(
4988            &touch(7, TouchPhase::Ended, 22.0, 12.0),
4989            Scale::new(2.0),
4990            modifiers,
4991            &mut primary,
4992        )
4993        .expect("primary touch end");
4994        let (_, second_move) = translate_touch_event(
4995            &touch(9, TouchPhase::Moved, 42.0, 22.0),
4996            Scale::new(2.0),
4997            modifiers,
4998            &mut primary,
4999        )
5000        .expect("secondary touch move");
5001
5002        assert_eq!(first.id(), PointerId::new(8));
5003        assert_eq!(first.position(), Point::new(10.0, 5.0));
5004        assert!(first.is_primary());
5005        assert!(!second.is_primary());
5006        assert!(first_end.is_primary());
5007        assert!(!second_move.is_primary());
5008
5009        let (_, second_end) = translate_touch_event(
5010            &touch(9, TouchPhase::Cancelled, 42.0, 22.0),
5011            Scale::new(2.0),
5012            modifiers,
5013            &mut primary,
5014        )
5015        .expect("secondary touch cancellation");
5016        let (_, next_sequence) = translate_touch_event(
5017            &touch(11, TouchPhase::Started, 60.0, 30.0),
5018            Scale::new(2.0),
5019            modifiers,
5020            &mut primary,
5021        )
5022        .expect("next touch sequence");
5023
5024        assert!(!second_end.is_primary());
5025        assert!(next_sequence.is_primary());
5026    }
5027
5028    #[test]
5029    fn clearing_touch_state_starts_a_new_primary_sequence() {
5030        let mut primary = TouchPrimaryTracker::default();
5031        assert!(primary.classify(1, TouchPhase::Started));
5032        assert!(!primary.classify(2, TouchPhase::Started));
5033
5034        primary.clear();
5035
5036        assert!(primary.classify(2, TouchPhase::Started));
5037    }
5038
5039    #[test]
5040    fn forced_input_bench_flush_drains_subsecond_counters() {
5041        let started = Instant::now();
5042        let mut counters = InputBenchCounters::new(started);
5043        counters.event_keyboard = 2;
5044        counters.route_event_us = 17;
5045
5046        let teardown = started + Duration::from_millis(10);
5047        counters.flush_values(teardown);
5048
5049        assert_eq!(counters.event_keyboard, 0);
5050        assert_eq!(counters.route_event_us, 0);
5051        assert_eq!(counters.last_flush, teardown);
5052    }
5053
5054    #[test]
5055    fn winit_keys_convert_to_core_keyboard_model() {
5056        assert_eq!(
5057            convert_key(&WinitKey::Named(WinitNamedKey::Backspace)),
5058            Key::Named(NamedKey::Backspace)
5059        );
5060        assert_eq!(
5061            convert_key(&WinitKey::Named(WinitNamedKey::F12)),
5062            Key::Named(NamedKey::F(12))
5063        );
5064        assert_eq!(
5065            convert_key(&WinitKey::Character("é".into())),
5066            Key::Character("é".into())
5067        );
5068        assert_eq!(
5069            convert_key(&WinitKey::Dead(Some('^'))),
5070            Key::Dead(Some("^".into()))
5071        );
5072    }
5073
5074    #[test]
5075    fn winit_ime_preserves_empty_preedit_and_explicit_lifecycle() {
5076        assert_eq!(
5077            convert_ime_event(&Ime::Preedit(String::new(), None)),
5078            Some(Event::Ime(ImeEvent::Preedit {
5079                preedit: ImePreedit::try_new(String::new(), None).unwrap(),
5080                pos: None,
5081            }))
5082        );
5083        assert_eq!(
5084            convert_ime_event(&Ime::Commit("é".into())),
5085            Some(Event::Ime(ImeEvent::Commit { text: "é".into() }))
5086        );
5087        assert_eq!(
5088            convert_ime_event(&Ime::Enabled),
5089            Some(Event::Ime(ImeEvent::Enabled))
5090        );
5091        assert_eq!(
5092            convert_ime_event(&Ime::Disabled),
5093            Some(Event::Ime(ImeEvent::Disabled))
5094        );
5095    }
5096
5097    #[test]
5098    fn winit_ime_rejects_invalid_utf8_selection() {
5099        assert_eq!(
5100            convert_ime_event(&Ime::Preedit("é".into(), Some((1, 2)))),
5101            None
5102        );
5103    }
5104
5105    #[test]
5106    fn quantize_ime_cursor_area_is_stable_for_identical_logical_rect() {
5107        let rect = Rect::new(10.25, 20.4, 100.0, 22.0);
5108        let scale = Scale::new(2.0);
5109        let a = quantize_ime_cursor_area(rect, scale);
5110        let b = quantize_ime_cursor_area(rect, scale);
5111        assert_eq!(a, b);
5112    }
5113
5114    #[test]
5115    fn quantize_ime_cursor_area_changes_with_dpr() {
5116        let rect = Rect::new(1.0, 2.0, 10.0, 12.0);
5117        let a = quantize_ime_cursor_area(rect, Scale::new(1.0));
5118        let b = quantize_ime_cursor_area(rect, Scale::new(2.0));
5119        assert_ne!(a, b);
5120    }
5121
5122    #[test]
5123    fn render_timeout_is_transient_retry_policy() {
5124        assert_eq!(
5125            render_error_action(&RendererError::SurfaceAcquireTimeout),
5126            RenderErrorAction::RetryFrame(RENDER_TIMEOUT_RETRY_BASE_DELAY)
5127        );
5128        assert_eq!(
5129            render_error_action(&RendererError::SurfaceAcquireLost),
5130            RenderErrorAction::ReconfigureSurface
5131        );
5132        assert_eq!(
5133            render_error_action(&RendererError::SurfaceAcquireOutdated),
5134            RenderErrorAction::ReconfigureSurface
5135        );
5136        assert_eq!(
5137            render_error_action(&RendererError::SurfaceConfigFailed),
5138            RenderErrorAction::ReconfigureSurface
5139        );
5140        assert_eq!(
5141            render_error_action(&RendererError::SurfaceRecreationRequired(
5142                "surface format changed"
5143            )),
5144            RenderErrorAction::ReconfigureSurface
5145        );
5146        assert_eq!(
5147            render_error_action(&RendererError::SurfaceAcquireOutOfMemory),
5148            RenderErrorAction::Fatal
5149        );
5150    }
5151
5152    #[test]
5153    fn render_timeout_retry_delay_is_bounded() {
5154        assert_eq!(
5155            render_timeout_retry_delay(1, RENDER_TIMEOUT_RETRY_BASE_DELAY),
5156            Duration::from_millis(16)
5157        );
5158        assert_eq!(
5159            render_timeout_retry_delay(2, RENDER_TIMEOUT_RETRY_BASE_DELAY),
5160            Duration::from_millis(32)
5161        );
5162        assert_eq!(
5163            render_timeout_retry_delay(99, RENDER_TIMEOUT_RETRY_BASE_DELAY),
5164            RENDER_TIMEOUT_RETRY_MAX_DELAY
5165        );
5166    }
5167
5168    #[test]
5169    fn keyboard_or_ime_without_interaction_change_defers_ime_cursor_update() {
5170        let outcome = ailloli_ui_runtime::input::RouteOutcome {
5171            interaction_changed: false,
5172            event_dispatched: true,
5173        };
5174        let key = Event::Keyboard(KeyEvent {
5175            state: KeyState::Pressed,
5176            key: Key::Character("a".into()),
5177            text: Some("a".into()),
5178            modifiers: Modifiers::default(),
5179            repeat: false,
5180            pointer_pos: None,
5181        });
5182        let ime = Event::Ime(ImeEvent::End);
5183
5184        assert!(!should_update_ime_after_event(&key, &outcome));
5185        assert!(!should_update_ime_after_event(&ime, &outcome));
5186    }
5187
5188    #[test]
5189    fn pointer_or_interaction_change_updates_ime_cursor_state() {
5190        let no_change = ailloli_ui_runtime::input::RouteOutcome {
5191            interaction_changed: false,
5192            event_dispatched: true,
5193        };
5194        let changed = ailloli_ui_runtime::input::RouteOutcome {
5195            interaction_changed: true,
5196            event_dispatched: true,
5197        };
5198        let pointer = Event::Pointer(PointerEvent::Moved {
5199            pos: Point::new(1.0, 1.0),
5200            modifiers: Modifiers::default(),
5201        });
5202        let key = Event::Keyboard(KeyEvent {
5203            state: KeyState::Pressed,
5204            key: Key::Character("a".into()),
5205            text: Some("a".into()),
5206            modifiers: Modifiers::default(),
5207            repeat: false,
5208            pointer_pos: None,
5209        });
5210
5211        assert!(should_update_ime_after_event(&pointer, &no_change));
5212        assert!(should_update_ime_after_event(&key, &changed));
5213    }
5214
5215    #[test]
5216    fn hover_cursor_role_mapping_uses_text_cursor_for_text_role() {
5217        assert_eq!(
5218            cursor_icon_for_hover_role(HoverCursorRole::Pointer),
5219            CursorIcon::Pointer
5220        );
5221        assert_eq!(
5222            cursor_icon_for_hover_role(HoverCursorRole::Text),
5223            CursorIcon::Text
5224        );
5225        assert_eq!(
5226            cursor_icon_for_hover_role(HoverCursorRole::Default),
5227            CursorIcon::Default
5228        );
5229        assert_eq!(
5230            cursor_icon_for_hover_role(HoverCursorRole::Inherit),
5231            CursorIcon::Default
5232        );
5233        assert_eq!(
5234            cursor_icon_for_hover_role(HoverCursorRole::ResizeX),
5235            CursorIcon::from(resize_edge_to_winit(ResizeEdge::E))
5236        );
5237        assert_eq!(
5238            cursor_icon_for_hover_role(HoverCursorRole::ResizeY),
5239            CursorIcon::from(resize_edge_to_winit(ResizeEdge::S))
5240        );
5241        assert_eq!(
5242            presentation_cursor_for_hover_role(HoverCursorRole::Pointer),
5243            PresentationCursor::Pointer
5244        );
5245        assert_eq!(
5246            presentation_cursor_for_hover_role(HoverCursorRole::Text),
5247            PresentationCursor::Text
5248        );
5249        assert_eq!(
5250            presentation_cursor_for_hover_role(HoverCursorRole::ResizeX),
5251            PresentationCursor::ResizeX
5252        );
5253        assert_eq!(
5254            presentation_cursor_for_hover_role(HoverCursorRole::ResizeY),
5255            PresentationCursor::ResizeY
5256        );
5257        assert_eq!(
5258            presentation_cursor_for_hover_role(HoverCursorRole::Default),
5259            PresentationCursor::Default
5260        );
5261    }
5262
5263    #[test]
5264    fn resize_cursor_takes_priority_over_text_hover_cursor() {
5265        assert_eq!(
5266            cursor_icon_for_hover_state(Some(ResizeEdge::E), HoverCursorRole::Text),
5267            CursorIcon::from(resize_edge_to_winit(ResizeEdge::E))
5268        );
5269        assert_eq!(
5270            cursor_icon_for_hover_state(None, HoverCursorRole::Text),
5271            CursorIcon::Text
5272        );
5273        assert_eq!(
5274            cursor_icon_for_hover_state(None, HoverCursorRole::Default),
5275            CursorIcon::Default
5276        );
5277    }
5278
5279    #[test]
5280    fn keyed_titlebar_bounds_ignore_rounded_root_wrapper() {
5281        let runtime = layout_titlebar_fixture(Some("titlebar"), true, None);
5282        let bounds = client_titlebar_bounds_logical(&runtime.tree, runtime.root, Some("titlebar"))
5283            .expect("titlebar bounds");
5284
5285        assert_eq!(bounds, Rect::new(0.0, 0.0, 1280.0, 36.0));
5286        assert!(hit_window_drag_region(bounds, Point::new(20.0, 12.0), true));
5287        assert!(!hit_window_drag_region(
5288            bounds,
5289            Point::new(20.0, 100.0),
5290            true
5291        ));
5292    }
5293
5294    #[test]
5295    fn legacy_titlebar_bounds_skip_window_root_clip_wrapper() {
5296        let runtime = layout_titlebar_fixture(None, true, None);
5297        let bounds =
5298            client_titlebar_bounds_logical(&runtime.tree, runtime.root, None).expect("bounds");
5299
5300        assert_eq!(bounds, Rect::new(0.0, 0.0, 1280.0, 36.0));
5301    }
5302
5303    #[test]
5304    fn client_titlebar_drag_requires_undecorated_client_title_row() {
5305        let enabled = WindowOptions {
5306            decorations: false,
5307            has_client_title_row: true,
5308            titlebar_draggable: true,
5309            ..Default::default()
5310        };
5311        assert!(client_titlebar_drag_enabled(&enabled));
5312
5313        assert!(!client_titlebar_drag_enabled(&WindowOptions {
5314            decorations: true,
5315            has_client_title_row: true,
5316            titlebar_draggable: true,
5317            ..Default::default()
5318        }));
5319        assert!(!client_titlebar_drag_enabled(&WindowOptions {
5320            decorations: false,
5321            has_client_title_row: false,
5322            titlebar_draggable: true,
5323            ..Default::default()
5324        }));
5325        assert!(!client_titlebar_drag_enabled(&WindowOptions {
5326            decorations: false,
5327            has_client_title_row: true,
5328            titlebar_draggable: false,
5329            ..Default::default()
5330        }));
5331    }
5332
5333    #[test]
5334    fn focusable_titlebar_child_blocks_window_drag() {
5335        let runtime = layout_titlebar_fixture(Some("titlebar"), false, Some("button"));
5336        let button = runtime
5337            .tree
5338            .resolve_element_by_view_key("button")
5339            .expect("button key");
5340
5341        assert!(hit_ancestor_blocks_titlebar_drag(&runtime.tree, button));
5342    }
5343
5344    /// Builds and lays out keyed/legacy title-row fixtures with optional focusable child.
5345    fn layout_titlebar_fixture(
5346        titlebar_key: Option<&str>,
5347        rounded_root: bool,
5348        button_key: Option<&str>,
5349    ) -> Runtime<()> {
5350        use ailloli_ui_runtime::app::RuntimeHandle;
5351        use ailloli_ui_runtime::component::{IntoView, IntoViewKeyExt, View};
5352        use ailloli_ui_widgets::controls::Button;
5353        use ailloli_ui_widgets::layout::{Column, Container, Row};
5354
5355        let titlebar_child = if let Some(button_key) = button_key {
5356            Row::<()>::new()
5357                .fill()
5358                .child(Button::new().key(button_key))
5359                .into_view()
5360        } else {
5361            View::empty()
5362        };
5363        let titlebar = Container::<()>::new()
5364            .fill_width()
5365            .height(36.0)
5366            .child(titlebar_child)
5367            .into_view();
5368        let titlebar = match titlebar_key {
5369            Some(key) => titlebar.key(key),
5370            None => titlebar,
5371        };
5372        let inner = Column::<()>::new()
5373            .fill()
5374            .child(titlebar)
5375            .child(Container::<()>::new().fill().flex_grow())
5376            .into_view();
5377        let root = if rounded_root {
5378            Container::<()>::new()
5379                .fill()
5380                .window_root_clip(true)
5381                .child(inner)
5382                .into_view()
5383        } else {
5384            inner
5385        };
5386
5387        let mut runtime = Runtime::new(RuntimeHandle::new());
5388        runtime.reconcile_view(root);
5389        let mut text_system = TextSystem::new();
5390        runtime.layout(
5391            Constraints::tight(1280.0, 720.0),
5392            Scale::new(1.0),
5393            &mut text_system,
5394        );
5395        runtime
5396    }
5397
5398    #[test]
5399    fn scene_to_layer_passes_preserves_window_root_clip_mode() {
5400        let clip = ailloli_ui_core::ClipShape::RoundRect {
5401            rect: Rect::new(0.0, 0.0, 100.0, 80.0),
5402            radius: 12.0,
5403        };
5404        let mut layer = ailloli_ui_runtime::Layer::base_with_clip(Some(clip), true);
5405        layer.cmds.push(ailloli_ui_runtime::DrawCmd::Rect(
5406            ailloli_ui_runtime::DrawRect {
5407                rect: Rect::new(0.0, 0.0, 100.0, 80.0),
5408                color: Color::WHITE,
5409            },
5410        ));
5411        let scene = ailloli_ui_runtime::Scene {
5412            layers: vec![layer],
5413        };
5414
5415        let passes = scene_to_layer_passes(&scene);
5416
5417        assert_eq!(passes.len(), 1);
5418        assert_eq!(
5419            passes[0].clip.entries(),
5420            &[ailloli_ui_runtime::scene::ClipEntry::new(clip, true)]
5421        );
5422        assert_eq!(
5423            passes[0].clip_plan.clip_mode,
5424            ailloli_ui_render_wgpu::ClipRenderMode::Stencil
5425        );
5426    }
5427
5428    #[test]
5429    fn window_default_clear_is_transparent_when_window_options_are_transparent() {
5430        let mut options = WindowOptions {
5431            transparent: true,
5432            ..Default::default()
5433        };
5434        let app = UiApp::<()>::new().window(options.clone(), View::empty());
5435        assert_eq!(app.pending[0].clear, Color::TRANSPARENT);
5436
5437        options.transparent = false;
5438        let app = UiApp::<()>::new().window(options, View::empty());
5439        assert_eq!(app.pending[0].clear, Color::hex("#1a1a1f").expect("hex"));
5440    }
5441
5442    #[test]
5443    fn window_with_clear_keeps_explicit_clear_for_transparent_windows() {
5444        let options = WindowOptions {
5445            transparent: true,
5446            ..Default::default()
5447        };
5448        let clear = Color::rgb(12, 34, 56);
5449
5450        let app = UiApp::<()>::new().window_with_clear(options, clear, View::empty());
5451
5452        assert_eq!(app.pending[0].clear, clear);
5453    }
5454
5455    #[test]
5456    fn window_state_persistence_roundtrips_storage_document() {
5457        let root = std::env::temp_dir().join(format!(
5458            "ailloli_ui_winit_window_state_{}_{}",
5459            std::process::id(),
5460            now_ms()
5461        ));
5462        let storage = ailloli_ui_app_storage::AppStorage::single_dir("my-app", root)
5463            .resolve_with_env(|_| None)
5464            .expect("storage");
5465        let mut snapshot = WindowSnapshot::new("main");
5466        snapshot.inner_size = Some(LogicalWindowSize::new(1024.0, 768.0));
5467        snapshot.maximized = true;
5468        let document = ailloli_ui_app_storage::WindowStateDocument::new(vec![snapshot.clone()]);
5469
5470        storage.write_window_state(&document).expect("write");
5471        let read = storage
5472            .read_window_state()
5473            .expect("read")
5474            .expect("document");
5475
5476        assert_eq!(read.snapshot_for("main"), Some(&snapshot));
5477    }
5478
5479    /// Provider-neutral suspend/resume, recovery, intent, batching, and test-fault scenarios.
5480    mod surface_lifecycle {
5481        use super::*;
5482
5483        /// Creates a reconciled but unattached retained window named `main`.
5484        fn retained_fixture() -> RetainedWindowState<u32> {
5485            retained_fixture_named("main")
5486        }
5487
5488        /// Creates one reconciled but unattached retained window by logical ID.
5489        fn retained_fixture_named(logical_window_id: &str) -> RetainedWindowState<u32> {
5490            let mut app = UiApp::<u32>::new();
5491            app.retain_pending_window(PendingWindow {
5492                options: WindowOptions {
5493                    logical_window_id: logical_window_id.to_string(),
5494                    ..Default::default()
5495                },
5496                root: View::empty(),
5497                clear: Color::BLACK,
5498            })
5499        }
5500
5501        #[test]
5502        fn suspend_resume_retains_runtime_and_increments_generation_once_per_attach() {
5503            let mut retained = retained_fixture();
5504            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5505            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5506            assert_eq!(retained.lifecycle.state(), PresentationState::Ready);
5507            assert_eq!(
5508                retained.lifecycle.generation(),
5509                PresentationGeneration::new(1)
5510            );
5511
5512            retained.runtime.runtime.dispatch(42);
5513            prepare_retained_for_detach(&mut retained, Size::new(800.0, 600.0));
5514
5515            assert_eq!(retained.lifecycle.state(), PresentationState::Suspended);
5516            assert_eq!(
5517                retained.lifecycle.generation(),
5518                PresentationGeneration::new(1)
5519            );
5520            assert_eq!(retained.runtime.runtime.take_actions(), vec![42]);
5521
5522            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5523            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5524            assert_eq!(retained.lifecycle.state(), PresentationState::Ready);
5525            assert_eq!(
5526                retained.lifecycle.generation(),
5527                PresentationGeneration::new(2)
5528            );
5529        }
5530
5531        #[test]
5532        fn detach_coalesces_size_cursor_and_redraw_intents() {
5533            let mut retained = retained_fixture();
5534            retained.current_cursor = PresentationCursor::Pointer;
5535            prepare_retained_for_detach(&mut retained, Size::new(1024.0, 768.0));
5536
5537            let intents = retained.presentation_intents.drain();
5538            assert_eq!(
5539                intents,
5540                vec![
5541                    PresentationIntent::SetInnerSize(Size::new(1024.0, 768.0)),
5542                    PresentationIntent::SetCursor(PresentationCursor::Pointer),
5543                    PresentationIntent::Redraw,
5544                ]
5545            );
5546        }
5547
5548        #[test]
5549        fn lost_surface_uses_unavailable_retry_and_new_generation() {
5550            let mut retained = retained_fixture();
5551            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5552            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5553            prepare_retained_for_detach(&mut retained, Size::new(640.0, 480.0));
5554            UiApp::<u32>::mark_attachment_unavailable(
5555                &mut retained,
5556                PresentationUnavailableReason::SurfaceLost,
5557            );
5558
5559            assert_eq!(
5560                retained.lifecycle.state(),
5561                PresentationState::Unavailable(PresentationUnavailableReason::SurfaceLost)
5562            );
5563            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5564            assert_eq!(
5565                retained.lifecycle.state(),
5566                PresentationState::CreationAllowed
5567            );
5568            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5569            assert_eq!(
5570                retained.lifecycle.generation(),
5571                PresentationGeneration::new(2)
5572            );
5573        }
5574
5575        #[test]
5576        fn zero_extent_remains_unavailable_until_nonzero_surface_apply() {
5577            let mut retained = retained_fixture();
5578            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5579            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5580
5581            UiApp::<u32>::mark_attachment_unavailable(
5582                &mut retained,
5583                PresentationUnavailableReason::ZeroExtent,
5584            );
5585            UiApp::<u32>::mark_attachment_unavailable(
5586                &mut retained,
5587                PresentationUnavailableReason::ZeroExtent,
5588            );
5589            assert_eq!(
5590                retained.lifecycle.state(),
5591                PresentationState::Unavailable(PresentationUnavailableReason::ZeroExtent)
5592            );
5593            assert_eq!(
5594                retained.presentation_generation,
5595                PresentationGeneration::new(1)
5596            );
5597
5598            UiApp::<u32>::complete_zero_extent_recovery(&mut retained).unwrap();
5599            assert_eq!(retained.lifecycle.state(), PresentationState::Ready);
5600            assert_eq!(
5601                retained.presentation_generation,
5602                PresentationGeneration::new(2)
5603            );
5604        }
5605
5606        #[test]
5607        fn redraw_is_retained_while_no_native_presentation_exists() {
5608            let mut app = UiApp::<u32>::new();
5609            app.retained_windows.push(retained_fixture());
5610            let logical_window_id = ailloli_ui_core::LogicalWindowId::new("main");
5611
5612            assert!(app.request_window_redraw(&logical_window_id));
5613            assert_eq!(
5614                app.retained_windows[0].presentation_intents.drain(),
5615                vec![PresentationIntent::Redraw]
5616            );
5617        }
5618
5619        #[test]
5620        fn dirty_runtime_trees_wake_only_exact_retained_presentations() {
5621            let mut app = UiApp::<u32>::new();
5622            let alpha = app.retain_pending_window(PendingWindow {
5623                options: WindowOptions {
5624                    logical_window_id: "alpha".to_string(),
5625                    ..Default::default()
5626                },
5627                root: View::empty(),
5628                clear: Color::BLACK,
5629            });
5630            let beta = app.retain_pending_window(PendingWindow {
5631                options: WindowOptions {
5632                    logical_window_id: "beta".to_string(),
5633                    ..Default::default()
5634                },
5635                root: View::empty(),
5636                clear: Color::BLACK,
5637            });
5638            let stable = app.retain_pending_window(PendingWindow {
5639                options: WindowOptions {
5640                    logical_window_id: "stable".to_string(),
5641                    ..Default::default()
5642                },
5643                root: View::empty(),
5644                clear: Color::BLACK,
5645            });
5646            let popup = Runtime::new(app.runtime.clone());
5647            let generation = PresentationGeneration::INITIAL;
5648            alpha
5649                .runtime
5650                .runtime
5651                .set_presentation_scope("alpha", generation);
5652            beta.runtime
5653                .runtime
5654                .set_presentation_scope("beta", generation);
5655            stable
5656                .runtime
5657                .runtime
5658                .set_presentation_scope("stable", generation);
5659            popup.runtime.set_presentation_scope("alpha", generation);
5660            popup.runtime.request_layout(ElementId(7));
5661            beta.runtime.runtime.request_repaint(ElementId(8));
5662            app.retained_windows.extend([alpha, beta, stable]);
5663
5664            assert_eq!(app.request_pending_presentation_redraws(), 2);
5665            assert_eq!(
5666                app.retained_windows[0].presentation_intents.drain(),
5667                vec![PresentationIntent::Redraw]
5668            );
5669            assert_eq!(
5670                app.retained_windows[1].presentation_intents.drain(),
5671                vec![PresentationIntent::Redraw]
5672            );
5673            assert!(app.retained_windows[2]
5674                .presentation_intents
5675                .drain()
5676                .is_empty());
5677
5678            popup.runtime.take_dirty_elements();
5679            popup.runtime.clear_presentation_scope();
5680            app.retained_windows[1]
5681                .runtime
5682                .runtime
5683                .take_dirty_elements();
5684            app.retained_windows.remove(0);
5685            app.retained_windows[0]
5686                .runtime
5687                .runtime
5688                .request_layout(ElementId(9));
5689            assert_eq!(app.request_pending_presentation_redraws(), 1);
5690            assert_eq!(
5691                app.retained_windows[0].presentation_intents.drain(),
5692                vec![PresentationIntent::Redraw]
5693            );
5694            assert!(app.retained_windows[1]
5695                .presentation_intents
5696                .drain()
5697                .is_empty());
5698        }
5699
5700        #[test]
5701        fn stale_dirty_generation_does_not_wake_newer_retained_attachment() {
5702            let mut app = UiApp::<u32>::new();
5703            let mut retained = app.retain_pending_window(PendingWindow {
5704                options: WindowOptions {
5705                    logical_window_id: "main".to_string(),
5706                    ..Default::default()
5707                },
5708                root: View::empty(),
5709                clear: Color::BLACK,
5710            });
5711            retained.presentation_generation = PresentationGeneration::new(2);
5712            retained
5713                .runtime
5714                .runtime
5715                .set_presentation_scope("main", PresentationGeneration::new(1));
5716            retained.runtime.runtime.request_repaint(ElementId(1));
5717            app.retained_windows.push(retained);
5718
5719            assert_eq!(app.request_pending_presentation_redraws(), 0);
5720            assert!(app.retained_windows[0]
5721                .presentation_intents
5722                .drain()
5723                .is_empty());
5724        }
5725
5726        #[test]
5727        fn stale_generation_is_rejected_by_ready_lifecycle() {
5728            let mut retained = retained_fixture();
5729            UiApp::<u32>::allow_presentation_creation(&mut retained).unwrap();
5730            UiApp::<u32>::complete_attachment(&mut retained).unwrap();
5731
5732            assert!(retained.lifecycle.accepts(PresentationGeneration::new(1)));
5733            assert!(!retained.lifecycle.accepts(PresentationGeneration::INITIAL));
5734            prepare_retained_for_detach(&mut retained, Size::new(320.0, 240.0));
5735            assert!(!retained.lifecycle.accepts(PresentationGeneration::new(1)));
5736        }
5737
5738        #[test]
5739        fn retained_redraw_sweep_waits_for_renderable_lifecycle_extent_and_retry() {
5740            let mut resize = ResizeController::default();
5741
5742            assert!(native_presentation_accepts_retained_redraw(
5743                PresentationState::Ready,
5744                &resize,
5745                None,
5746            ));
5747            assert!(!resize.request(PhysicalSize::new(0, 480)));
5748            assert!(!native_presentation_accepts_retained_redraw(
5749                PresentationState::Ready,
5750                &resize,
5751                None,
5752            ));
5753            assert!(!native_presentation_accepts_retained_redraw(
5754                PresentationState::Unavailable(PresentationUnavailableReason::ZeroExtent),
5755                &resize,
5756                None,
5757            ));
5758
5759            assert!(resize.request(PhysicalSize::new(640, 480)));
5760            assert!(native_presentation_accepts_retained_redraw(
5761                PresentationState::Unavailable(PresentationUnavailableReason::ZeroExtent),
5762                &resize,
5763                None,
5764            ));
5765            assert!(!native_presentation_accepts_retained_redraw(
5766                PresentationState::Suspended,
5767                &resize,
5768                None,
5769            ));
5770            assert!(!native_presentation_accepts_retained_redraw(
5771                PresentationState::Ready,
5772                &resize,
5773                Some(Instant::now()),
5774            ));
5775        }
5776
5777        #[cfg(feature = "test_support")]
5778        #[test]
5779        fn surface_reattach_outcomes_distinguish_context_reuse_from_rebuild() {
5780            let mut app = UiApp::<u32>::new();
5781            app.record_gpu_reattach_outcome("main", SurfaceReattachOutcome::ReusedGpuContext);
5782            app.record_gpu_reattach_outcome(
5783                "main",
5784                SurfaceReattachOutcome::RebuiltGpuContext {
5785                    reason: ailloli_ui_render_wgpu::SurfaceContextReuseFailure::FormatUnsupported,
5786                },
5787            );
5788
5789            let counters = app
5790                .presentation_test_counters
5791                .get(&ailloli_ui_core::LogicalWindowId::new("main"))
5792                .copied()
5793                .expect("reattach counters");
5794            assert_eq!(counters.gpu_context_reuse_count, 1);
5795            assert_eq!(counters.gpu_context_rebuild_count, 1);
5796        }
5797
5798        #[test]
5799        fn consecutive_file_events_are_batched_by_window_and_kind() {
5800            let mut app = UiApp::<u32>::new();
5801            let window_id = WindowId::dummy();
5802            app.queue_file_batch(
5803                window_id,
5804                PendingFileBatchKind::Entered,
5805                Some(ailloli_ui_core::UploadFile::from_path("one.txt".into())),
5806            );
5807            app.queue_file_batch(
5808                window_id,
5809                PendingFileBatchKind::Entered,
5810                Some(ailloli_ui_core::UploadFile::from_path("two.txt".into())),
5811            );
5812            app.queue_file_batch(
5813                window_id,
5814                PendingFileBatchKind::Dropped,
5815                Some(ailloli_ui_core::UploadFile::from_path("two.txt".into())),
5816            );
5817
5818            assert_eq!(app.pending_file_batches.len(), 2);
5819            assert_eq!(
5820                app.pending_file_batches[0].kind,
5821                PendingFileBatchKind::Entered
5822            );
5823            assert_eq!(app.pending_file_batches[0].files.len(), 2);
5824            assert_eq!(
5825                app.pending_file_batches[1].kind,
5826                PendingFileBatchKind::Dropped
5827            );
5828            assert_eq!(app.pending_file_batches[1].files.len(), 1);
5829        }
5830
5831        #[cfg(feature = "test_support")]
5832        #[test]
5833        fn presentation_fault_can_be_queued_before_first_resume() {
5834            let logical_window_id = ailloli_ui_core::LogicalWindowId::new("main");
5835            let mut app = UiApp::<u32>::new().window(
5836                WindowOptions {
5837                    logical_window_id: logical_window_id.as_str().to_string(),
5838                    ..Default::default()
5839                },
5840                View::empty(),
5841            );
5842
5843            assert!(app.inject_presentation_fault(
5844                &logical_window_id,
5845                PresentationTestFault::DetachReattach
5846            ));
5847            assert_eq!(app.presentation_test_faults.len(), 1);
5848        }
5849    }
5850}