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