Skip to main content

sui_runtime/
lib.rs

1#![forbid(unsafe_code)]
2
3mod app;
4mod command;
5mod diagnostics;
6mod layout_work;
7mod logo;
8mod measure_cache;
9mod output_cache;
10mod overlay;
11mod reactive;
12mod resources;
13use resources::ResourceStore;
14mod widget;
15
16use std::{
17    collections::{BTreeSet, HashMap, HashSet, VecDeque},
18    sync::{
19        Arc,
20        atomic::{AtomicU64, Ordering},
21    },
22};
23
24use sui_core::{
25    AsyncWakeToken, Clipboard, ClipboardBackend, CursorGrabMode, CustomEvent, DirtyRegion,
26    DragEvent, DragEventKind, DragOutcome, DragPayload, DragScopeId, DragSessionId, DropEffect,
27    Error, Event, FontHandle, ImageHandle, InvalidationKind, InvalidationRequest,
28    InvalidationTarget, KeyState, Point, PointerButton, PointerButtons, PointerEvent,
29    PointerEventKind, Rect, Result, SemanticsActionRequest, SemanticsEvent, SemanticsNode, Size,
30    TimerToken, Transform, Vector, WakeEvent, WidgetId, WindowEvent, WindowId,
31};
32use sui_layout::Constraints;
33use sui_scene::{
34    ImageRegistry, LayerCompositionMode, RegisteredImage, Scene, SceneCommand, SceneFrame,
35    SceneLayer, SceneLayerDescriptor, SceneLayerUpdate, SceneLayerUpdateKind,
36};
37use sui_text::{FontRegistry, RegisteredFont, TextLayoutHandle, TextSystem};
38use web_time::Instant;
39
40pub use app::{Application, EmbeddedSvgImageResource, WindowBuilder, WindowIcon};
41pub use command::{
42    Command, CommandController, CommandCtx, CommandDelivery, CommandKey, CommandSender,
43    CommandTarget,
44};
45use command::{CommandInvalidation, CommandListeners, QueuedCommand};
46pub use diagnostics::{
47    CacheMetrics, CacheMetricsDelta, CommandDispatchSample, FramePhase, FramePhaseSample,
48    InvalidationTraceSample, PresentationLatencyDiagnostics, ReactiveInvalidationSample,
49    RenderDiagnostics, RendererSubmissionDiagnostics, RetainedPacketHotspotDiagnostics,
50    RetainedPacketRebuildDiagnostics, SceneStatistics, SceneStatisticsDetailMode,
51    TextCacheDeltaDiagnostics, TextCacheDiagnostics, WidgetRebuildSample, WidgetTimingPhase,
52    WidgetTimingSample, WindowColorManagementMode, WindowDynamicRangeMode,
53    WindowOutputColorPrimaries, WindowPerformanceSnapshot, WindowPerformanceSummary,
54    WindowRenderOptions, WindowStemDarkening, WindowTextCoveragePolicy, WindowTextHinting,
55    WindowTextSubpixelOrder, WindowToneMappingMode, clear_window_performance_snapshot,
56    clear_window_performance_snapshots, clear_window_render_options,
57    publish_window_performance_snapshot, set_window_render_options,
58    set_window_scene_statistics_detail_mode, window_performance_snapshot,
59    window_performance_summary, window_performance_text_caches, window_render_options,
60    window_scene_statistics_detail_mode,
61};
62#[doc(hidden)]
63pub use layout_work::record_scrollbar_gutter_iteration;
64pub use layout_work::{
65    LayoutWorkSnapshot, begin_layout_work_collection, take_layout_work_collection,
66};
67pub use logo::{DEFAULT_SUI_LOGO_SVG, default_sui_logo_image};
68pub use overlay::{
69    OVERLAY_DISMISS_REQUEST, OverlayDismissPolicy, OverlayDismissReason, OverlayDismissRequest,
70    OverlayFocusBehavior, OverlayInitialFocus, OverlayKind, OverlayManagerSnapshot,
71    OverlayModality, OverlayOptions, OverlaySnapshot, OverlayTraceKind, OverlayTraceSample,
72};
73use std::rc::Rc;
74pub use sui_core::{DpiInfo, SafeAreaInsets};
75pub use sui_layout::LayoutContext;
76pub use widget::{
77    ArrangeCtx, EventCtx, EventPhase, FocusRestorePolicy, FocusScope, FocusScopeState,
78    KeyedChildren, KeyedReconcile, LayerOptions, MeasureCtx, PaintBoundaryMode, PaintCtx,
79    SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy, StackSurfaceOptions, Widget,
80    WidgetChildren, WidgetDiagnostic, WidgetDiagnosticsCtx, WidgetDiagnosticsSnapshot, WidgetPod,
81    WidgetPodMutVisitor, WidgetPodVisitor,
82};
83use widget::{ArrangeScope, MeasureScope};
84use widget::{
85    BeginDragRequest, CursorRequest, DragRequest, DropAcceptanceRequest, FocusRequest,
86    PaintImageResource, PointerCaptureRequest, WakeRequest,
87};
88
89/// Internal typed notification delivered to widgets whose observable
90/// dependencies changed.
91pub const REACTIVE_CHANGED: CommandKey<()> = CommandKey::new("sui.reactive.changed");
92
93type PaintOutput = (
94    Scene,
95    Vec<(ImageHandle, PaintImageResource)>,
96    HashMap<WidgetId, Rect>,
97    Vec<InvalidationRequest>,
98    Option<Rect>,
99);
100
101static NEXT_WINDOW_ID: AtomicU64 = AtomicU64::new(1);
102
103/// Legacy root-event kind. Platform wakes no longer synthesize this event; use
104/// [`CommandSender`] and window/application controllers instead.
105pub const EXTERNAL_WAKE_KIND: &str = "sui.external.wake";
106
107pub struct Runtime {
108    resources: ResourceStore,
109    text_system: Arc<TextSystem>,
110    clipboard: Clipboard,
111    windows: Vec<WindowState>,
112    external_waker: Option<Arc<dyn Fn() + Send + Sync>>,
113    command_sender: CommandSender,
114    command_listeners: CommandListeners,
115}
116
117/// Begin opt-in widget/text timing collection without dispatching a redraw or
118/// changing invalidation. Intended for diagnostic replay and custom hosts.
119#[cfg(feature = "layout-diagnostics")]
120pub fn begin_frame_timing_collection() {
121    diagnostics::begin_widget_timing_collection();
122    sui_text::begin_text_timing_collection();
123}
124
125impl Runtime {
126    pub fn new() -> Self {
127        Self::with_resources(ResourceStore::default())
128    }
129
130    fn with_resources(resources: ResourceStore) -> Self {
131        Self {
132            resources,
133            text_system: Arc::new(TextSystem::new()),
134            clipboard: Clipboard::new(),
135            windows: Vec::new(),
136            external_waker: None,
137            command_sender: CommandSender::new(),
138            command_listeners: CommandListeners::default(),
139        }
140    }
141
142    pub fn add_window(&mut self, builder: WindowBuilder) -> Result<WindowId> {
143        let window_id = self.alloc_window_id();
144        let mut window = builder.build(window_id, self.command_sender.clone())?;
145        window.clipboard = self.clipboard.clone();
146        window.reactive_hub.set_waker(self.external_waker.clone());
147        self.windows.push(window);
148        Ok(window_id)
149    }
150
151    /// Install the platform callback used to wake the UI after an observable
152    /// invalidates one or more subscribed widgets.
153    pub fn set_external_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
154        let waker: Arc<dyn Fn() + Send + Sync> = Arc::new(waker);
155        self.external_waker = Some(Arc::clone(&waker));
156        for window in &self.windows {
157            window.reactive_hub.set_waker(Some(Arc::clone(&waker)));
158        }
159    }
160
161    /// Install the platform callback used by the thread-safe command producer.
162    pub fn set_command_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
163        self.command_sender.set_waker(Some(Arc::new(waker)));
164    }
165
166    /// Return the cloneable command producer associated with this runtime.
167    pub fn command_sender(&self) -> CommandSender {
168        self.command_sender.clone()
169    }
170
171    pub fn has_pending_commands(&self) -> bool {
172        self.command_sender.has_pending()
173    }
174
175    /// Drain observable changes into targeted widget invalidations without
176    /// delivering an application-level external wake event.
177    ///
178    /// Platform integrations call this after their reactive wake signal.
179    pub fn process_reactive_updates(&mut self) {
180        for window in &mut self.windows {
181            window.drain_reactive_invalidations();
182        }
183    }
184
185    /// Drain queued commands and scheduler-only wakes on the UI thread.
186    ///
187    /// Platform integrations call this in response to the command producer's
188    /// waker. Delivery is independent of hit testing and widget ancestry.
189    pub fn process_commands(&mut self) {
190        const MAX_COMMAND_ROUNDS: usize = 8;
191
192        for _ in 0..MAX_COMMAND_ROUNDS {
193            let (manual_wake, commands) = self.command_sender.drain();
194            if !manual_wake && commands.is_empty() {
195                break;
196            }
197            if manual_wake {
198                self.dispatch_controller_wake();
199            }
200            for command in commands {
201                self.dispatch_queued_command(&command);
202            }
203        }
204    }
205
206    /// Enqueue and synchronously drain a command. Intended for headless hosts
207    /// and tests that own the runtime loop directly.
208    pub fn handle_command<T>(
209        &mut self,
210        target: CommandTarget,
211        delivery: CommandDelivery,
212        key: CommandKey<T>,
213        payload: T,
214    ) where
215        T: Send + Sync + 'static,
216    {
217        match delivery {
218            CommandDelivery::Directed => self.command_sender.send(target, key, payload),
219            CommandDelivery::Broadcast => self.command_sender.broadcast(target, key, payload),
220        }
221        self.process_commands();
222    }
223
224    /// Shared clipboard handle used by every window in this runtime.
225    pub fn clipboard(&self) -> Clipboard {
226        self.clipboard.clone()
227    }
228
229    /// Install a clipboard storage driver (for example an OS-clipboard bridge
230    /// provided by the platform). Existing windows pick it up immediately.
231    pub fn set_clipboard_backend(&self, backend: impl ClipboardBackend + 'static) {
232        self.clipboard.set_backend(backend);
233    }
234
235    pub fn remove_window(&mut self, window_id: WindowId) -> Result<()> {
236        let Some(window_index) = self
237            .windows
238            .iter()
239            .position(|window| window.id == window_id)
240        else {
241            return Err(Error::new(format!(
242                "window {} does not exist",
243                window_id.get()
244            )));
245        };
246
247        self.windows.remove(window_index);
248        clear_window_performance_snapshot(window_id);
249        Ok(())
250    }
251
252    pub fn handle_event(&mut self, window_id: WindowId, event: Event) -> Result<()> {
253        self.dispatch_event(window_id, event).map(|_| ())
254    }
255
256    /// Dispatch an event and report whether widget routing or a built-in runtime behavior
257    /// consumed it.
258    ///
259    /// Platform hosts can use this to provide native fallbacks only when application and
260    /// runtime behavior did not handle an event. Most callers should continue to use
261    /// [`Runtime::handle_event`] when the dispatch outcome is not relevant.
262    pub fn dispatch_event(&mut self, window_id: WindowId, event: Event) -> Result<bool> {
263        let text_system = Arc::clone(&self.text_system);
264        let font_registry = Arc::clone(self.resources.fonts());
265        let image_registry = Arc::clone(self.resources.images());
266        let window = self.window_mut(window_id)?;
267        window.drain_reactive_invalidations();
268        let handled = window.handle_event(event, text_system, font_registry, image_registry);
269        window.drain_reactive_invalidations();
270        Ok(handled)
271    }
272
273    /// Invoke an action advertised by a node in the latest semantic snapshot.
274    ///
275    /// The semantic node does not need to be a retained [`WidgetPod`]. Virtual
276    /// and generated nodes are routed to their nearest graph-backed semantic
277    /// ancestor while [`SemanticsEvent::target`] preserves the original node
278    /// identity for widget-local dispatch. The return value is `false` when the
279    /// node is stale, hidden, disabled, does not advertise the action, or no
280    /// widget handles an action without a built-in runtime fallback.
281    pub fn handle_semantics_action(
282        &mut self,
283        window_id: WindowId,
284        target: WidgetId,
285        action: SemanticsActionRequest,
286    ) -> Result<bool> {
287        let text_system = Arc::clone(&self.text_system);
288        let font_registry = Arc::clone(self.resources.fonts());
289        let image_registry = Arc::clone(self.resources.images());
290        let window = self.window_mut(window_id)?;
291        Ok(window.handle_semantics_action(
292            target,
293            action,
294            text_system,
295            font_registry,
296            image_registry,
297        ))
298    }
299
300    pub fn tick(&mut self, frame_time: f64) {
301        for window in &mut self.windows {
302            window.last_tick_time = frame_time;
303        }
304    }
305
306    pub fn drain_ready_events(&mut self) -> Vec<(WindowId, Event)> {
307        let mut ready = Vec::new();
308
309        for window in &mut self.windows {
310            let window_id = window.id;
311            ready.extend(
312                window
313                    .drain_ready_events()
314                    .into_iter()
315                    .map(|event| (window_id, event)),
316            );
317        }
318
319        ready
320    }
321
322    pub fn next_wakeup_time(&self, window_id: WindowId) -> Result<Option<f64>> {
323        let window = self.window(window_id)?;
324        Ok(window.next_wakeup_time())
325    }
326
327    pub fn wake_async(&mut self, window_id: WindowId, token: AsyncWakeToken) -> Result<bool> {
328        let window = self.window_mut(window_id)?;
329        Ok(window.wake_async(token))
330    }
331
332    /// Explicitly deliver the legacy external-wake [`Event::Custom`] (kind
333    /// [`EXTERNAL_WAKE_KIND`]) to a window's root widget.
334    ///
335    /// Platform wakes do not call this method. New integrations should enqueue a
336    /// typed command or use [`CommandSender::wake`] with a controller.
337    pub fn wake_root(&mut self, window_id: WindowId) -> Result<()> {
338        self.handle_event(
339            window_id,
340            Event::Custom(CustomEvent::new(EXTERNAL_WAKE_KIND)),
341        )
342    }
343
344    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
345        self.resources.register_font(handle, font)
346    }
347
348    pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
349        self.resources.register_font_bytes(data)
350    }
351
352    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
353        self.resources.register_image(handle, image)
354    }
355
356    pub fn register_svg_image_with_handle(
357        &mut self,
358        handle: ImageHandle,
359        data: impl AsRef<[u8]>,
360    ) -> Result<()> {
361        self.resources.register_svg_image_with_handle(handle, data)
362    }
363
364    pub fn register_rgba_image(
365        &mut self,
366        width: u32,
367        height: u32,
368        data: impl Into<Vec<u8>>,
369    ) -> Result<ImageHandle> {
370        self.resources.register_rgba_image(width, height, data)
371    }
372
373    pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
374        self.resources.register_svg_image(data)
375    }
376
377    pub fn register_svg_image_at_size_with_handle(
378        &mut self,
379        handle: ImageHandle,
380        width: u32,
381        height: u32,
382        data: impl AsRef<[u8]>,
383    ) -> Result<()> {
384        self.resources
385            .register_svg_image_at_size_with_handle(handle, width, height, data)
386    }
387
388    pub fn register_svg_image_at_size(
389        &mut self,
390        width: u32,
391        height: u32,
392        data: impl AsRef<[u8]>,
393    ) -> Result<ImageHandle> {
394        self.resources
395            .register_svg_image_at_size(width, height, data)
396    }
397
398    pub fn register_embedded_svg_image(
399        &mut self,
400        resource: EmbeddedSvgImageResource,
401    ) -> Result<()> {
402        self.resources.register_embedded_svg_image(resource)
403    }
404
405    pub fn register_embedded_svg_images(
406        &mut self,
407        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
408    ) -> Result<()> {
409        self.resources.register_embedded_svg_images(resources)
410    }
411
412    pub fn font_registry(&self) -> &Arc<FontRegistry> {
413        self.resources.fonts()
414    }
415
416    /// Read-only cache diagnostics for measurement/profiling tools.
417    pub fn text_preparation_cache_snapshot(&self) -> sui_text::TextPreparationCacheSnapshot {
418        self.text_system.preparation_cache_snapshot()
419    }
420
421    pub fn image_registry(&self) -> &Arc<ImageRegistry> {
422        self.resources.images()
423    }
424
425    pub fn render(&mut self, window_id: WindowId) -> Result<RenderOutput> {
426        let text_system = Arc::clone(&self.text_system);
427        let font_registry = Arc::clone(self.resources.fonts());
428        let image_registry = Arc::clone(self.resources.images());
429        let window = self.window_mut(window_id)?;
430        window.drain_reactive_invalidations();
431        Ok(window.render(text_system, font_registry, image_registry))
432    }
433
434    pub fn semantics(&self, window_id: WindowId) -> Result<&[SemanticsNode]> {
435        let window = self.window(window_id)?;
436        Ok(&window.last_semantics)
437    }
438
439    pub fn window_title(&self, window_id: WindowId) -> Result<&str> {
440        let window = self.window(window_id)?;
441        Ok(&window.title)
442    }
443
444    pub fn window_icon(&self, window_id: WindowId) -> Result<Option<&WindowIcon>> {
445        let window = self.window(window_id)?;
446        Ok(window.icon.as_ref())
447    }
448
449    pub fn window_ids(&self) -> Vec<WindowId> {
450        self.windows.iter().map(|window| window.id).collect()
451    }
452
453    pub fn needs_render(&self, window_id: WindowId) -> Result<bool> {
454        let window = self.window(window_id)?;
455        Ok(window.needs_render())
456    }
457
458    pub fn schedule(&self, window_id: WindowId) -> Result<FrameSchedule> {
459        let window = self.window(window_id)?;
460        Ok(window.schedule)
461    }
462
463    pub fn focus_state(&self, window_id: WindowId) -> Result<FocusState> {
464        let window = self.window(window_id)?;
465        Ok(window.focus)
466    }
467
468    pub fn focused_widget(&self, window_id: WindowId) -> Result<Option<WidgetId>> {
469        Ok(self.focus_state(window_id)?.focused_widget)
470    }
471
472    pub fn pointer_capture_target(
473        &self,
474        window_id: WindowId,
475        pointer_id: u64,
476    ) -> Result<Option<WidgetId>> {
477        let window = self.window(window_id)?;
478        Ok(window.pointer_capture.get(&pointer_id).copied())
479    }
480
481    /// Return the logical initial size requested by the window builder.
482    pub fn window_initial_size(&self, window_id: WindowId) -> Result<Option<Size>> {
483        Ok(self.window(window_id)?.initial_size)
484    }
485
486    /// Return the physical desktop position requested by the window builder.
487    pub fn window_initial_position(&self, window_id: WindowId) -> Result<Option<Point>> {
488        Ok(self.window(window_id)?.initial_position)
489    }
490
491    /// Return the desired cursor state for a host window.
492    ///
493    /// Platform hosts should apply a newer `revision` promptly after event
494    /// dispatch so web pointer-lock requests remain inside the browser's user
495    /// activation callback.
496    pub fn window_cursor_state(&self, window_id: WindowId) -> Result<WindowCursorState> {
497        Ok(self.window(window_id)?.cursor.state)
498    }
499
500    pub fn widget_graph(&self, window_id: WindowId) -> Result<WidgetGraphSnapshot> {
501        let window = self.window(window_id)?;
502        Ok(window.graph.snapshot())
503    }
504
505    /// Enable or disable bounded route and invalidation history for a window.
506    /// Structural snapshots remain available while tracing is disabled.
507    pub fn set_inspector_tracing(&mut self, window_id: WindowId, enabled: bool) -> Result<()> {
508        let window = self.window_mut(window_id)?;
509        if window.inspector_tracing_enabled != enabled {
510            window.clear_inspector_history();
511            window.last_render_diagnostics = RenderDiagnostics::default();
512        }
513        window.inspector_tracing_enabled = enabled;
514        Ok(())
515    }
516
517    pub fn inspector_tracing(&self, window_id: WindowId) -> Result<bool> {
518        Ok(self.window(window_id)?.inspector_tracing_enabled)
519    }
520
521    /// Capture a unified renderer-neutral snapshot for debug tooling.
522    pub fn inspector_snapshot(&self, window_id: WindowId) -> Result<WindowInspectorSnapshot> {
523        let window = self.window(window_id)?;
524        Ok(window.inspector_snapshot())
525    }
526
527    /// Inspect the window's currently presented overlay stack.
528    pub fn overlay_snapshot(&self, window_id: WindowId) -> Result<OverlayManagerSnapshot> {
529        let window = self.window(window_id)?;
530        Ok(window.overlay_manager.snapshot())
531    }
532
533    /// Drain overlay lifecycle and dismissal diagnostics for an inspector.
534    pub fn take_overlay_traces(&mut self, window_id: WindowId) -> Result<Vec<OverlayTraceSample>> {
535        let window = self.window_mut(window_id)?;
536        Ok(window.overlay_manager.take_traces())
537    }
538
539    fn dispatch_controller_wake(&mut self) {
540        let sender = self.command_sender.clone();
541        let mut app_ctx = CommandCtx::new(sender.clone(), None);
542        let app_handlers = self.command_listeners.wake(&mut app_ctx);
543        self.apply_command_ctx(
544            app_ctx,
545            "scheduler wake",
546            "()",
547            None,
548            0,
549            CommandTarget::Application,
550            CommandDelivery::Broadcast,
551            app_handlers,
552        );
553
554        for index in 0..self.windows.len() {
555            let window_id = self.windows[index].id;
556            let mut ctx = CommandCtx::new(sender.clone(), Some(window_id));
557            let handlers = self.windows[index].command_listeners.wake(&mut ctx);
558            self.apply_command_ctx(
559                ctx,
560                "scheduler wake",
561                "()",
562                Some(index),
563                0,
564                CommandTarget::Window(window_id),
565                CommandDelivery::Broadcast,
566                handlers,
567            );
568        }
569    }
570
571    fn dispatch_queued_command(&mut self, queued: &QueuedCommand) {
572        match queued.target {
573            CommandTarget::Widget {
574                window_id,
575                widget_id,
576            } => {
577                if let Some(index) = self
578                    .windows
579                    .iter()
580                    .position(|window| window.id == window_id)
581                {
582                    let Some(dispatch) =
583                        self.windows[index].dispatch_direct_command(widget_id, queued)
584                    else {
585                        push_trace(
586                            &mut self.windows[index].pending_command_diagnostics,
587                            command_sample(queued, Vec::new(), false, false),
588                        );
589                        return;
590                    };
591                    let (handlers, handled) = {
592                        let handled = dispatch.handled;
593                        (vec!["widget target".to_string()], handled)
594                    };
595                    let focus_request = dispatch.focus_request;
596                    let mut effects = EventEffects::default();
597                    effects.extend(dispatch);
598                    let mut invalidations = Vec::new();
599                    self.windows[index].apply_event_effects(effects, &mut invalidations);
600                    if let Some(request) = focus_request {
601                        let focus_effects = self.windows[index].apply_focus_request(request);
602                        self.windows[index].apply_event_effects(focus_effects, &mut invalidations);
603                    }
604                    self.windows[index].record_command_invalidations(
605                        &invalidations,
606                        queued.key.name,
607                        None,
608                    );
609                    self.windows[index].schedule.extend(&invalidations);
610                    self.windows[index]
611                        .pending_invalidations
612                        .extend(invalidations);
613                    push_trace(
614                        &mut self.windows[index].pending_command_diagnostics,
615                        command_sample(queued, handlers, handled, true),
616                    );
617                }
618            }
619            CommandTarget::FocusedWidget(window_id) => {
620                if let Some(index) = self
621                    .windows
622                    .iter()
623                    .position(|window| window.id == window_id)
624                {
625                    let Some(target) = self.windows[index].focus.focused_widget else {
626                        push_trace(
627                            &mut self.windows[index].pending_command_diagnostics,
628                            command_sample(queued, Vec::new(), false, false),
629                        );
630                        return;
631                    };
632                    let Some(dispatch) =
633                        self.windows[index].dispatch_direct_command(target, queued)
634                    else {
635                        push_trace(
636                            &mut self.windows[index].pending_command_diagnostics,
637                            command_sample(queued, Vec::new(), false, false),
638                        );
639                        return;
640                    };
641                    let handled = { dispatch.handled };
642                    let focus_request = dispatch.focus_request;
643                    let mut effects = EventEffects::default();
644                    effects.extend(dispatch);
645                    let mut invalidations = Vec::new();
646                    self.windows[index].apply_event_effects(effects, &mut invalidations);
647                    if let Some(request) = focus_request {
648                        let focus_effects = self.windows[index].apply_focus_request(request);
649                        self.windows[index].apply_event_effects(focus_effects, &mut invalidations);
650                    }
651                    self.windows[index].record_command_invalidations(
652                        &invalidations,
653                        queued.key.name,
654                        None,
655                    );
656                    self.windows[index].schedule.extend(&invalidations);
657                    self.windows[index]
658                        .pending_invalidations
659                        .extend(invalidations);
660                    push_trace(
661                        &mut self.windows[index].pending_command_diagnostics,
662                        command_sample(queued, vec!["focused widget".to_string()], handled, true),
663                    );
664                }
665            }
666            CommandTarget::Window(window_id) => {
667                if let Some(index) = self
668                    .windows
669                    .iter()
670                    .position(|window| window.id == window_id)
671                {
672                    self.dispatch_to_window_listeners(index, queued);
673                }
674            }
675            CommandTarget::Application => {
676                let sender = self.command_sender.clone();
677                let mut ctx = CommandCtx::new(sender.clone(), None);
678                let broadcast = queued.delivery == CommandDelivery::Broadcast;
679                let command = Command::new(queued);
680                let handlers = self
681                    .command_listeners
682                    .dispatch(&mut ctx, &command, broadcast);
683                self.apply_command_ctx(
684                    ctx,
685                    queued.key.name,
686                    queued.key.payload_type_name,
687                    None,
688                    queued.sequence,
689                    queued.target,
690                    queued.delivery,
691                    handlers,
692                );
693
694                if broadcast {
695                    for index in 0..self.windows.len() {
696                        self.dispatch_to_window_listeners(index, queued);
697                    }
698                }
699            }
700        }
701    }
702
703    fn dispatch_to_window_listeners(&mut self, index: usize, queued: &QueuedCommand) {
704        let sender = self.command_sender.clone();
705        let window_id = self.windows[index].id;
706        let mut ctx = CommandCtx::new(sender, Some(window_id));
707        let broadcast = queued.delivery == CommandDelivery::Broadcast;
708        let command = Command::new(queued);
709        let handlers = self.windows[index]
710            .command_listeners
711            .dispatch(&mut ctx, &command, broadcast);
712        self.apply_command_ctx(
713            ctx,
714            queued.key.name,
715            queued.key.payload_type_name,
716            Some(index),
717            queued.sequence,
718            queued.target,
719            queued.delivery,
720            handlers,
721        );
722    }
723
724    #[allow(clippy::too_many_arguments)]
725    fn apply_command_ctx(
726        &mut self,
727        mut ctx: CommandCtx,
728        source: &str,
729        payload_type: &str,
730        delivery_window: Option<usize>,
731        sequence: u64,
732        target: CommandTarget,
733        delivery: CommandDelivery,
734        handlers: Vec<String>,
735    ) {
736        let handled = ctx.is_handled();
737        let invalidations = ctx.take_invalidations();
738        let animations = ctx.take_animation_targets();
739        for invalidation in invalidations {
740            self.apply_command_invalidation(invalidation, source, delivery_window);
741        }
742        for (window_id, widget_id) in animations {
743            if let Some(window) = self
744                .windows
745                .iter_mut()
746                .find(|window| window.id == window_id)
747            {
748                window.requested_animation_frames.insert(widget_id);
749            }
750        }
751
752        let sample = CommandDispatchSample {
753            sequence,
754            name: source.to_string(),
755            payload_type: payload_type.to_string(),
756            target,
757            delivery,
758            delivered: !handlers.is_empty(),
759            handlers,
760            handled,
761        };
762        if let Some(index) = delivery_window {
763            push_trace(&mut self.windows[index].pending_command_diagnostics, sample);
764        } else {
765            for window in &mut self.windows {
766                push_trace(&mut window.pending_command_diagnostics, sample.clone());
767            }
768        }
769    }
770
771    fn apply_command_invalidation(
772        &mut self,
773        invalidation: CommandInvalidation,
774        source: &str,
775        delivery_window: Option<usize>,
776    ) {
777        let target_index = match invalidation.request.target {
778            InvalidationTarget::Window(window_id) => self
779                .windows
780                .iter()
781                .position(|window| window.id == window_id),
782            InvalidationTarget::Widget(widget_id) => self.windows.iter().position(|window| {
783                window.root.id() == widget_id || window.graph.contains(widget_id)
784            }),
785            InvalidationTarget::Surface(_) => delivery_window,
786        };
787        let Some(index) = target_index else {
788            return;
789        };
790        let request = invalidation.request;
791        push_trace(
792            &mut self.windows[index].pending_invalidation_diagnostics,
793            InvalidationTraceSample {
794                target: request.target,
795                kind: request.kind,
796                region: request.region,
797                source: format!("command:{source}"),
798                reason: invalidation.reason,
799            },
800        );
801        self.windows[index]
802            .schedule
803            .extend(std::slice::from_ref(&request));
804        self.windows[index].pending_invalidations.push(request);
805    }
806
807    fn alloc_window_id(&mut self) -> WindowId {
808        WindowId::new(NEXT_WINDOW_ID.fetch_add(1, Ordering::Relaxed))
809    }
810
811    fn window(&self, window_id: WindowId) -> Result<&WindowState> {
812        self.windows
813            .iter()
814            .find(|window| window.id == window_id)
815            .ok_or_else(|| Error::new(format!("window {} does not exist", window_id.get())))
816    }
817
818    fn window_mut(&mut self, window_id: WindowId) -> Result<&mut WindowState> {
819        self.windows
820            .iter_mut()
821            .find(|window| window.id == window_id)
822            .ok_or_else(|| Error::new(format!("window {} does not exist", window_id.get())))
823    }
824}
825
826impl Default for Runtime {
827    fn default() -> Self {
828        Self::new()
829    }
830}
831
832#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
833pub struct FocusState {
834    pub focused_widget: Option<WidgetId>,
835    pub window_focused: bool,
836}
837
838/// Desired host cursor state for one runtime window.
839///
840/// `revision` advances for every accepted widget request, including a repeated
841/// request for the same value. Platform hosts use it to retry a best-effort
842/// grab from a later user-activation event.
843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub struct WindowCursorState {
845    pub grab_mode: CursorGrabMode,
846    pub visible: bool,
847    pub revision: u64,
848}
849
850impl Default for WindowCursorState {
851    fn default() -> Self {
852        Self {
853            grab_mode: CursorGrabMode::None,
854            visible: true,
855            revision: 0,
856        }
857    }
858}
859
860#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
861pub struct FrameSchedule {
862    pub measure: bool,
863    pub arrange: bool,
864    pub ordering: bool,
865    pub paint: bool,
866    pub semantics: bool,
867    pub hit_test: bool,
868    pub text: bool,
869    pub resources: bool,
870}
871
872impl FrameSchedule {
873    fn bootstrap() -> Self {
874        Self {
875            measure: true,
876            arrange: true,
877            ordering: false,
878            paint: true,
879            semantics: true,
880            hit_test: true,
881            text: false,
882            resources: false,
883        }
884    }
885
886    pub const fn any(self) -> bool {
887        self.measure
888            || self.arrange
889            || self.ordering
890            || self.paint
891            || self.semantics
892            || self.hit_test
893            || self.text
894            || self.resources
895    }
896
897    pub const fn needs_render(self) -> bool {
898        self.measure
899            || self.arrange
900            || self.ordering
901            || self.paint
902            || self.semantics
903            || self.text
904            || self.resources
905    }
906
907    fn clear(&mut self) {
908        *self = Self::default();
909    }
910
911    fn mark(&mut self, kind: InvalidationKind) {
912        match kind {
913            InvalidationKind::Measure => {
914                self.measure = true;
915                self.arrange = true;
916                self.ordering = true;
917                self.paint = true;
918                self.hit_test = true;
919                self.semantics = true;
920            }
921            InvalidationKind::Arrange
922            | InvalidationKind::Transform
923            | InvalidationKind::Clip
924            | InvalidationKind::Visibility => {
925                self.ordering = true;
926                self.arrange = true;
927                self.paint = true;
928                self.hit_test = true;
929                self.semantics = true;
930            }
931            InvalidationKind::Ordering => {
932                self.ordering = true;
933                self.hit_test = true;
934            }
935            InvalidationKind::Effect => {
936                self.paint = true;
937            }
938            InvalidationKind::Paint => {
939                self.paint = true;
940            }
941            InvalidationKind::HitTest => {
942                self.hit_test = true;
943            }
944            InvalidationKind::Text => {
945                self.text = true;
946                self.measure = true;
947                self.arrange = true;
948                self.paint = true;
949                self.semantics = true;
950            }
951            InvalidationKind::Semantics => {
952                self.semantics = true;
953            }
954            InvalidationKind::Resources => {
955                self.resources = true;
956                self.paint = true;
957            }
958        }
959    }
960
961    fn extend(&mut self, invalidations: &[InvalidationRequest]) {
962        for request in invalidations {
963            self.mark(request.kind);
964        }
965    }
966}
967
968#[derive(Debug, Clone, PartialEq)]
969pub struct WidgetGeometrySnapshot {
970    pub layout_bounds: Rect,
971    pub input_bounds: Rect,
972    pub paint_bounds: Rect,
973}
974
975impl WidgetGeometrySnapshot {
976    pub const fn new(layout_bounds: Rect, input_bounds: Rect, paint_bounds: Rect) -> Self {
977        Self {
978            layout_bounds,
979            input_bounds,
980            paint_bounds,
981        }
982    }
983}
984
985#[derive(Debug, Clone, PartialEq)]
986pub struct WidgetNodeSnapshot {
987    pub id: WidgetId,
988    pub widget_name: &'static str,
989    pub parent: Option<WidgetId>,
990    pub children: Vec<WidgetId>,
991    pub measured_size: Size,
992    pub geometry: WidgetGeometrySnapshot,
993    pub local_bounds: Rect,
994    pub presentation_transform: Transform,
995    pub inverse_presentation_transform: Option<Transform>,
996    // Backward-compatible alias of geometry.layout_bounds.
997    pub bounds: Rect,
998    pub paint_boundary: PaintBoundaryMode,
999    pub stack_host: WidgetId,
1000    pub stack_surface: WidgetId,
1001    pub stack_surface_order: usize,
1002    pub transient_owner_surface: Option<WidgetId>,
1003    /// Logical overlay owner coordinating this node, when any.
1004    pub overlay_owner: Option<WidgetId>,
1005    pub is_overlay_owner: bool,
1006    pub is_stack_host: bool,
1007    pub is_stack_surface: bool,
1008    pub hit_test: bool,
1009    pub stack_order_policy: StackOrderPolicy,
1010    pub accepts_focus: bool,
1011    pub focused: bool,
1012}
1013
1014#[derive(Debug, Clone, PartialEq)]
1015pub struct StackHostSnapshot {
1016    pub host: WidgetId,
1017    pub order_policy: StackOrderPolicy,
1018    pub surfaces: Vec<WidgetId>,
1019}
1020
1021#[derive(Debug, Clone, PartialEq)]
1022pub struct WidgetGraphSnapshot {
1023    pub root: WidgetId,
1024    pub nodes: Vec<WidgetNodeSnapshot>,
1025    pub stack_hosts: Vec<StackHostSnapshot>,
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1029pub enum EventRoutePhase {
1030    Capture,
1031    Target,
1032    Bubble,
1033}
1034
1035#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1036pub struct EventRouteStep {
1037    pub widget_id: WidgetId,
1038    pub phase: EventRoutePhase,
1039    pub handled: bool,
1040}
1041
1042/// Privacy-safe event routing trace. Event payloads and typed characters are
1043/// intentionally not retained.
1044#[derive(Debug, Clone, PartialEq, Eq)]
1045pub struct EventRouteTraceSample {
1046    pub sequence: u64,
1047    pub event_kind: &'static str,
1048    pub target: WidgetId,
1049    pub path: Vec<WidgetId>,
1050    pub steps: Vec<EventRouteStep>,
1051    pub handled: bool,
1052}
1053
1054#[derive(Debug, Clone, Copy, PartialEq)]
1055pub struct TimerInspectorSnapshot {
1056    pub token: TimerToken,
1057    pub target: WidgetId,
1058    pub deadline: f64,
1059    pub delivering: bool,
1060}
1061
1062#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1063pub struct AsyncTaskInspectorSnapshot {
1064    pub token: AsyncWakeToken,
1065    pub target: WidgetId,
1066    pub pending_wake: bool,
1067}
1068
1069#[derive(Debug, Clone, PartialEq, Default)]
1070pub struct SchedulerInspectorSnapshot {
1071    pub timers: Vec<TimerInspectorSnapshot>,
1072    pub async_tasks: Vec<AsyncTaskInspectorSnapshot>,
1073    pub requested_animation_frames: Vec<WidgetId>,
1074    pub delivering_animation_frames: Vec<WidgetId>,
1075    pub last_animation_frame_time: Option<f64>,
1076}
1077
1078#[derive(Debug, Clone, PartialEq, Default)]
1079pub struct InspectorHistorySnapshot {
1080    pub event_routes: Vec<EventRouteTraceSample>,
1081    pub reactive_invalidations: Vec<ReactiveInvalidationSample>,
1082    pub command_dispatches: Vec<CommandDispatchSample>,
1083    pub invalidations: Vec<InvalidationTraceSample>,
1084    pub widget_rebuilds: Vec<WidgetRebuildSample>,
1085}
1086
1087/// Renderer-neutral, point-in-time state consumed by testing tools and live
1088/// inspector UIs. Capturing widget-specific diagnostics is opt-in and happens
1089/// only while this snapshot is requested.
1090#[derive(Debug, Clone, PartialEq)]
1091pub struct WindowInspectorSnapshot {
1092    pub window_id: WindowId,
1093    pub title: String,
1094    pub tracing_enabled: bool,
1095    pub focus_state: FocusState,
1096    pub schedule: FrameSchedule,
1097    pub semantics: Vec<SemanticsNode>,
1098    pub widget_graph: WidgetGraphSnapshot,
1099    pub overlays: OverlayManagerSnapshot,
1100    pub scheduler: SchedulerInspectorSnapshot,
1101    pub widget_diagnostics: Vec<WidgetDiagnosticsSnapshot>,
1102    pub last_render_diagnostics: RenderDiagnostics,
1103    pub history: InspectorHistorySnapshot,
1104    pub scene: Option<SceneStatistics>,
1105}
1106
1107#[derive(Debug, Clone, Copy, PartialEq)]
1108struct ScheduledTimer {
1109    token: TimerToken,
1110    deadline: f64,
1111    target: WidgetId,
1112}
1113
1114#[derive(Debug, Clone, Copy, PartialEq)]
1115struct LayerTranslation {
1116    widget_id: WidgetId,
1117    delta: Vector,
1118}
1119
1120#[derive(Debug, Clone, PartialEq)]
1121struct LayerDescriptorRefresh {
1122    widget_id: WidgetId,
1123    descriptor: SceneLayerDescriptor,
1124}
1125
1126#[derive(Debug, Default)]
1127struct GraphChangeSet {
1128    // Exact changed nodes, before promotion to a scene-layer repaint boundary.
1129    output_widgets: Vec<WidgetId>,
1130    repaint_widgets: Vec<WidgetId>,
1131    transform_widgets: Vec<LayerTranslation>,
1132}
1133
1134const ANIMATION_FRAME_INTERVAL_SECONDS: f64 = 1.0 / 120.0;
1135
1136#[derive(Debug, Clone)]
1137struct ActiveDrag {
1138    session_id: DragSessionId,
1139    scope_id: DragScopeId,
1140    pointer_id: u64,
1141    source: WidgetId,
1142    start_position: Point,
1143    position: Point,
1144    payload: DragPayload,
1145    allowed_effect: DropEffect,
1146    preview_label: Option<Arc<str>>,
1147    hover_path: Vec<WidgetId>,
1148    accepted_target: Option<WidgetId>,
1149    accepted_effect: DropEffect,
1150}
1151
1152impl ActiveDrag {
1153    fn from_request(request: BeginDragRequest) -> Self {
1154        Self {
1155            session_id: request.session_id,
1156            scope_id: request.scope_id,
1157            pointer_id: request.pointer_id,
1158            source: request.source,
1159            start_position: request.position,
1160            position: request.position,
1161            payload: request.payload,
1162            allowed_effect: request.allowed_effect,
1163            preview_label: request.preview_label.map(Arc::from),
1164            hover_path: Vec::new(),
1165            accepted_target: None,
1166            accepted_effect: DropEffect::None,
1167        }
1168    }
1169
1170    fn event(
1171        &self,
1172        kind: DragEventKind,
1173        position: Point,
1174        target: Option<WidgetId>,
1175        accepted_effect: DropEffect,
1176        outcome: Option<DragOutcome>,
1177    ) -> Event {
1178        Event::Drag(DragEvent {
1179            kind,
1180            session_id: self.session_id,
1181            scope_id: self.scope_id,
1182            pointer_id: self.pointer_id,
1183            source: self.source,
1184            target,
1185            position,
1186            start_position: self.start_position,
1187            payload: self.payload.clone(),
1188            allowed_effect: self.allowed_effect,
1189            accepted_effect,
1190            preview_label: self.preview_label.clone(),
1191            outcome,
1192        })
1193    }
1194}
1195
1196#[derive(Debug, Default)]
1197struct RuntimeCursorState {
1198    state: WindowCursorState,
1199    grab_owner: Option<WidgetId>,
1200    visibility_owner: Option<WidgetId>,
1201}
1202
1203struct WindowState {
1204    id: WindowId,
1205    title: String,
1206    icon: Option<WindowIcon>,
1207    initial_size: Option<Size>,
1208    initial_position: Option<Point>,
1209    root: WidgetPod,
1210    measure_queries: measure_cache::SharedQueryCache,
1211    output_cache: output_cache::SharedOutputCache,
1212    graph: WidgetGraph,
1213    overlay_manager: overlay::OverlayManager,
1214    pending_overlay_focus: Option<FocusRequest>,
1215    focus: FocusState,
1216    focused_semantics: Option<WidgetId>,
1217    schedule: FrameSchedule,
1218    scale_factor: f32,
1219    raw_dpi: Option<f32>,
1220    safe_area: SafeAreaInsets,
1221    viewport_hint: Option<Size>,
1222    viewport: Option<Size>,
1223    last_frame: Option<SceneFrame>,
1224    last_paint_bounds_by_widget: HashMap<WidgetId, Rect>,
1225    last_semantics: Vec<SemanticsNode>,
1226    pending_invalidations: Vec<InvalidationRequest>,
1227    // Counts preserve provenance without changing the public request type. If an
1228    // explicit request has the same target/kind, the combined request is a subtree
1229    // invalidation; layout/command-generated requests are conservative too.
1230    pending_local_output: HashMap<(WidgetId, InvalidationKind), usize>,
1231    pending_reactive_diagnostics: Vec<ReactiveInvalidationSample>,
1232    reactive_hub: Arc<reactive::ReactiveInvalidationHub>,
1233    pointer_capture: HashMap<u64, WidgetId>,
1234    cursor: RuntimeCursorState,
1235    last_pointer_events: HashMap<u64, PointerEvent>,
1236    pointer_hover_paths: HashMap<u64, Vec<WidgetId>>,
1237    active_drag: Option<ActiveDrag>,
1238    scheduled_timers: Vec<ScheduledTimer>,
1239    delivering_timers: HashMap<TimerToken, WidgetId>,
1240    async_wake_targets: HashMap<AsyncWakeToken, WidgetId>,
1241    pending_async_wakeups: VecDeque<AsyncWakeToken>,
1242    requested_animation_frames: BTreeSet<WidgetId>,
1243    delivering_animation_frames: VecDeque<WidgetId>,
1244    last_animation_frame_time: Option<f64>,
1245    next_animation_frame_index: u64,
1246    pending_animation_wake_count: usize,
1247    ime_composition_rect: Option<Rect>,
1248    last_tick_time: f64,
1249    clipboard: Clipboard,
1250    command_sender: CommandSender,
1251    command_listeners: CommandListeners,
1252    pending_command_diagnostics: Vec<CommandDispatchSample>,
1253    pending_invalidation_diagnostics: Vec<InvalidationTraceSample>,
1254    inspector_tracing_enabled: bool,
1255    next_event_route_sequence: u64,
1256    event_route_history: VecDeque<EventRouteTraceSample>,
1257    reactive_invalidation_history: VecDeque<ReactiveInvalidationSample>,
1258    command_dispatch_history: VecDeque<CommandDispatchSample>,
1259    invalidation_history: VecDeque<InvalidationTraceSample>,
1260    widget_rebuild_history: VecDeque<WidgetRebuildSample>,
1261    last_render_diagnostics: RenderDiagnostics,
1262}
1263
1264impl WindowState {
1265    #[allow(clippy::too_many_arguments)]
1266    fn new(
1267        id: WindowId,
1268        title: String,
1269        icon: Option<WindowIcon>,
1270        initial_size: Option<Size>,
1271        initial_position: Option<Point>,
1272        root: WidgetPod,
1273        command_listeners: CommandListeners,
1274        command_sender: CommandSender,
1275    ) -> Self {
1276        let focus = FocusState {
1277            focused_widget: None,
1278            window_focused: true,
1279        };
1280
1281        let reactive_hub = reactive::ReactiveInvalidationHub::new();
1282        reactive::register_window(id, &reactive_hub);
1283        Self {
1284            id,
1285            title,
1286            icon,
1287            initial_size,
1288            initial_position,
1289            graph: WidgetGraph::empty(root.id()),
1290            measure_queries: measure_cache::MeasureQueryCache::shared(),
1291            output_cache: output_cache::OutputCache::shared(),
1292            overlay_manager: overlay::OverlayManager::default(),
1293            pending_overlay_focus: None,
1294            root,
1295            focus,
1296            focused_semantics: None,
1297            schedule: FrameSchedule::bootstrap(),
1298            scale_factor: 1.0,
1299            raw_dpi: None,
1300            safe_area: SafeAreaInsets::ZERO,
1301            viewport_hint: None,
1302            viewport: None,
1303            last_frame: None,
1304            last_paint_bounds_by_widget: HashMap::new(),
1305            last_semantics: Vec::new(),
1306            pending_invalidations: Vec::new(),
1307            pending_local_output: HashMap::new(),
1308            pending_reactive_diagnostics: Vec::new(),
1309            reactive_hub,
1310            pointer_capture: HashMap::new(),
1311            cursor: RuntimeCursorState::default(),
1312            last_pointer_events: HashMap::new(),
1313            pointer_hover_paths: HashMap::new(),
1314            active_drag: None,
1315            scheduled_timers: Vec::new(),
1316            delivering_timers: HashMap::new(),
1317            async_wake_targets: HashMap::new(),
1318            pending_async_wakeups: VecDeque::new(),
1319            requested_animation_frames: BTreeSet::new(),
1320            delivering_animation_frames: VecDeque::new(),
1321            last_animation_frame_time: None,
1322            next_animation_frame_index: 0,
1323            pending_animation_wake_count: 0,
1324            ime_composition_rect: None,
1325            last_tick_time: 0.0,
1326            clipboard: Clipboard::new(),
1327            command_sender,
1328            command_listeners,
1329            pending_command_diagnostics: Vec::new(),
1330            pending_invalidation_diagnostics: Vec::new(),
1331            inspector_tracing_enabled: false,
1332            next_event_route_sequence: 0,
1333            event_route_history: VecDeque::new(),
1334            reactive_invalidation_history: VecDeque::new(),
1335            command_dispatch_history: VecDeque::new(),
1336            invalidation_history: VecDeque::new(),
1337            widget_rebuild_history: VecDeque::new(),
1338            last_render_diagnostics: RenderDiagnostics::default(),
1339        }
1340    }
1341
1342    fn drain_reactive_invalidations(&mut self) {
1343        const MAX_REACTIVE_ROUNDS: usize = 8;
1344
1345        for _ in 0..MAX_REACTIVE_ROUNDS {
1346            let pending = self.reactive_hub.drain();
1347            if pending.is_empty() {
1348                break;
1349            }
1350
1351            let mut invalidations = Vec::new();
1352            let mut targets = BTreeSet::new();
1353            for (request, mut sample, local_output) in pending {
1354                let InvalidationTarget::Widget(widget_id) = request.target else {
1355                    continue;
1356                };
1357                let delivered = self.graph.is_empty() || self.graph.contains(widget_id);
1358                sample.delivered = delivered;
1359                if delivered {
1360                    push_trace(
1361                        &mut self.pending_invalidation_diagnostics,
1362                        InvalidationTraceSample {
1363                            target: request.target,
1364                            kind: request.kind,
1365                            region: request.region,
1366                            source: format!("reactive:{}", sample.source_name),
1367                            reason: Some(format!("observable version {}", sample.version)),
1368                        },
1369                    );
1370                }
1371                self.pending_reactive_diagnostics.push(sample);
1372                if delivered {
1373                    if local_output {
1374                        *self
1375                            .pending_local_output
1376                            .entry((widget_id, request.kind))
1377                            .or_default() += 1;
1378                    }
1379                    targets.insert(widget_id);
1380                    invalidations.push(request);
1381                }
1382            }
1383
1384            for target in targets {
1385                let command = command::queued_command(
1386                    CommandTarget::Widget {
1387                        window_id: self.id,
1388                        widget_id: target,
1389                    },
1390                    CommandDelivery::Directed,
1391                    REACTIVE_CHANGED,
1392                    (),
1393                );
1394                let Some(dispatch) = self.dispatch_direct_command(target, &command) else {
1395                    continue;
1396                };
1397                if dispatch.handled {
1398                    // A handler may mutate descendants as part of reacting to
1399                    // the source. Retain the prior subtree callback contract.
1400                    self.pending_local_output.retain(|(id, _), _| *id != target);
1401                }
1402                let focus_request = dispatch.focus_request;
1403                let mut effects = EventEffects::default();
1404                effects.extend(dispatch);
1405                self.apply_event_effects(effects, &mut invalidations);
1406                if let Some(request) = focus_request {
1407                    let focus_effects = self.apply_focus_request(request);
1408                    self.apply_event_effects(focus_effects, &mut invalidations);
1409                }
1410            }
1411
1412            self.schedule.extend(&invalidations);
1413            self.pending_invalidations.extend(invalidations);
1414        }
1415    }
1416
1417    fn needs_render(&self) -> bool {
1418        self.last_frame.is_none() || self.schedule.needs_render() || self.reactive_hub.has_pending()
1419    }
1420
1421    fn handle_event(
1422        &mut self,
1423        event: Event,
1424        text_system: Arc<TextSystem>,
1425        font_registry: Arc<FontRegistry>,
1426        image_registry: Arc<ImageRegistry>,
1427    ) -> bool {
1428        if matches!(event, Event::Window(WindowEvent::RedrawRequested)) {
1429            diagnostics::begin_widget_timing_collection();
1430            sui_text::begin_text_timing_collection();
1431        }
1432        if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. })) {
1433            self.pending_animation_wake_count = self.pending_animation_wake_count.saturating_add(1);
1434        }
1435        if let Event::Pointer(pointer) = &event {
1436            self.last_pointer_events
1437                .insert(pointer.pointer_id, pointer.clone());
1438        }
1439
1440        self.preprocess_window_event(&event);
1441        self.ensure_graph_for_event(&event, text_system, font_registry, image_registry);
1442
1443        let mut invalidations = Vec::new();
1444        self.apply_pending_overlay_focus(&mut invalidations);
1445
1446        let captured_target = match &event {
1447            Event::Pointer(pointer) => self.pointer_capture.get(&pointer.pointer_id).copied(),
1448            _ => None,
1449        };
1450
1451        let pointer_hit_target = match &event {
1452            Event::Pointer(pointer) => self.pointer_hit_target(pointer.position),
1453            _ => None,
1454        };
1455        let mut hit_target = match &event {
1456            Event::Pointer(_) if captured_target.is_some() => None,
1457            Event::Pointer(_) => pointer_hit_target,
1458            _ => None,
1459        };
1460
1461        if matches!(event, Event::Window(WindowEvent::Focused(false))) {
1462            self.cancel_all_pointer_captures(&mut invalidations);
1463            self.pointer_capture.clear();
1464            self.last_pointer_events.clear();
1465            self.active_drag = None;
1466            self.reset_cursor_state();
1467        }
1468        let mut skip_primary_route = false;
1469        if let Event::Pointer(pointer) = &event {
1470            let hover_route = self.update_pointer_hover_path(pointer, hit_target);
1471            self.apply_event_effects(hover_route.effects, &mut invalidations);
1472
1473            if let Some(request) = hover_route.focus_request {
1474                let focus_effects = self.apply_focus_request(request);
1475                self.apply_event_effects(focus_effects, &mut invalidations);
1476            }
1477
1478            skip_primary_route = hover_route.skip_primary_route;
1479        }
1480
1481        if skip_primary_route {
1482            self.finish_event(&event);
1483            self.record_event_invalidations(&invalidations, &event);
1484            self.schedule.extend(&invalidations);
1485            self.pending_invalidations.extend(invalidations);
1486            return false;
1487        }
1488
1489        if matches!(
1490            &event,
1491            Event::Keyboard(key)
1492                if key.state == KeyState::Pressed
1493                    && key.key == "BrowserBack"
1494                    && !key.repeat
1495                    && !key.is_composing
1496        ) && self.ime_composition_rect.is_some()
1497            && self.focus.focused_widget.is_some()
1498        {
1499            // Android exposes its system Back key as `BrowserBack`. When an editor has
1500            // enabled the IME, the first press dismisses editing instead of closing the
1501            // containing window. This clear deliberately bypasses modal focus trapping:
1502            // keeping logical focus would cause the next frame to enable the IME again.
1503            self.ime_composition_rect = None;
1504            let effects = self.apply_focus_request_unconstrained(FocusRequest::Clear);
1505            self.apply_event_effects(effects, &mut invalidations);
1506            self.finish_event(&event);
1507            self.record_event_invalidations(&invalidations, &event);
1508            self.schedule.extend(&invalidations);
1509            self.pending_invalidations.extend(invalidations);
1510            return true;
1511        }
1512
1513        if matches!(
1514            &event,
1515            Event::Keyboard(key)
1516                if key.state == KeyState::Pressed
1517                    && matches!(key.key.as_str(), "Escape" | "BrowserBack")
1518                    && !key.repeat
1519                    && !key.is_composing
1520        ) && self.dispatch_overlay_dismissal(
1521            OverlayDismissReason::Escape,
1522            None,
1523            &mut invalidations,
1524        ) {
1525            self.finish_event(&event);
1526            self.record_event_invalidations(&invalidations, &event);
1527            self.schedule.extend(&invalidations);
1528            self.pending_invalidations.extend(invalidations);
1529            return true;
1530        }
1531
1532        if let Event::Pointer(pointer) = &event
1533            && pointer.kind == PointerEventKind::Down
1534            && pointer.button == Some(PointerButton::Primary)
1535            && let Some(entry) = self
1536                .overlay_manager
1537                .topmost_dismissible(OverlayDismissReason::OutsidePointer)
1538                .cloned()
1539            && !hit_target.is_some_and(|target| self.target_is_in_overlay(entry.owner, target))
1540        {
1541            self.dispatch_overlay_dismissal(
1542                OverlayDismissReason::OutsidePointer,
1543                Some(pointer.position),
1544                &mut invalidations,
1545            );
1546        }
1547
1548        if let Some(modal) = self.overlay_manager.active_modal()
1549            && hit_target.is_some_and(|target| !self.target_is_in_overlay(modal, target))
1550        {
1551            hit_target = Some(modal);
1552        }
1553
1554        let target = self.resolve_event_target(&event, hit_target);
1555
1556        let route = self.route_event(target, &event);
1557        let handled = route.handled;
1558
1559        let focus_request = route
1560            .focus_request
1561            .or_else(|| self.default_focus_request(&event, hit_target, &route.path));
1562        self.apply_event_effects(route.effects, &mut invalidations);
1563
1564        if let Some(request) = focus_request {
1565            let focus_effects = self.apply_focus_request(request);
1566            self.apply_event_effects(focus_effects, &mut invalidations);
1567        }
1568
1569        if let Event::Pointer(pointer) = &event {
1570            let drag_effects = self.handle_drag_pointer_event(pointer, pointer_hit_target);
1571            self.apply_event_effects(drag_effects, &mut invalidations);
1572        }
1573
1574        self.finish_event(&event);
1575        self.record_event_invalidations(&invalidations, &event);
1576        self.schedule.extend(&invalidations);
1577        self.pending_invalidations.extend(invalidations);
1578        handled
1579    }
1580
1581    fn record_event_invalidations(&mut self, invalidations: &[InvalidationRequest], event: &Event) {
1582        let source = event_trace_source(event);
1583        extend_traces(
1584            &mut self.pending_invalidation_diagnostics,
1585            invalidations.iter().map(|request| InvalidationTraceSample {
1586                target: request.target,
1587                kind: request.kind,
1588                region: request.region,
1589                source: source.clone(),
1590                reason: None,
1591            }),
1592        );
1593    }
1594
1595    fn target_is_in_overlay(&self, owner: WidgetId, target: WidgetId) -> bool {
1596        target == owner || self.graph.is_ancestor_of(owner, target)
1597    }
1598
1599    fn dispatch_overlay_dismissal(
1600        &mut self,
1601        reason: OverlayDismissReason,
1602        pointer_position: Option<Point>,
1603        invalidations: &mut Vec<InvalidationRequest>,
1604    ) -> bool {
1605        let Some(entry) = self.overlay_manager.topmost_dismissible(reason).cloned() else {
1606            return false;
1607        };
1608        let mut request = OverlayDismissRequest::new(reason);
1609        request.pointer_position = pointer_position;
1610        let queued = command::queued_command(
1611            CommandTarget::Widget {
1612                window_id: self.id,
1613                widget_id: entry.owner,
1614            },
1615            CommandDelivery::Directed,
1616            OVERLAY_DISMISS_REQUEST,
1617            request,
1618        );
1619        let Some(dispatch) = self.dispatch_direct_command(entry.owner, &queued) else {
1620            return false;
1621        };
1622        let handled = dispatch.handled;
1623        let focus_request = dispatch.focus_request;
1624        let mut effects = EventEffects::default();
1625        effects.extend(dispatch);
1626        self.apply_event_effects(effects, invalidations);
1627        if let Some(request) = focus_request {
1628            let effects = self.apply_focus_request(request);
1629            self.apply_event_effects(effects, invalidations);
1630        }
1631        if handled {
1632            self.overlay_manager
1633                .trace_dismissal(entry.owner, entry.options.kind, reason);
1634        }
1635        handled
1636    }
1637
1638    fn handle_semantics_action(
1639        &mut self,
1640        target: WidgetId,
1641        action: SemanticsActionRequest,
1642        text_system: Arc<TextSystem>,
1643        font_registry: Arc<FontRegistry>,
1644        image_registry: Arc<ImageRegistry>,
1645    ) -> bool {
1646        let Some(node) = self
1647            .last_semantics
1648            .iter()
1649            .find(|node| node.id == target)
1650            .cloned()
1651        else {
1652            return false;
1653        };
1654
1655        if node.state.hidden
1656            || node.state.disabled
1657            || !node.actions.contains(&action.advertised_action())
1658        {
1659            return false;
1660        }
1661
1662        if matches!(
1663            (&action, node.state.expanded),
1664            (SemanticsActionRequest::Expand, Some(true))
1665                | (SemanticsActionRequest::Collapse, Some(false))
1666        ) {
1667            return true;
1668        }
1669
1670        let event = Event::Semantics(SemanticsEvent::new(target, action.clone()));
1671        self.ensure_graph_for_event(
1672            &event,
1673            Arc::clone(&text_system),
1674            Arc::clone(&font_registry),
1675            Arc::clone(&image_registry),
1676        );
1677
1678        let route_target = self.semantics_route_target(target);
1679        let route = self.route_event(route_target, &event);
1680        let handled = route.handled;
1681        let semantics_was_focused = self.focused_semantics == Some(target);
1682        let mut focus_request = route.focus_request;
1683        let widget_requested_focus = matches!(focus_request, Some(FocusRequest::Focus(_)));
1684        let mut focus_succeeded = false;
1685        let mut invalidations = Vec::new();
1686        self.apply_event_effects(route.effects, &mut invalidations);
1687
1688        match action {
1689            SemanticsActionRequest::Focus => {
1690                let runtime_focus_request = focus_request
1691                    .is_none()
1692                    .then(|| self.focus_request_for(route_target))
1693                    .flatten();
1694                focus_succeeded =
1695                    handled || widget_requested_focus || runtime_focus_request.is_some();
1696                focus_request = focus_request.or(runtime_focus_request);
1697            }
1698            SemanticsActionRequest::Blur if semantics_was_focused => {
1699                focus_request = Some(FocusRequest::Clear);
1700            }
1701            _ => {}
1702        }
1703
1704        if let Some(request) = focus_request {
1705            let focus_effects = self.apply_focus_request(request);
1706            self.apply_event_effects(focus_effects, &mut invalidations);
1707        }
1708
1709        match action {
1710            SemanticsActionRequest::Focus if focus_succeeded => {
1711                self.focused_semantics = Some(target);
1712                self.schedule.mark(InvalidationKind::Semantics);
1713            }
1714            SemanticsActionRequest::Blur if semantics_was_focused => {
1715                self.focused_semantics = None;
1716                self.schedule.mark(InvalidationKind::Semantics);
1717            }
1718            _ => {}
1719        }
1720
1721        self.schedule.extend(&invalidations);
1722        self.pending_invalidations.extend(invalidations);
1723
1724        let pointer_fallback = matches!(
1725            action,
1726            SemanticsActionRequest::Activate
1727                | SemanticsActionRequest::Expand
1728                | SemanticsActionRequest::Collapse
1729        );
1730        if pointer_fallback && !handled && !node.bounds.is_empty() {
1731            self.dispatch_semantics_pointer_activation(
1732                node.bounds,
1733                text_system,
1734                font_registry,
1735                image_registry,
1736            );
1737            return true;
1738        }
1739
1740        handled
1741            || matches!(action, SemanticsActionRequest::Focus) && focus_succeeded
1742            || matches!(action, SemanticsActionRequest::Blur) && semantics_was_focused
1743    }
1744
1745    fn semantics_route_target(&self, target: WidgetId) -> WidgetId {
1746        let mut current = Some(target);
1747        let mut visited = HashSet::new();
1748
1749        while let Some(candidate) = current {
1750            if !visited.insert(candidate) {
1751                break;
1752            }
1753            if self.graph.contains(candidate) {
1754                return candidate;
1755            }
1756            current = self
1757                .last_semantics
1758                .iter()
1759                .find(|node| node.id == candidate)
1760                .and_then(|node| node.parent);
1761        }
1762
1763        self.root.id()
1764    }
1765
1766    fn focus_request_for(&self, target: WidgetId) -> Option<FocusRequest> {
1767        self.graph.path_to(target).and_then(|path| {
1768            path.into_iter()
1769                .rev()
1770                .find(|widget_id| {
1771                    self.graph
1772                        .node(*widget_id)
1773                        .is_some_and(|node| node.accepts_focus)
1774                })
1775                .map(FocusRequest::Focus)
1776        })
1777    }
1778
1779    fn dispatch_semantics_pointer_activation(
1780        &mut self,
1781        bounds: Rect,
1782        text_system: Arc<TextSystem>,
1783        font_registry: Arc<FontRegistry>,
1784        image_registry: Arc<ImageRegistry>,
1785    ) {
1786        let position = Point::new(
1787            bounds.x() + bounds.width() * 0.5,
1788            bounds.y() + bounds.height() * 0.5,
1789        );
1790
1791        let mut down = PointerEvent::new(PointerEventKind::Down, position);
1792        down.button = Some(PointerButton::Primary);
1793        down.buttons.insert(PointerButton::Primary);
1794        self.handle_event(
1795            Event::Pointer(down),
1796            Arc::clone(&text_system),
1797            Arc::clone(&font_registry),
1798            Arc::clone(&image_registry),
1799        );
1800
1801        let mut up = PointerEvent::new(PointerEventKind::Up, position);
1802        up.button = Some(PointerButton::Primary);
1803        self.handle_event(
1804            Event::Pointer(up),
1805            text_system,
1806            font_registry,
1807            image_registry,
1808        );
1809    }
1810
1811    fn update_pointer_hover_path(
1812        &mut self,
1813        pointer: &PointerEvent,
1814        hit_target: Option<WidgetId>,
1815    ) -> HoverTransitionResult {
1816        let skip_primary_route = matches!(
1817            pointer.kind,
1818            PointerEventKind::Enter | PointerEventKind::Leave
1819        );
1820
1821        let next_path = match pointer.kind {
1822            PointerEventKind::Move | PointerEventKind::Enter
1823                if pointer.buttons.is_empty()
1824                    && !self.pointer_capture.contains_key(&pointer.pointer_id) =>
1825            {
1826                self.hover_transition_path(hit_target)
1827            }
1828            PointerEventKind::Leave | PointerEventKind::Cancel => Vec::new(),
1829            _ => {
1830                return HoverTransitionResult {
1831                    skip_primary_route,
1832                    ..HoverTransitionResult::default()
1833                };
1834            }
1835        };
1836
1837        let previous_path = self
1838            .pointer_hover_paths
1839            .remove(&pointer.pointer_id)
1840            .unwrap_or_default();
1841        if previous_path == next_path {
1842            if !next_path.is_empty() {
1843                self.pointer_hover_paths
1844                    .insert(pointer.pointer_id, next_path);
1845            }
1846            return HoverTransitionResult {
1847                skip_primary_route,
1848                ..HoverTransitionResult::default()
1849            };
1850        }
1851
1852        let shared_prefix_len = previous_path
1853            .iter()
1854            .zip(next_path.iter())
1855            .take_while(|(left, right)| left == right)
1856            .count();
1857
1858        let mut result = HoverTransitionResult {
1859            skip_primary_route,
1860            ..HoverTransitionResult::default()
1861        };
1862
1863        let mut leave_pointer = pointer.clone();
1864        leave_pointer.kind = PointerEventKind::Leave;
1865        let leave_event = Event::Pointer(leave_pointer);
1866        for widget_id in previous_path[shared_prefix_len..].iter().rev().copied() {
1867            let dispatch = self.dispatch_direct_event(widget_id, &leave_event);
1868            let dispatch_focus_request = dispatch.focus_request;
1869            result.effects.extend(dispatch);
1870            if dispatch_focus_request.is_some() {
1871                result.focus_request = dispatch_focus_request;
1872            }
1873        }
1874
1875        let mut enter_pointer = pointer.clone();
1876        enter_pointer.kind = PointerEventKind::Enter;
1877        let enter_event = Event::Pointer(enter_pointer);
1878        for widget_id in next_path[shared_prefix_len..].iter().copied() {
1879            let dispatch = self.dispatch_direct_event(widget_id, &enter_event);
1880            let dispatch_focus_request = dispatch.focus_request;
1881            result.effects.extend(dispatch);
1882            if dispatch_focus_request.is_some() {
1883                result.focus_request = dispatch_focus_request;
1884            }
1885        }
1886
1887        if !next_path.is_empty() {
1888            self.pointer_hover_paths
1889                .insert(pointer.pointer_id, next_path);
1890        }
1891
1892        result
1893    }
1894
1895    fn hover_transition_path(&self, hit_target: Option<WidgetId>) -> Vec<WidgetId> {
1896        hit_target
1897            .and_then(|target| self.graph.path_to(target))
1898            .map(|path| path.into_iter().skip(1).collect())
1899            .unwrap_or_default()
1900    }
1901
1902    fn dispatch_direct_event(&mut self, target: WidgetId, event: &Event) -> widget::EventDispatch {
1903        let path = self.graph.path_to(target);
1904        let dpi_info = self.current_dpi_info();
1905        self.root
1906            .dispatch_event_for_path(
1907                path.as_deref().unwrap_or(&[self.root.id()]),
1908                self.id,
1909                dpi_info,
1910                self.last_tick_time,
1911                EventPhase::Target,
1912                self.focus.focused_widget,
1913                &self.clipboard,
1914                &self.command_sender,
1915                event,
1916            )
1917            .or_else(|| {
1918                self.root.dispatch_event_for(
1919                    target,
1920                    self.id,
1921                    dpi_info,
1922                    self.last_tick_time,
1923                    EventPhase::Target,
1924                    self.focus.focused_widget,
1925                    &self.clipboard,
1926                    &self.command_sender,
1927                    event,
1928                )
1929            })
1930            .unwrap_or_else(empty_dispatch)
1931    }
1932
1933    fn dispatch_direct_command(
1934        &mut self,
1935        target: WidgetId,
1936        command: &QueuedCommand,
1937    ) -> Option<widget::EventDispatch> {
1938        let path = if target == self.root.id() {
1939            vec![target]
1940        } else {
1941            self.graph.path_to(target)?
1942        };
1943        let dpi_info = self.current_dpi_info();
1944        let command = Command::new(command);
1945        self.root
1946            .dispatch_command_for_path(
1947                &path,
1948                self.id,
1949                dpi_info,
1950                self.last_tick_time,
1951                self.focus.focused_widget,
1952                &self.clipboard,
1953                &self.command_sender,
1954                &command,
1955            )
1956            .or_else(|| {
1957                self.root.dispatch_command_for(
1958                    target,
1959                    self.id,
1960                    dpi_info,
1961                    self.last_tick_time,
1962                    self.focus.focused_widget,
1963                    &self.clipboard,
1964                    &self.command_sender,
1965                    &command,
1966                )
1967            })
1968    }
1969
1970    fn record_command_invalidations(
1971        &mut self,
1972        invalidations: &[InvalidationRequest],
1973        source: &str,
1974        reason: Option<&str>,
1975    ) {
1976        extend_traces(
1977            &mut self.pending_invalidation_diagnostics,
1978            invalidations.iter().map(|request| InvalidationTraceSample {
1979                target: request.target,
1980                kind: request.kind,
1981                region: request.region,
1982                source: format!("command:{source}"),
1983                reason: reason.map(str::to_string),
1984            }),
1985        );
1986    }
1987
1988    fn pointer_hit_target(&mut self, point: Point) -> Option<WidgetId> {
1989        let floating_hit = self.floating_layer_hit_test(point);
1990        let focused_floating_hit = if floating_hit.is_none() {
1991            self.focused_floating_layer_hit_test(point)
1992        } else {
1993            None
1994        };
1995        floating_hit
1996            .or(focused_floating_hit)
1997            .or_else(|| self.graph.hit_test(point))
1998    }
1999
2000    fn floating_layer_hit_test(&mut self, point: Point) -> Option<WidgetId> {
2001        let effect_hit = {
2002            let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
2003            scene_hit_test_for_phase(
2004                scene,
2005                point,
2006                HitTestCompositionPhase::Effect,
2007                HitTestCompositionPhase::Normal,
2008            )
2009        };
2010        if let Some(widget_id) = effect_hit
2011            && self
2012                .current_widget_matches_hit_test_phase(widget_id, HitTestCompositionPhase::Effect)
2013        {
2014            return self
2015                .graph
2016                .hit_test_within(widget_id, point)
2017                .or(Some(widget_id));
2018        }
2019
2020        let overlay_hit = {
2021            let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
2022            scene_hit_test_for_phase(
2023                scene,
2024                point,
2025                HitTestCompositionPhase::Overlay,
2026                HitTestCompositionPhase::Normal,
2027            )
2028        };
2029        overlay_hit.and_then(|widget_id| {
2030            self.current_widget_matches_hit_test_phase(widget_id, HitTestCompositionPhase::Overlay)
2031                .then(|| {
2032                    self.graph
2033                        .hit_test_within(widget_id, point)
2034                        .unwrap_or(widget_id)
2035                })
2036        })
2037    }
2038
2039    fn focused_floating_layer_hit_test(&mut self, point: Point) -> Option<WidgetId> {
2040        let focused = self.focus.focused_widget?;
2041        if !self.current_widget_matches_hit_test_phase(focused, HitTestCompositionPhase::Overlay)
2042            && !self.current_widget_matches_hit_test_phase(focused, HitTestCompositionPhase::Effect)
2043        {
2044            return None;
2045        }
2046
2047        let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
2048        let descriptor = collect_scene_layers(scene).get(&focused)?.clone();
2049        (descriptor.hit_test && descriptor.paint_bounds.contains(point)).then_some(focused)
2050    }
2051
2052    fn current_widget_matches_hit_test_phase(
2053        &mut self,
2054        widget_id: WidgetId,
2055        target_phase: HitTestCompositionPhase,
2056    ) -> bool {
2057        if !self.graph.node(widget_id).is_some_and(|node| node.hit_test) {
2058            return false;
2059        }
2060        let Some(composition_mode) = self.current_widget_composition_mode(widget_id) else {
2061            return false;
2062        };
2063
2064        next_hit_test_phase(HitTestCompositionPhase::Normal, composition_mode) == target_phase
2065    }
2066
2067    fn current_widget_composition_mode(
2068        &mut self,
2069        widget_id: WidgetId,
2070    ) -> Option<LayerCompositionMode> {
2071        self.root.layer_composition_mode_for(widget_id)
2072    }
2073
2074    fn animation_frame_deadline(&self) -> Option<f64> {
2075        (!self.requested_animation_frames.is_empty()).then_some(
2076            self.last_animation_frame_time
2077                .map_or(self.last_tick_time, |last| {
2078                    last + ANIMATION_FRAME_INTERVAL_SECONDS
2079                }),
2080        )
2081    }
2082
2083    fn next_wakeup_time(&self) -> Option<f64> {
2084        let mut next = self
2085            .scheduled_timers
2086            .iter()
2087            .map(|timer| timer.deadline)
2088            .min_by(|left, right| left.total_cmp(right));
2089
2090        if !self.pending_async_wakeups.is_empty() {
2091            next = Some(next.map_or(self.last_tick_time, |deadline| {
2092                deadline.min(self.last_tick_time)
2093            }));
2094        }
2095
2096        if let Some(animation_deadline) = self.animation_frame_deadline() {
2097            next = Some(next.map_or(animation_deadline, |deadline| {
2098                deadline.min(animation_deadline)
2099            }));
2100        }
2101
2102        next
2103    }
2104
2105    fn active_animated_widget_count(&self) -> usize {
2106        self.requested_animation_frames
2107            .iter()
2108            .copied()
2109            .chain(self.delivering_animation_frames.iter().copied())
2110            .collect::<BTreeSet<_>>()
2111            .len()
2112    }
2113
2114    fn animation_frame_is_transform_only(
2115        &self,
2116        repainted: bool,
2117        layer_updates: &[SceneLayerUpdate],
2118    ) -> bool {
2119        !repainted
2120            && !layer_updates.is_empty()
2121            && layer_updates.iter().all(|update| {
2122                matches!(
2123                    update.kind,
2124                    SceneLayerUpdateKind::Transform
2125                        | SceneLayerUpdateKind::Effect
2126                        | SceneLayerUpdateKind::Visibility
2127                )
2128            })
2129    }
2130
2131    fn drain_ready_events(&mut self) -> Vec<Event> {
2132        let now = self.last_tick_time;
2133        let mut ready = Vec::new();
2134        let mut pending_timers = Vec::with_capacity(self.scheduled_timers.len());
2135
2136        for timer in self.scheduled_timers.drain(..) {
2137            if timer.deadline <= now {
2138                self.delivering_timers.insert(timer.token, timer.target);
2139                ready.push(Event::Wake(WakeEvent::Timer {
2140                    token: timer.token,
2141                    time: now,
2142                    deadline: timer.deadline,
2143                }));
2144            } else {
2145                pending_timers.push(timer);
2146            }
2147        }
2148        self.scheduled_timers = pending_timers;
2149
2150        while let Some(token) = self.pending_async_wakeups.pop_front() {
2151            if self.async_wake_targets.contains_key(&token) {
2152                ready.push(Event::Wake(WakeEvent::Async { token, time: now }));
2153            }
2154        }
2155
2156        if self
2157            .animation_frame_deadline()
2158            .is_some_and(|deadline| deadline <= now)
2159        {
2160            let delta = self
2161                .last_animation_frame_time
2162                .map(|last| (now - last).max(0.0))
2163                .unwrap_or(0.0);
2164            let frame_index = self.next_animation_frame_index;
2165            self.next_animation_frame_index = self.next_animation_frame_index.saturating_add(1);
2166
2167            let requested = std::mem::take(&mut self.requested_animation_frames);
2168            self.delivering_animation_frames
2169                .extend(requested.iter().copied());
2170            ready.extend(requested.iter().map(|_| {
2171                Event::Wake(WakeEvent::AnimationFrame {
2172                    time: now,
2173                    delta,
2174                    frame_index,
2175                })
2176            }));
2177            self.last_animation_frame_time = Some(now);
2178        } else if self.delivering_animation_frames.is_empty()
2179            && self.requested_animation_frames.is_empty()
2180        {
2181            self.last_animation_frame_time = None;
2182        }
2183
2184        ready
2185    }
2186
2187    fn wake_async(&mut self, token: AsyncWakeToken) -> bool {
2188        if !self.async_wake_targets.contains_key(&token) {
2189            return false;
2190        }
2191
2192        self.pending_async_wakeups.push_back(token);
2193        true
2194    }
2195
2196    /// A viewport (window) resize or DPI change can reflow every widget, so it must
2197    /// force a full re-measure rather than a scoped one. Marking the schedule alone is
2198    /// not enough: `build_measure_scope` only re-measures the whole tree when it sees a
2199    /// `Window`/`Surface` invalidation (or none at all), so record one explicitly —
2200    /// otherwise stale per-widget invalidations would scope the pass and width-responsive
2201    /// subtrees would keep their old bounds, failing to reflow on resize.
2202    fn invalidate_layout_for_viewport_change(&mut self) {
2203        self.schedule.mark(InvalidationKind::Measure);
2204        self.pending_invalidations.push(InvalidationRequest::new(
2205            InvalidationTarget::Window(self.id),
2206            InvalidationKind::Measure,
2207        ));
2208    }
2209
2210    fn preprocess_window_event(&mut self, event: &Event) {
2211        let Event::Window(window_event) = event else {
2212            return;
2213        };
2214
2215        match window_event {
2216            WindowEvent::Resized(size) => {
2217                self.viewport_hint = Some(*size);
2218                self.invalidate_layout_for_viewport_change();
2219            }
2220            WindowEvent::ScaleFactorChanged {
2221                scale_factor,
2222                raw_dpi,
2223                suggested_size,
2224            } => {
2225                self.scale_factor = *scale_factor as f32;
2226                self.raw_dpi = *raw_dpi;
2227                if let Some(size) = suggested_size {
2228                    self.viewport_hint = Some(*size);
2229                }
2230                self.invalidate_layout_for_viewport_change();
2231            }
2232            WindowEvent::SafeAreaChanged(safe_area) => {
2233                let safe_area = safe_area.normalized();
2234                if self.safe_area != safe_area {
2235                    self.safe_area = safe_area;
2236                    self.invalidate_layout_for_viewport_change();
2237                }
2238            }
2239            WindowEvent::Focused(focused) => {
2240                self.focus.window_focused = *focused;
2241            }
2242            WindowEvent::RedrawRequested => {
2243                self.schedule.mark(InvalidationKind::Paint);
2244            }
2245            WindowEvent::CloseRequested
2246            | WindowEvent::Moved(_)
2247            | WindowEvent::Occluded(_)
2248            | WindowEvent::ExternalFileHovered(_)
2249            | WindowEvent::ExternalFileHoverCancelled
2250            | WindowEvent::ExternalFileDropped(_) => {}
2251        }
2252    }
2253
2254    fn ensure_graph_for_event(
2255        &mut self,
2256        event: &Event,
2257        text_system: Arc<TextSystem>,
2258        font_registry: Arc<FontRegistry>,
2259        image_registry: Arc<ImageRegistry>,
2260    ) {
2261        if self.schedule.measure || self.schedule.arrange || self.viewport.is_none() {
2262            let scope_source = self.pending_invalidations.clone();
2263            let invalidations = self.run_measure_arrange_pass(
2264                &scope_source,
2265                text_system,
2266                font_registry,
2267                image_registry,
2268            );
2269            self.schedule.extend(&invalidations);
2270            self.pending_invalidations.extend(invalidations);
2271            return;
2272        }
2273
2274        if self.schedule.hit_test || self.graph.is_empty() {
2275            self.refresh_graph();
2276        }
2277
2278        if matches!(event, Event::Keyboard(_) | Event::Ime(_))
2279            && self.focus.focused_widget.is_some()
2280            && !self
2281                .graph
2282                .contains(self.focus.focused_widget.unwrap_or_default())
2283        {
2284            self.focus.focused_widget = None;
2285            self.focused_semantics = None;
2286        }
2287    }
2288
2289    fn resolve_event_target(&self, event: &Event, hit_target: Option<WidgetId>) -> WidgetId {
2290        match event {
2291            Event::Pointer(pointer) => self
2292                .pointer_capture
2293                .get(&pointer.pointer_id)
2294                .copied()
2295                .or(hit_target)
2296                .unwrap_or(self.root.id()),
2297            Event::RawMouseMotion(_) => self
2298                .cursor
2299                .grab_owner
2300                .filter(|_| self.cursor.state.grab_mode != CursorGrabMode::None)
2301                .unwrap_or(self.root.id()),
2302            Event::Keyboard(_) | Event::Ime(_) => {
2303                self.focus.focused_widget.unwrap_or(self.root.id())
2304            }
2305            Event::Semantics(semantics) => self.semantics_route_target(semantics.target),
2306            Event::Wake(wake_event) => self.wake_target(*wake_event).unwrap_or(self.root.id()),
2307            _ => self.root.id(),
2308        }
2309    }
2310
2311    fn wake_target(&self, wake_event: WakeEvent) -> Option<WidgetId> {
2312        match wake_event {
2313            WakeEvent::Timer { token, .. } => self.delivering_timers.get(&token).copied(),
2314            WakeEvent::Async { token, .. } => self.async_wake_targets.get(&token).copied(),
2315            WakeEvent::AnimationFrame { .. } => self.delivering_animation_frames.front().copied(),
2316        }
2317    }
2318
2319    fn apply_event_effects(
2320        &mut self,
2321        effects: EventEffects,
2322        invalidations: &mut Vec<InvalidationRequest>,
2323    ) {
2324        invalidations.extend(effects.invalidations);
2325        self.apply_wake_requests(effects.wake_requests);
2326        self.apply_pointer_capture_requests(effects.pointer_capture_requests, invalidations);
2327        self.apply_cursor_requests(effects.cursor_requests);
2328        self.apply_drag_requests(effects.drag_requests, invalidations);
2329        self.apply_posted_events(effects.posted_events, invalidations);
2330        self.apply_posted_commands(effects.posted_commands, invalidations);
2331    }
2332
2333    /// Deliver widget-posted events (see `EventCtx::post_event`) directly to
2334    /// their targets. Posted events may post follow-ups; rounds are capped so
2335    /// two widgets posting at each other cannot wedge the event loop.
2336    fn apply_posted_events(
2337        &mut self,
2338        mut posted: Vec<widget::PostedEventRequest>,
2339        invalidations: &mut Vec<InvalidationRequest>,
2340    ) {
2341        const MAX_POSTED_EVENT_ROUNDS: usize = 8;
2342
2343        let mut rounds = 0;
2344        while !posted.is_empty() && rounds < MAX_POSTED_EVENT_ROUNDS {
2345            rounds += 1;
2346            for request in std::mem::take(&mut posted) {
2347                let dispatch = self.dispatch_direct_event(request.target, &request.event);
2348                invalidations.extend(dispatch.invalidations);
2349                self.apply_wake_requests(dispatch.wake_requests);
2350                self.apply_pointer_capture_requests(
2351                    dispatch.pointer_capture_requests,
2352                    invalidations,
2353                );
2354                self.apply_cursor_requests(dispatch.cursor_requests);
2355                self.apply_drag_requests(dispatch.drag_requests, invalidations);
2356                posted.extend(dispatch.posted_events);
2357                self.apply_posted_commands(dispatch.posted_commands, invalidations);
2358                if let Some(request) = dispatch.focus_request {
2359                    let focus_effects = self.apply_focus_request(request);
2360                    invalidations.extend(focus_effects.invalidations);
2361                    self.apply_wake_requests(focus_effects.wake_requests);
2362                    self.apply_pointer_capture_requests(
2363                        focus_effects.pointer_capture_requests,
2364                        invalidations,
2365                    );
2366                    self.apply_cursor_requests(focus_effects.cursor_requests);
2367                    self.apply_drag_requests(focus_effects.drag_requests, invalidations);
2368                    posted.extend(focus_effects.posted_events);
2369                    self.apply_posted_commands(focus_effects.posted_commands, invalidations);
2370                }
2371            }
2372        }
2373    }
2374
2375    fn apply_posted_commands(
2376        &mut self,
2377        mut posted: Vec<widget::PostedCommandRequest>,
2378        invalidations: &mut Vec<InvalidationRequest>,
2379    ) {
2380        const MAX_POSTED_COMMAND_ROUNDS: usize = 8;
2381        let mut rounds = 0;
2382        while !posted.is_empty() && rounds < MAX_POSTED_COMMAND_ROUNDS {
2383            rounds += 1;
2384            for request in std::mem::take(&mut posted) {
2385                let CommandTarget::Widget { widget_id, .. } = request.command.target else {
2386                    continue;
2387                };
2388                let Some(dispatch) = self.dispatch_direct_command(widget_id, &request.command)
2389                else {
2390                    push_trace(
2391                        &mut self.pending_command_diagnostics,
2392                        command_sample(&request.command, Vec::new(), false, false),
2393                    );
2394                    continue;
2395                };
2396                self.record_command_invalidations(
2397                    &dispatch.invalidations,
2398                    request.command.key.name,
2399                    Some("posted by widget"),
2400                );
2401                invalidations.extend(dispatch.invalidations);
2402                self.apply_wake_requests(dispatch.wake_requests);
2403                self.apply_pointer_capture_requests(
2404                    dispatch.pointer_capture_requests,
2405                    invalidations,
2406                );
2407                self.apply_cursor_requests(dispatch.cursor_requests);
2408                self.apply_drag_requests(dispatch.drag_requests, invalidations);
2409                self.apply_posted_events(dispatch.posted_events, invalidations);
2410                posted.extend(dispatch.posted_commands);
2411                push_trace(
2412                    &mut self.pending_command_diagnostics,
2413                    command_sample(
2414                        &request.command,
2415                        vec!["widget target".to_string()],
2416                        dispatch.handled,
2417                        true,
2418                    ),
2419                );
2420                if let Some(focus_request) = dispatch.focus_request {
2421                    let effects = self.apply_focus_request(focus_request);
2422                    self.apply_event_effects(effects, invalidations);
2423                }
2424            }
2425        }
2426    }
2427
2428    fn apply_drag_requests(
2429        &mut self,
2430        requests: Vec<DragRequest>,
2431        invalidations: &mut Vec<InvalidationRequest>,
2432    ) {
2433        for request in requests {
2434            match request {
2435                DragRequest::Begin(request) => {
2436                    self.active_drag = Some(ActiveDrag::from_request(request));
2437                    invalidations.push(InvalidationRequest::new(
2438                        InvalidationTarget::Window(self.id),
2439                        InvalidationKind::Paint,
2440                    ));
2441                }
2442            }
2443        }
2444    }
2445
2446    fn handle_drag_pointer_event(
2447        &mut self,
2448        pointer: &PointerEvent,
2449        hit_target: Option<WidgetId>,
2450    ) -> EventEffects {
2451        if self
2452            .active_drag
2453            .as_ref()
2454            .is_none_or(|drag| drag.pointer_id != pointer.pointer_id)
2455        {
2456            return EventEffects::default();
2457        }
2458
2459        match pointer.kind {
2460            PointerEventKind::Move => self.update_active_drag(pointer.position, hit_target),
2461            PointerEventKind::Up => {
2462                let mut effects = self.update_active_drag(pointer.position, hit_target);
2463                effects.merge(self.finish_active_drag(pointer.position, false));
2464                effects
2465            }
2466            PointerEventKind::Cancel | PointerEventKind::Leave => {
2467                self.finish_active_drag(pointer.position, true)
2468            }
2469            _ => EventEffects::default(),
2470        }
2471    }
2472
2473    fn update_active_drag(
2474        &mut self,
2475        position: Point,
2476        hit_target: Option<WidgetId>,
2477    ) -> EventEffects {
2478        let Some((previous_path, active_snapshot)) = self.active_drag.as_mut().map(|active| {
2479            active.position = position;
2480            (active.hover_path.clone(), active.clone())
2481        }) else {
2482            return EventEffects::default();
2483        };
2484
2485        let next_path = hit_target
2486            .and_then(|target| self.graph.path_to(target))
2487            .unwrap_or_default();
2488
2489        let mut effects = EventEffects::default();
2490        effects.invalidations.push(InvalidationRequest::new(
2491            InvalidationTarget::Window(self.id),
2492            InvalidationKind::Paint,
2493        ));
2494
2495        let shared_prefix_len = previous_path
2496            .iter()
2497            .zip(next_path.iter())
2498            .take_while(|(left, right)| left == right)
2499            .count();
2500
2501        for widget_id in previous_path[shared_prefix_len..].iter().rev().copied() {
2502            let event = active_snapshot.event(
2503                DragEventKind::Leave,
2504                position,
2505                Some(widget_id),
2506                DropEffect::None,
2507                None,
2508            );
2509            effects.extend(self.dispatch_direct_event(widget_id, &event));
2510        }
2511
2512        for widget_id in next_path[shared_prefix_len..].iter().copied() {
2513            let event = active_snapshot.event(
2514                DragEventKind::Enter,
2515                position,
2516                Some(widget_id),
2517                DropEffect::None,
2518                None,
2519            );
2520            effects.extend(self.dispatch_direct_event(widget_id, &event));
2521        }
2522
2523        let mut accepted = None;
2524        if let Some(target) = hit_target {
2525            let event = active_snapshot.event(
2526                DragEventKind::Over,
2527                position,
2528                Some(target),
2529                DropEffect::None,
2530                None,
2531            );
2532            let route = self.route_event(target, &event);
2533            accepted = nearest_drop_acceptance(&route.effects.drop_acceptances, &route.path);
2534            if let Some(request) = route.focus_request {
2535                effects.merge(self.apply_focus_request(request));
2536            }
2537            effects.merge(route.effects);
2538        }
2539
2540        if let Some(active) = self.active_drag.as_mut() {
2541            active.hover_path = next_path;
2542            if let Some(accepted) = accepted {
2543                active.accepted_target = Some(accepted.target);
2544                active.accepted_effect = accepted.effect;
2545            } else {
2546                active.accepted_target = None;
2547                active.accepted_effect = DropEffect::None;
2548            }
2549        }
2550
2551        effects
2552    }
2553
2554    fn finish_active_drag(&mut self, position: Point, cancelled: bool) -> EventEffects {
2555        let Some(active) = self.active_drag.take() else {
2556            return EventEffects::default();
2557        };
2558
2559        let mut effects = EventEffects::default();
2560        let outcome = if !cancelled {
2561            active
2562                .accepted_target
2563                .filter(|_| active.accepted_effect.is_some())
2564                .map(|target| DragOutcome::Dropped {
2565                    target,
2566                    effect: active.accepted_effect,
2567                })
2568                .unwrap_or(DragOutcome::Cancelled)
2569        } else {
2570            DragOutcome::Cancelled
2571        };
2572
2573        if let DragOutcome::Dropped { target, effect } = outcome {
2574            let event = active.event(
2575                DragEventKind::Drop,
2576                position,
2577                Some(target),
2578                effect,
2579                Some(outcome),
2580            );
2581            effects.extend(self.dispatch_direct_event(target, &event));
2582        }
2583
2584        for widget_id in active.hover_path.iter().rev().copied() {
2585            let event = active.event(
2586                DragEventKind::Leave,
2587                position,
2588                Some(widget_id),
2589                DropEffect::None,
2590                None,
2591            );
2592            effects.extend(self.dispatch_direct_event(widget_id, &event));
2593        }
2594
2595        let end_event = active.event(
2596            DragEventKind::End,
2597            position,
2598            active.accepted_target,
2599            active.accepted_effect,
2600            Some(outcome),
2601        );
2602        effects.extend(self.dispatch_direct_event(active.source, &end_event));
2603        effects.invalidations.push(InvalidationRequest::new(
2604            InvalidationTarget::Window(self.id),
2605            InvalidationKind::Paint,
2606        ));
2607        effects
2608    }
2609
2610    fn apply_wake_requests(&mut self, requests: Vec<WakeRequest>) {
2611        for request in requests {
2612            match request {
2613                WakeRequest::ScheduleTimer {
2614                    token,
2615                    deadline,
2616                    target,
2617                } => {
2618                    self.scheduled_timers.retain(|timer| timer.token != token);
2619                    self.scheduled_timers.push(ScheduledTimer {
2620                        token,
2621                        deadline,
2622                        target,
2623                    });
2624                }
2625                WakeRequest::CancelTimer { token } => {
2626                    self.scheduled_timers.retain(|timer| timer.token != token);
2627                    self.delivering_timers.remove(&token);
2628                }
2629                WakeRequest::RegisterAsync { token, target } => {
2630                    self.async_wake_targets.insert(token, target);
2631                }
2632                WakeRequest::UnregisterAsync { token } => {
2633                    self.async_wake_targets.remove(&token);
2634                    self.pending_async_wakeups.retain(|queued| *queued != token);
2635                }
2636                WakeRequest::RequestAnimationFrame { target } => {
2637                    self.requested_animation_frames.insert(target);
2638                }
2639            }
2640        }
2641    }
2642
2643    fn apply_pointer_capture_requests(
2644        &mut self,
2645        requests: Vec<PointerCaptureRequest>,
2646        invalidations: &mut Vec<InvalidationRequest>,
2647    ) {
2648        for request in requests {
2649            match request {
2650                PointerCaptureRequest::Capture { pointer_id, target } => {
2651                    self.reconcile_pointer_capture(pointer_id, Some(target), invalidations);
2652                }
2653                PointerCaptureRequest::Release { pointer_id } => {
2654                    self.pointer_capture.remove(&pointer_id);
2655                }
2656            }
2657        }
2658    }
2659
2660    fn apply_cursor_requests(&mut self, requests: Vec<CursorRequest>) {
2661        for request in requests {
2662            match request {
2663                CursorRequest::Grab { target, mode } => {
2664                    if !self.focus.window_focused && mode != CursorGrabMode::None {
2665                        continue;
2666                    }
2667                    if mode == CursorGrabMode::None {
2668                        if self.cursor.grab_owner.is_some()
2669                            && self.cursor.grab_owner != Some(target)
2670                        {
2671                            continue;
2672                        }
2673                        self.cursor.grab_owner = None;
2674                    } else {
2675                        self.cursor.grab_owner = Some(target);
2676                    }
2677                    self.cursor.state.grab_mode = mode;
2678                    self.cursor.state.revision = self.cursor.state.revision.wrapping_add(1);
2679                }
2680                CursorRequest::Visibility { target, visible } => {
2681                    if !self.focus.window_focused && !visible {
2682                        continue;
2683                    }
2684                    if visible {
2685                        if self.cursor.visibility_owner.is_some()
2686                            && self.cursor.visibility_owner != Some(target)
2687                        {
2688                            continue;
2689                        }
2690                        self.cursor.visibility_owner = None;
2691                    } else {
2692                        self.cursor.visibility_owner = Some(target);
2693                    }
2694                    self.cursor.state.visible = visible;
2695                    self.cursor.state.revision = self.cursor.state.revision.wrapping_add(1);
2696                }
2697            }
2698        }
2699    }
2700
2701    fn reset_cursor_state(&mut self) {
2702        if self.cursor.state.grab_mode == CursorGrabMode::None
2703            && self.cursor.state.visible
2704            && self.cursor.grab_owner.is_none()
2705            && self.cursor.visibility_owner.is_none()
2706        {
2707            return;
2708        }
2709
2710        self.cursor.state.grab_mode = CursorGrabMode::None;
2711        self.cursor.state.visible = true;
2712        self.cursor.state.revision = self.cursor.state.revision.wrapping_add(1);
2713        self.cursor.grab_owner = None;
2714        self.cursor.visibility_owner = None;
2715    }
2716
2717    fn cancel_all_pointer_captures(&mut self, invalidations: &mut Vec<InvalidationRequest>) {
2718        let pointer_ids = self.pointer_capture.keys().copied().collect::<Vec<_>>();
2719        for pointer_id in pointer_ids {
2720            self.reconcile_pointer_capture(pointer_id, None, invalidations);
2721        }
2722    }
2723
2724    fn reconcile_pointer_capture(
2725        &mut self,
2726        pointer_id: u64,
2727        requested_target: Option<WidgetId>,
2728        invalidations: &mut Vec<InvalidationRequest>,
2729    ) {
2730        let mut cancelled_owners = HashSet::new();
2731
2732        loop {
2733            let current = self.pointer_capture.get(&pointer_id).copied();
2734            match (current, requested_target) {
2735                (None, Some(target)) => {
2736                    self.pointer_capture.insert(pointer_id, target);
2737                    return;
2738                }
2739                (None, None) => return,
2740                (Some(owner), Some(target)) if owner == target => return,
2741                (Some(owner), _) => {
2742                    self.pointer_capture.remove(&pointer_id);
2743                    if !cancelled_owners.insert(owner) {
2744                        // A cancellation handler may try to recapture synchronously. The original
2745                        // request remains authoritative, so suppress repeated ownership without
2746                        // dispatching an unbounded series of duplicate cancellation events.
2747                        continue;
2748                    }
2749
2750                    let cancel = self.pointer_cancel_event(pointer_id);
2751                    let dispatch = self.dispatch_direct_event(owner, &Event::Pointer(cancel));
2752                    self.apply_pointer_cancel_dispatch(dispatch, invalidations);
2753                }
2754            }
2755        }
2756    }
2757
2758    fn pointer_cancel_event(&self, pointer_id: u64) -> PointerEvent {
2759        let mut pointer = self
2760            .last_pointer_events
2761            .get(&pointer_id)
2762            .cloned()
2763            .unwrap_or_else(|| PointerEvent::new(PointerEventKind::Cancel, Point::ZERO));
2764        pointer.pointer_id = pointer_id;
2765        pointer.kind = PointerEventKind::Cancel;
2766        pointer.delta = Vector::ZERO;
2767        pointer.scroll_delta = None;
2768        pointer.button = None;
2769        pointer.buttons = PointerButtons::NONE;
2770        pointer
2771    }
2772
2773    fn apply_pointer_cancel_dispatch(
2774        &mut self,
2775        dispatch: widget::EventDispatch,
2776        invalidations: &mut Vec<InvalidationRequest>,
2777    ) {
2778        let focus_request = dispatch.focus_request;
2779        let mut effects = EventEffects::default();
2780        effects.extend(dispatch);
2781        self.apply_event_effects(effects, invalidations);
2782
2783        if let Some(request) = focus_request {
2784            let focus_effects = self.apply_focus_request(request);
2785            self.apply_event_effects(focus_effects, invalidations);
2786        }
2787    }
2788
2789    fn finish_event(&mut self, event: &Event) {
2790        match event {
2791            Event::Pointer(pointer)
2792                if matches!(
2793                    pointer.kind,
2794                    PointerEventKind::Up | PointerEventKind::Cancel
2795                ) =>
2796            {
2797                self.pointer_capture.remove(&pointer.pointer_id);
2798                self.last_pointer_events.remove(&pointer.pointer_id);
2799            }
2800            Event::Wake(WakeEvent::Timer { token, .. }) => {
2801                self.delivering_timers.remove(token);
2802            }
2803            Event::Wake(WakeEvent::AnimationFrame { .. }) => {
2804                self.delivering_animation_frames.pop_front();
2805                if self.delivering_animation_frames.is_empty()
2806                    && self.requested_animation_frames.is_empty()
2807                {
2808                    self.last_animation_frame_time = None;
2809                }
2810            }
2811            _ => {}
2812        }
2813    }
2814
2815    fn route_event(&mut self, target: WidgetId, event: &Event) -> EventRouteResult {
2816        let path = self
2817            .graph
2818            .path_to(target)
2819            .unwrap_or_else(|| vec![self.root.id()]);
2820        let dpi_info = self.current_dpi_info();
2821        let mut effects = EventEffects::default();
2822        let mut handled = false;
2823        let mut focus_request = None;
2824        let mut route_steps = self.inspector_tracing_enabled.then(Vec::new);
2825        let target_only = matches!(event, Event::Wake(_));
2826        let ignore_handled = matches!(event, Event::Drag(_));
2827
2828        if !target_only && path.len() > 1 {
2829            for path_len in 1..path.len() {
2830                let dispatch = self
2831                    .root
2832                    .dispatch_event_for_path(
2833                        &path[..path_len],
2834                        self.id,
2835                        dpi_info,
2836                        self.last_tick_time,
2837                        EventPhase::Capture,
2838                        self.focus.focused_widget,
2839                        &self.clipboard,
2840                        &self.command_sender,
2841                        event,
2842                    )
2843                    .unwrap_or_else(empty_dispatch);
2844                let dispatch_handled = dispatch.handled;
2845                let dispatch_focus_request = dispatch.focus_request;
2846                if let Some(route_steps) = &mut route_steps {
2847                    route_steps.push(EventRouteStep {
2848                        widget_id: path[path_len - 1],
2849                        phase: EventRoutePhase::Capture,
2850                        handled: dispatch_handled,
2851                    });
2852                }
2853                effects.extend(dispatch);
2854                if dispatch_focus_request.is_some() {
2855                    focus_request = dispatch_focus_request;
2856                }
2857                if dispatch_handled && !ignore_handled {
2858                    handled = true;
2859                    break;
2860                }
2861            }
2862        }
2863
2864        if !handled || ignore_handled {
2865            let dispatch = self
2866                .root
2867                .dispatch_event_for_path(
2868                    &path,
2869                    self.id,
2870                    dpi_info,
2871                    self.last_tick_time,
2872                    EventPhase::Target,
2873                    self.focus.focused_widget,
2874                    &self.clipboard,
2875                    &self.command_sender,
2876                    event,
2877                )
2878                .or_else(|| {
2879                    self.root.dispatch_event_for(
2880                        target,
2881                        self.id,
2882                        dpi_info,
2883                        self.last_tick_time,
2884                        EventPhase::Target,
2885                        self.focus.focused_widget,
2886                        &self.clipboard,
2887                        &self.command_sender,
2888                        event,
2889                    )
2890                })
2891                .unwrap_or_else(empty_dispatch);
2892            let dispatch_handled = dispatch.handled;
2893            let dispatch_focus_request = dispatch.focus_request;
2894            if let Some(route_steps) = &mut route_steps {
2895                route_steps.push(EventRouteStep {
2896                    widget_id: target,
2897                    phase: EventRoutePhase::Target,
2898                    handled: dispatch_handled,
2899                });
2900            }
2901            effects.extend(dispatch);
2902            if dispatch_focus_request.is_some() {
2903                focus_request = dispatch_focus_request;
2904            }
2905            handled = dispatch_handled && !ignore_handled;
2906        }
2907
2908        if !target_only && (!handled || ignore_handled) && path.len() > 1 {
2909            for path_len in (1..path.len()).rev() {
2910                let dispatch = self
2911                    .root
2912                    .dispatch_event_for_path(
2913                        &path[..path_len],
2914                        self.id,
2915                        dpi_info,
2916                        self.last_tick_time,
2917                        EventPhase::Bubble,
2918                        self.focus.focused_widget,
2919                        &self.clipboard,
2920                        &self.command_sender,
2921                        event,
2922                    )
2923                    .unwrap_or_else(empty_dispatch);
2924                let dispatch_handled = dispatch.handled;
2925                let dispatch_focus_request = dispatch.focus_request;
2926                if let Some(route_steps) = &mut route_steps {
2927                    route_steps.push(EventRouteStep {
2928                        widget_id: path[path_len - 1],
2929                        phase: EventRoutePhase::Bubble,
2930                        handled: dispatch_handled,
2931                    });
2932                }
2933                effects.extend(dispatch);
2934                if dispatch_focus_request.is_some() {
2935                    focus_request = dispatch_focus_request;
2936                }
2937                if dispatch_handled && !ignore_handled {
2938                    handled = true;
2939                    break;
2940                }
2941            }
2942        }
2943
2944        if let Some(route_steps) = route_steps {
2945            let trace_handled = route_steps.iter().any(|step| step.handled);
2946            let sample = EventRouteTraceSample {
2947                sequence: self.next_event_route_sequence,
2948                event_kind: inspector_event_kind(event),
2949                target,
2950                path: path.clone(),
2951                steps: route_steps,
2952                handled: trace_handled,
2953            };
2954            self.next_event_route_sequence = self.next_event_route_sequence.wrapping_add(1);
2955            push_inspector_history(&mut self.event_route_history, sample);
2956        }
2957
2958        EventRouteResult {
2959            path,
2960            effects,
2961            focus_request,
2962            handled,
2963        }
2964    }
2965
2966    fn default_focus_request(
2967        &self,
2968        event: &Event,
2969        hit_target: Option<WidgetId>,
2970        path: &[WidgetId],
2971    ) -> Option<FocusRequest> {
2972        match event {
2973            Event::Keyboard(keyboard)
2974                if keyboard.state == KeyState::Pressed
2975                    && keyboard.key == "Tab"
2976                    && !keyboard.repeat
2977                    && !keyboard.is_composing
2978                    && !keyboard.modifiers.control
2979                    && !keyboard.modifiers.alt
2980                    && !keyboard.modifiers.meta =>
2981            {
2982                self.overlay_manager
2983                    .focus_trap()
2984                    .and_then(|scope| {
2985                        self.graph.next_focusable_within(
2986                            scope,
2987                            self.focus.focused_widget,
2988                            keyboard.modifiers.shift,
2989                        )
2990                    })
2991                    .or_else(|| {
2992                        self.graph
2993                            .next_focusable(self.focus.focused_widget, keyboard.modifiers.shift)
2994                    })
2995                    .map(FocusRequest::Focus)
2996                    .or(Some(FocusRequest::Clear))
2997            }
2998            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
2999                let Some(hit_target) = hit_target else {
3000                    return Some(FocusRequest::Clear);
3001                };
3002
3003                path.iter()
3004                    .rev()
3005                    .copied()
3006                    .find(|widget_id| {
3007                        self.graph
3008                            .node(*widget_id)
3009                            .is_some_and(|node| node.accepts_focus)
3010                    })
3011                    .map(FocusRequest::Focus)
3012                    .or(Some(FocusRequest::Clear))
3013                    .filter(|request| {
3014                        matches!(request, FocusRequest::Focus(id) if *id == hit_target)
3015                            || matches!(request, FocusRequest::Clear)
3016                    })
3017            }
3018            Event::Window(WindowEvent::Focused(false)) => Some(FocusRequest::Clear),
3019            _ => None,
3020        }
3021    }
3022
3023    fn apply_focus_request(&mut self, request: FocusRequest) -> EventEffects {
3024        let request = self.constrain_focus_request(request);
3025        self.apply_focus_request_unconstrained(request)
3026    }
3027
3028    fn apply_focus_request_unconstrained(&mut self, request: FocusRequest) -> EventEffects {
3029        let next_focus = match request {
3030            FocusRequest::Focus(widget_id) => Some(widget_id),
3031            FocusRequest::Clear => None,
3032        };
3033
3034        if self.focus.focused_widget == next_focus {
3035            if self.focused_semantics != next_focus {
3036                self.focused_semantics = next_focus;
3037                self.schedule.mark(InvalidationKind::Semantics);
3038            }
3039            return EventEffects::default();
3040        }
3041
3042        let previous_focus = self.focus.focused_widget;
3043        self.focus.focused_widget = next_focus;
3044        self.focused_semantics = next_focus;
3045        let dpi_info = self.current_dpi_info();
3046
3047        let mut effects = EventEffects::default();
3048
3049        if let Some(widget_id) = previous_focus {
3050            effects
3051                .invalidations
3052                .extend(self.focus_transition_invalidations(widget_id));
3053            let extra = self
3054                .graph
3055                .path_to(widget_id)
3056                .and_then(|path| {
3057                    self.root.notify_focus_change_for_path(
3058                        &path,
3059                        self.id,
3060                        dpi_info,
3061                        self.last_tick_time,
3062                        self.focus.focused_widget,
3063                        &self.clipboard,
3064                        &self.command_sender,
3065                        false,
3066                    )
3067                })
3068                .or_else(|| {
3069                    self.root.notify_focus_change_for(
3070                        widget_id,
3071                        self.id,
3072                        dpi_info,
3073                        self.last_tick_time,
3074                        self.focus.focused_widget,
3075                        &self.clipboard,
3076                        &self.command_sender,
3077                        false,
3078                    )
3079                });
3080            if let Some(extra) = extra {
3081                effects.extend(extra);
3082            }
3083        }
3084
3085        if let Some(widget_id) = next_focus {
3086            effects
3087                .invalidations
3088                .extend(self.focus_transition_invalidations(widget_id));
3089            let extra = self
3090                .graph
3091                .path_to(widget_id)
3092                .and_then(|path| {
3093                    self.root.notify_focus_change_for_path(
3094                        &path,
3095                        self.id,
3096                        dpi_info,
3097                        self.last_tick_time,
3098                        self.focus.focused_widget,
3099                        &self.clipboard,
3100                        &self.command_sender,
3101                        true,
3102                    )
3103                })
3104                .or_else(|| {
3105                    self.root.notify_focus_change_for(
3106                        widget_id,
3107                        self.id,
3108                        dpi_info,
3109                        self.last_tick_time,
3110                        self.focus.focused_widget,
3111                        &self.clipboard,
3112                        &self.command_sender,
3113                        true,
3114                    )
3115                });
3116            if let Some(extra) = extra {
3117                effects.extend(extra);
3118            }
3119        }
3120
3121        self.schedule.mark(InvalidationKind::Paint);
3122        self.schedule.mark(InvalidationKind::Semantics);
3123        self.schedule.mark(InvalidationKind::HitTest);
3124        self.graph.set_focused_widget(self.focus.focused_widget);
3125
3126        effects
3127    }
3128
3129    fn constrain_focus_request(&self, request: FocusRequest) -> FocusRequest {
3130        let Some(scope) = self.overlay_manager.focus_trap() else {
3131            return request;
3132        };
3133        match request {
3134            FocusRequest::Focus(widget_id)
3135                if widget_id == scope || self.graph.is_ancestor_of(scope, widget_id) =>
3136            {
3137                return request;
3138            }
3139            FocusRequest::Focus(_) | FocusRequest::Clear => {}
3140        }
3141
3142        self.focus
3143            .focused_widget
3144            .filter(|focused| *focused == scope || self.graph.is_ancestor_of(scope, *focused))
3145            .or_else(|| self.graph.first_focusable_within(scope, true))
3146            .map(FocusRequest::Focus)
3147            .unwrap_or(FocusRequest::Clear)
3148    }
3149
3150    fn apply_pending_overlay_focus(&mut self, invalidations: &mut Vec<InvalidationRequest>) {
3151        let Some(request) = self.pending_overlay_focus.take() else {
3152            return;
3153        };
3154        let effects = self.apply_focus_request(request);
3155        self.apply_event_effects(effects, invalidations);
3156    }
3157
3158    fn focus_transition_invalidations(&self, widget_id: WidgetId) -> Vec<InvalidationRequest> {
3159        let mut invalidations = vec![InvalidationRequest::new(
3160            InvalidationTarget::Widget(widget_id),
3161            InvalidationKind::Semantics,
3162        )];
3163
3164        if let Some(node) = self.graph.node(widget_id) {
3165            invalidations.push(
3166                InvalidationRequest::new(
3167                    InvalidationTarget::Widget(widget_id),
3168                    InvalidationKind::Paint,
3169                )
3170                .with_region(node.geometry.paint_bounds),
3171            );
3172        }
3173
3174        invalidations
3175    }
3176
3177    fn render(
3178        &mut self,
3179        text_system: Arc<TextSystem>,
3180        font_registry: Arc<FontRegistry>,
3181        image_registry: Arc<ImageRegistry>,
3182    ) -> RenderOutput {
3183        let diagnostics_enabled = window_scene_statistics_detail_mode(self.id).is_detailed();
3184        let mut diagnostics = RenderDiagnostics::default();
3185        let mut invalidations = std::mem::take(&mut self.pending_invalidations);
3186        let local_output = std::mem::take(&mut self.pending_local_output);
3187        let mut repainted = false;
3188        let mut repaint_layers = Vec::new();
3189        let mut dirty_layers = Vec::new();
3190        let mut layer_updates = Vec::new();
3191        let root_repaint_covers_graph_changes =
3192            root_repaint_covers_graph_changes(self.root.id(), &invalidations);
3193        let previous_graph = if (self.schedule.measure || self.schedule.arrange)
3194            && !self.graph.is_empty()
3195            && !root_repaint_covers_graph_changes
3196        {
3197            Some(self.graph.snapshot())
3198        } else {
3199            None
3200        };
3201        let mut graph_changes = GraphChangeSet::default();
3202
3203        // WindowState starts with a bootstrap schedule. Initial size/DPI events
3204        // can already have completed layout; preserve that work and any later
3205        // invalidations instead of resetting all phases before the first paint.
3206        if self.schedule.measure || self.schedule.arrange || self.viewport.is_none() {
3207            let started = Instant::now();
3208            let pass_invalidations = self.run_measure_arrange_pass(
3209                &invalidations,
3210                Arc::clone(&text_system),
3211                Arc::clone(&font_registry),
3212                Arc::clone(&image_registry),
3213            );
3214            self.schedule.extend(&pass_invalidations);
3215            invalidations.extend(pass_invalidations);
3216            graph_changes = if root_repaint_covers_graph_changes {
3217                GraphChangeSet::default()
3218            } else {
3219                self.collect_graph_changes(previous_graph.as_ref())
3220            };
3221            if diagnostics_enabled {
3222                diagnostics.push(FramePhase::MeasureArrange, started.elapsed());
3223            }
3224        } else if self.schedule.hit_test || self.graph.is_empty() {
3225            let started = Instant::now();
3226            self.refresh_graph();
3227            if diagnostics_enabled {
3228                diagnostics.push(FramePhase::HitTest, started.elapsed());
3229            }
3230        }
3231
3232        self.apply_pending_overlay_focus(&mut invalidations);
3233
3234        let viewport = self.viewport.unwrap_or(Size::ZERO);
3235        let dpi_info = self.dpi_info_for_viewport(viewport);
3236        self.prepare_output_reuse(
3237            &invalidations,
3238            &local_output,
3239            &graph_changes,
3240            dpi_info,
3241            Arc::clone(&font_registry),
3242            Arc::clone(&image_registry),
3243        );
3244        let previous_scene = self.last_frame.as_ref().map(|frame| &frame.scene);
3245        let mut composition_only_transforms = self
3246            .select_composition_only_transforms(previous_scene, &graph_changes.transform_widgets);
3247        for translation in
3248            self.select_explicit_transform_translations(previous_scene, &invalidations)
3249        {
3250            if composition_only_transforms
3251                .iter()
3252                .all(|existing| existing.widget_id != translation.widget_id)
3253            {
3254                composition_only_transforms.push(translation);
3255            }
3256        }
3257        let previous_scene_for_refresh = self.last_frame.as_ref().map(|frame| frame.scene.clone());
3258        let layer_descriptor_refreshes = self.collect_explicit_layer_descriptor_refreshes(
3259            previous_scene_for_refresh.as_ref(),
3260            &invalidations,
3261        );
3262        let composition_only_transform_ids = composition_only_transforms
3263            .iter()
3264            .map(|translation| translation.widget_id)
3265            .collect::<HashSet<_>>();
3266        let mut repaint_graph_widgets = graph_changes.repaint_widgets.clone();
3267        for translation in &graph_changes.transform_widgets {
3268            if !composition_only_transform_ids.contains(&translation.widget_id) {
3269                repaint_graph_widgets.push(translation.widget_id);
3270            }
3271        }
3272
3273        if self.schedule.paint || self.last_frame.is_none() || !repaint_graph_widgets.is_empty() {
3274            repaint_layers = self.collect_dirty_layers(&invalidations);
3275            dirty_layers = repaint_layers.clone();
3276            for widget_id in repaint_graph_widgets.iter().copied() {
3277                if self.graph.contains(widget_id) && !dirty_layers.contains(&widget_id) {
3278                    dirty_layers.push(widget_id);
3279                }
3280                if self.graph.contains(widget_id) && !repaint_layers.contains(&widget_id) {
3281                    repaint_layers.push(widget_id);
3282                }
3283            }
3284
3285            // A freshly repainted descendant is already painted at its new
3286            // absolute bounds. Translating its retained ancestor afterward
3287            // would move that replacement twice, so promote the mixed update
3288            // to a content repaint of the retained ancestor.
3289            let mixed_update_roots = composition_only_transforms
3290                .iter()
3291                .filter(|translation| {
3292                    dirty_layers.iter().any(|dirty_widget| {
3293                        self.widget_is_ancestor_of(translation.widget_id, *dirty_widget)
3294                    })
3295                })
3296                .map(|translation| translation.widget_id)
3297                .collect::<Vec<_>>();
3298            repaint_layers.extend(mixed_update_roots.iter().copied());
3299            dirty_layers.extend(mixed_update_roots);
3300            self.minimize_layer_roots(&mut repaint_layers);
3301            self.minimize_layer_roots(&mut dirty_layers);
3302
3303            composition_only_transforms.retain(|translation| {
3304                !dirty_layers.iter().any(|dirty_widget| {
3305                    *dirty_widget == translation.widget_id
3306                        || self.widget_is_ancestor_of(*dirty_widget, translation.widget_id)
3307                })
3308            });
3309        }
3310
3311        let mut scene_changed = false;
3312        let has_ordering_updates = invalidations
3313            .iter()
3314            .any(|request| request.kind == InvalidationKind::Ordering);
3315        if self.last_frame.is_none()
3316            || !repaint_layers.is_empty()
3317            || !composition_only_transforms.is_empty()
3318            || !layer_descriptor_refreshes.is_empty()
3319            || has_ordering_updates
3320        {
3321            let started = Instant::now();
3322            repainted = self.last_frame.is_none() || !repaint_layers.is_empty();
3323            scene_changed = true;
3324
3325            let focused_path = self
3326                .focus
3327                .focused_widget
3328                .and_then(|widget_id| self.graph.path_to(widget_id));
3329            let preserve_ime = focused_path.as_ref().is_none_or(|path| {
3330                !repaint_layers
3331                    .iter()
3332                    .any(|widget_id| path.iter().any(|candidate| candidate == widget_id))
3333            });
3334            let baseline_ime_composition_rect = if preserve_ime {
3335                self.ime_composition_rect
3336            } else {
3337                None
3338            };
3339
3340            let (
3341                scene,
3342                paint_images,
3343                mut paint_bounds_by_widget,
3344                paint_invalidations,
3345                mut ime_composition_rect,
3346            ) = if self.last_frame.is_none() || repaint_layers.contains(&self.root.id()) {
3347                self.paint_full_scene(
3348                    dpi_info,
3349                    Arc::clone(&text_system),
3350                    Arc::clone(&font_registry),
3351                    Arc::clone(&image_registry),
3352                )
3353            } else if repaint_layers.is_empty() {
3354                (
3355                    self.last_frame
3356                        .as_ref()
3357                        .map(|frame| frame.scene.clone())
3358                        .unwrap_or_default(),
3359                    Vec::new(),
3360                    self.last_paint_bounds_by_widget.clone(),
3361                    Vec::new(),
3362                    baseline_ime_composition_rect,
3363                )
3364            } else {
3365                self.repaint_dirty_layers(
3366                    dpi_info,
3367                    &repaint_layers,
3368                    baseline_ime_composition_rect,
3369                    Arc::clone(&text_system),
3370                    Arc::clone(&font_registry),
3371                    Arc::clone(&image_registry),
3372                )
3373            };
3374            let mut scene = scene;
3375            for translation in &composition_only_transforms {
3376                let _ = scene.translate_layer(translation.widget_id, translation.delta);
3377                for widget_id in self.graph.subtree_ids(translation.widget_id) {
3378                    if let Some(bounds) = paint_bounds_by_widget.get_mut(&widget_id) {
3379                        *bounds = bounds.translate(translation.delta);
3380                    }
3381                }
3382                if let Some(moved_bounds) =
3383                    paint_bounds_by_widget.get(&translation.widget_id).copied()
3384                {
3385                    // Flat ancestors can derive their paint bounds from this
3386                    // explicit child. Without repainting we cannot separate an
3387                    // ancestor's own ink from its old child contribution, so
3388                    // conservatively include the moved bounds. This prevents
3389                    // later damage from missing the child's new location.
3390                    let mut ancestor = self
3391                        .graph
3392                        .node(translation.widget_id)
3393                        .and_then(|node| node.parent);
3394                    while let Some(widget_id) = ancestor {
3395                        paint_bounds_by_widget
3396                            .entry(widget_id)
3397                            .and_modify(|bounds| *bounds = bounds.union(moved_bounds))
3398                            .or_insert(moved_bounds);
3399                        ancestor = self.graph.node(widget_id).and_then(|node| node.parent);
3400                    }
3401                }
3402                if focused_path
3403                    .as_ref()
3404                    .is_some_and(|path| path.contains(&translation.widget_id))
3405                {
3406                    ime_composition_rect =
3407                        ime_composition_rect.map(|rect| rect.translate(translation.delta));
3408                }
3409            }
3410            for refresh in &layer_descriptor_refreshes {
3411                let _ =
3412                    scene.replace_layer_descriptor(refresh.widget_id, refresh.descriptor.clone());
3413            }
3414            self.sync_scene_stack_metadata(&mut scene);
3415            self.last_paint_bounds_by_widget = paint_bounds_by_widget;
3416            self.graph
3417                .update_paint_bounds_from_snapshot(&self.last_paint_bounds_by_widget);
3418            invalidations.extend(paint_invalidations);
3419            self.ime_composition_rect = ime_composition_rect;
3420            let previous_scene = self.last_frame.as_ref().map(|frame| &frame.scene);
3421            layer_updates = self.collect_layer_updates(
3422                previous_scene,
3423                &scene,
3424                &invalidations,
3425                &dirty_layers,
3426                &composition_only_transforms
3427                    .iter()
3428                    .map(|translation| translation.widget_id)
3429                    .collect::<Vec<_>>(),
3430            );
3431            let frame_image_registry =
3432                self.frame_image_registry(Arc::clone(&image_registry), paint_images);
3433            retain_text_layouts_for_scene(text_system.as_ref(), &scene);
3434            self.last_frame = Some(SceneFrame {
3435                window_id: self.id,
3436                viewport,
3437                surface_size: dpi_info.surface_size,
3438                scale_factor: dpi_info.scale_factor,
3439                dirty_regions: Vec::new(),
3440                layer_updates: layer_updates.clone(),
3441                scene,
3442                font_registry: Arc::clone(&font_registry),
3443                image_registry: frame_image_registry,
3444                text_layout_registry: text_system.text_layout_registry(),
3445            });
3446            if diagnostics_enabled && repainted {
3447                diagnostics.push(FramePhase::Paint, started.elapsed());
3448            }
3449        }
3450
3451        if self.schedule.semantics || self.last_semantics.is_empty() {
3452            let started = Instant::now();
3453            let mut semantics_ctx = SemanticsCtx::new(
3454                self.id,
3455                self.root.id(),
3456                self.root.id(),
3457                self.root.bounds(),
3458                self.focus.focused_widget,
3459            );
3460            semantics_ctx.output_cache = output_cache::OutputCache::scope(&self.output_cache);
3461            self.root.semantics(&mut semantics_ctx);
3462            let semantics = self.assemble_semantics_tree(semantics_ctx.into_nodes());
3463            self.last_semantics = self.filter_modal_semantics(semantics);
3464            if diagnostics_enabled {
3465                diagnostics.push(FramePhase::Semantics, started.elapsed());
3466            }
3467        }
3468
3469        let viewport_rect = Rect::from_origin_size(Point::ZERO, viewport);
3470        let dirty_regions = collect_dirty_regions(viewport, &invalidations, repainted, |request| {
3471            self.default_dirty_region_for_request(viewport_rect, request)
3472        });
3473        let mut frame = self
3474            .last_frame
3475            .clone()
3476            .unwrap_or_else(|| SceneFrame::new(self.id, viewport));
3477        frame.viewport = viewport;
3478        frame.surface_size = dpi_info.surface_size;
3479        frame.scale_factor = dpi_info.scale_factor;
3480        frame.dirty_regions = dirty_regions;
3481        frame.layer_updates = if scene_changed {
3482            layer_updates
3483        } else {
3484            self.collect_layer_updates(
3485                self.last_frame.as_ref().map(|stored| &stored.scene),
3486                &frame.scene,
3487                &invalidations,
3488                &[],
3489                &composition_only_transforms
3490                    .iter()
3491                    .map(|translation| translation.widget_id)
3492                    .collect::<Vec<_>>(),
3493            )
3494        };
3495        frame.font_registry = font_registry;
3496        frame.image_registry = self.frame_image_registry(image_registry, Vec::new());
3497
3498        if diagnostics_enabled {
3499            let layout_cache = text_system.layout_cache_snapshot();
3500            diagnostics.text_caches.runtime_layout =
3501                CacheMetrics::new(layout_cache.entries, layout_cache.hits, layout_cache.misses);
3502        }
3503
3504        diagnostics.widget_count = self.graph.nodes.len();
3505        diagnostics.runtime_text_timing = sui_text::take_text_timing_collection();
3506        diagnostics.widget_timings = diagnostics::take_widget_timing_collection();
3507        diagnostics.reactive_invalidations = std::mem::take(&mut self.pending_reactive_diagnostics);
3508        diagnostics.command_dispatches = std::mem::take(&mut self.pending_command_diagnostics);
3509        diagnostics.invalidations = std::mem::take(&mut self.pending_invalidation_diagnostics);
3510        diagnostics.widget_rebuilds = diagnostics::take_widget_rebuilds(self.id);
3511        diagnostics.active_animated_widget_count = self.active_animated_widget_count();
3512        diagnostics.animation_frame_wake_count = self.pending_animation_wake_count;
3513        diagnostics.animation_repaint_frame_count =
3514            usize::from(self.pending_animation_wake_count > 0 && repainted);
3515        diagnostics.animation_transform_effect_only_frame_count = usize::from(
3516            self.pending_animation_wake_count > 0
3517                && self.animation_frame_is_transform_only(repainted, &frame.layer_updates),
3518        );
3519        self.pending_animation_wake_count = 0;
3520
3521        self.capture_inspector_diagnostics(&diagnostics);
3522
3523        self.schedule.clear();
3524
3525        RenderOutput {
3526            title: self.title.clone(),
3527            frame,
3528            semantics: self.last_semantics.clone(),
3529            ime_composition_rect: self.ime_composition_rect,
3530            diagnostics,
3531        }
3532    }
3533
3534    fn frame_image_registry(
3535        &self,
3536        base: Arc<ImageRegistry>,
3537        paint_images: Vec<(ImageHandle, PaintImageResource)>,
3538    ) -> Arc<ImageRegistry> {
3539        let mut registry = self
3540            .last_frame
3541            .as_ref()
3542            .map(|frame| frame.image_registry.as_ref().clone())
3543            .unwrap_or_else(|| base.as_ref().clone());
3544        for (handle, image) in base.iter() {
3545            registry.insert(handle, image.clone());
3546        }
3547        for (handle, image) in base.iter_external() {
3548            registry.insert_external(handle, *image);
3549        }
3550        for (handle, image) in paint_images {
3551            match image {
3552                PaintImageResource::Cpu(image) => {
3553                    registry.insert(handle, image);
3554                }
3555                PaintImageResource::External(image) => {
3556                    registry.insert_external(handle, image);
3557                }
3558            }
3559        }
3560        Arc::new(registry)
3561    }
3562
3563    fn prepare_output_reuse(
3564        &mut self,
3565        invalidations: &[InvalidationRequest],
3566        local_output: &HashMap<(WidgetId, InvalidationKind), usize>,
3567        changes: &GraphChangeSet,
3568        dpi: DpiInfo,
3569        fonts: Arc<FontRegistry>,
3570        images: Arc<ImageRegistry>,
3571    ) {
3572        if invalidations.is_empty()
3573            && changes.output_widgets.is_empty()
3574            && !self.schedule.paint
3575            && !self.schedule.semantics
3576        {
3577            // Retrieving an unchanged frame needs no cache scan or resource
3578            // comparison, but saved contexts must still expire.
3579            self.output_cache.borrow_mut().next_frame();
3580            return;
3581        }
3582        let mut cache = self.output_cache.borrow_mut();
3583        cache.next_frame();
3584        cache.context(
3585            dpi,
3586            self.focus.focused_widget,
3587            fonts,
3588            images,
3589            window_render_options(self.id),
3590        );
3591        if self.last_frame.is_none() {
3592            cache.clear();
3593            return;
3594        }
3595        // Full window/explicit root requests need no per-node bookkeeping.
3596        // In particular, resizing must not build two dirty sets only to discard
3597        // both caches. Geometry changes that already cover half the graph also
3598        // satisfy the broad-update policy without expanding ancestor paths.
3599        let mut explicit_full_paint = false;
3600        let mut explicit_full_semantics = false;
3601        for request in invalidations {
3602            let full = match request.target {
3603                InvalidationTarget::Widget(id) => {
3604                    id == self.root.id() && !local_output.contains_key(&(id, request.kind))
3605                }
3606                _ => true,
3607            };
3608            if full {
3609                match request.kind {
3610                    InvalidationKind::Paint | InvalidationKind::Effect => {
3611                        explicit_full_paint = true
3612                    }
3613                    InvalidationKind::Semantics => explicit_full_semantics = true,
3614                    _ => {
3615                        explicit_full_paint = true;
3616                        explicit_full_semantics = true;
3617                    }
3618                }
3619            }
3620        }
3621        if (explicit_full_paint && explicit_full_semantics)
3622            || (!changes.output_widgets.is_empty()
3623                && changes.output_widgets.len().saturating_mul(2) >= self.graph.nodes.len())
3624        {
3625            cache.disable_paint();
3626            cache.disable_semantics();
3627            return;
3628        }
3629        let mut counts = HashMap::<_, usize>::new();
3630        for request in invalidations {
3631            if let InvalidationTarget::Widget(id) = request.target
3632                && local_output.contains_key(&(id, request.kind))
3633            {
3634                *counts.entry((id, request.kind)).or_default() += 1;
3635            }
3636        }
3637        let mut paint_dirty = HashSet::new();
3638        let mut semantics_dirty = HashSet::new();
3639        let mut full_paint = invalidations.is_empty() && self.schedule.paint;
3640        let mut full_semantics = invalidations.is_empty() && self.schedule.semantics;
3641        // A flat child's geometry change can repaint the root scene, but it does
3642        // not invalidate every sibling's retained callback output.
3643        for id in &changes.output_widgets {
3644            paint_dirty.insert(*id);
3645            semantics_dirty.insert(*id);
3646            if let Some(path) = self.graph.path_to(*id) {
3647                paint_dirty.extend(path.iter().copied());
3648                semantics_dirty.extend(path);
3649            }
3650        }
3651        for request in invalidations {
3652            let (paint, semantics) = match request.kind {
3653                InvalidationKind::Paint | InvalidationKind::Effect => (true, false),
3654                InvalidationKind::Semantics => (false, true),
3655                _ => (true, true),
3656            };
3657            let InvalidationTarget::Widget(id) = request.target else {
3658                full_paint |= paint;
3659                full_semantics |= semantics;
3660                continue;
3661            };
3662            let local = local_output
3663                .get(&(id, request.kind))
3664                .is_some_and(|count| counts.get(&(id, request.kind)) == Some(count));
3665            if !self.graph.contains(id) || (id == self.root.id() && !local) {
3666                full_paint |= paint;
3667                full_semantics |= semantics;
3668                continue;
3669            }
3670            let nodes = if local {
3671                vec![id]
3672            } else {
3673                self.graph.subtree_ids(id)
3674            };
3675            if paint {
3676                paint_dirty.extend(nodes.iter().copied());
3677            }
3678            if semantics {
3679                semantics_dirty.extend(nodes);
3680            }
3681            if let Some(path) = self.graph.path_to(id) {
3682                if paint {
3683                    paint_dirty.extend(path.iter().copied());
3684                }
3685                if semantics {
3686                    semantics_dirty.extend(path);
3687                }
3688            }
3689        }
3690        // Broad updates have little reusable output. Avoid filling the cache
3691        // with copies that the next bulk update would immediately invalidate.
3692        if full_paint || paint_dirty.len().saturating_mul(2) >= self.graph.nodes.len() {
3693            cache.disable_paint();
3694        }
3695        if full_semantics || semantics_dirty.len().saturating_mul(2) >= self.graph.nodes.len() {
3696            cache.disable_semantics();
3697        }
3698        cache.retain(
3699            |id| self.graph.contains(id) && !paint_dirty.contains(&id),
3700            |id| self.graph.contains(id) && !semantics_dirty.contains(&id),
3701        );
3702    }
3703
3704    fn paint_full_scene(
3705        &mut self,
3706        dpi_info: DpiInfo,
3707        text_system: Arc<TextSystem>,
3708        font_registry: Arc<FontRegistry>,
3709        image_registry: Arc<ImageRegistry>,
3710    ) -> PaintOutput {
3711        let mut paint_ctx = PaintCtx::new(
3712            self.id,
3713            self.root.id(),
3714            self.root.bounds(),
3715            self.focus.focused_widget,
3716            dpi_info,
3717            text_system,
3718            font_registry,
3719            self.last_frame
3720                .as_ref()
3721                .map(|frame| Arc::clone(&frame.image_registry))
3722                .unwrap_or(image_registry),
3723        );
3724        paint_ctx.output_cache = output_cache::OutputCache::scope(&self.output_cache);
3725        let _ = self
3726            .root
3727            .paint_layer_contents_for(self.root.id(), &mut paint_ctx);
3728        paint_ctx.into_parts()
3729    }
3730
3731    fn repaint_dirty_layers(
3732        &mut self,
3733        dpi_info: DpiInfo,
3734        dirty_layers: &[WidgetId],
3735        baseline_ime_composition_rect: Option<Rect>,
3736        text_system: Arc<TextSystem>,
3737        font_registry: Arc<FontRegistry>,
3738        image_registry: Arc<ImageRegistry>,
3739    ) -> PaintOutput {
3740        let mut scene = self
3741            .last_frame
3742            .as_ref()
3743            .map(|frame| frame.scene.clone())
3744            .unwrap_or_default();
3745        let mut images = Vec::new();
3746        let mut invalidations = Vec::new();
3747        let mut paint_bounds_by_widget = self.last_paint_bounds_by_widget.clone();
3748        let mut ime_composition_rect = baseline_ime_composition_rect;
3749
3750        for &widget_id in dirty_layers {
3751            let Some(bounds) = self
3752                .graph
3753                .node(widget_id)
3754                .map(|node| node.geometry.layout_bounds)
3755            else {
3756                return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
3757            };
3758
3759            let mut paint_ctx = PaintCtx::new(
3760                self.id,
3761                widget_id,
3762                bounds,
3763                self.focus.focused_widget,
3764                dpi_info,
3765                Arc::clone(&text_system),
3766                Arc::clone(&font_registry),
3767                self.last_frame
3768                    .as_ref()
3769                    .map(|frame| Arc::clone(&frame.image_registry))
3770                    .unwrap_or_else(|| Arc::clone(&image_registry)),
3771            );
3772            paint_ctx.output_cache = output_cache::OutputCache::scope(&self.output_cache);
3773            if !self
3774                .root
3775                .paint_layer_contents_for(widget_id, &mut paint_ctx)
3776            {
3777                return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
3778            }
3779
3780            let (
3781                layer_scene,
3782                layer_images,
3783                layer_paint_bounds,
3784                layer_invalidations,
3785                layer_ime_composition_rect,
3786            ) = paint_ctx.into_parts();
3787            let Some(descriptor) = self.root.layer_descriptor_for(widget_id, &layer_scene) else {
3788                return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
3789            };
3790            if widget_id == self.root.id()
3791                || !scene.replace_layer(
3792                    widget_id,
3793                    SceneLayer::from_descriptor(descriptor, layer_scene),
3794                )
3795            {
3796                return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
3797            }
3798
3799            images.extend(layer_images);
3800            paint_bounds_by_widget.extend(layer_paint_bounds);
3801            invalidations.extend(layer_invalidations);
3802            if layer_ime_composition_rect.is_some() {
3803                ime_composition_rect = layer_ime_composition_rect;
3804            }
3805        }
3806
3807        (
3808            scene,
3809            images,
3810            paint_bounds_by_widget,
3811            invalidations,
3812            ime_composition_rect,
3813        )
3814    }
3815
3816    fn collect_dirty_layers(&self, invalidations: &[InvalidationRequest]) -> Vec<WidgetId> {
3817        let candidates: HashSet<WidgetId> = invalidations
3818            .iter()
3819            .filter(|request| {
3820                matches!(
3821                    request.kind,
3822                    InvalidationKind::Measure
3823                        | InvalidationKind::Clip
3824                        | InvalidationKind::Visibility
3825                        | InvalidationKind::Paint
3826                        | InvalidationKind::Text
3827                        | InvalidationKind::Resources
3828                )
3829            })
3830            .map(|request| match request.target {
3831                InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => self
3832                    .graph
3833                    .nearest_paint_boundary_ancestor_or_root(widget_id),
3834                InvalidationTarget::Widget(_) => self.root.id(),
3835                InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => self.root.id(),
3836            })
3837            .collect();
3838
3839        if self.last_frame.is_none() || candidates.contains(&self.root.id()) {
3840            return vec![self.root.id()];
3841        }
3842
3843        let mut candidates: Vec<_> = candidates
3844            .into_iter()
3845            .filter(|widget_id| self.graph.contains(*widget_id))
3846            .collect();
3847        candidates.sort_by_key(|widget_id| {
3848            self.graph
3849                .path_to(*widget_id)
3850                .map_or(usize::MAX, |path| path.len())
3851        });
3852
3853        let mut minimized = Vec::new();
3854        for widget_id in candidates {
3855            if minimized
3856                .iter()
3857                .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
3858            {
3859                continue;
3860            }
3861            minimized.push(widget_id);
3862        }
3863
3864        minimized
3865    }
3866
3867    fn collect_graph_changes(&self, previous: Option<&WidgetGraphSnapshot>) -> GraphChangeSet {
3868        let Some(previous) = previous else {
3869            return GraphChangeSet {
3870                output_widgets: vec![self.graph.root],
3871                repaint_widgets: vec![self.graph.root],
3872                transform_widgets: Vec::new(),
3873            };
3874        };
3875
3876        let current_snapshot = self.graph.snapshot();
3877        let previous_nodes: HashMap<_, _> =
3878            previous.nodes.iter().map(|node| (node.id, node)).collect();
3879        let current_nodes: HashMap<_, _> = current_snapshot
3880            .nodes
3881            .iter()
3882            .map(|node| (node.id, node))
3883            .collect();
3884        let widget_ids = previous_nodes
3885            .keys()
3886            .chain(current_nodes.keys())
3887            .copied()
3888            .collect::<HashSet<_>>();
3889        let mut output_widgets = Vec::new();
3890        let mut repaint_candidates = HashSet::new();
3891        let mut transform_candidates = Vec::new();
3892
3893        for widget_id in widget_ids {
3894            match (
3895                previous_nodes.get(&widget_id),
3896                current_nodes.get(&widget_id),
3897            ) {
3898                (Some(previous_node), Some(current_node)) => {
3899                    if previous_node.measured_size != current_node.measured_size
3900                        || previous_node.geometry.layout_bounds.size
3901                            != current_node.geometry.layout_bounds.size
3902                        || previous_node.parent != current_node.parent
3903                        || previous_node.children != current_node.children
3904                    {
3905                        output_widgets.push(current_node.id);
3906                        repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3907                            &current_snapshot,
3908                            current_node.id,
3909                        ));
3910                        continue;
3911                    }
3912
3913                    let delta = current_node.geometry.layout_bounds.origin
3914                        - previous_node.geometry.layout_bounds.origin;
3915                    if delta != Vector::ZERO
3916                        || previous_node.geometry.input_bounds != current_node.geometry.input_bounds
3917                    {
3918                        output_widgets.push(current_node.id);
3919                    }
3920                    if delta != Vector::ZERO {
3921                        let resolved_boundary = resolve_snapshot_paint_boundary_or_root(
3922                            &current_snapshot,
3923                            current_node.id,
3924                        );
3925                        if resolved_boundary == current_node.id
3926                            && current_node.paint_boundary == PaintBoundaryMode::Explicit
3927                        {
3928                            transform_candidates.push(LayerTranslation {
3929                                widget_id: current_node.id,
3930                                delta,
3931                            });
3932                        } else if current_nodes
3933                            .get(&resolved_boundary)
3934                            .zip(previous_nodes.get(&resolved_boundary))
3935                            .is_some_and(|(current_boundary, previous_boundary)| {
3936                                current_boundary.paint_boundary == PaintBoundaryMode::Explicit
3937                                    && current_boundary.geometry.layout_bounds.origin
3938                                        - previous_boundary.geometry.layout_bounds.origin
3939                                        == delta
3940                            })
3941                        {
3942                            // A descendant that moved by exactly the same delta as its
3943                            // explicit paint boundary is covered by that boundary's
3944                            // composition-only transform. Treating each flat descendant
3945                            // as an independent move would unnecessarily repaint the layer.
3946                        } else {
3947                            repaint_candidates.insert(resolved_boundary);
3948                        }
3949                    }
3950                }
3951                (None, Some(current_node)) => {
3952                    output_widgets.push(current_node.id);
3953                    repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3954                        &current_snapshot,
3955                        current_node.id,
3956                    ));
3957                }
3958                (Some(previous_node), None) => {
3959                    repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3960                        previous,
3961                        previous_node.id,
3962                    ));
3963                }
3964                (None, None) => {}
3965            }
3966        }
3967
3968        let mut repaint_widgets = repaint_candidates.into_iter().collect::<Vec<_>>();
3969        repaint_widgets.sort_by_key(|widget_id| self.widget_depth(*widget_id));
3970        let mut minimized_repaint = Vec::new();
3971        for widget_id in repaint_widgets {
3972            if minimized_repaint
3973                .iter()
3974                .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
3975            {
3976                continue;
3977            }
3978            minimized_repaint.push(widget_id);
3979        }
3980
3981        transform_candidates.sort_by_key(|translation| self.widget_depth(translation.widget_id));
3982        let mut minimized_transforms = Vec::new();
3983        for candidate in transform_candidates {
3984            if minimized_repaint
3985                .iter()
3986                .any(|ancestor| self.widget_is_ancestor_of(*ancestor, candidate.widget_id))
3987            {
3988                continue;
3989            }
3990
3991            let inherited_delta = minimized_transforms
3992                .iter()
3993                .filter(|translation: &&LayerTranslation| {
3994                    self.widget_is_ancestor_of(translation.widget_id, candidate.widget_id)
3995                })
3996                .fold(Vector::ZERO, |current, translation| {
3997                    current + translation.delta
3998                });
3999            let residual = candidate.delta - inherited_delta;
4000            if residual == Vector::ZERO {
4001                continue;
4002            }
4003
4004            minimized_transforms.push(LayerTranslation {
4005                widget_id: candidate.widget_id,
4006                delta: residual,
4007            });
4008        }
4009
4010        GraphChangeSet {
4011            output_widgets,
4012            repaint_widgets: minimized_repaint,
4013            transform_widgets: minimized_transforms,
4014        }
4015    }
4016
4017    fn select_composition_only_transforms(
4018        &self,
4019        previous_scene: Option<&Scene>,
4020        transform_widgets: &[LayerTranslation],
4021    ) -> Vec<LayerTranslation> {
4022        let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
4023        transform_widgets
4024            .iter()
4025            .copied()
4026            .filter(|translation| previous_layers.contains_key(&translation.widget_id))
4027            .collect()
4028    }
4029
4030    fn select_explicit_transform_translations(
4031        &self,
4032        previous_scene: Option<&Scene>,
4033        invalidations: &[InvalidationRequest],
4034    ) -> Vec<LayerTranslation> {
4035        let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
4036        let mut translations = Vec::new();
4037
4038        for request in invalidations {
4039            if request.kind != InvalidationKind::Transform {
4040                continue;
4041            }
4042
4043            let InvalidationTarget::Widget(widget_id) = request.target else {
4044                continue;
4045            };
4046            let resolved_boundary = self
4047                .graph
4048                .nearest_paint_boundary_ancestor_or_root(widget_id);
4049            if resolved_boundary == self.root.id() {
4050                continue;
4051            }
4052            let Some(previous) = previous_layers.get(&resolved_boundary) else {
4053                continue;
4054            };
4055            let Some(current) = self.graph.node(resolved_boundary) else {
4056                continue;
4057            };
4058
4059            let delta = current.geometry.layout_bounds.origin - previous.bounds.origin;
4060            if delta == Vector::ZERO {
4061                continue;
4062            }
4063
4064            if translations
4065                .iter()
4066                .all(|translation: &LayerTranslation| translation.widget_id != resolved_boundary)
4067            {
4068                translations.push(LayerTranslation {
4069                    widget_id: resolved_boundary,
4070                    delta,
4071                });
4072            }
4073        }
4074
4075        translations
4076    }
4077
4078    fn collect_explicit_layer_descriptor_refreshes(
4079        &mut self,
4080        previous_scene: Option<&Scene>,
4081        invalidations: &[InvalidationRequest],
4082    ) -> Vec<LayerDescriptorRefresh> {
4083        let Some(previous_scene) = previous_scene else {
4084            return Vec::new();
4085        };
4086        if !invalidations.iter().any(|request| {
4087            matches!(
4088                request.kind,
4089                InvalidationKind::Transform | InvalidationKind::Effect
4090            )
4091        }) {
4092            return Vec::new();
4093        }
4094
4095        let previous_layers = collect_scene_layers(previous_scene);
4096        let mut refreshes = Vec::new();
4097
4098        for (widget_id, previous_descriptor) in previous_layers {
4099            let Some(layer_scene) = previous_scene.layer_scene(widget_id).cloned() else {
4100                continue;
4101            };
4102            let Some(descriptor) = self.root.layer_descriptor_for(widget_id, &layer_scene) else {
4103                continue;
4104            };
4105            if descriptor.properties == previous_descriptor.properties {
4106                continue;
4107            }
4108            refreshes.push(LayerDescriptorRefresh {
4109                widget_id,
4110                descriptor,
4111            });
4112        }
4113
4114        refreshes
4115    }
4116
4117    fn widget_depth(&self, widget_id: WidgetId) -> usize {
4118        self.graph.depth(widget_id).unwrap_or(usize::MAX)
4119    }
4120
4121    fn minimize_layer_roots(&self, candidates: &mut Vec<WidgetId>) {
4122        candidates.sort_by_key(|widget_id| (self.widget_depth(*widget_id), widget_id.get()));
4123        candidates.dedup();
4124        let mut minimized = Vec::with_capacity(candidates.len());
4125        for widget_id in candidates.iter().copied() {
4126            if minimized
4127                .iter()
4128                .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
4129            {
4130                continue;
4131            }
4132            minimized.push(widget_id);
4133        }
4134        *candidates = minimized;
4135    }
4136
4137    fn default_dirty_region_for_request(
4138        &self,
4139        viewport_rect: Rect,
4140        request: &InvalidationRequest,
4141    ) -> Rect {
4142        match request.target {
4143            InvalidationTarget::Widget(widget_id) => self
4144                .graph
4145                .node(widget_id)
4146                .map(|node| node.geometry.paint_bounds)
4147                .unwrap_or(viewport_rect),
4148            InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => viewport_rect,
4149        }
4150    }
4151
4152    fn collect_layer_updates(
4153        &self,
4154        previous_scene: Option<&Scene>,
4155        scene: &Scene,
4156        invalidations: &[InvalidationRequest],
4157        dirty_layers: &[WidgetId],
4158        graph_dirty_widgets: &[WidgetId],
4159    ) -> Vec<SceneLayerUpdate> {
4160        let current_layers = collect_scene_layers(scene);
4161        if current_layers.is_empty() {
4162            return Vec::new();
4163        }
4164
4165        let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
4166        let mut updates = HashMap::<WidgetId, SceneLayerUpdateKind>::new();
4167        let mut damage_regions = HashMap::<WidgetId, Rect>::new();
4168        let explicit_transform_widgets = invalidations
4169            .iter()
4170            .filter_map(|request| {
4171                if request.kind != InvalidationKind::Transform {
4172                    return None;
4173                }
4174
4175                match request.target {
4176                    InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => {
4177                        Some(
4178                            self.graph
4179                                .nearest_paint_boundary_ancestor_or_root(widget_id),
4180                        )
4181                    }
4182                    _ => None,
4183                }
4184            })
4185            .collect::<HashSet<_>>();
4186
4187        for request in invalidations {
4188            let Some(kind) = invalidation_to_layer_update_kind(request.kind) else {
4189                continue;
4190            };
4191            let widget_id = match request.target {
4192                InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => self
4193                    .graph
4194                    .nearest_paint_boundary_ancestor_or_root(widget_id),
4195                InvalidationTarget::Widget(_) => self.root.id(),
4196                InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => self.root.id(),
4197            };
4198            if request.kind == InvalidationKind::Arrange
4199                && explicit_transform_widgets
4200                    .iter()
4201                    .any(|candidate| self.widget_is_ancestor_of(widget_id, *candidate))
4202            {
4203                continue;
4204            }
4205            merge_layer_update_kind(&mut updates, widget_id, kind);
4206            if let Some(region) = request.region {
4207                damage_regions
4208                    .entry(widget_id)
4209                    .and_modify(|current| *current = current.union(region))
4210                    .or_insert(region);
4211            }
4212        }
4213
4214        for (widget_id, descriptor) in &current_layers {
4215            let Some(previous) = previous_layers.get(widget_id) else {
4216                merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Content);
4217                continue;
4218            };
4219            if descriptor.stack_host != previous.stack_host
4220                || descriptor.stack_order != previous.stack_order
4221                || descriptor.transient_owner_surface != previous.transient_owner_surface
4222                || descriptor.is_stack_surface != previous.is_stack_surface
4223            {
4224                merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Ordering);
4225            }
4226            if descriptor.properties.translation != previous.properties.translation {
4227                merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Transform);
4228            }
4229            if descriptor.properties.opacity != previous.properties.opacity {
4230                merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Effect);
4231            }
4232        }
4233
4234        for widget_id in graph_dirty_widgets.iter().copied() {
4235            merge_layer_update_kind(&mut updates, widget_id, SceneLayerUpdateKind::Transform);
4236        }
4237
4238        for widget_id in dirty_layers.iter().copied() {
4239            merge_layer_update_kind(&mut updates, widget_id, SceneLayerUpdateKind::Content);
4240        }
4241
4242        let mut resolved_updates = Vec::new();
4243        for (widget_id, kind) in updates {
4244            let Some(descriptor) = current_layers.get(&widget_id).cloned() else {
4245                continue;
4246            };
4247            let fallback_damage = previous_layers
4248                .get(&widget_id)
4249                .map(|previous| {
4250                    previous
4251                        .presented_paint_bounds()
4252                        .union(descriptor.presented_paint_bounds())
4253                })
4254                .unwrap_or(descriptor.presented_paint_bounds());
4255            let damage = damage_regions
4256                .get(&widget_id)
4257                .copied()
4258                .unwrap_or(fallback_damage);
4259            resolved_updates
4260                .push(SceneLayerUpdate::from_descriptor(kind, descriptor).with_damage(damage));
4261        }
4262
4263        resolved_updates.sort_by_key(|update| update.owner.get());
4264        resolved_updates
4265    }
4266
4267    fn widget_is_ancestor_of(&self, ancestor: WidgetId, widget_id: WidgetId) -> bool {
4268        self.graph.is_ancestor_of(ancestor, widget_id)
4269    }
4270
4271    /// Build the measure scope for this pass from the pending invalidations.
4272    ///
4273    /// Measure/Text/Visibility/Ordering invalidations targeting a widget that is
4274    /// in the current graph define the changed subtrees; their ancestor paths
4275    /// must also re-measure. Anything that cannot be resolved to concrete widgets
4276    /// (non-widget targets, widgets missing from the graph, or no relevant
4277    /// invalidation at all) falls back to re-measuring everything, which is always
4278    /// correct.
4279    fn build_measure_scope(&self, invalidations: &[InvalidationRequest]) -> Rc<MeasureScope> {
4280        let mut subtree_roots: HashSet<WidgetId> = HashSet::new();
4281        let mut force_all = false;
4282        for request in invalidations {
4283            if !matches!(
4284                request.kind,
4285                InvalidationKind::Measure
4286                    | InvalidationKind::Text
4287                    | InvalidationKind::Visibility
4288                    | InvalidationKind::Ordering
4289            ) {
4290                continue;
4291            }
4292            match request.target {
4293                InvalidationTarget::Widget(widget_id) => {
4294                    subtree_roots.insert(widget_id);
4295                }
4296                InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => {
4297                    force_all = true;
4298                }
4299            }
4300        }
4301
4302        if force_all || subtree_roots.is_empty() {
4303            return Rc::new(MeasureScope::force_all());
4304        }
4305
4306        let mut dirty: HashSet<WidgetId> = HashSet::new();
4307        for widget_id in &subtree_roots {
4308            if !self.graph.extend_ancestors(*widget_id, &mut dirty) {
4309                return Rc::new(MeasureScope::force_all());
4310            }
4311        }
4312
4313        Rc::new(MeasureScope::scoped(dirty, subtree_roots))
4314    }
4315
4316    fn build_arrange_scope(&self, invalidations: &[InvalidationRequest]) -> Rc<ArrangeScope> {
4317        let mut subtree_roots: HashSet<WidgetId> = HashSet::new();
4318        let mut force_all = false;
4319        for request in invalidations {
4320            if !matches!(
4321                request.kind,
4322                InvalidationKind::Measure
4323                    | InvalidationKind::Arrange
4324                    | InvalidationKind::Transform
4325                    | InvalidationKind::Clip
4326                    | InvalidationKind::Visibility
4327                    | InvalidationKind::Text
4328            ) {
4329                continue;
4330            }
4331            match request.target {
4332                InvalidationTarget::Widget(widget_id) => {
4333                    subtree_roots.insert(widget_id);
4334                }
4335                InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => {
4336                    force_all = true;
4337                }
4338            }
4339        }
4340
4341        if force_all || subtree_roots.is_empty() {
4342            return Rc::new(ArrangeScope::force_all());
4343        }
4344
4345        let mut dirty: HashSet<WidgetId> = HashSet::new();
4346        for widget_id in subtree_roots {
4347            if !self.graph.extend_ancestors(widget_id, &mut dirty) {
4348                return Rc::new(ArrangeScope::force_all());
4349            }
4350        }
4351        Rc::new(ArrangeScope::scoped(dirty))
4352    }
4353
4354    fn run_measure_arrange_pass(
4355        &mut self,
4356        invalidations: &[InvalidationRequest],
4357        text_system: Arc<TextSystem>,
4358        font_registry: Arc<FontRegistry>,
4359        image_registry: Arc<ImageRegistry>,
4360    ) -> Vec<InvalidationRequest> {
4361        let constraints = self.measure_constraints();
4362        let scope = self.build_measure_scope(invalidations);
4363        if (self.schedule.measure || self.viewport.is_none()) && scope.is_full_invalidation() {
4364            self.measure_queries.borrow_mut().invalidate_context();
4365        }
4366        let mut measure_ctx = MeasureCtx::new_scoped_at(
4367            self.id,
4368            self.root.id(),
4369            self.root.bounds(),
4370            self.current_dpi_info(),
4371            text_system,
4372            font_registry,
4373            image_registry,
4374            scope,
4375            self.last_tick_time,
4376        );
4377        measure_ctx.set_query_cache(self.measure_queries.clone());
4378        layout_work::record(|work| work.layout_passes += 1);
4379        let measure_started = layout_work::started();
4380        let measured_root = if self.schedule.measure || self.viewport.is_none() {
4381            self.root.measure(&mut measure_ctx, constraints)
4382        } else {
4383            self.root.measured_size()
4384        };
4385        layout_work::elapsed(measure_started, |work, us| work.measure_us += us);
4386        let viewport = constraints.clamp(measured_root);
4387
4388        let mut pass_invalidations = measure_ctx.take_invalidations();
4389        let mut arrange_invalidations = invalidations.to_vec();
4390        arrange_invalidations.extend(pass_invalidations.iter().cloned());
4391        let arrange_scope = self.build_arrange_scope(&arrange_invalidations);
4392        let mut arrange_ctx = ArrangeCtx::new_scoped_at(
4393            self.id,
4394            self.root.id(),
4395            self.current_dpi_info(),
4396            self.last_tick_time,
4397            arrange_scope,
4398        );
4399        let arrange_started = layout_work::started();
4400        self.root.arrange(
4401            &mut arrange_ctx,
4402            Rect::from_origin_size(Point::ZERO, viewport),
4403        );
4404        layout_work::elapsed(arrange_started, |work, us| work.arrange_us += us);
4405        self.viewport = Some(viewport);
4406        self.schedule.measure = false;
4407        self.schedule.arrange = false;
4408        self.schedule.hit_test = false;
4409        self.refresh_graph();
4410
4411        let mut invalidations = std::mem::take(&mut pass_invalidations);
4412        self.apply_wake_requests(measure_ctx.take_wake_requests());
4413        invalidations.extend(arrange_ctx.take_invalidations());
4414        self.apply_wake_requests(arrange_ctx.take_wake_requests());
4415        invalidations
4416    }
4417
4418    fn refresh_graph(&mut self) {
4419        let graph_started = layout_work::started();
4420        self.graph.rebuild_in_place(
4421            &self.root,
4422            self.focus.focused_widget,
4423            &self.last_paint_bounds_by_widget,
4424        );
4425        let overlay_focus = self.overlay_manager.sync(
4426            self.graph.overlay_snapshots(),
4427            &self.graph,
4428            self.focus.focused_widget,
4429        );
4430        if overlay_focus.is_some() {
4431            self.pending_overlay_focus = overlay_focus;
4432        }
4433        self.prune_runtime_state();
4434        self.schedule.hit_test = false;
4435        layout_work::elapsed(graph_started, |work, us| work.graph_us += us);
4436    }
4437
4438    fn filter_modal_semantics(&self, mut nodes: Vec<SemanticsNode>) -> Vec<SemanticsNode> {
4439        let Some(modal) = self.overlay_manager.active_modal() else {
4440            return nodes;
4441        };
4442
4443        let modal_subtree = self
4444            .graph
4445            .subtree_ids(modal)
4446            .into_iter()
4447            .collect::<HashSet<_>>();
4448        let mut allowed = modal_subtree.clone();
4449        let mut ancestor = self.graph.node(modal).and_then(|node| node.parent);
4450        while let Some(widget_id) = ancestor {
4451            allowed.insert(widget_id);
4452            ancestor = self.graph.node(widget_id).and_then(|node| node.parent);
4453        }
4454
4455        let parents = nodes
4456            .iter()
4457            .map(|node| (node.id, node.parent))
4458            .collect::<HashMap<_, _>>();
4459        let belongs_to_modal = |node: &SemanticsNode| {
4460            if allowed.contains(&node.id) {
4461                return true;
4462            }
4463            let mut current = node.parent;
4464            let mut visited = HashSet::new();
4465            while let Some(parent) = current {
4466                if !visited.insert(parent) {
4467                    break;
4468                }
4469                if modal_subtree.contains(&parent) {
4470                    return true;
4471                }
4472                current = parents.get(&parent).copied().flatten();
4473            }
4474            false
4475        };
4476        nodes.retain(belongs_to_modal);
4477        if let Some(node) = nodes.iter_mut().find(|node| node.id == modal) {
4478            node.state.modal = true;
4479        }
4480        nodes
4481    }
4482
4483    fn sync_scene_stack_metadata(&self, scene: &mut Scene) {
4484        scene.visit_layers_mut(&mut |layer| {
4485            if let Some(node) = self.graph.node(layer.widget_id()) {
4486                layer.descriptor.stack_host = node.stack_host;
4487                layer.descriptor.stack_order = node.stack_surface_order;
4488                layer.descriptor.transient_owner_surface = node.transient_owner_surface;
4489                layer.descriptor.is_stack_surface = node.is_stack_surface;
4490                layer.descriptor.hit_test = node.hit_test;
4491            }
4492        });
4493        scene.reorder_stack_surfaces();
4494    }
4495
4496    fn prune_runtime_state(&mut self) {
4497        self.pointer_capture
4498            .retain(|_, widget_id| self.graph.contains(*widget_id));
4499        let stale_grab_owner = self
4500            .cursor
4501            .grab_owner
4502            .is_some_and(|widget_id| !self.graph.contains(widget_id));
4503        let stale_visibility_owner = self
4504            .cursor
4505            .visibility_owner
4506            .is_some_and(|widget_id| !self.graph.contains(widget_id));
4507        if stale_grab_owner || stale_visibility_owner {
4508            self.reset_cursor_state();
4509        }
4510        if self
4511            .active_drag
4512            .as_ref()
4513            .is_some_and(|drag| !self.graph.contains(drag.source))
4514        {
4515            self.active_drag = None;
4516        }
4517        self.scheduled_timers
4518            .retain(|timer| self.graph.contains(timer.target));
4519        self.delivering_timers
4520            .retain(|_, widget_id| self.graph.contains(*widget_id));
4521        self.async_wake_targets
4522            .retain(|_, widget_id| self.graph.contains(*widget_id));
4523        self.pending_async_wakeups
4524            .retain(|token| self.async_wake_targets.contains_key(token));
4525        self.requested_animation_frames
4526            .retain(|widget_id| self.graph.contains(*widget_id));
4527        self.delivering_animation_frames
4528            .retain(|widget_id| self.graph.contains(*widget_id));
4529        if self.requested_animation_frames.is_empty() && self.delivering_animation_frames.is_empty()
4530        {
4531            self.last_animation_frame_time = None;
4532        }
4533
4534        if self
4535            .focus
4536            .focused_widget
4537            .is_some_and(|widget_id| !self.graph.contains(widget_id))
4538        {
4539            self.focus.focused_widget = None;
4540            self.focused_semantics = None;
4541        }
4542    }
4543
4544    fn measure_constraints(&self) -> Constraints {
4545        self.viewport_hint
4546            .map(Constraints::tight)
4547            .unwrap_or(Constraints::UNBOUNDED)
4548    }
4549
4550    fn dpi_info_for_viewport(&self, viewport: Size) -> DpiInfo {
4551        DpiInfo::new(
4552            self.scale_factor,
4553            self.raw_dpi,
4554            viewport,
4555            scale_viewport_to_surface_size(viewport, self.scale_factor),
4556        )
4557        .with_safe_area(self.safe_area)
4558    }
4559
4560    fn current_dpi_info(&self) -> DpiInfo {
4561        let viewport = self.viewport.or(self.viewport_hint).unwrap_or(Size::ZERO);
4562        self.dpi_info_for_viewport(viewport)
4563    }
4564
4565    fn clear_inspector_history(&mut self) {
4566        self.event_route_history.clear();
4567        self.reactive_invalidation_history.clear();
4568        self.command_dispatch_history.clear();
4569        self.invalidation_history.clear();
4570        self.widget_rebuild_history.clear();
4571    }
4572
4573    fn capture_inspector_diagnostics(&mut self, diagnostics: &RenderDiagnostics) {
4574        if !self.inspector_tracing_enabled {
4575            return;
4576        }
4577
4578        extend_inspector_history(
4579            &mut self.reactive_invalidation_history,
4580            diagnostics.reactive_invalidations.iter().cloned(),
4581        );
4582        extend_inspector_history(
4583            &mut self.command_dispatch_history,
4584            diagnostics.command_dispatches.iter().cloned(),
4585        );
4586        extend_inspector_history(
4587            &mut self.invalidation_history,
4588            diagnostics.invalidations.iter().cloned(),
4589        );
4590        extend_inspector_history(
4591            &mut self.widget_rebuild_history,
4592            diagnostics.widget_rebuilds.iter().cloned(),
4593        );
4594        self.last_render_diagnostics = diagnostics.clone();
4595    }
4596
4597    fn scheduler_snapshot(&self) -> SchedulerInspectorSnapshot {
4598        let mut timers = self
4599            .scheduled_timers
4600            .iter()
4601            .map(|timer| TimerInspectorSnapshot {
4602                token: timer.token,
4603                target: timer.target,
4604                deadline: timer.deadline,
4605                delivering: self.delivering_timers.contains_key(&timer.token),
4606            })
4607            .collect::<Vec<_>>();
4608        for (&token, &target) in &self.delivering_timers {
4609            if timers.iter().all(|timer| timer.token != token) {
4610                timers.push(TimerInspectorSnapshot {
4611                    token,
4612                    target,
4613                    deadline: self.last_tick_time,
4614                    delivering: true,
4615                });
4616            }
4617        }
4618        timers.sort_by(|left, right| left.deadline.total_cmp(&right.deadline));
4619
4620        let mut async_tasks = self
4621            .async_wake_targets
4622            .iter()
4623            .map(|(&token, &target)| AsyncTaskInspectorSnapshot {
4624                token,
4625                target,
4626                pending_wake: self.pending_async_wakeups.contains(&token),
4627            })
4628            .collect::<Vec<_>>();
4629        async_tasks.sort_by_key(|task| task.token.get());
4630
4631        SchedulerInspectorSnapshot {
4632            timers,
4633            async_tasks,
4634            requested_animation_frames: self.requested_animation_frames.iter().copied().collect(),
4635            delivering_animation_frames: self.delivering_animation_frames.iter().copied().collect(),
4636            last_animation_frame_time: self.last_animation_frame_time,
4637        }
4638    }
4639
4640    fn inspector_snapshot(&self) -> WindowInspectorSnapshot {
4641        let mut widget_diagnostics = Vec::new();
4642        self.root.collect_diagnostics(&mut widget_diagnostics);
4643        WindowInspectorSnapshot {
4644            window_id: self.id,
4645            title: self.title.clone(),
4646            tracing_enabled: self.inspector_tracing_enabled,
4647            focus_state: self.focus,
4648            schedule: self.schedule,
4649            semantics: self.last_semantics.clone(),
4650            widget_graph: self.graph.snapshot(),
4651            overlays: self.overlay_manager.snapshot(),
4652            scheduler: self.scheduler_snapshot(),
4653            widget_diagnostics,
4654            last_render_diagnostics: self.last_render_diagnostics.clone(),
4655            history: InspectorHistorySnapshot {
4656                event_routes: self.event_route_history.iter().cloned().collect(),
4657                reactive_invalidations: self
4658                    .reactive_invalidation_history
4659                    .iter()
4660                    .cloned()
4661                    .collect(),
4662                command_dispatches: self.command_dispatch_history.iter().cloned().collect(),
4663                invalidations: self.invalidation_history.iter().cloned().collect(),
4664                widget_rebuilds: self.widget_rebuild_history.iter().cloned().collect(),
4665            },
4666            scene: self.last_frame.as_ref().map(|frame| {
4667                SceneStatistics::from_frame_with_mode(
4668                    frame,
4669                    self.graph.nodes.len(),
4670                    window_scene_statistics_detail_mode(self.id),
4671                )
4672            }),
4673        }
4674    }
4675}
4676
4677impl Drop for WindowState {
4678    fn drop(&mut self) {
4679        self.output_cache.borrow_mut().close();
4680        reactive::unregister_window(self.id);
4681        diagnostics::clear_widget_rebuilds(self.id);
4682    }
4683}
4684
4685fn normalize_scale_factor(scale_factor: f32) -> f32 {
4686    if scale_factor.is_finite() && scale_factor > 0.0 {
4687        scale_factor
4688    } else {
4689        1.0
4690    }
4691}
4692
4693fn scale_viewport_to_surface_size(viewport: Size, scale_factor: f32) -> Size {
4694    if viewport.is_empty() {
4695        return Size::ZERO;
4696    }
4697
4698    let scale_factor = normalize_scale_factor(scale_factor);
4699    Size::new(
4700        (viewport.width * scale_factor).round().max(1.0),
4701        (viewport.height * scale_factor).round().max(1.0),
4702    )
4703}
4704
4705impl WindowState {
4706    fn assemble_semantics_tree(&mut self, nodes: Vec<SemanticsNode>) -> Vec<SemanticsNode> {
4707        let semantic_ids: HashSet<_> = nodes.iter().map(|node| node.id).collect();
4708        if self
4709            .focused_semantics
4710            .is_some_and(|focused| !semantic_ids.contains(&focused))
4711        {
4712            self.focused_semantics = self.focus.focused_widget;
4713        }
4714
4715        nodes
4716            .into_iter()
4717            .map(|mut node| {
4718                node.parent = self.resolve_semantics_parent(&semantic_ids, node.id, node.parent);
4719                node.state.focused |= Some(node.id) == self.focused_semantics;
4720                node
4721            })
4722            .collect()
4723    }
4724
4725    fn resolve_semantics_parent(
4726        &self,
4727        semantic_ids: &HashSet<WidgetId>,
4728        widget_id: WidgetId,
4729        explicit_parent: Option<WidgetId>,
4730    ) -> Option<WidgetId> {
4731        if let Some(parent) =
4732            explicit_parent.filter(|parent| *parent != widget_id && semantic_ids.contains(parent))
4733        {
4734            return Some(parent);
4735        }
4736
4737        let mut current = self.graph.node(widget_id).and_then(|node| node.parent);
4738        while let Some(candidate) = current {
4739            if semantic_ids.contains(&candidate) {
4740                return Some(candidate);
4741            }
4742            current = self.graph.node(candidate).and_then(|node| node.parent);
4743        }
4744        None
4745    }
4746}
4747
4748#[derive(Default)]
4749struct WidgetGraph {
4750    root: WidgetId,
4751    nodes: HashMap<WidgetId, WidgetNodeSnapshot>,
4752    order: Vec<WidgetId>,
4753    host_surface_order: HashMap<WidgetId, Vec<WidgetId>>,
4754    host_order_policy: HashMap<WidgetId, StackOrderPolicy>,
4755    overlay_options: HashMap<WidgetId, OverlayOptions>,
4756    overlay_parents: HashMap<WidgetId, Option<WidgetId>>,
4757    overlay_surfaces: HashMap<WidgetId, Vec<WidgetId>>,
4758    child_buffers: Vec<Vec<WidgetId>>,
4759}
4760
4761#[derive(Clone, Copy)]
4762struct GraphCollectContext {
4763    stack_host: WidgetId,
4764    stack_surface: WidgetId,
4765    overlay_owner: Option<WidgetId>,
4766}
4767
4768impl WidgetGraph {
4769    fn empty(root: WidgetId) -> Self {
4770        Self {
4771            root,
4772            nodes: HashMap::new(),
4773            order: Vec::new(),
4774            host_surface_order: HashMap::new(),
4775            host_order_policy: HashMap::new(),
4776            overlay_options: HashMap::new(),
4777            overlay_parents: HashMap::new(),
4778            overlay_surfaces: HashMap::new(),
4779            child_buffers: Vec::new(),
4780        }
4781    }
4782
4783    fn rebuild_in_place(
4784        &mut self,
4785        root: &WidgetPod,
4786        focused_widget: Option<WidgetId>,
4787        paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
4788    ) {
4789        self.root = root.id();
4790        for (_, mut node) in self.nodes.drain() {
4791            node.children.clear();
4792            self.child_buffers.push(node.children);
4793        }
4794        self.order.clear();
4795        self.host_surface_order.clear();
4796        self.host_order_policy.clear();
4797        self.overlay_options.clear();
4798        self.overlay_parents.clear();
4799        self.overlay_surfaces.clear();
4800        let mut inverse_cache = HashMap::new();
4801        self.collect(
4802            root,
4803            None,
4804            focused_widget,
4805            paint_bounds_by_widget,
4806            GraphCollectContext {
4807                stack_host: root.id(),
4808                stack_surface: root.id(),
4809                overlay_owner: None,
4810            },
4811            &mut inverse_cache,
4812        );
4813        self.recompute_stack_surface_order();
4814    }
4815
4816    fn recompute_stack_surface_order(&mut self) {
4817        let mut position_by_surface = HashMap::<(WidgetId, WidgetId), usize>::new();
4818        for (host, surfaces) in &self.host_surface_order {
4819            for (index, surface) in surfaces.iter().copied().enumerate() {
4820                position_by_surface.insert((*host, surface), index);
4821            }
4822        }
4823
4824        for node in self.nodes.values_mut() {
4825            if let Some(order) = position_by_surface.get(&(node.stack_host, node.stack_surface)) {
4826                node.stack_surface_order = *order;
4827            }
4828        }
4829    }
4830
4831    fn update_paint_bounds_from_snapshot(
4832        &mut self,
4833        paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
4834    ) {
4835        for node in self.nodes.values_mut() {
4836            node.geometry.paint_bounds = paint_bounds_by_widget
4837                .get(&node.id)
4838                .copied()
4839                .unwrap_or(node.geometry.layout_bounds);
4840        }
4841    }
4842
4843    fn set_focused_widget(&mut self, focused_widget: Option<WidgetId>) {
4844        for node in self.nodes.values_mut() {
4845            node.focused = Some(node.id) == focused_widget;
4846        }
4847    }
4848
4849    fn is_empty(&self) -> bool {
4850        self.nodes.is_empty()
4851    }
4852
4853    fn contains(&self, widget_id: WidgetId) -> bool {
4854        self.nodes.contains_key(&widget_id)
4855    }
4856
4857    fn node(&self, widget_id: WidgetId) -> Option<&WidgetNodeSnapshot> {
4858        self.nodes.get(&widget_id)
4859    }
4860
4861    fn snapshot(&self) -> WidgetGraphSnapshot {
4862        let mut stack_hosts = self
4863            .host_order_policy
4864            .iter()
4865            .map(|(host, order_policy)| StackHostSnapshot {
4866                host: *host,
4867                order_policy: *order_policy,
4868                surfaces: self
4869                    .host_surface_order
4870                    .get(host)
4871                    .cloned()
4872                    .unwrap_or_default(),
4873            })
4874            .collect::<Vec<_>>();
4875        stack_hosts.sort_by_key(|host| host.host.get());
4876
4877        WidgetGraphSnapshot {
4878            root: self.root,
4879            nodes: self
4880                .order
4881                .iter()
4882                .filter_map(|widget_id| self.nodes.get(widget_id).cloned())
4883                .collect(),
4884            stack_hosts,
4885        }
4886    }
4887
4888    fn hit_test(&self, point: Point) -> Option<WidgetId> {
4889        self.hit_test_node(self.root, point)
4890    }
4891
4892    fn hit_test_within(&self, widget_id: WidgetId, point: Point) -> Option<WidgetId> {
4893        self.hit_test_node(widget_id, point)
4894    }
4895
4896    fn path_to(&self, target: WidgetId) -> Option<Vec<WidgetId>> {
4897        let mut path = Vec::new();
4898        let mut current = Some(target);
4899
4900        while let Some(widget_id) = current {
4901            let node = self.node(widget_id)?;
4902            path.push(widget_id);
4903            current = node.parent;
4904        }
4905
4906        path.reverse();
4907        Some(path)
4908    }
4909
4910    fn depth(&self, target: WidgetId) -> Option<usize> {
4911        let mut depth = 0usize;
4912        let mut current = Some(target);
4913        while let Some(widget_id) = current {
4914            let node = self.node(widget_id)?;
4915            depth += 1;
4916            current = node.parent;
4917        }
4918        Some(depth)
4919    }
4920
4921    fn is_ancestor_of(&self, ancestor: WidgetId, target: WidgetId) -> bool {
4922        let mut current = self.node(target).and_then(|node| node.parent);
4923        while let Some(widget_id) = current {
4924            if widget_id == ancestor {
4925                return true;
4926            }
4927            current = self.node(widget_id).and_then(|node| node.parent);
4928        }
4929        false
4930    }
4931
4932    fn extend_ancestors(&self, target: WidgetId, ancestors: &mut HashSet<WidgetId>) -> bool {
4933        let mut current = Some(target);
4934        while let Some(widget_id) = current {
4935            let Some(node) = self.node(widget_id) else {
4936                return false;
4937            };
4938            ancestors.insert(widget_id);
4939            current = node.parent;
4940        }
4941        true
4942    }
4943
4944    fn subtree_ids(&self, root: WidgetId) -> Vec<WidgetId> {
4945        let mut subtree = Vec::new();
4946        let mut pending = vec![root];
4947        while let Some(widget_id) = pending.pop() {
4948            let Some(node) = self.node(widget_id) else {
4949                continue;
4950            };
4951            subtree.push(widget_id);
4952            pending.extend(node.children.iter().copied());
4953        }
4954        subtree
4955    }
4956
4957    fn nearest_paint_boundary_ancestor_or_root(&self, widget_id: WidgetId) -> WidgetId {
4958        let mut current = Some(widget_id);
4959        while let Some(candidate) = current {
4960            let Some(node) = self.node(candidate) else {
4961                break;
4962            };
4963            if node.paint_boundary == PaintBoundaryMode::Explicit {
4964                return candidate;
4965            }
4966            current = node.parent;
4967        }
4968        self.root
4969    }
4970
4971    fn next_focusable(&self, current: Option<WidgetId>, backwards: bool) -> Option<WidgetId> {
4972        let focusable: Vec<_> = self
4973            .order
4974            .iter()
4975            .copied()
4976            .filter(|widget_id| self.node(*widget_id).is_some_and(|node| node.accepts_focus))
4977            .collect();
4978
4979        if focusable.is_empty() {
4980            return None;
4981        }
4982
4983        let fallback = if backwards {
4984            focusable.last().copied()
4985        } else {
4986            focusable.first().copied()
4987        };
4988
4989        let Some(current) = current else {
4990            return fallback;
4991        };
4992
4993        let Some(index) = focusable.iter().position(|widget_id| *widget_id == current) else {
4994            return fallback;
4995        };
4996
4997        if backwards {
4998            Some(focusable[(index + focusable.len() - 1) % focusable.len()])
4999        } else {
5000            Some(focusable[(index + 1) % focusable.len()])
5001        }
5002    }
5003
5004    fn first_focusable_within(
5005        &self,
5006        overlay_owner: WidgetId,
5007        include_owner: bool,
5008    ) -> Option<WidgetId> {
5009        self.order.iter().copied().find(|candidate| {
5010            self.node(*candidate).is_some_and(|node| node.accepts_focus)
5011                && (include_owner && *candidate == overlay_owner
5012                    || self.is_ancestor_of(overlay_owner, *candidate))
5013        })
5014    }
5015
5016    fn next_focusable_within(
5017        &self,
5018        scope: WidgetId,
5019        current: Option<WidgetId>,
5020        backwards: bool,
5021    ) -> Option<WidgetId> {
5022        let focusable = self
5023            .order
5024            .iter()
5025            .copied()
5026            .filter(|candidate| {
5027                self.node(*candidate).is_some_and(|node| node.accepts_focus)
5028                    && (*candidate == scope || self.is_ancestor_of(scope, *candidate))
5029            })
5030            .collect::<Vec<_>>();
5031        if focusable.is_empty() {
5032            return None;
5033        }
5034        let fallback = if backwards {
5035            focusable.last().copied()
5036        } else {
5037            focusable.first().copied()
5038        };
5039        let Some(current) = current else {
5040            return fallback;
5041        };
5042        let Some(index) = focusable.iter().position(|candidate| *candidate == current) else {
5043            return fallback;
5044        };
5045        if backwards {
5046            Some(focusable[(index + focusable.len() - 1) % focusable.len()])
5047        } else {
5048            Some(focusable[(index + 1) % focusable.len()])
5049        }
5050    }
5051
5052    fn overlay_snapshots(&self) -> Vec<OverlaySnapshot> {
5053        self.order
5054            .iter()
5055            .copied()
5056            .filter_map(|owner| {
5057                let options = self.overlay_options.get(&owner).copied()?;
5058                Some(OverlaySnapshot {
5059                    owner,
5060                    parent: self.overlay_parents.get(&owner).copied().flatten(),
5061                    surfaces: self
5062                        .overlay_surfaces
5063                        .get(&owner)
5064                        .cloned()
5065                        .unwrap_or_default(),
5066                    options,
5067                    order: 0,
5068                })
5069            })
5070            .enumerate()
5071            .map(|(order, mut snapshot)| {
5072                snapshot.order = order;
5073                snapshot
5074            })
5075            .collect()
5076    }
5077
5078    fn collect(
5079        &mut self,
5080        pod: &WidgetPod,
5081        parent: Option<WidgetId>,
5082        focused_widget: Option<WidgetId>,
5083        paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
5084        context: GraphCollectContext,
5085        inverse_cache: &mut HashMap<[u32; 6], Option<Transform>>,
5086    ) {
5087        let id = pod.id();
5088        self.order.push(id);
5089
5090        let overlay_options = pod.current_overlay_options();
5091        let is_overlay_owner = overlay_options.is_some();
5092        let overlay_owner = if is_overlay_owner {
5093            Some(id)
5094        } else {
5095            context.overlay_owner
5096        };
5097        if let Some(options) = overlay_options {
5098            self.overlay_options.insert(id, options);
5099            self.overlay_parents.insert(id, context.overlay_owner);
5100        }
5101
5102        let host_options = if id == self.root {
5103            Some(pod.current_stack_host_options().unwrap_or_default())
5104        } else {
5105            pod.current_stack_host_options()
5106        };
5107        let is_stack_host = host_options.is_some();
5108        let resolved_host = if is_stack_host {
5109            id
5110        } else {
5111            context.stack_host
5112        };
5113        let host_policy = host_options
5114            .map(|options| options.order_policy)
5115            .unwrap_or(StackOrderPolicy::Stable);
5116        if is_stack_host {
5117            self.host_order_policy.insert(resolved_host, host_policy);
5118        } else {
5119            self.host_order_policy
5120                .entry(resolved_host)
5121                .or_insert(StackOrderPolicy::Stable);
5122        }
5123        let resolved_policy = *self
5124            .host_order_policy
5125            .get(&resolved_host)
5126            .unwrap_or(&StackOrderPolicy::Stable);
5127
5128        let surface_options = pod.current_stack_surface_options();
5129        let emits_layer = pod.current_layer_options().emits_layer();
5130        let is_direct_child_of_host = parent == Some(resolved_host);
5131        let is_stack_surface = id != self.root
5132            && emits_layer
5133            && (surface_options.is_some() || is_direct_child_of_host);
5134        let hit_test = surface_options.is_none_or(|options| options.hit_test);
5135        let resolved_surface = if is_stack_surface {
5136            id
5137        } else {
5138            context.stack_surface
5139        };
5140        let transient_owner_surface = surface_options
5141            .filter(|options| emits_layer && options.transient && context.stack_surface != id)
5142            .map(|_| context.stack_surface);
5143        if is_stack_surface {
5144            let surfaces = self.host_surface_order.entry(resolved_host).or_default();
5145            if !surfaces.contains(&id) {
5146                surfaces.push(id);
5147            }
5148        }
5149        if is_stack_surface && let Some(owner) = overlay_owner {
5150            self.overlay_surfaces.entry(owner).or_default().push(id);
5151        }
5152        let stack_surface_order = self
5153            .host_surface_order
5154            .get(&resolved_host)
5155            .and_then(|surfaces| {
5156                surfaces
5157                    .iter()
5158                    .position(|surface| *surface == resolved_surface)
5159            })
5160            .unwrap_or(0);
5161
5162        let children = {
5163            let mut children = self.child_buffers.pop().unwrap_or_default();
5164            children.clear();
5165            let mut visitor = CollectChildrenVisitor {
5166                graph: self,
5167                parent: id,
5168                focused_widget,
5169                paint_bounds_by_widget,
5170                context: GraphCollectContext {
5171                    stack_host: resolved_host,
5172                    stack_surface: resolved_surface,
5173                    overlay_owner,
5174                },
5175                children,
5176                inverse_cache,
5177            };
5178            pod.visit_children(&mut visitor);
5179            visitor.children
5180        };
5181
5182        let local_bounds = pod.bounds();
5183        let presentation_transform = pod.presentation_transform();
5184        let inverse_presentation_transform = *inverse_cache
5185            .entry(transform_bits(presentation_transform))
5186            .or_insert_with(|| presentation_transform.inverse());
5187        let layout_bounds = presentation_transform.transform_rect_bbox(local_bounds);
5188        let input_bounds = layout_bounds;
5189        let paint_bounds = paint_bounds_by_widget
5190            .get(&id)
5191            .copied()
5192            .unwrap_or(layout_bounds);
5193
5194        self.nodes.insert(
5195            id,
5196            WidgetNodeSnapshot {
5197                id,
5198                widget_name: pod.debug_name(),
5199                parent,
5200                children,
5201                measured_size: pod.measured_size(),
5202                geometry: WidgetGeometrySnapshot::new(layout_bounds, input_bounds, paint_bounds),
5203                local_bounds,
5204                presentation_transform,
5205                inverse_presentation_transform,
5206                bounds: layout_bounds,
5207                paint_boundary: pod.current_paint_boundary_mode(),
5208                stack_host: resolved_host,
5209                stack_surface: resolved_surface,
5210                stack_surface_order,
5211                transient_owner_surface,
5212                overlay_owner,
5213                is_overlay_owner,
5214                is_stack_host,
5215                is_stack_surface,
5216                hit_test,
5217                stack_order_policy: resolved_policy,
5218                accepts_focus: pod.accepts_focus(),
5219                focused: Some(id) == focused_widget,
5220            },
5221        );
5222    }
5223
5224    fn hit_test_node(&self, widget_id: WidgetId, point: Point) -> Option<WidgetId> {
5225        let node = self.node(widget_id)?;
5226        if !node.hit_test || !node.geometry.input_bounds.contains(point) {
5227            return None;
5228        }
5229        let local_point = node.inverse_presentation_transform?.transform_point(point);
5230        if !node.local_bounds.contains(local_point) {
5231            return None;
5232        }
5233
5234        if node.is_stack_host {
5235            let mut tested_surfaces = HashSet::new();
5236            if let Some(ordered_surfaces) = self.host_surface_order.get(&node.id) {
5237                for surface_id in ordered_surfaces.iter().rev().copied() {
5238                    if surface_id == widget_id {
5239                        continue;
5240                    }
5241                    tested_surfaces.insert(surface_id);
5242                    if let Some(hit) = self.hit_test_node(surface_id, point) {
5243                        return Some(hit);
5244                    }
5245                }
5246            }
5247
5248            for child_id in node.children.iter().rev() {
5249                if self.node(*child_id).is_some_and(|child| {
5250                    child.is_stack_surface || tested_surfaces.contains(child_id)
5251                }) {
5252                    continue;
5253                }
5254                if let Some(hit) = self.hit_test_node(*child_id, point) {
5255                    return Some(hit);
5256                }
5257            }
5258
5259            return Some(widget_id);
5260        }
5261
5262        for child_id in node.children.iter().rev() {
5263            if let Some(hit) = self.hit_test_node(*child_id, point) {
5264                return Some(hit);
5265            }
5266        }
5267
5268        Some(widget_id)
5269    }
5270}
5271
5272struct CollectChildrenVisitor<'a> {
5273    graph: &'a mut WidgetGraph,
5274    parent: WidgetId,
5275    focused_widget: Option<WidgetId>,
5276    paint_bounds_by_widget: &'a HashMap<WidgetId, Rect>,
5277    context: GraphCollectContext,
5278    children: Vec<WidgetId>,
5279    inverse_cache: &'a mut HashMap<[u32; 6], Option<Transform>>,
5280}
5281
5282impl WidgetPodVisitor for CollectChildrenVisitor<'_> {
5283    fn visit(&mut self, child: &WidgetPod) {
5284        self.children.push(child.id());
5285        self.graph.collect(
5286            child,
5287            Some(self.parent),
5288            self.focused_widget,
5289            self.paint_bounds_by_widget,
5290            self.context,
5291            self.inverse_cache,
5292        );
5293    }
5294}
5295
5296fn transform_bits(transform: Transform) -> [u32; 6] {
5297    [
5298        transform.xx.to_bits(),
5299        transform.yx.to_bits(),
5300        transform.xy.to_bits(),
5301        transform.yy.to_bits(),
5302        transform.dx.to_bits(),
5303        transform.dy.to_bits(),
5304    ]
5305}
5306
5307struct EventRouteResult {
5308    path: Vec<WidgetId>,
5309    effects: EventEffects,
5310    focus_request: Option<FocusRequest>,
5311    handled: bool,
5312}
5313
5314#[derive(Default)]
5315struct HoverTransitionResult {
5316    effects: EventEffects,
5317    focus_request: Option<FocusRequest>,
5318    skip_primary_route: bool,
5319}
5320
5321#[derive(Default)]
5322struct EventEffects {
5323    invalidations: Vec<InvalidationRequest>,
5324    wake_requests: Vec<WakeRequest>,
5325    pointer_capture_requests: Vec<PointerCaptureRequest>,
5326    cursor_requests: Vec<CursorRequest>,
5327    drag_requests: Vec<DragRequest>,
5328    drop_acceptances: Vec<DropAcceptanceRequest>,
5329    posted_events: Vec<widget::PostedEventRequest>,
5330    posted_commands: Vec<widget::PostedCommandRequest>,
5331}
5332
5333impl EventEffects {
5334    fn extend(&mut self, dispatch: widget::EventDispatch) {
5335        self.invalidations.extend(dispatch.invalidations);
5336        self.wake_requests.extend(dispatch.wake_requests);
5337        self.pointer_capture_requests
5338            .extend(dispatch.pointer_capture_requests);
5339        self.cursor_requests.extend(dispatch.cursor_requests);
5340        self.drag_requests.extend(dispatch.drag_requests);
5341        self.drop_acceptances.extend(dispatch.drop_acceptances);
5342        self.posted_events.extend(dispatch.posted_events);
5343        self.posted_commands.extend(dispatch.posted_commands);
5344    }
5345
5346    fn merge(&mut self, effects: EventEffects) {
5347        self.invalidations.extend(effects.invalidations);
5348        self.wake_requests.extend(effects.wake_requests);
5349        self.pointer_capture_requests
5350            .extend(effects.pointer_capture_requests);
5351        self.cursor_requests.extend(effects.cursor_requests);
5352        self.drag_requests.extend(effects.drag_requests);
5353        self.drop_acceptances.extend(effects.drop_acceptances);
5354        self.posted_events.extend(effects.posted_events);
5355        self.posted_commands.extend(effects.posted_commands);
5356    }
5357}
5358
5359fn empty_dispatch() -> widget::EventDispatch {
5360    widget::EventDispatch {
5361        handled: false,
5362        invalidations: Vec::new(),
5363        focus_request: None,
5364        wake_requests: Vec::new(),
5365        pointer_capture_requests: Vec::new(),
5366        cursor_requests: Vec::new(),
5367        drag_requests: Vec::new(),
5368        drop_acceptances: Vec::new(),
5369        posted_events: Vec::new(),
5370        posted_commands: Vec::new(),
5371    }
5372}
5373
5374const MAX_PENDING_TRACE_SAMPLES: usize = 512;
5375const MAX_INSPECTOR_HISTORY_SAMPLES: usize = 256;
5376
5377fn push_trace<T>(samples: &mut Vec<T>, sample: T) {
5378    if samples.len() == MAX_PENDING_TRACE_SAMPLES {
5379        samples.remove(0);
5380    }
5381    samples.push(sample);
5382}
5383
5384fn extend_traces<T>(samples: &mut Vec<T>, additions: impl IntoIterator<Item = T>) {
5385    for sample in additions {
5386        push_trace(samples, sample);
5387    }
5388}
5389
5390fn push_inspector_history<T>(samples: &mut VecDeque<T>, sample: T) {
5391    if samples.len() == MAX_INSPECTOR_HISTORY_SAMPLES {
5392        samples.pop_front();
5393    }
5394    samples.push_back(sample);
5395}
5396
5397fn extend_inspector_history<T>(samples: &mut VecDeque<T>, additions: impl IntoIterator<Item = T>) {
5398    for sample in additions {
5399        push_inspector_history(samples, sample);
5400    }
5401}
5402
5403fn command_sample(
5404    command: &QueuedCommand,
5405    handlers: Vec<String>,
5406    handled: bool,
5407    delivered: bool,
5408) -> CommandDispatchSample {
5409    CommandDispatchSample {
5410        sequence: command.sequence,
5411        name: command.key.name.to_string(),
5412        payload_type: command.key.payload_type_name.to_string(),
5413        target: command.target,
5414        delivery: command.delivery,
5415        handlers,
5416        handled,
5417        delivered,
5418    }
5419}
5420
5421fn event_trace_source(event: &Event) -> String {
5422    let kind = match event {
5423        Event::Pointer(event) => format!("pointer:{:?}", event.kind),
5424        Event::RawMouseMotion(_) => "raw-mouse-motion".to_string(),
5425        Event::Drag(event) => format!("drag:{:?}", event.kind),
5426        Event::Keyboard(_) => "keyboard".to_string(),
5427        Event::Ime(_) => "ime".to_string(),
5428        Event::Semantics(_) => "semantics".to_string(),
5429        Event::Wake(event) => format!("wake:{event:?}"),
5430        Event::Window(event) => format!("window:{event:?}"),
5431        Event::Custom(event) => format!("custom:{}", event.kind),
5432    };
5433    format!("event:{kind}")
5434}
5435
5436fn inspector_event_kind(event: &Event) -> &'static str {
5437    match event {
5438        Event::Pointer(_) => "pointer",
5439        Event::RawMouseMotion(_) => "raw-mouse-motion",
5440        Event::Drag(_) => "drag",
5441        Event::Keyboard(_) => "keyboard",
5442        Event::Ime(_) => "ime",
5443        Event::Semantics(_) => "semantics",
5444        Event::Wake(_) => "wake",
5445        Event::Window(_) => "window",
5446        Event::Custom(_) => "custom",
5447    }
5448}
5449
5450fn nearest_drop_acceptance(
5451    acceptances: &[DropAcceptanceRequest],
5452    path: &[WidgetId],
5453) -> Option<DropAcceptanceRequest> {
5454    acceptances
5455        .iter()
5456        .filter_map(|acceptance| {
5457            path.iter()
5458                .position(|widget_id| *widget_id == acceptance.target)
5459                .map(|index| (index, *acceptance))
5460        })
5461        .max_by_key(|(index, _)| *index)
5462        .map(|(_, acceptance)| acceptance)
5463}
5464
5465fn collect_dirty_regions<F>(
5466    viewport: Size,
5467    invalidations: &[InvalidationRequest],
5468    repainted: bool,
5469    default_region_for: F,
5470) -> Vec<DirtyRegion>
5471where
5472    F: FnMut(&InvalidationRequest) -> Rect,
5473{
5474    let viewport_rect = Rect::from_origin_size(Point::ZERO, viewport);
5475    let mut default_region_for = default_region_for;
5476
5477    if invalidations.is_empty() {
5478        return if repainted {
5479            vec![DirtyRegion::new(viewport_rect, InvalidationKind::Paint)]
5480        } else {
5481            Vec::new()
5482        };
5483    }
5484    let mut dirty_regions: Vec<_> = invalidations
5485        .iter()
5486        .map(|request| {
5487            DirtyRegion::new(
5488                request
5489                    .region
5490                    .unwrap_or_else(|| default_region_for(request)),
5491                request.kind,
5492            )
5493        })
5494        .collect();
5495
5496    if repainted
5497        && dirty_regions
5498            .iter()
5499            .all(|region| region.kind != InvalidationKind::Paint)
5500    {
5501        dirty_regions.push(DirtyRegion::new(viewport_rect, InvalidationKind::Paint));
5502    }
5503
5504    dirty_regions
5505}
5506
5507fn collect_scene_layers(scene: &Scene) -> HashMap<WidgetId, SceneLayerDescriptor> {
5508    let mut layers = HashMap::new();
5509    scene.visit_layers(&mut |layer| {
5510        layers.insert(layer.widget_id(), layer.descriptor.clone());
5511    });
5512    layers
5513}
5514
5515fn retain_text_layouts_for_scene(text_system: &TextSystem, scene: &Scene) {
5516    text_system.retain_persistent_layouts(&active_text_layout_handles(scene));
5517}
5518
5519fn active_text_layout_handles(scene: &Scene) -> HashSet<TextLayoutHandle> {
5520    let mut handles = HashSet::new();
5521    scene.visit_commands(&mut |command| match command {
5522        SceneCommand::DrawShapedText(text) => {
5523            handles.insert(text.layout_handle);
5524        }
5525        SceneCommand::DrawShapedTextWindow(text) => {
5526            handles.insert(text.layout_handle);
5527        }
5528        _ => {}
5529    });
5530    handles
5531}
5532
5533fn resolve_snapshot_paint_boundary_or_root(
5534    snapshot: &WidgetGraphSnapshot,
5535    widget_id: WidgetId,
5536) -> WidgetId {
5537    let nodes = snapshot
5538        .nodes
5539        .iter()
5540        .map(|node| (node.id, node))
5541        .collect::<HashMap<_, _>>();
5542    let mut current = Some(widget_id);
5543    while let Some(candidate) = current {
5544        let Some(node) = nodes.get(&candidate) else {
5545            break;
5546        };
5547        if node.paint_boundary == PaintBoundaryMode::Explicit {
5548            return candidate;
5549        }
5550        current = node.parent;
5551    }
5552    snapshot.root
5553}
5554
5555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5556enum HitTestCompositionPhase {
5557    Normal,
5558    Overlay,
5559    Effect,
5560}
5561
5562fn scene_hit_test_for_phase(
5563    scene: &Scene,
5564    point: Point,
5565    target_phase: HitTestCompositionPhase,
5566    inherited_phase: HitTestCompositionPhase,
5567) -> Option<WidgetId> {
5568    for command in scene.commands().iter().rev() {
5569        let SceneCommand::Layer(layer) = command else {
5570            continue;
5571        };
5572
5573        let layer_phase = next_hit_test_phase(inherited_phase, layer.descriptor.composition_mode);
5574        if !layer.descriptor.paint_bounds.contains(point) {
5575            continue;
5576        }
5577        if !layer.descriptor.hit_test {
5578            continue;
5579        }
5580
5581        if let Some(hit) = scene_hit_test_for_phase(&layer.scene, point, target_phase, layer_phase)
5582        {
5583            return Some(hit);
5584        }
5585
5586        if layer_phase == target_phase {
5587            return Some(layer.widget_id());
5588        }
5589    }
5590
5591    None
5592}
5593
5594fn next_hit_test_phase(
5595    inherited_phase: HitTestCompositionPhase,
5596    composition_mode: LayerCompositionMode,
5597) -> HitTestCompositionPhase {
5598    match (inherited_phase, composition_mode) {
5599        (HitTestCompositionPhase::Effect, _) | (_, LayerCompositionMode::Effect) => {
5600            HitTestCompositionPhase::Effect
5601        }
5602        (HitTestCompositionPhase::Overlay, _) | (_, LayerCompositionMode::Overlay) => {
5603            HitTestCompositionPhase::Overlay
5604        }
5605        _ => HitTestCompositionPhase::Normal,
5606    }
5607}
5608
5609fn root_repaint_covers_graph_changes(
5610    root: WidgetId,
5611    invalidations: &[InvalidationRequest],
5612) -> bool {
5613    let root_transform = invalidations.iter().any(|request| {
5614        request.kind == InvalidationKind::Transform
5615            && request.target == InvalidationTarget::Widget(root)
5616    });
5617    let root_content = invalidations.iter().any(|request| {
5618        matches!(
5619            request.kind,
5620            InvalidationKind::Measure
5621                | InvalidationKind::Clip
5622                | InvalidationKind::Visibility
5623                | InvalidationKind::Paint
5624                | InvalidationKind::Text
5625                | InvalidationKind::Resources
5626        ) && request.target == InvalidationTarget::Widget(root)
5627    });
5628    root_transform && root_content
5629}
5630
5631fn invalidation_to_layer_update_kind(kind: InvalidationKind) -> Option<SceneLayerUpdateKind> {
5632    match kind {
5633        InvalidationKind::Measure | InvalidationKind::Arrange | InvalidationKind::Transform => {
5634            Some(SceneLayerUpdateKind::Transform)
5635        }
5636        InvalidationKind::Ordering => Some(SceneLayerUpdateKind::Ordering),
5637        InvalidationKind::Clip => Some(SceneLayerUpdateKind::Clip),
5638        InvalidationKind::Effect => Some(SceneLayerUpdateKind::Effect),
5639        InvalidationKind::Visibility => Some(SceneLayerUpdateKind::Visibility),
5640        InvalidationKind::Paint | InvalidationKind::Text => Some(SceneLayerUpdateKind::Content),
5641        InvalidationKind::Resources => Some(SceneLayerUpdateKind::Resources),
5642        InvalidationKind::HitTest | InvalidationKind::Semantics => None,
5643    }
5644}
5645
5646fn merge_layer_update_kind(
5647    updates: &mut HashMap<WidgetId, SceneLayerUpdateKind>,
5648    widget_id: WidgetId,
5649    kind: SceneLayerUpdateKind,
5650) {
5651    updates
5652        .entry(widget_id)
5653        .and_modify(|current| {
5654            if layer_update_priority(kind) > layer_update_priority(*current) {
5655                *current = kind;
5656            }
5657        })
5658        .or_insert(kind);
5659}
5660
5661fn layer_update_priority(kind: SceneLayerUpdateKind) -> u8 {
5662    match kind {
5663        SceneLayerUpdateKind::Visibility => 0,
5664        SceneLayerUpdateKind::Ordering => 1,
5665        SceneLayerUpdateKind::Transform => 2,
5666        SceneLayerUpdateKind::Clip => 3,
5667        SceneLayerUpdateKind::Content => 4,
5668        SceneLayerUpdateKind::Effect => 5,
5669        SceneLayerUpdateKind::Resources => 6,
5670    }
5671}
5672
5673#[derive(Debug, Clone, PartialEq)]
5674pub struct RenderOutput {
5675    pub title: String,
5676    pub frame: SceneFrame,
5677    pub semantics: Vec<SemanticsNode>,
5678    pub ime_composition_rect: Option<Rect>,
5679    pub diagnostics: RenderDiagnostics,
5680}
5681
5682#[cfg(test)]
5683mod tests;