Skip to main content

sui_runtime/
lib.rs

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