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