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