Skip to main content

sui_runtime/
widget.rs

1#![allow(clippy::too_many_arguments, clippy::type_complexity)]
2
3use std::{
4    cell::Cell,
5    collections::{HashMap, HashSet, hash_map::DefaultHasher},
6    hash::{Hash, Hasher},
7    rc::Rc,
8    sync::{
9        Arc, Mutex,
10        atomic::{AtomicU64, Ordering},
11    },
12};
13
14use crate::{
15    Command, CommandDelivery, CommandKey, CommandSender, CommandTarget,
16    command::{QueuedCommand, queued_command},
17    diagnostics::{WidgetTimingPhase, record_widget_timing, start_widget_timing},
18    motion::{FrameClock, Motion},
19    overlay::OverlayOptions,
20    reactive::{ObservationPhase, ObservationScope},
21};
22use sui_animation::{AnimationSpec, Interpolate};
23
24use sui_core::{
25    AsyncWakeToken, Clipboard, Color, CursorGrabMode, DpiInfo, DragPayload, DragScopeId,
26    DragSessionId, DropEffect, DropEffects, Event, ImageHandle, InvalidationKind,
27    InvalidationRequest, InvalidationTarget, MotionPolicy, Path, Point, Rect, SemanticsNode, Size,
28    TimerToken, Transform, Vector, WakeEvent, WidgetId, WindowId,
29};
30use sui_layout::{Axis, Constraints, IntrinsicSize, LayoutContext};
31use sui_reactive::{Observable, Signal};
32use sui_scene::{
33    Border, Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
34    RegisteredExternalImage, RegisteredImage, Scene, SceneCommand, SceneLayer,
35    SceneLayerDescriptor, SceneLayerId, ShadowParams, StrokeStyle, TextRenderPolicy, WidgetShader,
36};
37use sui_text::{
38    FontRegistry, PersistentTextLayout, ShapedText, ShapedTextWindow, TextLayout, TextLayoutHandle,
39    TextLayoutRequest, TextMeasurement, TextRun, TextStyle, TextSystem,
40};
41
42static NEXT_WIDGET_ID: AtomicU64 = AtomicU64::new(1);
43static NEXT_TIMER_TOKEN: AtomicU64 = AtomicU64::new(1);
44static NEXT_ASYNC_WAKE_TOKEN: AtomicU64 = AtomicU64::new(1);
45static NEXT_DRAG_SESSION_ID: AtomicU64 = AtomicU64::new(1);
46const WIDGET_IMAGE_HANDLE_NAMESPACE: u64 = 1 << 63;
47const TRANSFORM_EQ_ULPS: f32 = 16.0;
48
49fn relative_transform(child: Transform, parent: Transform) -> Transform {
50    if transforms_nearly_equal(child, parent) {
51        return Transform::IDENTITY;
52    }
53    parent
54        .inverse()
55        .map(|inverse| child.then(inverse))
56        .unwrap_or(child)
57}
58
59fn transforms_nearly_equal(left: Transform, right: Transform) -> bool {
60    let nearly_equal = |left: f32, right: f32| {
61        let scale = left.abs().max(right.abs()).max(1.0);
62        (left - right).abs() <= f32::EPSILON * TRANSFORM_EQ_ULPS * scale
63    };
64    nearly_equal(left.xx, right.xx)
65        && nearly_equal(left.yx, right.yx)
66        && nearly_equal(left.xy, right.xy)
67        && nearly_equal(left.yy, right.yy)
68        && nearly_equal(left.dx, right.dx)
69        && nearly_equal(left.dy, right.dy)
70}
71
72fn event_for_transform(event: &Event, inverse: Transform) -> Event {
73    if inverse.is_identity() {
74        return event.clone();
75    }
76    match event {
77        Event::Pointer(pointer) => {
78            let mut pointer = pointer.clone();
79            pointer.position = inverse.transform_point(pointer.position);
80            pointer.delta = inverse.transform_vector(pointer.delta);
81            pointer.scroll_delta = pointer.scroll_delta.map(|delta| match delta {
82                sui_core::ScrollDelta::Pixels(delta) => {
83                    sui_core::ScrollDelta::Pixels(inverse.transform_vector(delta))
84                }
85                sui_core::ScrollDelta::Lines(delta) => sui_core::ScrollDelta::Lines(delta),
86            });
87            Event::Pointer(pointer)
88        }
89        Event::Drag(drag) => {
90            let mut drag = drag.clone();
91            drag.position = inverse.transform_point(drag.position);
92            drag.start_position = inverse.transform_point(drag.start_position);
93            Event::Drag(drag)
94        }
95        _ => event.clone(),
96    }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum EventPhase {
101    Capture,
102    Target,
103    Bubble,
104}
105
106pub trait WidgetPodVisitor {
107    fn visit(&mut self, child: &WidgetPod);
108}
109
110pub trait WidgetPodMutVisitor {
111    fn visit(&mut self, child: &mut WidgetPod);
112}
113
114/// One opt-in diagnostic value published by a widget for live inspection.
115///
116/// Values are deliberately presentation-neutral strings. Widgets should expose
117/// compact operational state here (cache sizes, visible ranges, parser
118/// revisions, and similar data), never user content or other sensitive data.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct WidgetDiagnostic {
121    pub name: String,
122    pub value: String,
123}
124
125/// Collector passed to [`Widget::diagnostics`].
126#[derive(Debug, Default)]
127pub struct WidgetDiagnosticsCtx {
128    entries: Vec<WidgetDiagnostic>,
129}
130
131impl WidgetDiagnosticsCtx {
132    pub fn record(&mut self, name: impl Into<String>, value: impl Into<String>) {
133        self.entries.push(WidgetDiagnostic {
134            name: name.into(),
135            value: value.into(),
136        });
137    }
138
139    fn into_entries(self) -> Vec<WidgetDiagnostic> {
140        self.entries
141    }
142}
143
144/// On-demand widget-specific state included in an inspector snapshot.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct WidgetDiagnosticsSnapshot {
147    pub widget_id: WidgetId,
148    pub widget_name: &'static str,
149    pub entries: Vec<WidgetDiagnostic>,
150}
151
152pub trait Widget {
153    fn event(&mut self, _ctx: &mut EventCtx, _event: &Event) {}
154
155    /// Receive a typed command addressed directly to this widget. Commands are
156    /// target-only and do not capture or bubble through the widget tree.
157    fn command(&mut self, _ctx: &mut EventCtx, _command: &Command<'_>) {}
158
159    fn debug_name(&self) -> &'static str {
160        std::any::type_name::<Self>()
161    }
162
163    /// Publish widget-specific state for an inspector snapshot.
164    ///
165    /// The runtime only calls this while explicitly capturing a snapshot, so
166    /// normal event, layout, and paint passes pay no cost for this hook.
167    fn diagnostics(&self, _ctx: &mut WidgetDiagnosticsCtx) {}
168
169    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
170        constraints.max
171    }
172
173    /// Compute a provisional size. Containers can override this to query child
174    /// sizes without committing their final layouts. The default preserves
175    /// existing custom widgets by delegating to `measure`; it may mutate state.
176    /// Child `measure` calls still commit state. Use child size probes explicitly
177    /// when only their scalar results are needed.
178    /// Results must match `measure` for the same content and constraints.
179    /// A final `measure` is still required before arrangement after a probe miss.
180    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
181        self.measure(ctx, constraints)
182    }
183
184    /// Query one component of `measure_size` under exactly the same constraints.
185    /// Overrides may avoid computing the other component, but must return the
186    /// same extent. Like size probes, this does not replace final measurement.
187    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
188        let size = self.measure_size(ctx, constraints);
189        match axis {
190            Axis::Horizontal => size.width,
191            Axis::Vertical => size.height,
192        }
193    }
194
195    /// Report the smallest and preferred extent along one axis.
196    ///
197    /// The conservative default treats the ordinary natural measurement as
198    /// unbreakable. Text and other shrinkable widgets can override this to
199    /// expose a smaller minimum without changing the normal measure contract.
200    fn intrinsic_size(
201        &mut self,
202        ctx: &mut MeasureCtx,
203        axis: Axis,
204        available_cross: f32,
205    ) -> IntrinsicSize {
206        let cross = if available_cross.is_finite() {
207            available_cross.max(0.0)
208        } else {
209            f32::INFINITY
210        };
211        let constraints = match axis {
212            Axis::Horizontal => Constraints::new(Size::ZERO, Size::new(f32::INFINITY, cross)),
213            Axis::Vertical => Constraints::new(Size::ZERO, Size::new(cross, f32::INFINITY)),
214        };
215        let size = self.measure_size(ctx, constraints);
216        IntrinsicSize::fixed(match axis {
217            Axis::Horizontal => size.width,
218            Axis::Vertical => size.height,
219        })
220    }
221
222    fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
223
224    fn paint(&self, _ctx: &mut PaintCtx) {}
225
226    /// Opt into retaining paint and semantics between targeted invalidations.
227    /// Output must depend only on widget state, context, and observed sources;
228    /// changes must invalidate the widget. Untracked readers and callbacks with
229    /// side effects should keep the default. An opaque descendant also prevents
230    /// caching its ancestors. Explicit subtree/window requests always rerun them.
231    /// A source observed only in paint or semantics invalidates that callback,
232    /// not its descendants. Mutating child state requires a child/subtree request.
233    fn supports_output_reuse(&self) -> bool {
234        false
235    }
236
237    fn layer_options(&self) -> LayerOptions {
238        LayerOptions::default()
239    }
240
241    fn layer_properties(&self) -> LayerProperties {
242        LayerProperties::default()
243    }
244
245    /// Layer properties for the frame shown at `frame_time`. Override this
246    /// instead of [`Widget::layer_properties`] when they come from [`Motion`]
247    /// values; the runtime refreshes them without repainting when the motion
248    /// invalidates `Transform` or `Effect`.
249    fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
250        let _ = frame_time;
251        self.layer_properties()
252    }
253
254    fn stack_host_options(&self) -> Option<StackHostOptions> {
255        None
256    }
257
258    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
259        None
260    }
261
262    /// Describe this widget as the logical owner of a presented overlay.
263    ///
264    /// The overlay's rendered surfaces may be retained descendants. Returning
265    /// options here lets the window runtime coordinate nesting, focus,
266    /// dismissal, modality, and diagnostics independently of paint ownership.
267    fn overlay_options(&self) -> Option<OverlayOptions> {
268        None
269    }
270
271    fn semantics(&self, _ctx: &mut SemanticsCtx) {}
272
273    fn accepts_focus(&self) -> bool {
274        false
275    }
276
277    /// Whether points inside this widget that none of its children take hit
278    /// the widget itself. Containers laid over other content, like a layer of
279    /// floating views, return `false` so those points reach what is behind
280    /// them.
281    fn hit_test_self(&self) -> bool {
282        true
283    }
284
285    fn focus_changed(&mut self, _ctx: &mut EventCtx, _focused: bool) {}
286
287    /// Visit this widget's logical children.
288    ///
289    /// The children do not need to correspond to every piece of state or every
290    /// visual element a widget owns internally. A widget may expose retained
291    /// local children, generated/virtual children, remote children represented
292    /// by local pods, or only the subset that should cooperate with the SUI
293    /// runtime for this pass.
294    fn visit_children(&self, _visitor: &mut dyn WidgetPodVisitor) {}
295
296    /// Mutably visit this widget's logical children.
297    ///
298    /// This is the mutable counterpart to [`Widget::visit_children`]; SUI uses
299    /// it as a cooperation point for the retained runtime, not as ownership of
300    /// a widget's complete internal model.
301    fn visit_children_mut(&mut self, _visitor: &mut dyn WidgetPodMutVisitor) {}
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum PaintBoundaryMode {
306    Flat,
307    Explicit,
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub struct LayerOptions {
312    pub paint_boundary: PaintBoundaryMode,
313    pub composition_mode: LayerCompositionMode,
314}
315
316impl LayerOptions {
317    pub const fn emits_layer(self) -> bool {
318        matches!(self.paint_boundary, PaintBoundaryMode::Explicit)
319    }
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum StackOrderPolicy {
324    Stable,
325    FocusFronted,
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub struct StackHostOptions {
330    pub order_policy: StackOrderPolicy,
331}
332
333impl Default for StackHostOptions {
334    fn default() -> Self {
335        Self {
336            order_policy: StackOrderPolicy::Stable,
337        }
338    }
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub struct StackSurfaceOptions {
343    pub dynamic_ordering: bool,
344    pub transient: bool,
345    pub hit_test: bool,
346}
347
348impl Default for StackSurfaceOptions {
349    fn default() -> Self {
350        Self {
351            dynamic_ordering: true,
352            transient: false,
353            hit_test: true,
354        }
355    }
356}
357
358impl Default for LayerOptions {
359    fn default() -> Self {
360        Self {
361            paint_boundary: PaintBoundaryMode::Flat,
362            composition_mode: LayerCompositionMode::Normal,
363        }
364    }
365}
366
367pub struct SingleChild {
368    child: WidgetPod,
369}
370
371impl SingleChild {
372    pub fn new<W>(child: W) -> Self
373    where
374        W: Widget + 'static,
375    {
376        Self::from_pod(WidgetPod::new(child))
377    }
378
379    /// Creates a child whose scene is retained behind an explicit paint boundary.
380    ///
381    /// This is useful for containers that move their complete child subtree as a
382    /// unit. The child's own composition mode and layer properties are preserved;
383    /// only a flat paint boundary is promoted to an explicit one.
384    pub fn new_with_paint_boundary<W>(child: W) -> Self
385    where
386        W: Widget + 'static,
387    {
388        let mut child = WidgetPod::new(child);
389        child.force_paint_boundary = true;
390        Self::from_pod(child)
391    }
392
393    /// Returns this child wrapper with an explicit paint boundary forced on.
394    /// The consuming form keeps layer-topology changes in builder flows.
395    pub fn with_paint_boundary(mut self) -> Self {
396        self.child.force_paint_boundary = true;
397        self
398    }
399
400    pub fn from_pod(child: WidgetPod) -> Self {
401        Self { child }
402    }
403
404    pub fn child(&self) -> &WidgetPod {
405        &self.child
406    }
407
408    pub fn child_mut(&mut self) -> &mut WidgetPod {
409        &mut self.child
410    }
411
412    pub fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
413        self.child.measure(ctx, constraints)
414    }
415
416    pub fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
417        self.child.probe_measure(ctx, constraints)
418    }
419
420    pub fn measure_axis(
421        &mut self,
422        ctx: &mut MeasureCtx,
423        constraints: Constraints,
424        axis: Axis,
425    ) -> f32 {
426        self.child.probe_measure_axis(ctx, constraints, axis)
427    }
428
429    pub fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
430        self.child.arrange(ctx, bounds);
431    }
432
433    pub fn arrange_transformed(
434        &mut self,
435        ctx: &mut ArrangeCtx,
436        bounds: Rect,
437        transform: Transform,
438    ) {
439        self.child.arrange_transformed(ctx, bounds, transform);
440    }
441
442    pub fn set_bounds(&mut self, bounds: Rect) {
443        self.child.set_bounds(bounds);
444    }
445
446    pub fn paint(&self, ctx: &mut PaintCtx) {
447        self.child.paint(ctx);
448    }
449
450    pub fn semantics(&self, ctx: &mut SemanticsCtx) {
451        self.child.semantics(ctx);
452    }
453
454    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
455        visitor.visit(&self.child);
456    }
457
458    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
459        visitor.visit(&mut self.child);
460    }
461}
462
463#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
464pub enum FocusRestorePolicy {
465    /// Restore only a descendant that previously held focus.
466    LastFocused,
467    /// Focus the first currently mounted focusable descendant.
468    FirstFocusable,
469    /// Prefer the last focused descendant, falling back to the first focusable one.
470    #[default]
471    LastFocusedOrFirstFocusable,
472}
473
474#[derive(Debug, Default)]
475struct FocusScopeStateInner {
476    last_focused: Option<WidgetId>,
477    restore_requested: bool,
478    /// The pending restore was asked for by application code and takes
479    /// focus even from outside the scope.
480    restore_forced: bool,
481}
482
483/// Shared retained focus history for a [`FocusScope`].
484///
485/// Presentation policies call [`Self::request_restore`] when a previously
486/// hidden pane or route becomes visible. The associated scope performs the
487/// focus change on its next runtime wake without rebuilding its child subtree,
488/// unless focus is by then on a widget outside the scope.
489#[derive(Clone, Debug)]
490pub struct FocusScopeState {
491    inner: Arc<Mutex<FocusScopeStateInner>>,
492    restore_revision: Signal<u64>,
493    last_focused_signal: Signal<Option<WidgetId>>,
494}
495
496impl FocusScopeState {
497    pub fn new() -> Self {
498        Self {
499            inner: Arc::new(Mutex::new(FocusScopeStateInner::default())),
500            restore_revision: Signal::named("FocusScopeState::restore", 0),
501            last_focused_signal: Signal::named("FocusScopeState::last_focused", None),
502        }
503    }
504
505    /// The widget in the scope that had focus last, which may since have
506    /// moved elsewhere. Commands for "the editor you were using", such as a
507    /// toolbar's, go to it.
508    pub fn last_focused(&self) -> Option<WidgetId> {
509        self.lock_inner().last_focused
510    }
511
512    /// [`Self::last_focused`] as a value to observe, so a widget showing it
513    /// follows focus into the scope.
514    pub fn last_focused_observable(
515        &self,
516    ) -> impl Observable<Option<WidgetId>> + Clone + Send + Sync + 'static {
517        self.last_focused_signal
518            .select_named("FocusScopeState::last_focused", |widget| *widget)
519    }
520
521    pub fn request_restore(&self) -> bool {
522        let changed = {
523            let mut inner = self.lock_inner();
524            if inner.restore_requested {
525                false
526            } else {
527                inner.restore_requested = true;
528                true
529            }
530        };
531        if changed {
532            self.restore_revision
533                .update(|revision| *revision = revision.wrapping_add(1));
534        }
535        changed
536    }
537
538    /// Move focus into the scope at its next frame: to the descendant chosen
539    /// by the scope's restore policy, even when focus is currently outside
540    /// the scope. Use this for application-driven focus, such as focusing a
541    /// search field; [`Self::request_restore`] leaves focus the person moved
542    /// elsewhere alone.
543    pub fn request_focus(&self) -> bool {
544        self.lock_inner().restore_forced = true;
545        self.request_restore()
546    }
547
548    pub fn clear(&self) {
549        let restore_was_requested = {
550            let mut inner = self.lock_inner();
551            let restore_was_requested = inner.restore_requested;
552            inner.last_focused = None;
553            inner.restore_requested = false;
554            inner.restore_forced = false;
555            restore_was_requested
556        };
557        self.last_focused_signal.set(None);
558        if restore_was_requested {
559            self.restore_revision
560                .update(|revision| *revision = revision.wrapping_add(1));
561        }
562    }
563
564    fn remember(&self, widget_id: WidgetId) {
565        let changed = {
566            let mut inner = self.lock_inner();
567            let changed = inner.last_focused != Some(widget_id);
568            inner.last_focused = Some(widget_id);
569            changed
570        };
571        // Set outside the lock, and only on a change: scopes remember focus
572        // on every event and paint.
573        if changed {
574            self.last_focused_signal.set(Some(widget_id));
575        }
576    }
577
578    fn restore_requested(&self) -> bool {
579        self.lock_inner().restore_requested
580    }
581
582    /// Finish the pending restore and report whether it was forced.
583    fn complete_restore(&self) -> bool {
584        let mut inner = self.lock_inner();
585        inner.restore_requested = false;
586        std::mem::take(&mut inner.restore_forced)
587    }
588
589    fn lock_inner(&self) -> std::sync::MutexGuard<'_, FocusScopeStateInner> {
590        self.inner
591            .lock()
592            .unwrap_or_else(std::sync::PoisonError::into_inner)
593    }
594}
595
596impl Default for FocusScopeState {
597    fn default() -> Self {
598        Self::new()
599    }
600}
601
602/// Retains focus history for a stable child subtree.
603///
604/// The scope does not impose visibility or navigation behavior. Adaptive
605/// containers keep the scope and its child mounted, then request restoration
606/// through [`FocusScopeState`] when the subtree is presented again.
607pub struct FocusScope {
608    state: FocusScopeState,
609    restore_policy: FocusRestorePolicy,
610    child: SingleChild,
611}
612
613impl FocusScope {
614    pub fn new<W>(child: W) -> Self
615    where
616        W: Widget + 'static,
617    {
618        Self {
619            state: FocusScopeState::new(),
620            restore_policy: FocusRestorePolicy::default(),
621            child: SingleChild::new(child),
622        }
623    }
624
625    pub fn state(mut self, state: FocusScopeState) -> Self {
626        self.state = state;
627        self
628    }
629
630    pub fn restore_policy(mut self, restore_policy: FocusRestorePolicy) -> Self {
631        self.restore_policy = restore_policy;
632        self
633    }
634
635    pub fn child(&self) -> &WidgetPod {
636        self.child.child()
637    }
638
639    pub fn child_mut(&mut self) -> &mut WidgetPod {
640        self.child.child_mut()
641    }
642
643    fn restore_target(&self) -> Option<WidgetId> {
644        let last_focused = self
645            .state
646            .last_focused()
647            .filter(|target| pod_contains(self.child.child(), *target));
648        match self.restore_policy {
649            FocusRestorePolicy::LastFocused => last_focused,
650            FocusRestorePolicy::FirstFocusable => first_focusable(self.child.child()),
651            FocusRestorePolicy::LastFocusedOrFirstFocusable => {
652                last_focused.or_else(|| first_focusable(self.child.child()))
653            }
654        }
655    }
656
657    fn remember_current_focus(&self, focused_widget_id: Option<WidgetId>) {
658        if let Some(focused) = focused_widget_id
659            && pod_contains(self.child.child(), focused)
660        {
661            self.state.remember(focused);
662        }
663    }
664}
665
666impl Widget for FocusScope {
667    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
668        self.remember_current_focus(ctx.focused_widget_id());
669        if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. }))
670            && self.state.restore_requested()
671        {
672            let target = self.restore_target();
673            let forced = self.state.complete_restore();
674            // Restoring recovers focus that hiding content lost. Focus the
675            // person has since put somewhere else stays there, unless the
676            // application asked for focus explicitly.
677            let focused_elsewhere = !forced
678                && ctx
679                    .focused_widget_id()
680                    .is_some_and(|focused| !pod_contains(self.child.child(), focused));
681            if !focused_elsewhere && let Some(target) = target {
682                ctx.request_focus_for(target);
683                ctx.request_paint();
684                ctx.request_semantics();
685                ctx.set_handled();
686            }
687        }
688    }
689
690    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
691        let _ = ctx.observe(&self.state.restore_revision);
692        if self.state.restore_requested() {
693            ctx.request_animation_frame();
694        }
695        self.child.measure(ctx, constraints)
696    }
697
698    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
699        self.child.arrange(ctx, bounds);
700    }
701
702    fn paint(&self, ctx: &mut PaintCtx) {
703        self.remember_current_focus(ctx.focused_widget_id());
704        self.child.paint(ctx);
705    }
706
707    fn semantics(&self, ctx: &mut SemanticsCtx) {
708        self.remember_current_focus(ctx.focused_widget_id());
709        self.child.semantics(ctx);
710    }
711
712    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
713        self.child.visit_children(visitor);
714    }
715
716    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
717        self.child.visit_children_mut(visitor);
718    }
719}
720
721fn pod_contains(root: &WidgetPod, target: WidgetId) -> bool {
722    if root.id() == target {
723        return true;
724    }
725
726    struct Finder {
727        target: WidgetId,
728        found: bool,
729    }
730
731    impl WidgetPodVisitor for Finder {
732        fn visit(&mut self, child: &WidgetPod) {
733            if self.found {
734                return;
735            }
736            if child.id() == self.target {
737                self.found = true;
738            } else {
739                child.visit_children(self);
740            }
741        }
742    }
743
744    let mut finder = Finder {
745        target,
746        found: false,
747    };
748    root.visit_children(&mut finder);
749    finder.found
750}
751
752fn first_focusable(root: &WidgetPod) -> Option<WidgetId> {
753    if root.accepts_focus() {
754        return Some(root.id());
755    }
756
757    struct Finder {
758        target: Option<WidgetId>,
759    }
760
761    impl WidgetPodVisitor for Finder {
762        fn visit(&mut self, child: &WidgetPod) {
763            if self.target.is_some() {
764                return;
765            }
766            if child.accepts_focus() {
767                self.target = Some(child.id());
768            } else {
769                child.visit_children(self);
770            }
771        }
772    }
773
774    let mut finder = Finder { target: None };
775    root.visit_children(&mut finder);
776    finder.target
777}
778
779#[derive(Default)]
780pub struct WidgetChildren {
781    children: Vec<WidgetPod>,
782}
783
784impl WidgetChildren {
785    pub fn new() -> Self {
786        Self::default()
787    }
788
789    pub fn with_capacity(capacity: usize) -> Self {
790        Self {
791            children: Vec::with_capacity(capacity),
792        }
793    }
794
795    pub fn push<W>(&mut self, child: W)
796    where
797        W: Widget + 'static,
798    {
799        self.push_pod(WidgetPod::new(child));
800    }
801
802    pub fn push_pod(&mut self, child: WidgetPod) {
803        self.children.push(child);
804    }
805
806    pub fn len(&self) -> usize {
807        self.children.len()
808    }
809
810    pub fn is_empty(&self) -> bool {
811        self.children.is_empty()
812    }
813
814    pub fn as_slice(&self) -> &[WidgetPod] {
815        &self.children
816    }
817
818    pub fn as_mut_slice(&mut self) -> &mut [WidgetPod] {
819        &mut self.children
820    }
821
822    pub fn measure_child(
823        &mut self,
824        index: usize,
825        ctx: &mut MeasureCtx,
826        constraints: Constraints,
827    ) -> Size {
828        self.children[index].measure(ctx, constraints)
829    }
830
831    pub fn intrinsic_size_child(
832        &mut self,
833        index: usize,
834        ctx: &mut MeasureCtx,
835        axis: Axis,
836        available_cross: f32,
837    ) -> IntrinsicSize {
838        self.children[index].intrinsic_size(ctx, axis, available_cross)
839    }
840
841    pub fn arrange_child(&mut self, index: usize, ctx: &mut ArrangeCtx, bounds: Rect) {
842        self.children[index].arrange(ctx, bounds);
843    }
844
845    pub fn paint(&self, ctx: &mut PaintCtx) {
846        for child in &self.children {
847            child.paint(ctx);
848        }
849    }
850
851    pub fn semantics(&self, ctx: &mut SemanticsCtx) {
852        for child in &self.children {
853            child.semantics(ctx);
854        }
855    }
856
857    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
858        for child in &self.children {
859            visitor.visit(child);
860        }
861    }
862
863    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
864        for child in &mut self.children {
865            visitor.visit(child);
866        }
867    }
868}
869
870#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
871pub struct KeyedReconcile {
872    pub inserted: usize,
873    pub removed: usize,
874    pub moved: usize,
875    pub updated: usize,
876    pub unchanged: usize,
877    pub duplicate_keys: usize,
878}
879
880struct KeyedChild<K, T> {
881    key: K,
882    value: Signal<T>,
883    child: WidgetPod,
884}
885
886/// Layout-neutral retained child collection reconciled by stable application
887/// keys.
888///
889/// Existing [`WidgetPod`] instances are moved rather than recreated. Each
890/// child also receives a per-item [`Signal`] so changing item data can update
891/// the retained widget without replacing it.
892pub struct KeyedChildren<K, T> {
893    entries: Vec<KeyedChild<K, T>>,
894}
895
896impl<K, T> KeyedChildren<K, T> {
897    pub const fn new() -> Self {
898        Self {
899            entries: Vec::new(),
900        }
901    }
902
903    pub fn len(&self) -> usize {
904        self.entries.len()
905    }
906
907    pub fn is_empty(&self) -> bool {
908        self.entries.is_empty()
909    }
910
911    pub fn iter(&self) -> impl Iterator<Item = (&K, &Signal<T>, &WidgetPod)> {
912        self.entries
913            .iter()
914            .map(|entry| (&entry.key, &entry.value, &entry.child))
915    }
916
917    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &Signal<T>, &mut WidgetPod)> {
918        self.entries
919            .iter_mut()
920            .map(|entry| (&entry.key, &entry.value, &mut entry.child))
921    }
922
923    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
924        for entry in &self.entries {
925            visitor.visit(&entry.child);
926        }
927    }
928
929    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
930        for entry in &mut self.entries {
931            visitor.visit(&mut entry.child);
932        }
933    }
934}
935
936impl<K, T> KeyedChildren<K, T>
937where
938    K: Clone + Eq + Hash,
939    T: Clone + PartialEq + 'static,
940{
941    pub fn reconcile<I, KF, B, W>(
942        &mut self,
943        items: I,
944        mut key_for: KF,
945        mut build: B,
946    ) -> KeyedReconcile
947    where
948        I: IntoIterator<Item = T>,
949        KF: FnMut(&T) -> K,
950        B: FnMut(&K, Signal<T>) -> W,
951        W: Widget + 'static,
952    {
953        let previous_len = self.entries.len();
954        let mut previous = std::mem::take(&mut self.entries)
955            .into_iter()
956            .enumerate()
957            .map(|(index, entry)| (entry.key.clone(), (index, entry)))
958            .collect::<HashMap<_, _>>();
959        let mut seen = HashSet::new();
960        let mut next = Vec::new();
961        let mut report = KeyedReconcile::default();
962
963        for item in items {
964            let key = key_for(&item);
965            if !seen.insert(key.clone()) {
966                report.duplicate_keys += 1;
967                continue;
968            }
969
970            let next_index = next.len();
971            if let Some((previous_index, entry)) = previous.remove(&key) {
972                if previous_index != next_index {
973                    report.moved += 1;
974                }
975                if entry.value.set(item) {
976                    report.updated += 1;
977                } else {
978                    report.unchanged += 1;
979                }
980                next.push(entry);
981            } else {
982                let value = Signal::named("Keyed item", item);
983                let child = WidgetPod::new(build(&key, value.clone()));
984                next.push(KeyedChild { key, value, child });
985                report.inserted += 1;
986            }
987        }
988
989        report.removed = previous.len();
990        debug_assert_eq!(previous_len + report.inserted, next.len() + report.removed);
991        self.entries = next;
992        report
993    }
994}
995
996impl<K, T> Default for KeyedChildren<K, T> {
997    fn default() -> Self {
998        Self::new()
999    }
1000}
1001
1002/// Standard retained-widget adapter used by the SUI runtime.
1003///
1004/// `WidgetPod` gives a `Widget` stable identity, cached layout state, event
1005/// routing participation, and scene/semantics cooperation. It is the default
1006/// local retained model, but a widget's own internals may still use custom
1007/// state, virtualization, worker threads, or remote systems before rejoining
1008/// SUI through widget contexts and scene output.
1009pub struct WidgetPod {
1010    id: WidgetId,
1011    layout_state: LayoutState,
1012    probe_cache: Option<Box<ProbeCache>>,
1013    query_context: Option<crate::measure_cache::QueryContext>,
1014    last_probe_invalidation: u64,
1015    force_paint_boundary: bool,
1016    inert: bool,
1017    observed_phases: Cell<u8>,
1018    widget: Box<dyn Widget>,
1019}
1020
1021impl Drop for WidgetPod {
1022    fn drop(&mut self) {
1023        crate::layout_work::record(|work| work.dropped += 1);
1024        crate::reactive::clear_widget(self.id);
1025    }
1026}
1027
1028// Four recent natural constraints plus one cross extent per intrinsic axis.
1029// Allocate only for widgets actually queried by a multi-pass layout.
1030#[derive(Default)]
1031struct ProbeCache {
1032    revision: u64,
1033    promoted: bool,
1034    measurements: [Option<(Constraints, Option<Axis>, Size)>; 4],
1035    intrinsics: [Option<(f32, IntrinsicSize)>; 2],
1036}
1037
1038#[derive(Debug, Clone, Copy, PartialEq)]
1039struct LayoutState {
1040    measured_size: Size,
1041    arranged_bounds: Rect,
1042    relative_presentation_transform: Transform,
1043    presentation_transform: Transform,
1044    last_constraints: Constraints,
1045    measure_valid: bool,
1046    arrange_valid: bool,
1047}
1048
1049impl Default for LayoutState {
1050    fn default() -> Self {
1051        Self {
1052            measured_size: Size::ZERO,
1053            arranged_bounds: Rect::ZERO,
1054            relative_presentation_transform: Transform::IDENTITY,
1055            presentation_transform: Transform::IDENTITY,
1056            last_constraints: Constraints::default(),
1057            measure_valid: false,
1058            arrange_valid: false,
1059        }
1060    }
1061}
1062
1063impl WidgetPod {
1064    pub fn new<W>(widget: W) -> Self
1065    where
1066        W: Widget + 'static,
1067    {
1068        Self::new_boxed(Box::new(widget))
1069    }
1070
1071    /// Retain a type-erased widget without inserting an additional adapter
1072    /// into the logical widget tree.
1073    ///
1074    /// Dynamic widget registries use this when the concrete widget type is
1075    /// selected from application data at runtime.
1076    pub fn new_boxed(widget: Box<dyn Widget>) -> Self {
1077        crate::layout_work::record(|work| work.constructed += 1);
1078        Self {
1079            id: WidgetId::new(NEXT_WIDGET_ID.fetch_add(1, Ordering::Relaxed)),
1080            layout_state: LayoutState::default(),
1081            probe_cache: None,
1082            query_context: None,
1083            last_probe_invalidation: 0,
1084            force_paint_boundary: false,
1085            inert: false,
1086            observed_phases: Cell::new(0),
1087            widget,
1088        }
1089    }
1090
1091    pub const fn id(&self) -> WidgetId {
1092        self.id
1093    }
1094
1095    /// Whether this subtree is inert: still painted, but out of hit testing,
1096    /// focus, and semantics. Containers make content inert while it animates
1097    /// out, so it looks gone to everything but the eye.
1098    pub const fn is_inert(&self) -> bool {
1099        self.inert
1100    }
1101
1102    /// Make this subtree inert or live again (see [`WidgetPod::is_inert`]).
1103    /// Focus and pointer capture inside an inert subtree are released when
1104    /// the runtime next refreshes its widget graph, after the current layout
1105    /// pass.
1106    pub fn set_inert(&mut self, inert: bool) {
1107        self.inert = inert;
1108    }
1109
1110    pub fn debug_name(&self) -> &'static str {
1111        self.widget.debug_name()
1112    }
1113
1114    pub fn diagnostics_snapshot(&self) -> WidgetDiagnosticsSnapshot {
1115        let mut ctx = WidgetDiagnosticsCtx::default();
1116        self.widget.diagnostics(&mut ctx);
1117        WidgetDiagnosticsSnapshot {
1118            widget_id: self.id,
1119            widget_name: self.widget.debug_name(),
1120            entries: ctx.into_entries(),
1121        }
1122    }
1123
1124    pub fn collect_diagnostics(&self, output: &mut Vec<WidgetDiagnosticsSnapshot>) {
1125        let snapshot = self.diagnostics_snapshot();
1126        if !snapshot.entries.is_empty() {
1127            output.push(snapshot);
1128        }
1129        let mut visitor = CollectDiagnosticsVisitor { output };
1130        self.visit_children(&mut visitor);
1131    }
1132
1133    pub const fn bounds(&self) -> Rect {
1134        self.layout_state.arranged_bounds
1135    }
1136
1137    pub const fn measured_size(&self) -> Size {
1138        self.layout_state.measured_size
1139    }
1140
1141    pub const fn presentation_transform(&self) -> Transform {
1142        self.layout_state.presentation_transform
1143    }
1144
1145    pub fn set_bounds(&mut self, bounds: Rect) {
1146        let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
1147        crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
1148        self.layout_state.arranged_bounds = bounds;
1149        self.layout_state.measured_size = bounds.size;
1150        self.layout_state.arrange_valid = true;
1151        self.translate_descendants(delta);
1152    }
1153
1154    /// Query a size without requiring the widget's retained layout to match it.
1155    ///
1156    /// Keep four recent results locally, backed by the window's bounded query
1157    /// cache. Widget revisions and layout contexts invalidate both tiers.
1158    /// Call `measure` with the final constraints before arrangement: a probe hit
1159    /// does not restore child layouts, text handles, or other committed state.
1160    /// Final `measure` calls in dirty/forced subtrees still always execute.
1161    pub fn probe_measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1162        self.probe_measure_query(parent_ctx, constraints, None)
1163    }
1164
1165    /// Size-only query for one axis; shares the exact-key, invalidation and
1166    /// bounded eviction rules of `probe_measure`, with a distinct query kind.
1167    pub fn probe_measure_axis(
1168        &mut self,
1169        parent_ctx: &mut MeasureCtx,
1170        constraints: Constraints,
1171        axis: Axis,
1172    ) -> f32 {
1173        let size = self.probe_measure_query(parent_ctx, constraints, Some(axis));
1174        match axis {
1175            Axis::Horizontal => size.width,
1176            Axis::Vertical => size.height,
1177        }
1178    }
1179
1180    fn probe_measure_query(
1181        &mut self,
1182        parent_ctx: &mut MeasureCtx,
1183        constraints: Constraints,
1184        axis: Option<Axis>,
1185    ) -> Size {
1186        crate::layout_work::record(|work| work.probe_requests += 1);
1187        self.invalidate_probes(parent_ctx);
1188        if let Some(size) = self.probe_cache.as_ref().and_then(|cache| {
1189            cache
1190                .measurements
1191                .iter()
1192                .flatten()
1193                .find(|(key, kind, _)| *key == constraints && *kind == axis)
1194                .map(|(_, _, size)| *size)
1195        }) {
1196            crate::layout_work::record(|work| work.probe_cache_hits += 1);
1197            return size;
1198        }
1199        let cache = self.probe_cache.get_or_insert_with(Default::default);
1200        let revision = cache.revision;
1201        let shared = parent_ctx
1202            .query_cache
1203            .as_ref()
1204            .filter(|_| parent_ctx.scope.reusable_queries && cache.measurements[3].is_some());
1205        let key = shared
1206            .and_then(|_| crate::measure_cache::QueryKey::new(self.id, revision, constraints))
1207            .map(|key| key.with_axis(axis));
1208        let cached = shared
1209            .zip(parent_ctx.query_context)
1210            .zip(key.as_ref())
1211            .and_then(|((shared, context), key)| {
1212                let mut window = shared.borrow_mut();
1213                if !cache.promoted {
1214                    for (constraints, axis, size) in cache.measurements.iter().flatten() {
1215                        if let Some(key) =
1216                            crate::measure_cache::QueryKey::new(self.id, revision, *constraints)
1217                        {
1218                            window.put(context, key.with_axis(*axis), *size);
1219                        }
1220                    }
1221                    cache.promoted = true;
1222                }
1223                window.get(context, key)
1224            });
1225        let size = if let Some(size) = cached {
1226            crate::layout_work::record(|work| {
1227                work.probe_cache_hits += 1;
1228                work.shared_probe_cache_hits += 1;
1229            });
1230            size
1231        } else {
1232            let size = self.measure_impl(parent_ctx, constraints, true, axis);
1233            if let Some(cache) = parent_ctx
1234                .query_cache
1235                .as_ref()
1236                .filter(|_| parent_ctx.scope.reusable_queries)
1237                && let Some(context) = parent_ctx.query_context
1238                && let Some(key) = key
1239            {
1240                cache.borrow_mut().put(context, key, size);
1241            }
1242            size
1243        };
1244        let cache = self.probe_cache.get_or_insert_with(Default::default);
1245        if cache.measurements[0].is_none_or(|(key, kind, _)| key != constraints || kind != axis) {
1246            cache.measurements.rotate_right(1);
1247        }
1248        cache.measurements[0] = Some((constraints, axis, size));
1249        size
1250    }
1251
1252    fn invalidate_probes(&mut self, ctx: &MeasureCtx) -> bool {
1253        let context = ctx.query_context;
1254        let context_changed = self.query_context != context;
1255        self.query_context = context;
1256        let dirty = context_changed || ctx.child_force() || ctx.scope().must_remeasure(self.id);
1257        if context_changed {
1258            self.layout_state.measure_valid = false;
1259            self.layout_state.arrange_valid = false;
1260        }
1261        if dirty
1262            && (context_changed
1263                || !ctx.scope().reusable_queries
1264                || self.last_probe_invalidation != ctx.scope().generation)
1265        {
1266            if let Some(cache) = &mut self.probe_cache {
1267                let revision = cache.revision.wrapping_add(1);
1268                **cache = ProbeCache {
1269                    revision,
1270                    ..Default::default()
1271                };
1272            }
1273            // A reused external context disables scalar caching, but its final
1274            // measure must not erase dependencies read by earlier probes.
1275            if context_changed || self.last_probe_invalidation != ctx.scope().generation {
1276                crate::reactive::clear_probe_observations(self.id, &self.observed_phases);
1277            }
1278            self.last_probe_invalidation = ctx.scope().generation;
1279        }
1280        dirty
1281    }
1282
1283    pub fn measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1284        self.measure_impl(parent_ctx, constraints, false, None)
1285    }
1286
1287    fn measure_impl(
1288        &mut self,
1289        parent_ctx: &mut MeasureCtx,
1290        constraints: Constraints,
1291        size_only: bool,
1292        axis: Option<Axis>,
1293    ) -> Size {
1294        let probing = size_only || parent_ctx.probing;
1295        crate::layout_work::record(|work| work.measure_requests += 1);
1296        // Incremental-layout fast path. Cache invalidation is driven entirely by
1297        // the measure recursion (never a separate tree walk), so it cannot diverge
1298        // from how parents actually reach their children:
1299        //
1300        // - `force` is true when this pod sits inside a subtree rooted at a widget
1301        //   that changed this frame; such a pod always re-measures (which also
1302        //   preserves any side effects of measuring more than once per pass).
1303        // - otherwise a pod whose own id is listed dirty re-measures, while a clean
1304        //   pod measured before under identical constraints returns its cached size
1305        //   without recursing.
1306        let force = parent_ctx.child_force();
1307        let must_remeasure = self.invalidate_probes(parent_ctx);
1308        if !probing
1309            && !must_remeasure
1310            && self.layout_state.measure_valid
1311            && self.layout_state.last_constraints == constraints
1312        {
1313            crate::layout_work::record(|work| work.measure_cache_hits += 1);
1314            return self.layout_state.measured_size;
1315        }
1316        crate::layout_work::record(|work| {
1317            work.measure_executions += 1;
1318            work.size_measure_executions += u64::from(size_only);
1319            work.forced_measures += u64::from(must_remeasure);
1320            work.constraint_changes += u64::from(
1321                self.layout_state.measure_valid
1322                    && self.layout_state.last_constraints != constraints,
1323            );
1324            work.first_measures += u64::from(!self.layout_state.measure_valid);
1325        });
1326
1327        let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
1328        child_ctx.probing = probing;
1329        let started = start_widget_timing();
1330        let observations = ObservationScope::new(
1331            parent_ctx.window_id(),
1332            self.id,
1333            if probing {
1334                ObservationPhase::MeasureProbe
1335            } else {
1336                ObservationPhase::Measure
1337            },
1338            &self.observed_phases,
1339        );
1340        let size = if let Some(axis) = axis {
1341            let extent = self.widget.measure_axis(&mut child_ctx, constraints, axis);
1342            match axis {
1343                Axis::Horizontal => Size::new(extent, 0.0),
1344                Axis::Vertical => Size::new(0.0, extent),
1345            }
1346        } else if size_only {
1347            self.widget.measure_size(&mut child_ctx, constraints)
1348        } else {
1349            self.widget.measure(&mut child_ctx, constraints)
1350        };
1351        drop(observations);
1352        record_widget_timing(
1353            self.id,
1354            self.widget.debug_name(),
1355            WidgetTimingPhase::Measure,
1356            started,
1357        );
1358        // An axis query has no complete size to publish as committed geometry.
1359        if axis.is_none() {
1360            self.layout_state.measured_size = size;
1361            self.layout_state.last_constraints = constraints;
1362        }
1363        self.layout_state.measure_valid = !size_only;
1364        // Keep measurement probes separate from the last arranged geometry.
1365        // Parents can measure a clean sibling more than once before giving it
1366        // the same final bounds; those probes must not invalidate its paint or
1367        // arrangement cache. Explicitly invalidated subtrees still arrange even
1368        // if their outer bounds are unchanged (their internal layout may differ).
1369        if must_remeasure {
1370            self.layout_state.arrange_valid = false;
1371        }
1372        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1373        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1374        size
1375    }
1376
1377    pub fn intrinsic_size(
1378        &mut self,
1379        parent_ctx: &mut MeasureCtx,
1380        axis: Axis,
1381        available_cross: f32,
1382    ) -> IntrinsicSize {
1383        crate::layout_work::record(|work| match axis {
1384            Axis::Horizontal => work.intrinsic_horizontal += 1,
1385            Axis::Vertical => work.intrinsic_vertical += 1,
1386        });
1387        self.invalidate_probes(parent_ctx);
1388        let axis_index = match axis {
1389            Axis::Horizontal => 0,
1390            Axis::Vertical => 1,
1391        };
1392        let cross = available_cross;
1393        if let Some((key, size)) = self
1394            .probe_cache
1395            .as_ref()
1396            .and_then(|cache| cache.intrinsics[axis_index])
1397            && key == cross
1398        {
1399            crate::layout_work::record(|work| work.intrinsic_cache_hits += 1);
1400            return size;
1401        }
1402        crate::layout_work::record(|work| work.intrinsic_executions += 1);
1403        let force = parent_ctx.child_force();
1404        let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
1405        child_ctx.probing = true;
1406        // The default intrinsic implementation invokes Widget::measure directly.
1407        // Its scalar result does not describe the retained final measurement.
1408        self.layout_state.measure_valid = false;
1409        let started = start_widget_timing();
1410        let phase = match axis {
1411            Axis::Horizontal => ObservationPhase::IntrinsicHorizontal,
1412            Axis::Vertical => ObservationPhase::IntrinsicVertical,
1413        };
1414        let observations = ObservationScope::new(
1415            parent_ctx.window_id(),
1416            self.id,
1417            phase,
1418            &self.observed_phases,
1419        );
1420        let intrinsic = self.widget.intrinsic_size(&mut child_ctx, axis, cross);
1421        drop(observations);
1422        record_widget_timing(
1423            self.id,
1424            self.widget.debug_name(),
1425            WidgetTimingPhase::Measure,
1426            started,
1427        );
1428        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1429        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1430        let intrinsic = IntrinsicSize::new(intrinsic.minimum, intrinsic.natural);
1431        self.probe_cache
1432            .get_or_insert_with(Default::default)
1433            .intrinsics[axis_index] = Some((cross, intrinsic));
1434        intrinsic
1435    }
1436
1437    pub fn arrange(&mut self, parent_ctx: &mut ArrangeCtx, bounds: Rect) {
1438        self.arrange_with_transform(parent_ctx, bounds, Transform::IDENTITY);
1439    }
1440
1441    /// Arrange this widget in parent coordinates and apply an affine transform
1442    /// to its complete retained subtree for paint, input, and semantics.
1443    pub fn arrange_transformed(
1444        &mut self,
1445        parent_ctx: &mut ArrangeCtx,
1446        bounds: Rect,
1447        transform: Transform,
1448    ) {
1449        self.arrange_with_transform(parent_ctx, bounds, transform);
1450    }
1451
1452    fn arrange_with_transform(
1453        &mut self,
1454        parent_ctx: &mut ArrangeCtx,
1455        bounds: Rect,
1456        transform: Transform,
1457    ) {
1458        crate::layout_work::record(|work| work.arrange_requests += 1);
1459        let presentation_transform = transform.then(parent_ctx.presentation_transform());
1460        if self.layout_state.arrange_valid
1461            && !parent_ctx.scope().must_rearrange(self.id)
1462            && self.layout_state.arranged_bounds == bounds
1463        {
1464            self.layout_state.relative_presentation_transform = transform;
1465            if self.layout_state.presentation_transform != presentation_transform {
1466                self.layout_state.presentation_transform = presentation_transform;
1467                let mut visitor = ReprojectPresentationVisitor {
1468                    parent_transform: presentation_transform,
1469                };
1470                self.visit_children_mut(&mut visitor);
1471            }
1472            crate::layout_work::record(|work| work.arrange_cache_hits += 1);
1473            return;
1474        }
1475        crate::layout_work::record(|work| work.arrange_executions += 1);
1476        let size_changed = self.layout_state.arranged_bounds.size != bounds.size;
1477        let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
1478        crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
1479        self.layout_state.arranged_bounds = bounds;
1480        self.layout_state.relative_presentation_transform = transform;
1481        self.layout_state.presentation_transform = presentation_transform;
1482        self.layout_state.arrange_valid = true;
1483        self.translate_descendants(delta);
1484
1485        let mut child_ctx = ArrangeCtx::new_at_with_transform(
1486            parent_ctx.window_id(),
1487            self.id,
1488            parent_ctx.dpi(),
1489            parent_ctx.current_time(),
1490            self.layout_state.presentation_transform,
1491            Rc::clone(parent_ctx.scope_rc()),
1492        );
1493        // Event dispatch may eagerly arrange before render compares the graph.
1494        // Record damage only for a committed size change, never a measure probe.
1495        if size_changed {
1496            child_ctx.request_paint();
1497        }
1498        let started = start_widget_timing();
1499        let observations = ObservationScope::new(
1500            parent_ctx.window_id(),
1501            self.id,
1502            ObservationPhase::Arrange,
1503            &self.observed_phases,
1504        );
1505        self.widget.arrange(&mut child_ctx, bounds);
1506        drop(observations);
1507        record_widget_timing(
1508            self.id,
1509            self.widget.debug_name(),
1510            WidgetTimingPhase::Arrange,
1511            started,
1512        );
1513        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1514        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1515    }
1516
1517    pub fn paint(&self, parent_ctx: &mut PaintCtx) {
1518        self.paint_into(parent_ctx, true);
1519    }
1520
1521    fn paint_into(&self, parent_ctx: &mut PaintCtx, emit_layer: bool) {
1522        let presentation_transform = self.layout_state.presentation_transform;
1523        let relative_transform =
1524            relative_transform(presentation_transform, parent_ctx.presentation_transform());
1525        let reusable = self.widget.supports_output_reuse();
1526        parent_ctx.output_reusable &= reusable;
1527        let output_cache = parent_ctx
1528            .output_cache
1529            .as_ref()
1530            .filter(|_| reusable)
1531            .cloned();
1532        let key = crate::output_cache::GeometryKey {
1533            bounds: self.bounds(),
1534            transform: presentation_transform,
1535        };
1536        let cached = output_cache.as_ref().and_then(|cache| {
1537            cache.paint(self.id, key, &parent_ctx.text_system.text_layout_registry())
1538        });
1539        if let Some(fragment) = &cached
1540            && relative_transform.is_identity()
1541            && !(emit_layer
1542                && presentation_transform.is_identity()
1543                && self.current_layer_options().emits_layer())
1544        {
1545            crate::layout_work::record(|work| work.paint_cache_hits += 1);
1546            parent_ctx.record_widget_paint_bounds(
1547                self.id,
1548                fragment
1549                    .scene
1550                    .paint_bounds()
1551                    .unwrap_or(self.layout_state.arranged_bounds),
1552            );
1553            parent_ctx.scene.append_ref(&fragment.scene);
1554            parent_ctx
1555                .widget_paint_bounds
1556                .extend(fragment.bounds.iter().map(|(&id, &rect)| (id, rect)));
1557            parent_ctx.extend_ime_composition_rect(fragment.ime);
1558            return;
1559        }
1560        let mut child_ctx = PaintCtx::new_with_transform(
1561            parent_ctx.window_id(),
1562            self.id,
1563            self.layout_state.arranged_bounds,
1564            parent_ctx.focused_widget_id(),
1565            parent_ctx.dpi(),
1566            Arc::clone(&parent_ctx.text_system),
1567            Arc::clone(&parent_ctx.font_registry),
1568            Arc::clone(&parent_ctx.image_registry),
1569            presentation_transform,
1570        )
1571        .with_frame_time(parent_ctx.frame_time);
1572        child_ctx.output_cache = output_cache.clone();
1573        let (mut scene, images, mut widget_paint_bounds, mut ime_composition_rect) =
1574            if let Some(fragment) = cached {
1575                crate::layout_work::record(|work| work.paint_cache_hits += 1);
1576                (
1577                    fragment.scene.clone(),
1578                    Vec::new(),
1579                    fragment.bounds.clone(),
1580                    fragment.ime,
1581                )
1582            } else {
1583                crate::layout_work::record(|work| work.paint_executions += 1);
1584                let started = start_widget_timing();
1585                let observations = ObservationScope::new(
1586                    parent_ctx.window_id(),
1587                    self.id,
1588                    ObservationPhase::Paint,
1589                    &self.observed_phases,
1590                );
1591                self.widget.paint(&mut child_ctx);
1592                drop(observations);
1593                record_widget_timing(
1594                    self.id,
1595                    self.widget.debug_name(),
1596                    WidgetTimingPhase::Paint,
1597                    started,
1598                );
1599
1600                parent_ctx.output_reusable &= child_ctx.output_reusable;
1601                let can_reuse = child_ctx.output_reusable;
1602                let parts = child_ctx.into_parts();
1603                if can_reuse
1604                    && parts.1.is_empty()
1605                    && let Some(cache) = &output_cache
1606                {
1607                    cache.put_paint(self.id, key, &parts.0, &parts.2, parts.3);
1608                }
1609                parts
1610            };
1611        if !relative_transform.is_identity() {
1612            let mut transformed = Scene::new();
1613            transformed.push(SceneCommand::PushTransform {
1614                transform: relative_transform,
1615            });
1616            transformed.append(scene);
1617            transformed.push(SceneCommand::PopTransform);
1618            scene = transformed;
1619            for bounds in widget_paint_bounds.values_mut() {
1620                *bounds = relative_transform.transform_rect_bbox(*bounds);
1621            }
1622            ime_composition_rect =
1623                ime_composition_rect.map(|bounds| relative_transform.transform_rect_bbox(bounds));
1624        }
1625        let paint_bounds = scene.paint_bounds().unwrap_or_else(|| {
1626            relative_transform.transform_rect_bbox(self.layout_state.arranged_bounds)
1627        });
1628        parent_ctx.record_widget_paint_bounds(self.id, paint_bounds);
1629        if emit_layer
1630            && presentation_transform.is_identity()
1631            && self.current_layer_options().emits_layer()
1632        {
1633            parent_ctx.push_layer(
1634                self.build_layer_descriptor(&scene, parent_ctx.frame_time),
1635                scene,
1636            );
1637        } else {
1638            parent_ctx.append_scene(scene);
1639        }
1640        parent_ctx.extend_widget_paint_bounds(widget_paint_bounds);
1641        parent_ctx.extend_images(images);
1642        parent_ctx.extend_ime_composition_rect(ime_composition_rect);
1643    }
1644
1645    pub(crate) fn paint_layer_contents_for(
1646        &mut self,
1647        target: WidgetId,
1648        parent_ctx: &mut PaintCtx,
1649    ) -> bool {
1650        self.find_mut(target, &mut |pod| {
1651            pod.paint_into(parent_ctx, false);
1652        })
1653        .is_some()
1654    }
1655
1656    pub(crate) fn layer_descriptor_for(
1657        &mut self,
1658        target: WidgetId,
1659        scene: &Scene,
1660        frame_time: f64,
1661    ) -> Option<SceneLayerDescriptor> {
1662        self.find_mut(target, &mut |pod| {
1663            pod.build_layer_descriptor(scene, frame_time)
1664        })
1665    }
1666
1667    pub fn semantics(&self, parent_ctx: &mut SemanticsCtx) {
1668        if self.inert {
1669            return;
1670        }
1671        let presentation_transform = self.layout_state.presentation_transform;
1672        let relative_transform =
1673            relative_transform(presentation_transform, parent_ctx.presentation_transform());
1674        let reusable = self.widget.supports_output_reuse();
1675        parent_ctx.output_reusable &= reusable;
1676        let output_cache = parent_ctx
1677            .output_cache
1678            .as_ref()
1679            .filter(|_| reusable)
1680            .cloned();
1681        let key = crate::output_cache::GeometryKey {
1682            bounds: self.bounds(),
1683            transform: presentation_transform,
1684        };
1685        if let Some(nodes) = output_cache
1686            .as_ref()
1687            .and_then(|cache| cache.semantics(self.id, key))
1688        {
1689            crate::layout_work::record(|work| work.semantics_cache_hits += 1);
1690            parent_ctx.extend_nodes(nodes.iter().cloned().map(|mut node| {
1691                if !relative_transform.is_identity() {
1692                    node.bounds = relative_transform.transform_rect_bbox(node.bounds);
1693                }
1694                node
1695            }));
1696            return;
1697        }
1698        let mut child_ctx = SemanticsCtx::new_with_transform(
1699            parent_ctx.window_id(),
1700            self.id,
1701            parent_ctx.root_widget_id(),
1702            self.layout_state.arranged_bounds,
1703            parent_ctx.focused_widget_id(),
1704            presentation_transform,
1705        );
1706        child_ctx.output_cache = output_cache.clone();
1707        let mut nodes = {
1708            crate::layout_work::record(|work| work.semantics_executions += 1);
1709            let started = start_widget_timing();
1710            let observations = ObservationScope::new(
1711                parent_ctx.window_id(),
1712                self.id,
1713                ObservationPhase::Semantics,
1714                &self.observed_phases,
1715            );
1716            self.widget.semantics(&mut child_ctx);
1717            drop(observations);
1718            record_widget_timing(
1719                self.id,
1720                self.widget.debug_name(),
1721                WidgetTimingPhase::Semantics,
1722                started,
1723            );
1724            parent_ctx.output_reusable &= child_ctx.output_reusable;
1725            let can_reuse = child_ctx.output_reusable;
1726            let nodes = child_ctx.into_nodes();
1727            if can_reuse && let Some(cache) = &output_cache {
1728                cache.put_semantics(self.id, key, &nodes);
1729            }
1730            nodes
1731        };
1732        if !relative_transform.is_identity() {
1733            for node in &mut nodes {
1734                node.bounds = relative_transform.transform_rect_bbox(node.bounds);
1735            }
1736        }
1737        parent_ctx.extend_nodes(nodes);
1738    }
1739
1740    /// Return whether this retained widget is a focus target.
1741    ///
1742    /// Adaptive containers use this while selecting a restoration fallback for
1743    /// a subtree that has just become visible again.
1744    pub fn accepts_focus(&self) -> bool {
1745        self.widget.accepts_focus()
1746    }
1747
1748    /// Visit this pod's direct children. Public so container widgets can walk
1749    /// their own subtree (e.g. to derive a focus-within visual by comparing
1750    /// descendant ids against the focused widget id — sui has no focus-within
1751    /// event, and any focus change repaints every window, so polling at paint
1752    /// time stays correct).
1753    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1754        self.widget.visit_children(visitor);
1755    }
1756
1757    pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1758        self.widget.visit_children_mut(visitor);
1759    }
1760
1761    #[allow(clippy::too_many_arguments)]
1762    pub(crate) fn dispatch_event_for_path(
1763        &mut self,
1764        path: &[WidgetId],
1765        window_id: WindowId,
1766        dpi_info: DpiInfo,
1767        current_time: f64,
1768        phase: EventPhase,
1769        focused_widget: Option<WidgetId>,
1770        clipboard: &Clipboard,
1771        command_sender: &CommandSender,
1772        event: &Event,
1773    ) -> Option<EventDispatch> {
1774        self.find_mut_path(path, &mut |pod| {
1775            pod.dispatch_event(
1776                window_id,
1777                dpi_info,
1778                current_time,
1779                phase,
1780                focused_widget,
1781                clipboard,
1782                command_sender,
1783                event,
1784            )
1785        })
1786    }
1787
1788    #[allow(clippy::too_many_arguments)]
1789    pub(crate) fn dispatch_event_for(
1790        &mut self,
1791        target: WidgetId,
1792        window_id: WindowId,
1793        dpi_info: DpiInfo,
1794        current_time: f64,
1795        phase: EventPhase,
1796        focused_widget: Option<WidgetId>,
1797        clipboard: &Clipboard,
1798        command_sender: &CommandSender,
1799        event: &Event,
1800    ) -> Option<EventDispatch> {
1801        self.find_mut(target, &mut |pod| {
1802            pod.dispatch_event(
1803                window_id,
1804                dpi_info,
1805                current_time,
1806                phase,
1807                focused_widget,
1808                clipboard,
1809                command_sender,
1810                event,
1811            )
1812        })
1813    }
1814
1815    #[allow(clippy::too_many_arguments)]
1816    pub(crate) fn dispatch_command_for_path(
1817        &mut self,
1818        path: &[WidgetId],
1819        window_id: WindowId,
1820        dpi_info: DpiInfo,
1821        current_time: f64,
1822        focused_widget: Option<WidgetId>,
1823        clipboard: &Clipboard,
1824        command_sender: &CommandSender,
1825        command: &Command<'_>,
1826    ) -> Option<EventDispatch> {
1827        self.find_mut_path(path, &mut |pod| {
1828            pod.dispatch_command(
1829                window_id,
1830                dpi_info,
1831                current_time,
1832                focused_widget,
1833                clipboard,
1834                command_sender,
1835                command,
1836            )
1837        })
1838    }
1839
1840    #[allow(clippy::too_many_arguments)]
1841    pub(crate) fn dispatch_command_for(
1842        &mut self,
1843        target: WidgetId,
1844        window_id: WindowId,
1845        dpi_info: DpiInfo,
1846        current_time: f64,
1847        focused_widget: Option<WidgetId>,
1848        clipboard: &Clipboard,
1849        command_sender: &CommandSender,
1850        command: &Command<'_>,
1851    ) -> Option<EventDispatch> {
1852        self.find_mut(target, &mut |pod| {
1853            pod.dispatch_command(
1854                window_id,
1855                dpi_info,
1856                current_time,
1857                focused_widget,
1858                clipboard,
1859                command_sender,
1860                command,
1861            )
1862        })
1863    }
1864
1865    #[allow(clippy::too_many_arguments)]
1866    pub(crate) fn notify_focus_change_for(
1867        &mut self,
1868        target: WidgetId,
1869        window_id: WindowId,
1870        dpi_info: DpiInfo,
1871        current_time: f64,
1872        focused_widget: Option<WidgetId>,
1873        clipboard: &Clipboard,
1874        command_sender: &CommandSender,
1875        focused: bool,
1876    ) -> Option<EventDispatch> {
1877        self.find_mut(target, &mut |pod| {
1878            pod.focus_changed(
1879                window_id,
1880                dpi_info,
1881                current_time,
1882                focused_widget,
1883                clipboard,
1884                command_sender,
1885                focused,
1886            )
1887        })
1888    }
1889
1890    #[allow(clippy::too_many_arguments)]
1891    pub(crate) fn notify_focus_change_for_path(
1892        &mut self,
1893        path: &[WidgetId],
1894        window_id: WindowId,
1895        dpi_info: DpiInfo,
1896        current_time: f64,
1897        focused_widget: Option<WidgetId>,
1898        clipboard: &Clipboard,
1899        command_sender: &CommandSender,
1900        focused: bool,
1901    ) -> Option<EventDispatch> {
1902        self.find_mut_path(path, &mut |pod| {
1903            pod.focus_changed(
1904                window_id,
1905                dpi_info,
1906                current_time,
1907                focused_widget,
1908                clipboard,
1909                command_sender,
1910                focused,
1911            )
1912        })
1913    }
1914
1915    #[allow(clippy::too_many_arguments)]
1916    fn dispatch_event(
1917        &mut self,
1918        window_id: WindowId,
1919        dpi_info: DpiInfo,
1920        current_time: f64,
1921        phase: EventPhase,
1922        focused_widget: Option<WidgetId>,
1923        clipboard: &Clipboard,
1924        command_sender: &CommandSender,
1925        event: &Event,
1926    ) -> EventDispatch {
1927        let local_event = event_for_transform(
1928            event,
1929            self.layout_state
1930                .presentation_transform
1931                .inverse()
1932                .unwrap_or(Transform::IDENTITY),
1933        );
1934        let mut ctx = EventCtx::new(
1935            window_id,
1936            self.id,
1937            self.layout_state.arranged_bounds,
1938            dpi_info,
1939            current_time,
1940            phase,
1941            focused_widget,
1942            clipboard.clone(),
1943            command_sender.clone(),
1944        );
1945        self.widget.event(&mut ctx, &local_event);
1946        let mut drag_requests = ctx.take_drag_requests();
1947        for request in &mut drag_requests {
1948            match request {
1949                DragRequest::Begin(request) => {
1950                    request.position = self
1951                        .layout_state
1952                        .presentation_transform
1953                        .transform_point(request.position);
1954                }
1955                DragRequest::RefreshTargets => {}
1956            }
1957        }
1958        EventDispatch {
1959            handled: ctx.is_handled(),
1960            invalidations: ctx.take_invalidations(),
1961            focus_request: ctx.take_focus_request(),
1962            wake_requests: ctx.take_wake_requests(),
1963            pointer_capture_requests: ctx.take_pointer_capture_requests(),
1964            cursor_requests: ctx.take_cursor_requests(),
1965            drag_requests,
1966            drop_acceptances: ctx.take_drop_acceptances(),
1967            posted_events: ctx.take_posted_events(),
1968            posted_commands: ctx.take_posted_commands(),
1969        }
1970    }
1971
1972    #[allow(clippy::too_many_arguments)]
1973    fn dispatch_command(
1974        &mut self,
1975        window_id: WindowId,
1976        dpi_info: DpiInfo,
1977        current_time: f64,
1978        focused_widget: Option<WidgetId>,
1979        clipboard: &Clipboard,
1980        command_sender: &CommandSender,
1981        command: &Command<'_>,
1982    ) -> EventDispatch {
1983        let mut ctx = EventCtx::new(
1984            window_id,
1985            self.id,
1986            self.layout_state.arranged_bounds,
1987            dpi_info,
1988            current_time,
1989            EventPhase::Target,
1990            focused_widget,
1991            clipboard.clone(),
1992            command_sender.clone(),
1993        );
1994        self.widget.command(&mut ctx, command);
1995        ctx.into_dispatch()
1996    }
1997
1998    fn focus_changed(
1999        &mut self,
2000        window_id: WindowId,
2001        dpi_info: DpiInfo,
2002        current_time: f64,
2003        focused_widget: Option<WidgetId>,
2004        clipboard: &Clipboard,
2005        command_sender: &CommandSender,
2006        focused: bool,
2007    ) -> EventDispatch {
2008        let mut ctx = EventCtx::new(
2009            window_id,
2010            self.id,
2011            self.layout_state.arranged_bounds,
2012            dpi_info,
2013            current_time,
2014            EventPhase::Target,
2015            focused_widget,
2016            clipboard.clone(),
2017            command_sender.clone(),
2018        );
2019        self.widget.focus_changed(&mut ctx, focused);
2020        EventDispatch {
2021            handled: ctx.is_handled(),
2022            invalidations: ctx.take_invalidations(),
2023            focus_request: ctx.take_focus_request(),
2024            wake_requests: ctx.take_wake_requests(),
2025            pointer_capture_requests: ctx.take_pointer_capture_requests(),
2026            cursor_requests: ctx.take_cursor_requests(),
2027            drag_requests: ctx.take_drag_requests(),
2028            drop_acceptances: ctx.take_drop_acceptances(),
2029            posted_events: ctx.take_posted_events(),
2030            posted_commands: ctx.take_posted_commands(),
2031        }
2032    }
2033
2034    fn find_mut<R, F>(&mut self, target: WidgetId, f: &mut F) -> Option<R>
2035    where
2036        F: FnMut(&mut WidgetPod) -> R,
2037    {
2038        if self.id == target {
2039            return Some(f(self));
2040        }
2041
2042        let mut result = None;
2043        let mut visitor = FindMutVisitor {
2044            target,
2045            callback: f,
2046            result: &mut result,
2047        };
2048        self.visit_children_mut(&mut visitor);
2049        result
2050    }
2051
2052    fn find_mut_path<R, F>(&mut self, path: &[WidgetId], f: &mut F) -> Option<R>
2053    where
2054        F: FnMut(&mut WidgetPod) -> R,
2055    {
2056        let (&current, rest) = path.split_first()?;
2057        if current != self.id {
2058            return None;
2059        }
2060
2061        if rest.is_empty() {
2062            return Some(f(self));
2063        }
2064
2065        let mut result = None;
2066        let mut visitor = FindPathMutVisitor {
2067            path: rest,
2068            callback: f,
2069            result: &mut result,
2070        };
2071        self.visit_children_mut(&mut visitor);
2072        result
2073    }
2074
2075    fn translate_descendants(&mut self, delta: Vector) {
2076        if delta == Vector::ZERO {
2077            return;
2078        }
2079
2080        let mut visitor = TranslateVisitor { delta };
2081        self.visit_children_mut(&mut visitor);
2082    }
2083
2084    fn translate_subtree(&mut self, delta: Vector) {
2085        if delta == Vector::ZERO {
2086            return;
2087        }
2088
2089        self.layout_state.arranged_bounds = self.layout_state.arranged_bounds.translate(delta);
2090        self.translate_descendants(delta);
2091    }
2092
2093    fn reproject_presentation_subtree(&mut self, parent_transform: Transform) {
2094        self.layout_state.presentation_transform = self
2095            .layout_state
2096            .relative_presentation_transform
2097            .then(parent_transform);
2098        let mut visitor = ReprojectPresentationVisitor {
2099            parent_transform: self.layout_state.presentation_transform,
2100        };
2101        self.visit_children_mut(&mut visitor);
2102    }
2103
2104    pub(crate) fn build_layer_descriptor(
2105        &self,
2106        scene: &Scene,
2107        frame_time: f64,
2108    ) -> SceneLayerDescriptor {
2109        let options = self.current_layer_options();
2110        SceneLayerDescriptor::new(
2111            SceneLayerId::from_widget(self.id),
2112            self.id,
2113            self.layout_state.arranged_bounds,
2114        )
2115        .with_content_bounds(
2116            scene
2117                .content_bounds()
2118                .unwrap_or(self.layout_state.arranged_bounds),
2119        )
2120        .with_paint_bounds(
2121            scene
2122                .paint_bounds()
2123                .unwrap_or(self.layout_state.arranged_bounds),
2124        )
2125        .with_properties(self.current_layer_properties(frame_time))
2126        .with_clip_to_ancestors(matches!(
2127            options.composition_mode,
2128            LayerCompositionMode::Normal
2129        ))
2130        .with_composition_mode(options.composition_mode)
2131    }
2132
2133    pub(crate) fn current_layer_options(&self) -> LayerOptions {
2134        let mut options = self.widget.layer_options();
2135        if self.force_paint_boundary {
2136            options.paint_boundary = PaintBoundaryMode::Explicit;
2137        }
2138        if !self.layout_state.presentation_transform.is_identity() {
2139            options.paint_boundary = PaintBoundaryMode::Flat;
2140            options.composition_mode = LayerCompositionMode::Normal;
2141        }
2142        options
2143    }
2144
2145    pub(crate) fn current_layer_properties(&self, frame_time: f64) -> LayerProperties {
2146        self.widget.layer_properties_at(frame_time)
2147    }
2148
2149    pub(crate) fn current_paint_boundary_mode(&self) -> PaintBoundaryMode {
2150        self.current_layer_options().paint_boundary
2151    }
2152
2153    pub(crate) fn current_stack_host_options(&self) -> Option<StackHostOptions> {
2154        self.widget.stack_host_options()
2155    }
2156
2157    pub(crate) fn current_stack_surface_options(&self) -> Option<StackSurfaceOptions> {
2158        self.widget.stack_surface_options()
2159    }
2160
2161    pub(crate) fn current_hit_test_self(&self) -> bool {
2162        self.widget.hit_test_self()
2163    }
2164
2165    pub(crate) fn current_overlay_options(&self) -> Option<OverlayOptions> {
2166        self.widget.overlay_options()
2167    }
2168
2169    pub(crate) fn layer_composition_mode_for(
2170        &mut self,
2171        target: WidgetId,
2172    ) -> Option<LayerCompositionMode> {
2173        self.find_mut(target, &mut |pod| {
2174            pod.current_layer_options().composition_mode
2175        })
2176    }
2177}
2178
2179struct ReprojectPresentationVisitor {
2180    parent_transform: Transform,
2181}
2182
2183impl WidgetPodMutVisitor for ReprojectPresentationVisitor {
2184    fn visit(&mut self, pod: &mut WidgetPod) {
2185        pod.reproject_presentation_subtree(self.parent_transform);
2186    }
2187}
2188
2189struct TranslateVisitor {
2190    delta: Vector,
2191}
2192
2193impl WidgetPodMutVisitor for TranslateVisitor {
2194    fn visit(&mut self, child: &mut WidgetPod) {
2195        child.translate_subtree(self.delta);
2196    }
2197}
2198
2199struct CollectDiagnosticsVisitor<'a> {
2200    output: &'a mut Vec<WidgetDiagnosticsSnapshot>,
2201}
2202
2203impl WidgetPodVisitor for CollectDiagnosticsVisitor<'_> {
2204    fn visit(&mut self, child: &WidgetPod) {
2205        child.collect_diagnostics(self.output);
2206    }
2207}
2208
2209struct FindMutVisitor<'a, F, R>
2210where
2211    F: FnMut(&mut WidgetPod) -> R,
2212{
2213    target: WidgetId,
2214    callback: &'a mut F,
2215    result: &'a mut Option<R>,
2216}
2217
2218impl<F, R> WidgetPodMutVisitor for FindMutVisitor<'_, F, R>
2219where
2220    F: FnMut(&mut WidgetPod) -> R,
2221{
2222    fn visit(&mut self, child: &mut WidgetPod) {
2223        if self.result.is_none() {
2224            *self.result = child.find_mut(self.target, self.callback);
2225        }
2226    }
2227}
2228
2229struct FindPathMutVisitor<'a, F, R>
2230where
2231    F: FnMut(&mut WidgetPod) -> R,
2232{
2233    path: &'a [WidgetId],
2234    callback: &'a mut F,
2235    result: &'a mut Option<R>,
2236}
2237
2238impl<F, R> WidgetPodMutVisitor for FindPathMutVisitor<'_, F, R>
2239where
2240    F: FnMut(&mut WidgetPod) -> R,
2241{
2242    fn visit(&mut self, child: &mut WidgetPod) {
2243        if self.result.is_none() && self.path.first().copied() == Some(child.id) {
2244            *self.result = child.find_mut_path(self.path, self.callback);
2245        }
2246    }
2247}
2248
2249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2250pub(crate) enum FocusRequest {
2251    Focus(WidgetId),
2252    Clear,
2253    /// Leave focus where it is, overriding the runtime's default.
2254    Keep,
2255}
2256
2257#[derive(Debug, Clone, Copy, PartialEq)]
2258pub(crate) enum WakeRequest {
2259    ScheduleTimer {
2260        token: TimerToken,
2261        deadline: f64,
2262        target: WidgetId,
2263    },
2264    CancelTimer {
2265        token: TimerToken,
2266    },
2267    RegisterAsync {
2268        token: AsyncWakeToken,
2269        target: WidgetId,
2270    },
2271    UnregisterAsync {
2272        token: AsyncWakeToken,
2273    },
2274    RequestAnimationFrame {
2275        target: WidgetId,
2276    },
2277    Motion {
2278        target: WidgetId,
2279        kind: InvalidationKind,
2280        until: f64,
2281    },
2282    MotionEnd {
2283        target: WidgetId,
2284        kind: InvalidationKind,
2285        until: f64,
2286    },
2287}
2288
2289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2290pub(crate) enum PointerCaptureRequest {
2291    Capture { pointer_id: u64, target: WidgetId },
2292    Release { pointer_id: u64 },
2293}
2294
2295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2296pub(crate) enum CursorRequest {
2297    Grab {
2298        target: WidgetId,
2299        mode: CursorGrabMode,
2300    },
2301    Visibility {
2302        target: WidgetId,
2303        visible: bool,
2304    },
2305}
2306
2307#[derive(Debug, Clone)]
2308pub(crate) struct BeginDragRequest {
2309    pub session_id: DragSessionId,
2310    pub scope_id: DragScopeId,
2311    pub pointer_id: u64,
2312    pub source: WidgetId,
2313    pub position: Point,
2314    pub payload: DragPayload,
2315    pub allowed_effects: DropEffects,
2316    pub preview_label: Option<String>,
2317}
2318
2319#[derive(Debug, Clone)]
2320pub(crate) enum DragRequest {
2321    Begin(BeginDragRequest),
2322    RefreshTargets,
2323}
2324
2325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2326pub(crate) struct DropAcceptanceRequest {
2327    pub target: WidgetId,
2328    pub effect: DropEffect,
2329}
2330
2331/// An event queued by a widget for delivery to another widget once the
2332/// current dispatch finishes.
2333#[derive(Debug, Clone)]
2334pub(crate) struct PostedEventRequest {
2335    pub target: WidgetId,
2336    pub event: Event,
2337}
2338
2339/// A typed, target-only command posted during widget dispatch.
2340#[derive(Debug, Clone)]
2341pub(crate) struct PostedCommandRequest {
2342    pub command: QueuedCommand,
2343}
2344
2345#[derive(Debug, Clone)]
2346pub(crate) struct EventDispatch {
2347    pub handled: bool,
2348    pub invalidations: Vec<InvalidationRequest>,
2349    pub focus_request: Option<FocusRequest>,
2350    pub wake_requests: Vec<WakeRequest>,
2351    pub pointer_capture_requests: Vec<PointerCaptureRequest>,
2352    pub cursor_requests: Vec<CursorRequest>,
2353    pub drag_requests: Vec<DragRequest>,
2354    pub drop_acceptances: Vec<DropAcceptanceRequest>,
2355    pub posted_events: Vec<PostedEventRequest>,
2356    pub posted_commands: Vec<PostedCommandRequest>,
2357}
2358
2359#[derive(Debug, Clone)]
2360pub struct EventCtx {
2361    window_id: WindowId,
2362    widget_id: WidgetId,
2363    bounds: Rect,
2364    dpi_info: DpiInfo,
2365    current_time: f64,
2366    phase: EventPhase,
2367    focused_widget_id: Option<WidgetId>,
2368    clipboard: Clipboard,
2369    command_sender: CommandSender,
2370    handled: bool,
2371    invalidations: Vec<InvalidationRequest>,
2372    focus_request: Option<FocusRequest>,
2373    wake_requests: Vec<WakeRequest>,
2374    pointer_capture_requests: Vec<PointerCaptureRequest>,
2375    cursor_requests: Vec<CursorRequest>,
2376    drag_requests: Vec<DragRequest>,
2377    drop_acceptances: Vec<DropAcceptanceRequest>,
2378    posted_events: Vec<PostedEventRequest>,
2379    posted_commands: Vec<PostedCommandRequest>,
2380}
2381
2382impl EventCtx {
2383    #[allow(clippy::too_many_arguments)]
2384    pub(crate) fn new(
2385        window_id: WindowId,
2386        widget_id: WidgetId,
2387        bounds: Rect,
2388        dpi_info: DpiInfo,
2389        current_time: f64,
2390        phase: EventPhase,
2391        focused_widget_id: Option<WidgetId>,
2392        clipboard: Clipboard,
2393        command_sender: CommandSender,
2394    ) -> Self {
2395        Self {
2396            window_id,
2397            widget_id,
2398            bounds,
2399            dpi_info,
2400            current_time,
2401            phase,
2402            focused_widget_id,
2403            clipboard,
2404            command_sender,
2405            handled: false,
2406            invalidations: Vec::new(),
2407            focus_request: None,
2408            wake_requests: Vec::new(),
2409            pointer_capture_requests: Vec::new(),
2410            cursor_requests: Vec::new(),
2411            drag_requests: Vec::new(),
2412            drop_acceptances: Vec::new(),
2413            posted_events: Vec::new(),
2414            posted_commands: Vec::new(),
2415        }
2416    }
2417
2418    fn into_dispatch(mut self) -> EventDispatch {
2419        EventDispatch {
2420            handled: self.is_handled(),
2421            invalidations: self.take_invalidations(),
2422            focus_request: self.take_focus_request(),
2423            wake_requests: self.take_wake_requests(),
2424            pointer_capture_requests: self.take_pointer_capture_requests(),
2425            cursor_requests: self.take_cursor_requests(),
2426            drag_requests: self.take_drag_requests(),
2427            drop_acceptances: self.take_drop_acceptances(),
2428            posted_events: self.take_posted_events(),
2429            posted_commands: self.take_posted_commands(),
2430        }
2431    }
2432
2433    pub const fn window_id(&self) -> WindowId {
2434        self.window_id
2435    }
2436
2437    pub const fn widget_id(&self) -> WidgetId {
2438        self.widget_id
2439    }
2440
2441    /// Read an observable and subscribe this widget to the requested
2442    /// invalidation kind.
2443    pub fn observe<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2444    where
2445        O: Observable<T> + ?Sized,
2446    {
2447        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2448    }
2449
2450    /// Record a development diagnostic explaining a structural widget rebuild.
2451    pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
2452        crate::diagnostics::record_widget_rebuild(
2453            self.window_id,
2454            self.widget_id,
2455            widget_name,
2456            reason,
2457        );
2458    }
2459
2460    pub const fn bounds(&self) -> Rect {
2461        self.bounds
2462    }
2463
2464    pub const fn dpi(&self) -> DpiInfo {
2465        self.dpi_info
2466    }
2467
2468    pub const fn current_time(&self) -> f64 {
2469        self.current_time
2470    }
2471
2472    /// The motion policy that transitions started now should follow.
2473    pub fn motion_policy(&self) -> MotionPolicy {
2474        crate::motion_policy()
2475    }
2476
2477    /// Animate `motion` toward `target` with `spec`, under the motion
2478    /// policy. The runtime invalidates this widget (with the motion's
2479    /// invalidation kind) every frame until the transition ends; read the
2480    /// value with `motion.get(ctx)`. Returns whether a transition started.
2481    pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
2482    where
2483        T: Interpolate + Copy + PartialEq,
2484    {
2485        self.animate_after(motion, target, 0.0, spec)
2486    }
2487
2488    /// Like `animate`, starting `delay` seconds from now. Use a
2489    /// [`Stagger`](sui_animation::Stagger) to start a group of transitions one
2490    /// after another.
2491    pub fn animate_after<T>(
2492        &mut self,
2493        motion: &mut Motion<T>,
2494        target: T,
2495        delay: f64,
2496        spec: AnimationSpec,
2497    ) -> bool
2498    where
2499        T: Interpolate + Copy + PartialEq,
2500    {
2501        let before = motion.target();
2502        let until = motion.start_after(target, self.current_time, delay, spec);
2503        if before != target {
2504            // The value may change right away (an instant jump under the
2505            // motion policy), so repaint now as well as every frame.
2506            self.request_widget(motion.invalidation());
2507        }
2508        if let Some(until) = until {
2509            self.track_motion(until, motion.invalidation());
2510        }
2511        until.is_some()
2512    }
2513
2514    /// Keep invalidating this widget with `kind` every animation frame until
2515    /// `until` (in frame time), for presentation that is a function of time.
2516    pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
2517        self.track_motion_for(self.widget_id, until, kind);
2518    }
2519
2520    /// Like `track_motion`, for another widget: a container animating a
2521    /// child's layer keeps the child's layer updated until `until`.
2522    pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
2523        self.wake_requests.push(WakeRequest::Motion {
2524            target,
2525            kind,
2526            until,
2527        });
2528    }
2529
2530    /// Invalidate this widget with `kind` once, at the first frame at or
2531    /// after `until`: for state that changes when a motion ends, such as
2532    /// content that stops taking space once it has faded out.
2533    pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
2534        self.track_motion_end_for(self.widget_id, until, kind);
2535    }
2536
2537    /// Like `track_motion_end`, for another widget.
2538    pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
2539        self.wake_requests.push(WakeRequest::MotionEnd {
2540            target,
2541            kind,
2542            until,
2543        });
2544    }
2545
2546    pub const fn phase(&self) -> EventPhase {
2547        self.phase
2548    }
2549
2550    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
2551        self.focused_widget_id
2552    }
2553
2554    pub fn is_focused(&self) -> bool {
2555        self.focused_widget_id == Some(self.widget_id)
2556    }
2557
2558    pub const fn is_handled(&self) -> bool {
2559        self.handled
2560    }
2561
2562    pub fn set_handled(&mut self) {
2563        self.handled = true;
2564    }
2565
2566    /// Shared clipboard service for this window. Backed by the OS clipboard
2567    /// when the platform installed a native backend, otherwise by in-process
2568    /// storage shared across the runtime.
2569    pub fn clipboard(&self) -> &Clipboard {
2570        &self.clipboard
2571    }
2572
2573    pub fn clipboard_text(&self) -> Option<String> {
2574        self.clipboard.text()
2575    }
2576
2577    pub fn set_clipboard_text(&mut self, text: impl AsRef<str>) {
2578        self.clipboard.set_text(text);
2579    }
2580
2581    /// Return the runtime's cloneable typed command producer.
2582    ///
2583    /// Widget callbacks can use this to address window or application
2584    /// controllers without routing through an ancestor widget. Delivery is
2585    /// queued until the current event dispatch completes.
2586    pub fn command_sender(&self) -> &CommandSender {
2587        &self.command_sender
2588    }
2589
2590    /// Queue an event for delivery to `target` after the current dispatch
2591    /// completes. Used to route commands (for example clipboard actions from
2592    /// a context menu) to a specific widget outside the normal hit-test or
2593    /// focus routing.
2594    pub fn post_event(&mut self, target: WidgetId, event: Event) {
2595        self.posted_events
2596            .push(PostedEventRequest { target, event });
2597    }
2598
2599    /// Queue a typed command for target-only delivery after the current widget
2600    /// dispatch completes.
2601    pub fn post_command<T>(&mut self, target: WidgetId, key: CommandKey<T>, payload: T)
2602    where
2603        T: Send + Sync + 'static,
2604    {
2605        self.posted_commands.push(PostedCommandRequest {
2606            command: queued_command(
2607                CommandTarget::Widget {
2608                    window_id: self.window_id,
2609                    widget_id: target,
2610                },
2611                CommandDelivery::Directed,
2612                key,
2613                payload,
2614            ),
2615        });
2616    }
2617
2618    pub fn request_focus(&mut self) {
2619        self.focus_request = Some(FocusRequest::Focus(self.widget_id));
2620    }
2621
2622    /// Request focus for a retained widget in the current window.
2623    ///
2624    /// Containers use this to restore focus to a descendant after adaptive
2625    /// presentation changes. The target must be mounted in the widget graph by
2626    /// the time the current event dispatch completes.
2627    pub fn request_focus_for(&mut self, widget_id: WidgetId) {
2628        self.focus_request = Some(FocusRequest::Focus(widget_id));
2629    }
2630
2631    pub fn clear_focus(&mut self) {
2632        self.focus_request = Some(FocusRequest::Clear);
2633    }
2634
2635    /// Leave focus where it is. A pointer press otherwise focuses the widget
2636    /// pressed, or clears focus when it cannot take it; a toolbar button that
2637    /// acts on an editor keeps the editor focused this way. Tab and
2638    /// assistive technology still focus the widget as usual.
2639    pub fn keep_focus(&mut self) {
2640        self.focus_request = Some(FocusRequest::Keep);
2641    }
2642
2643    pub fn schedule_timer_at(&mut self, deadline: f64) -> TimerToken {
2644        let token = TimerToken::new(NEXT_TIMER_TOKEN.fetch_add(1, Ordering::Relaxed));
2645        self.wake_requests.push(WakeRequest::ScheduleTimer {
2646            token,
2647            deadline,
2648            target: self.widget_id,
2649        });
2650        token
2651    }
2652
2653    pub fn schedule_timer_after(&mut self, delay: f64) -> TimerToken {
2654        self.schedule_timer_at(self.current_time + delay)
2655    }
2656
2657    pub fn cancel_timer(&mut self, token: TimerToken) {
2658        self.wake_requests.push(WakeRequest::CancelTimer { token });
2659    }
2660
2661    pub fn register_async_wakeup(&mut self) -> AsyncWakeToken {
2662        let token = AsyncWakeToken::new(NEXT_ASYNC_WAKE_TOKEN.fetch_add(1, Ordering::Relaxed));
2663        self.wake_requests.push(WakeRequest::RegisterAsync {
2664            token,
2665            target: self.widget_id,
2666        });
2667        token
2668    }
2669
2670    pub fn unregister_async_wakeup(&mut self, token: AsyncWakeToken) {
2671        self.wake_requests
2672            .push(WakeRequest::UnregisterAsync { token });
2673    }
2674
2675    pub fn request_animation_frame(&mut self) {
2676        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
2677            target: self.widget_id,
2678        });
2679    }
2680
2681    pub fn request_pointer_capture(&mut self, pointer_id: u64) {
2682        self.pointer_capture_requests
2683            .push(PointerCaptureRequest::Capture {
2684                pointer_id,
2685                target: self.widget_id,
2686            });
2687    }
2688
2689    pub fn release_pointer_capture(&mut self, pointer_id: u64) {
2690        self.pointer_capture_requests
2691            .push(PointerCaptureRequest::Release { pointer_id });
2692    }
2693
2694    /// Request host-level cursor grabbing for this widget.
2695    ///
2696    /// The request is best effort. Desktop hosts try [`CursorGrabMode::Locked`]
2697    /// first and then fall back to [`CursorGrabMode::Confined`]. Relative mouse
2698    /// motion is routed to this widget while a grab is active. Request
2699    /// [`CursorGrabMode::None`] to release a grab owned by this widget.
2700    pub fn request_cursor_grab(&mut self, mode: CursorGrabMode) {
2701        self.cursor_requests.push(CursorRequest::Grab {
2702            target: self.widget_id,
2703            mode,
2704        });
2705    }
2706
2707    /// Request whether the host system cursor is visible for this widget.
2708    ///
2709    /// Cursor visibility is independent of cursor grabbing. Focus loss always
2710    /// restores visibility.
2711    pub fn request_cursor_visibility(&mut self, visible: bool) {
2712        self.cursor_requests.push(CursorRequest::Visibility {
2713            target: self.widget_id,
2714            visible,
2715        });
2716    }
2717
2718    /// Start a drag of `payload` with the pointer `pointer_id`. The source
2719    /// allows `allowed_effects`: a single [`DropEffect`] or a
2720    /// [`DropEffects`] set, whose [`DropEffects::default_effect`] applies
2721    /// when no modifier key asks for another.
2722    pub fn begin_drag(
2723        &mut self,
2724        scope_id: DragScopeId,
2725        pointer_id: u64,
2726        position: Point,
2727        payload: DragPayload,
2728        allowed_effects: impl Into<DropEffects>,
2729        preview_label: Option<String>,
2730    ) -> DragSessionId {
2731        let session_id = DragSessionId::new(NEXT_DRAG_SESSION_ID.fetch_add(1, Ordering::Relaxed));
2732        self.drag_requests
2733            .push(DragRequest::Begin(BeginDragRequest {
2734                session_id,
2735                scope_id,
2736                pointer_id,
2737                source: self.widget_id,
2738                position,
2739                payload,
2740                allowed_effects: allowed_effects.into(),
2741                preview_label,
2742            }));
2743        session_id
2744    }
2745
2746    /// Ask the runtime to work out again which drop targets an active drag is
2747    /// over, as content moved under a pointer that did not. Scroll views call
2748    /// this when they scroll during a drag.
2749    pub fn refresh_drag_targets(&mut self) {
2750        self.drag_requests.push(DragRequest::RefreshTargets);
2751    }
2752
2753    pub fn accept_drop(&mut self, effect: DropEffect) {
2754        if effect.is_none() {
2755            return;
2756        }
2757        self.drop_acceptances.push(DropAcceptanceRequest {
2758            target: self.widget_id,
2759            effect,
2760        });
2761    }
2762
2763    pub fn request(&mut self, request: InvalidationRequest) {
2764        self.invalidations.push(request);
2765    }
2766
2767    pub fn request_measure(&mut self) {
2768        self.request_widget(InvalidationKind::Measure);
2769    }
2770
2771    pub fn request_arrange(&mut self) {
2772        self.request_widget(InvalidationKind::Arrange);
2773    }
2774
2775    pub fn request_ordering(&mut self) {
2776        self.request_widget(InvalidationKind::Ordering);
2777    }
2778
2779    pub fn request_paint(&mut self) {
2780        self.request_widget(InvalidationKind::Paint);
2781    }
2782
2783    pub fn request_paint_rect(&mut self, rect: Rect) {
2784        self.request(
2785            InvalidationRequest::new(
2786                InvalidationTarget::Widget(self.widget_id),
2787                InvalidationKind::Paint,
2788            )
2789            .with_region(rect),
2790        );
2791    }
2792
2793    pub fn request_transform(&mut self) {
2794        self.request_widget(InvalidationKind::Transform);
2795    }
2796
2797    pub fn request_effect(&mut self) {
2798        self.request_widget(InvalidationKind::Effect);
2799    }
2800
2801    pub fn request_visibility(&mut self) {
2802        self.request_widget(InvalidationKind::Visibility);
2803    }
2804
2805    pub fn request_hit_test(&mut self) {
2806        self.request_widget(InvalidationKind::HitTest);
2807    }
2808
2809    pub fn request_text(&mut self) {
2810        self.request_widget(InvalidationKind::Text);
2811    }
2812
2813    pub fn request_semantics(&mut self) {
2814        self.request_widget(InvalidationKind::Semantics);
2815    }
2816
2817    pub fn request_resources(&mut self) {
2818        self.request_widget(InvalidationKind::Resources);
2819    }
2820
2821    pub fn invalidations(&self) -> &[InvalidationRequest] {
2822        &self.invalidations
2823    }
2824
2825    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
2826        std::mem::take(&mut self.invalidations)
2827    }
2828
2829    pub(crate) fn take_focus_request(&mut self) -> Option<FocusRequest> {
2830        self.focus_request.take()
2831    }
2832
2833    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
2834        std::mem::take(&mut self.wake_requests)
2835    }
2836
2837    pub(crate) fn take_pointer_capture_requests(&mut self) -> Vec<PointerCaptureRequest> {
2838        std::mem::take(&mut self.pointer_capture_requests)
2839    }
2840
2841    pub(crate) fn take_cursor_requests(&mut self) -> Vec<CursorRequest> {
2842        std::mem::take(&mut self.cursor_requests)
2843    }
2844
2845    pub(crate) fn take_drag_requests(&mut self) -> Vec<DragRequest> {
2846        std::mem::take(&mut self.drag_requests)
2847    }
2848
2849    pub(crate) fn take_drop_acceptances(&mut self) -> Vec<DropAcceptanceRequest> {
2850        std::mem::take(&mut self.drop_acceptances)
2851    }
2852
2853    pub(crate) fn take_posted_events(&mut self) -> Vec<PostedEventRequest> {
2854        std::mem::take(&mut self.posted_events)
2855    }
2856
2857    pub(crate) fn take_posted_commands(&mut self) -> Vec<PostedCommandRequest> {
2858        std::mem::take(&mut self.posted_commands)
2859    }
2860
2861    fn request_widget(&mut self, kind: InvalidationKind) {
2862        self.request(InvalidationRequest::new(
2863            InvalidationTarget::Widget(self.widget_id),
2864            kind,
2865        ));
2866    }
2867}
2868
2869/// Per-measure-pass invalidation scope, shared (via `Rc`) by every `MeasureCtx`
2870/// in a single pass. Drives which pods may reuse their cached measure.
2871///
2872/// - `force_all`: ignore all caches and re-measure everything (bootstrap, resize,
2873///   or any frame whose dirty set could not be resolved to concrete widgets).
2874/// - `dirty`: pods that must recompute their own measure — the changed widgets
2875///   plus every ancestor on the path from the root (an ancestor's layout can
2876///   depend on a descendant's size).
2877/// - `subtree_roots`: the changed widgets themselves; entering their children
2878///   forces the whole subtree to re-measure, because the change is inside them.
2879static NEXT_MEASURE_GENERATION: AtomicU64 = AtomicU64::new(1);
2880
2881#[derive(Debug)]
2882pub(crate) struct MeasureScope {
2883    generation: u64,
2884    reusable_queries: bool,
2885    force_all: bool,
2886    dirty: HashSet<WidgetId>,
2887    subtree_roots: HashSet<WidgetId>,
2888}
2889
2890/// Per-arrange-pass invalidation scope used to skip clean retained subtrees.
2891#[derive(Debug, Default)]
2892pub(crate) struct ArrangeScope {
2893    force_all: bool,
2894    dirty: HashSet<WidgetId>,
2895}
2896
2897impl ArrangeScope {
2898    pub(crate) fn force_all() -> Self {
2899        Self {
2900            force_all: true,
2901            dirty: HashSet::new(),
2902        }
2903    }
2904
2905    pub(crate) fn scoped(dirty: HashSet<WidgetId>) -> Self {
2906        Self {
2907            force_all: false,
2908            dirty,
2909        }
2910    }
2911
2912    fn must_rearrange(&self, widget_id: WidgetId) -> bool {
2913        self.force_all || self.dirty.contains(&widget_id)
2914    }
2915}
2916
2917impl Default for MeasureScope {
2918    fn default() -> Self {
2919        Self {
2920            generation: NEXT_MEASURE_GENERATION.fetch_add(1, Ordering::Relaxed),
2921            reusable_queries: true,
2922            force_all: false,
2923            dirty: HashSet::new(),
2924            subtree_roots: HashSet::new(),
2925        }
2926    }
2927}
2928
2929impl MeasureScope {
2930    pub(crate) fn is_full_invalidation(&self) -> bool {
2931        self.force_all
2932    }
2933
2934    pub(crate) fn force_all() -> Self {
2935        Self {
2936            force_all: true,
2937            dirty: HashSet::new(),
2938            subtree_roots: HashSet::new(),
2939            ..Self::default()
2940        }
2941    }
2942
2943    pub(crate) fn scoped(dirty: HashSet<WidgetId>, subtree_roots: HashSet<WidgetId>) -> Self {
2944        Self {
2945            force_all: false,
2946            dirty,
2947            subtree_roots,
2948            ..Self::default()
2949        }
2950    }
2951
2952    fn must_remeasure(&self, widget_id: WidgetId) -> bool {
2953        self.force_all || self.dirty.contains(&widget_id)
2954    }
2955
2956    fn forces_subtree(&self, widget_id: WidgetId) -> bool {
2957        self.subtree_roots.contains(&widget_id)
2958    }
2959}
2960
2961#[derive(Debug, Clone)]
2962pub struct MeasureCtx {
2963    window_id: WindowId,
2964    widget_id: WidgetId,
2965    bounds: Rect,
2966    layout: LayoutContext,
2967    current_time: f64,
2968    invalidations: Vec<InvalidationRequest>,
2969    wake_requests: Vec<WakeRequest>,
2970    scope: Rc<MeasureScope>,
2971    /// Whether the pod this ctx belongs to is inside a forced subtree.
2972    force: bool,
2973    probing: bool,
2974    query_cache: Option<crate::measure_cache::SharedQueryCache>,
2975    query_context: Option<crate::measure_cache::QueryContext>,
2976}
2977
2978impl MeasureCtx {
2979    pub fn with_layout(
2980        window_id: WindowId,
2981        widget_id: WidgetId,
2982        bounds: Rect,
2983        layout: LayoutContext,
2984    ) -> Self {
2985        // External / test callers get full-measure semantics by default.
2986        Self::with_layout_scoped(
2987            window_id,
2988            widget_id,
2989            bounds,
2990            layout,
2991            0.0,
2992            Rc::new(MeasureScope {
2993                // External callers can reuse this context across arbitrary
2994                // measure calls, without the runtime's per-pass lifetime.
2995                reusable_queries: false,
2996                ..MeasureScope::force_all()
2997            }),
2998            true,
2999        )
3000    }
3001
3002    pub(crate) fn with_layout_scoped(
3003        window_id: WindowId,
3004        widget_id: WidgetId,
3005        bounds: Rect,
3006        layout: LayoutContext,
3007        current_time: f64,
3008        scope: Rc<MeasureScope>,
3009        force: bool,
3010    ) -> Self {
3011        Self {
3012            window_id,
3013            widget_id,
3014            bounds,
3015            layout,
3016            current_time,
3017            invalidations: Vec::new(),
3018            wake_requests: Vec::new(),
3019            scope,
3020            force,
3021            probing: false,
3022            query_cache: None,
3023            query_context: None,
3024        }
3025    }
3026
3027    #[cfg(test)]
3028    pub(crate) fn new(
3029        window_id: WindowId,
3030        widget_id: WidgetId,
3031        bounds: Rect,
3032        dpi_info: DpiInfo,
3033        text_system: Arc<TextSystem>,
3034        font_registry: Arc<FontRegistry>,
3035        image_registry: Arc<ImageRegistry>,
3036    ) -> Self {
3037        Self::with_layout(
3038            window_id,
3039            widget_id,
3040            bounds,
3041            LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
3042        )
3043    }
3044
3045    pub(crate) fn new_scoped_at(
3046        window_id: WindowId,
3047        widget_id: WidgetId,
3048        bounds: Rect,
3049        dpi_info: DpiInfo,
3050        text_system: Arc<TextSystem>,
3051        font_registry: Arc<FontRegistry>,
3052        image_registry: Arc<ImageRegistry>,
3053        scope: Rc<MeasureScope>,
3054        current_time: f64,
3055    ) -> Self {
3056        Self::with_layout_scoped(
3057            window_id,
3058            widget_id,
3059            bounds,
3060            LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
3061            current_time,
3062            scope,
3063            false,
3064        )
3065    }
3066
3067    pub(crate) fn set_query_cache(&mut self, cache: crate::measure_cache::SharedQueryCache) {
3068        self.query_context = Some(cache.borrow().context());
3069        self.query_cache = Some(cache);
3070    }
3071
3072    pub(crate) fn scope(&self) -> &MeasureScope {
3073        &self.scope
3074    }
3075
3076    /// Whether the *children* of this pod must be force-remeasured: either this
3077    /// pod is already inside a forced subtree, or this pod is itself a changed
3078    /// widget whose subtree must be rebuilt.
3079    pub(crate) fn child_force(&self) -> bool {
3080        self.force || self.scope.forces_subtree(self.widget_id)
3081    }
3082
3083    /// Build the measure ctx for a child pod, carrying the shared scope and the
3084    /// child's resolved force flag.
3085    pub(crate) fn child(&self, widget_id: WidgetId, bounds: Rect, force: bool) -> Self {
3086        let mut child = Self::with_layout_scoped(
3087            self.window_id,
3088            widget_id,
3089            bounds,
3090            self.layout.clone(),
3091            self.current_time,
3092            Rc::clone(&self.scope),
3093            force,
3094        );
3095        child.probing = self.probing;
3096        child.query_cache = self.query_cache.clone();
3097        child.query_context = self.query_context;
3098        child
3099    }
3100
3101    pub const fn window_id(&self) -> WindowId {
3102        self.window_id
3103    }
3104
3105    pub const fn widget_id(&self) -> WidgetId {
3106        self.widget_id
3107    }
3108
3109    /// Read an observable whose changes affect measurement.
3110    pub fn observe<T, O>(&self, observable: &O) -> T
3111    where
3112        O: Observable<T> + ?Sized,
3113    {
3114        self.observe_with(observable, InvalidationKind::Measure)
3115    }
3116
3117    /// Read an observable and explicitly declare the resulting invalidation.
3118    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3119    where
3120        O: Observable<T> + ?Sized,
3121    {
3122        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3123    }
3124
3125    /// Record a development diagnostic explaining a structural widget rebuild.
3126    pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
3127        crate::diagnostics::record_widget_rebuild(
3128            self.window_id,
3129            self.widget_id,
3130            widget_name,
3131            reason,
3132        );
3133    }
3134
3135    pub const fn bounds(&self) -> Rect {
3136        self.bounds
3137    }
3138
3139    pub const fn layout(&self) -> &LayoutContext {
3140        &self.layout
3141    }
3142
3143    pub const fn dpi(&self) -> DpiInfo {
3144        self.layout.dpi()
3145    }
3146
3147    pub const fn current_time(&self) -> f64 {
3148        self.current_time
3149    }
3150
3151    /// The motion policy that transitions started now should follow.
3152    pub fn motion_policy(&self) -> MotionPolicy {
3153        crate::motion_policy()
3154    }
3155
3156    /// Animate `motion` toward `target` with `spec`, under the motion
3157    /// policy. The runtime invalidates this widget (with the motion's
3158    /// invalidation kind) every frame until the transition ends; read the
3159    /// value with `motion.get(ctx)`. Returns whether a transition started.
3160    pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
3161    where
3162        T: Interpolate + Copy + PartialEq,
3163    {
3164        self.animate_after(motion, target, 0.0, spec)
3165    }
3166
3167    /// Like `animate`, starting `delay` seconds from now. Use a
3168    /// [`Stagger`](sui_animation::Stagger) to start a group of transitions one
3169    /// after another.
3170    pub fn animate_after<T>(
3171        &mut self,
3172        motion: &mut Motion<T>,
3173        target: T,
3174        delay: f64,
3175        spec: AnimationSpec,
3176    ) -> bool
3177    where
3178        T: Interpolate + Copy + PartialEq,
3179    {
3180        let before = motion.target();
3181        let until = motion.start_after(target, self.current_time, delay, spec);
3182        if before != target {
3183            // The value may change right away (an instant jump under the
3184            // motion policy), so repaint now as well as every frame.
3185            self.request_widget(motion.invalidation());
3186        }
3187        if let Some(until) = until {
3188            self.track_motion(until, motion.invalidation());
3189        }
3190        until.is_some()
3191    }
3192
3193    /// Keep invalidating this widget with `kind` every animation frame until
3194    /// `until` (in frame time), for presentation that is a function of time.
3195    pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
3196        self.track_motion_for(self.widget_id, until, kind);
3197    }
3198
3199    /// Like `track_motion`, for another widget: a container animating a
3200    /// child's layer keeps the child's layer updated until `until`.
3201    pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3202        self.wake_requests.push(WakeRequest::Motion {
3203            target,
3204            kind,
3205            until,
3206        });
3207    }
3208
3209    /// Invalidate this widget with `kind` once, at the first frame at or
3210    /// after `until`: for state that changes when a motion ends, such as
3211    /// content that stops taking space once it has faded out.
3212    pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
3213        self.track_motion_end_for(self.widget_id, until, kind);
3214    }
3215
3216    /// Like `track_motion_end`, for another widget.
3217    pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3218        self.wake_requests.push(WakeRequest::MotionEnd {
3219            target,
3220            kind,
3221            until,
3222        });
3223    }
3224
3225    pub fn request(&mut self, request: InvalidationRequest) {
3226        self.invalidations.push(request);
3227    }
3228
3229    pub fn request_measure(&mut self) {
3230        self.request_widget(InvalidationKind::Measure);
3231    }
3232
3233    pub fn request_arrange(&mut self) {
3234        self.request_widget(InvalidationKind::Arrange);
3235    }
3236
3237    pub fn request_ordering(&mut self) {
3238        self.request_widget(InvalidationKind::Ordering);
3239    }
3240
3241    pub fn request_paint(&mut self) {
3242        self.request_widget(InvalidationKind::Paint);
3243    }
3244
3245    pub fn request_semantics(&mut self) {
3246        self.request_widget(InvalidationKind::Semantics);
3247    }
3248
3249    pub fn request_animation_frame(&mut self) {
3250        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
3251            target: self.widget_id,
3252        });
3253    }
3254
3255    pub fn invalidations(&self) -> &[InvalidationRequest] {
3256        &self.invalidations
3257    }
3258
3259    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
3260        std::mem::take(&mut self.invalidations)
3261    }
3262
3263    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
3264        std::mem::take(&mut self.wake_requests)
3265    }
3266
3267    pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
3268        self.invalidations.extend(invalidations);
3269    }
3270
3271    pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
3272        self.wake_requests.extend(wake_requests);
3273    }
3274
3275    fn request_widget(&mut self, kind: InvalidationKind) {
3276        self.request(InvalidationRequest::new(
3277            InvalidationTarget::Widget(self.widget_id),
3278            kind,
3279        ));
3280    }
3281}
3282
3283#[derive(Debug, Clone)]
3284pub struct ArrangeCtx {
3285    window_id: WindowId,
3286    widget_id: WidgetId,
3287    dpi_info: DpiInfo,
3288    current_time: f64,
3289    presentation_transform: Transform,
3290    scope: Rc<ArrangeScope>,
3291    invalidations: Vec<InvalidationRequest>,
3292    wake_requests: Vec<WakeRequest>,
3293}
3294
3295impl ArrangeCtx {
3296    #[cfg(test)]
3297    pub(crate) fn new(window_id: WindowId, widget_id: WidgetId, dpi_info: DpiInfo) -> Self {
3298        Self::new_at(window_id, widget_id, dpi_info, 0.0)
3299    }
3300
3301    #[cfg(test)]
3302    pub(crate) fn new_at(
3303        window_id: WindowId,
3304        widget_id: WidgetId,
3305        dpi_info: DpiInfo,
3306        current_time: f64,
3307    ) -> Self {
3308        Self::new_at_with_transform(
3309            window_id,
3310            widget_id,
3311            dpi_info,
3312            current_time,
3313            Transform::IDENTITY,
3314            Rc::new(ArrangeScope::force_all()),
3315        )
3316    }
3317
3318    pub(crate) fn new_scoped_at(
3319        window_id: WindowId,
3320        widget_id: WidgetId,
3321        dpi_info: DpiInfo,
3322        current_time: f64,
3323        scope: Rc<ArrangeScope>,
3324    ) -> Self {
3325        Self::new_at_with_transform(
3326            window_id,
3327            widget_id,
3328            dpi_info,
3329            current_time,
3330            Transform::IDENTITY,
3331            scope,
3332        )
3333    }
3334
3335    pub(crate) fn new_at_with_transform(
3336        window_id: WindowId,
3337        widget_id: WidgetId,
3338        dpi_info: DpiInfo,
3339        current_time: f64,
3340        presentation_transform: Transform,
3341        scope: Rc<ArrangeScope>,
3342    ) -> Self {
3343        Self {
3344            window_id,
3345            widget_id,
3346            dpi_info,
3347            current_time,
3348            presentation_transform,
3349            scope,
3350            invalidations: Vec::new(),
3351            wake_requests: Vec::new(),
3352        }
3353    }
3354
3355    pub const fn window_id(&self) -> WindowId {
3356        self.window_id
3357    }
3358
3359    pub const fn widget_id(&self) -> WidgetId {
3360        self.widget_id
3361    }
3362
3363    pub const fn presentation_transform(&self) -> Transform {
3364        self.presentation_transform
3365    }
3366
3367    pub(crate) fn scope(&self) -> &ArrangeScope {
3368        self.scope.as_ref()
3369    }
3370
3371    pub(crate) fn scope_rc(&self) -> &Rc<ArrangeScope> {
3372        &self.scope
3373    }
3374
3375    /// Read an observable whose changes affect arrangement.
3376    pub fn observe<T, O>(&self, observable: &O) -> T
3377    where
3378        O: Observable<T> + ?Sized,
3379    {
3380        self.observe_with(observable, InvalidationKind::Arrange)
3381    }
3382
3383    /// Read an observable and explicitly declare the resulting invalidation.
3384    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3385    where
3386        O: Observable<T> + ?Sized,
3387    {
3388        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3389    }
3390
3391    pub const fn dpi(&self) -> DpiInfo {
3392        self.dpi_info
3393    }
3394
3395    pub const fn current_time(&self) -> f64 {
3396        self.current_time
3397    }
3398
3399    /// The motion policy that transitions started now should follow.
3400    pub fn motion_policy(&self) -> MotionPolicy {
3401        crate::motion_policy()
3402    }
3403
3404    /// Animate `motion` toward `target` with `spec`, under the motion
3405    /// policy. The runtime invalidates this widget (with the motion's
3406    /// invalidation kind) every frame until the transition ends; read the
3407    /// value with `motion.get(ctx)`. Returns whether a transition started.
3408    pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
3409    where
3410        T: Interpolate + Copy + PartialEq,
3411    {
3412        self.animate_after(motion, target, 0.0, spec)
3413    }
3414
3415    /// Like `animate`, starting `delay` seconds from now. Use a
3416    /// [`Stagger`](sui_animation::Stagger) to start a group of transitions one
3417    /// after another.
3418    pub fn animate_after<T>(
3419        &mut self,
3420        motion: &mut Motion<T>,
3421        target: T,
3422        delay: f64,
3423        spec: AnimationSpec,
3424    ) -> bool
3425    where
3426        T: Interpolate + Copy + PartialEq,
3427    {
3428        let before = motion.target();
3429        let until = motion.start_after(target, self.current_time, delay, spec);
3430        if before != target {
3431            // The value may change right away (an instant jump under the
3432            // motion policy), so repaint now as well as every frame.
3433            self.request_widget(motion.invalidation());
3434        }
3435        if let Some(until) = until {
3436            self.track_motion(until, motion.invalidation());
3437        }
3438        until.is_some()
3439    }
3440
3441    /// Keep invalidating this widget with `kind` every animation frame until
3442    /// `until` (in frame time), for presentation that is a function of time.
3443    pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
3444        self.track_motion_for(self.widget_id, until, kind);
3445    }
3446
3447    /// Like `track_motion`, for another widget: a container animating a
3448    /// child's layer keeps the child's layer updated until `until`.
3449    pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3450        self.wake_requests.push(WakeRequest::Motion {
3451            target,
3452            kind,
3453            until,
3454        });
3455    }
3456
3457    /// Invalidate this widget with `kind` once, at the first frame at or
3458    /// after `until`: for state that changes when a motion ends, such as
3459    /// content that stops taking space once it has faded out.
3460    pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
3461        self.track_motion_end_for(self.widget_id, until, kind);
3462    }
3463
3464    /// Like `track_motion_end`, for another widget.
3465    pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3466        self.wake_requests.push(WakeRequest::MotionEnd {
3467            target,
3468            kind,
3469            until,
3470        });
3471    }
3472
3473    pub fn request(&mut self, request: InvalidationRequest) {
3474        self.invalidations.push(request);
3475    }
3476
3477    pub fn request_measure(&mut self) {
3478        self.request_widget(InvalidationKind::Measure);
3479    }
3480
3481    pub fn request_arrange(&mut self) {
3482        self.request_widget(InvalidationKind::Arrange);
3483    }
3484
3485    pub fn request_ordering(&mut self) {
3486        self.request_widget(InvalidationKind::Ordering);
3487    }
3488
3489    pub fn request_paint(&mut self) {
3490        self.request_widget(InvalidationKind::Paint);
3491    }
3492
3493    pub fn request_semantics(&mut self) {
3494        self.request_widget(InvalidationKind::Semantics);
3495    }
3496
3497    pub fn request_transform(&mut self) {
3498        self.request_widget(InvalidationKind::Transform);
3499    }
3500
3501    /// Schedule an animation frame for this widget after arrangement.
3502    ///
3503    /// This is useful for retained layout transitions, which discover their
3504    /// new destination during arrange rather than during event delivery.
3505    pub fn request_animation_frame(&mut self) {
3506        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
3507            target: self.widget_id,
3508        });
3509    }
3510
3511    pub fn invalidations(&self) -> &[InvalidationRequest] {
3512        &self.invalidations
3513    }
3514
3515    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
3516        std::mem::take(&mut self.invalidations)
3517    }
3518
3519    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
3520        std::mem::take(&mut self.wake_requests)
3521    }
3522
3523    pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
3524        self.invalidations.extend(invalidations);
3525    }
3526
3527    pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
3528        self.wake_requests.extend(wake_requests);
3529    }
3530
3531    fn request_widget(&mut self, kind: InvalidationKind) {
3532        self.request(InvalidationRequest::new(
3533            InvalidationTarget::Widget(self.widget_id),
3534            kind,
3535        ));
3536    }
3537}
3538
3539#[derive(Debug, Clone)]
3540pub struct PaintCtx {
3541    pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
3542    output_reusable: bool,
3543    window_id: WindowId,
3544    widget_id: WidgetId,
3545    focused_widget_id: Option<WidgetId>,
3546    bounds: Rect,
3547    presentation_transform: Transform,
3548    dpi_info: DpiInfo,
3549    text_system: Arc<TextSystem>,
3550    font_registry: Arc<FontRegistry>,
3551    image_registry: Arc<ImageRegistry>,
3552    scene: Scene,
3553    images: Vec<(ImageHandle, PaintImageResource)>,
3554    widget_paint_bounds: HashMap<WidgetId, Rect>,
3555    ime_composition_rect: Option<Rect>,
3556    frame_time: f64,
3557}
3558
3559macro_rules! impl_animate_ctx {
3560    ($($ctx:ty),*) => {$(
3561        impl crate::motion::AnimateCtx for $ctx {
3562            fn animate_after<T>(
3563                &mut self,
3564                motion: &mut Motion<T>,
3565                target: T,
3566                delay: f64,
3567                spec: AnimationSpec,
3568            ) -> bool
3569            where
3570                T: Interpolate + Copy + PartialEq,
3571            {
3572                <$ctx>::animate_after(self, motion, target, delay, spec)
3573            }
3574        }
3575    )*};
3576}
3577
3578impl_animate_ctx!(EventCtx, MeasureCtx, ArrangeCtx);
3579
3580impl FrameClock for PaintCtx {
3581    fn frame_time(&self) -> f64 {
3582        self.frame_time
3583    }
3584}
3585
3586impl FrameClock for EventCtx {
3587    fn frame_time(&self) -> f64 {
3588        self.current_time
3589    }
3590}
3591
3592impl FrameClock for MeasureCtx {
3593    fn frame_time(&self) -> f64 {
3594        self.current_time
3595    }
3596}
3597
3598impl FrameClock for ArrangeCtx {
3599    fn frame_time(&self) -> f64 {
3600        self.current_time
3601    }
3602}
3603
3604#[derive(Debug, Clone)]
3605pub(crate) enum PaintImageResource {
3606    Cpu(RegisteredImage),
3607    External(RegisteredExternalImage),
3608}
3609
3610impl PaintCtx {
3611    /// The motion policy in effect, for paint that depends on it (such as
3612    /// an entrance offset that reduced motion turns off).
3613    pub fn motion_policy(&self) -> MotionPolicy {
3614        crate::motion_policy()
3615    }
3616
3617    /// What the window's output can show, or `None` before the platform has
3618    /// said. Painting reads it as an observation, so the widget is painted
3619    /// again when it changes.
3620    pub fn output_color_range(&self) -> Option<crate::OutputColorRange> {
3621        self.observe(&crate::window_output_color_range_signal(self.window_id))
3622    }
3623
3624    pub(crate) fn new(
3625        window_id: WindowId,
3626        widget_id: WidgetId,
3627        bounds: Rect,
3628        focused_widget_id: Option<WidgetId>,
3629        dpi_info: DpiInfo,
3630        text_system: Arc<TextSystem>,
3631        font_registry: Arc<FontRegistry>,
3632        image_registry: Arc<ImageRegistry>,
3633    ) -> Self {
3634        Self::new_with_transform(
3635            window_id,
3636            widget_id,
3637            bounds,
3638            focused_widget_id,
3639            dpi_info,
3640            text_system,
3641            font_registry,
3642            image_registry,
3643            Transform::IDENTITY,
3644        )
3645    }
3646
3647    #[allow(clippy::too_many_arguments)]
3648    pub(crate) fn new_with_transform(
3649        window_id: WindowId,
3650        widget_id: WidgetId,
3651        bounds: Rect,
3652        focused_widget_id: Option<WidgetId>,
3653        dpi_info: DpiInfo,
3654        text_system: Arc<TextSystem>,
3655        font_registry: Arc<FontRegistry>,
3656        image_registry: Arc<ImageRegistry>,
3657        presentation_transform: Transform,
3658    ) -> Self {
3659        Self {
3660            output_cache: None,
3661            output_reusable: true,
3662            window_id,
3663            widget_id,
3664            focused_widget_id,
3665            bounds,
3666            presentation_transform,
3667            dpi_info,
3668            text_system,
3669            font_registry,
3670            image_registry,
3671            scene: Scene::new(),
3672            images: Vec::new(),
3673            widget_paint_bounds: HashMap::new(),
3674            ime_composition_rect: None,
3675            frame_time: 0.0,
3676        }
3677    }
3678
3679    pub(crate) const fn with_frame_time(mut self, frame_time: f64) -> Self {
3680        self.frame_time = frame_time;
3681        self
3682    }
3683
3684    /// The time this frame is expected on screen. Read [`Motion`] values at
3685    /// this time (`motion.get(ctx)`).
3686    pub const fn frame_time(&self) -> f64 {
3687        self.frame_time
3688    }
3689
3690    pub const fn window_id(&self) -> WindowId {
3691        self.window_id
3692    }
3693
3694    pub const fn widget_id(&self) -> WidgetId {
3695        self.widget_id
3696    }
3697
3698    pub const fn presentation_transform(&self) -> Transform {
3699        self.presentation_transform
3700    }
3701
3702    /// Read an observable whose changes affect painting.
3703    pub fn observe<T, O>(&self, observable: &O) -> T
3704    where
3705        O: Observable<T> + ?Sized,
3706    {
3707        self.observe_with(observable, InvalidationKind::Paint)
3708    }
3709
3710    /// Read an observable and explicitly declare the resulting invalidation.
3711    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3712    where
3713        O: Observable<T> + ?Sized,
3714    {
3715        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3716    }
3717
3718    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
3719        self.focused_widget_id
3720    }
3721
3722    pub fn is_focused(&self) -> bool {
3723        self.focused_widget_id == Some(self.widget_id)
3724    }
3725
3726    pub const fn bounds(&self) -> Rect {
3727        self.bounds
3728    }
3729
3730    pub const fn dpi(&self) -> DpiInfo {
3731        self.dpi_info
3732    }
3733
3734    pub fn measure_text(
3735        &self,
3736        text: impl Into<String>,
3737        style: TextStyle,
3738    ) -> sui_core::Result<TextMeasurement> {
3739        self.text_system
3740            .measure_text(text, style, self.font_registry.as_ref())
3741    }
3742
3743    pub fn shape_text(
3744        &self,
3745        text: impl Into<String>,
3746        box_size: Size,
3747        style: TextStyle,
3748    ) -> sui_core::Result<TextLayout> {
3749        self.text_system
3750            .shape_text(text, box_size, style, self.font_registry.as_ref())
3751    }
3752
3753    pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
3754        self.text_system
3755            .layout_document(request, self.font_registry.as_ref())
3756    }
3757
3758    pub fn clear(&mut self, color: Color) {
3759        self.scene.push(SceneCommand::Clear(color));
3760    }
3761
3762    pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
3763        self.scene.push(SceneCommand::FillPath {
3764            path: path.into(),
3765            brush: brush.into(),
3766        });
3767    }
3768
3769    pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
3770        self.scene.push(SceneCommand::FillRect {
3771            rect,
3772            brush: brush.into(),
3773        });
3774    }
3775
3776    pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
3777        self.fill_rect(self.bounds, brush);
3778    }
3779
3780    pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
3781        self.scene.push(SceneCommand::StrokePath {
3782            path: path.into(),
3783            brush: brush.into(),
3784            stroke,
3785        });
3786    }
3787
3788    pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
3789        self.scene.push(SceneCommand::StrokeRect {
3790            rect,
3791            brush: brush.into(),
3792            stroke,
3793        });
3794    }
3795
3796    pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
3797        self.stroke_rect(self.bounds, brush, stroke);
3798    }
3799
3800    pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
3801        let text = text.into();
3802        let paint_color = style.color;
3803        let mut layout_style = style.clone();
3804        layout_style.color = Color::WHITE;
3805        let layout_run = TextRun {
3806            rect,
3807            text: text.clone(),
3808            style: layout_style,
3809        };
3810        let fallback_run = TextRun { rect, text, style };
3811
3812        match self.text_system.shape_text_run_persistent(
3813            Some(stable_text_run_handle(&layout_run)),
3814            &layout_run,
3815            self.font_registry.as_ref(),
3816        ) {
3817            Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
3818                ShapedText::new(rect.origin, &layout).with_color(paint_color),
3819            )),
3820            Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
3821        }
3822    }
3823
3824    pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
3825        let persistent = self.text_system.adopt_layout(layout.clone());
3826        self.draw_persistent_text_layout(origin, &persistent);
3827    }
3828
3829    pub fn draw_text_layout_with_color(
3830        &mut self,
3831        origin: Point,
3832        layout: &TextLayout,
3833        color: Color,
3834    ) {
3835        let persistent = self.text_system.adopt_layout(layout.clone());
3836        self.draw_persistent_text_layout_with_color(origin, &persistent, color);
3837    }
3838
3839    pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
3840        self.text_system.touch_persistent_layout(layout);
3841        self.scene
3842            .push(SceneCommand::DrawShapedText(ShapedText::new(
3843                origin, layout,
3844            )));
3845    }
3846
3847    pub fn draw_persistent_text_layout_with_color(
3848        &mut self,
3849        origin: Point,
3850        layout: &PersistentTextLayout,
3851        color: Color,
3852    ) {
3853        self.text_system.touch_persistent_layout(layout);
3854        self.scene.push(SceneCommand::DrawShapedText(
3855            ShapedText::new(origin, layout).with_color(color),
3856        ));
3857    }
3858
3859    pub fn draw_persistent_text_layout_window(
3860        &mut self,
3861        origin: Point,
3862        layout: &PersistentTextLayout,
3863        line_range: std::ops::Range<usize>,
3864    ) {
3865        self.text_system.touch_persistent_layout(layout);
3866        self.scene
3867            .push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
3868                origin, layout, line_range,
3869            )));
3870    }
3871
3872    pub fn draw_persistent_text_layout_window_with_color(
3873        &mut self,
3874        origin: Point,
3875        layout: &PersistentTextLayout,
3876        line_range: std::ops::Range<usize>,
3877        color: Color,
3878    ) {
3879        self.text_system.touch_persistent_layout(layout);
3880        self.scene.push(SceneCommand::DrawShapedTextWindow(
3881            ShapedTextWindow::new(origin, layout, line_range).with_color(color),
3882        ));
3883    }
3884
3885    pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
3886        self.draw_text(rect, text, TextStyle::new(color));
3887    }
3888
3889    pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
3890        self.scene.push(SceneCommand::PushTextRenderPolicy {
3891            policy: policy.normalized(),
3892        });
3893    }
3894
3895    pub fn pop_text_render_policy(&mut self) {
3896        self.scene.push(SceneCommand::PopTextRenderPolicy);
3897    }
3898
3899    pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
3900        self.scene.push(SceneCommand::DrawImage {
3901            rect,
3902            source: ImageSource::new(image),
3903        });
3904    }
3905
3906    pub fn image_registered(&self, image: ImageHandle) -> bool {
3907        self.image_registry.contains(image)
3908            || self.images.iter().any(|(handle, _)| *handle == image)
3909    }
3910
3911    pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
3912        self.scene.push(SceneCommand::DrawImage { rect, source });
3913    }
3914
3915    pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
3916        self.draw_image_quad_source(points, ImageSource::new(image));
3917    }
3918
3919    pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
3920        self.scene
3921            .push(SceneCommand::DrawImageQuad { points, source });
3922    }
3923
3924    pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
3925        let mut hasher = DefaultHasher::new();
3926        self.widget_id.hash(&mut hasher);
3927        slot.hash(&mut hasher);
3928        ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
3929    }
3930
3931    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
3932        self.images.push((handle, PaintImageResource::Cpu(image)));
3933    }
3934
3935    /// Register renderer-neutral metadata for an externally owned image.
3936    ///
3937    /// The active renderer must have a matching backend resource registered
3938    /// for `handle`. The external resource remains app-owned; this only makes
3939    /// its dimensions available to layout and scene construction for the
3940    /// current frame.
3941    pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
3942        self.images
3943            .push((handle, PaintImageResource::External(image)));
3944    }
3945
3946    pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
3947        self.scene
3948            .push(SceneCommand::DrawShaderRect { rect, shader });
3949    }
3950
3951    /// Fill a rounded rectangle (per-corner radii `[tl, tr, br, bl]`) with a brush.
3952    pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
3953        self.scene.push(SceneCommand::FillRoundedRect {
3954            rect,
3955            radii,
3956            brush: brush.into(),
3957            border: None,
3958            shadow: None,
3959        });
3960    }
3961
3962    /// Fill a rounded rectangle with a brush and stroke an inset border.
3963    pub fn fill_rrect_bordered(
3964        &mut self,
3965        rect: Rect,
3966        radii: [f32; 4],
3967        brush: impl Into<Brush>,
3968        border: Border,
3969    ) {
3970        self.scene.push(SceneCommand::FillRoundedRect {
3971            rect,
3972            radii,
3973            brush: brush.into(),
3974            border: Some(border),
3975            shadow: None,
3976        });
3977    }
3978
3979    /// Paint just a soft drop shadow for a rounded rectangle (no fill).
3980    pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
3981        self.scene.push(SceneCommand::FillRoundedRect {
3982            rect,
3983            radii,
3984            brush: Brush::Solid(Color::TRANSPARENT),
3985            border: None,
3986            shadow: Some(shadow),
3987        });
3988    }
3989
3990    /// Fill a rounded rectangle with a brush behind a soft drop shadow.
3991    pub fn fill_rrect_with_shadow(
3992        &mut self,
3993        rect: Rect,
3994        radii: [f32; 4],
3995        brush: impl Into<Brush>,
3996        shadow: ShadowParams,
3997    ) {
3998        self.scene.push(SceneCommand::FillRoundedRect {
3999            rect,
4000            radii,
4001            brush: brush.into(),
4002            border: None,
4003            shadow: Some(shadow),
4004        });
4005    }
4006
4007    pub fn push_clip(&mut self, path: impl Into<Path>) {
4008        self.scene
4009            .push(SceneCommand::PushClipPath { path: path.into() });
4010    }
4011
4012    pub fn push_clip_rect(&mut self, rect: Rect) {
4013        self.scene.push(SceneCommand::PushClip { rect });
4014    }
4015
4016    pub fn pop_clip(&mut self) {
4017        self.scene.push(SceneCommand::PopClip);
4018    }
4019
4020    pub fn push_transform(&mut self, transform: Transform) {
4021        self.scene.push(SceneCommand::PushTransform { transform });
4022    }
4023
4024    /// Paint several retained children or drawing operations under one shared
4025    /// affine transform.
4026    ///
4027    /// Unlike a raw [`Self::push_transform`] call, the nested context also
4028    /// advertises the transformed presentation space to retained child pods.
4029    /// Children arranged with the same presentation transform can therefore
4030    /// append their scenes directly instead of emitting an identical
4031    /// `PushTransform`/`PopTransform` pair for every child. Paint bounds and IME
4032    /// geometry produced inside the callback are mapped back into this
4033    /// context's coordinate space when the group is appended.
4034    pub fn with_transform<R>(
4035        &mut self,
4036        transform: Transform,
4037        paint: impl FnOnce(&mut PaintCtx) -> R,
4038    ) -> R {
4039        let presentation_transform = transform.then(self.presentation_transform);
4040        let mut child_ctx = PaintCtx::new_with_transform(
4041            self.window_id,
4042            self.widget_id,
4043            self.bounds,
4044            self.focused_widget_id,
4045            self.dpi_info,
4046            Arc::clone(&self.text_system),
4047            Arc::clone(&self.font_registry),
4048            Arc::clone(&self.image_registry),
4049            presentation_transform,
4050        )
4051        .with_frame_time(self.frame_time);
4052        let output = paint(&mut child_ctx);
4053        let (scene, images, mut widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4054
4055        if !scene.commands().is_empty() {
4056            self.scene.push(SceneCommand::PushTransform { transform });
4057            self.scene.append(scene);
4058            self.scene.push(SceneCommand::PopTransform);
4059        }
4060        for bounds in widget_paint_bounds.values_mut() {
4061            *bounds = transform.transform_rect_bbox(*bounds);
4062        }
4063        self.extend_widget_paint_bounds(widget_paint_bounds);
4064        self.extend_images(images);
4065        self.extend_ime_composition_rect(
4066            ime_composition_rect.map(|bounds| transform.transform_rect_bbox(bounds)),
4067        );
4068        output
4069    }
4070
4071    pub fn translate(&mut self, delta: Vector) {
4072        self.push_transform(Transform::translation_vector(delta));
4073    }
4074
4075    pub fn pop_transform(&mut self) {
4076        self.scene.push(SceneCommand::PopTransform);
4077    }
4078
4079    pub fn push(&mut self, command: SceneCommand) {
4080        self.scene.push(command);
4081    }
4082
4083    /// Insert a stable retained scene layer owned by another logical widget.
4084    ///
4085    /// Canvas-style containers use this to keep world-space drawing cached
4086    /// beneath a changing outer transform. Reusing `owner` preserves renderer
4087    /// packet identity; changing `scene` still invalidates the packet by its
4088    /// content signature. The owner must be exposed through normal widget
4089    /// visitation so runtime ordering and diagnostics can resolve it.
4090    pub fn push_retained_scene_layer(&mut self, owner: WidgetId, bounds: Rect, scene: Arc<Scene>) {
4091        let content_bounds = scene.content_bounds().unwrap_or(bounds);
4092        let paint_bounds = scene.paint_bounds().unwrap_or(bounds);
4093        let descriptor = SceneLayerDescriptor::new(SceneLayerId::from_widget(owner), owner, bounds)
4094            .with_content_bounds(content_bounds)
4095            .with_paint_bounds(paint_bounds)
4096            .with_hit_test(false);
4097        self.scene
4098            .push(SceneCommand::Layer(SceneLayer::from_shared_descriptor(
4099                descriptor, scene,
4100            )));
4101        self.record_widget_paint_bounds(owner, paint_bounds);
4102    }
4103
4104    /// Paint a logical widget subtree into one retained scene layer.
4105    ///
4106    /// The callback uses the current presentation space, so this composes with
4107    /// [`Self::with_transform`] without repeating the transform in every child.
4108    /// A stable `owner` lets the renderer reuse the layer packet when the
4109    /// callback produces identical scene content on a later frame. Child paint
4110    /// bounds, resource registrations, invalidations, and IME geometry are
4111    /// merged back into this context.
4112    pub fn with_retained_scene_layer<R>(
4113        &mut self,
4114        owner: WidgetId,
4115        bounds: Rect,
4116        paint: impl FnOnce(&mut PaintCtx) -> R,
4117    ) -> R {
4118        let mut child_ctx = PaintCtx::new_with_transform(
4119            self.window_id,
4120            owner,
4121            bounds,
4122            self.focused_widget_id,
4123            self.dpi_info,
4124            Arc::clone(&self.text_system),
4125            Arc::clone(&self.font_registry),
4126            Arc::clone(&self.image_registry),
4127            self.presentation_transform,
4128        )
4129        .with_frame_time(self.frame_time);
4130        child_ctx.output_cache = self.output_cache.clone();
4131        let output = paint(&mut child_ctx);
4132        self.output_reusable &= child_ctx.output_reusable;
4133        let (scene, images, widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4134
4135        if !scene.commands().is_empty() {
4136            self.push_retained_scene_layer(owner, bounds, Arc::new(scene));
4137        }
4138        self.extend_widget_paint_bounds(widget_paint_bounds);
4139        self.extend_images(images);
4140        self.extend_ime_composition_rect(ime_composition_rect);
4141        output
4142    }
4143
4144    pub fn scene(&self) -> &Scene {
4145        &self.scene
4146    }
4147
4148    pub fn scene_mut(&mut self) -> &mut Scene {
4149        &mut self.scene
4150    }
4151
4152    pub fn set_ime_composition_rect(&mut self, rect: Rect) {
4153        self.ime_composition_rect = Some(rect);
4154    }
4155
4156    pub fn clear_ime_composition_rect(&mut self) {
4157        self.ime_composition_rect = None;
4158    }
4159
4160    pub const fn ime_composition_rect(&self) -> Option<Rect> {
4161        self.ime_composition_rect
4162    }
4163
4164    pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
4165        self.scene
4166            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
4167                descriptor, scene,
4168            )));
4169    }
4170
4171    pub(crate) fn append_scene(&mut self, scene: Scene) {
4172        self.scene.append(scene);
4173    }
4174
4175    pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
4176        self.widget_paint_bounds.insert(widget_id, paint_bounds);
4177    }
4178
4179    pub(crate) fn extend_widget_paint_bounds(
4180        &mut self,
4181        widget_paint_bounds: HashMap<WidgetId, Rect>,
4182    ) {
4183        self.widget_paint_bounds.extend(widget_paint_bounds);
4184    }
4185
4186    pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
4187        self.images.extend(images);
4188    }
4189
4190    pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
4191        if ime_composition_rect.is_some() {
4192            self.ime_composition_rect = ime_composition_rect;
4193        }
4194    }
4195
4196    pub(crate) fn into_parts(
4197        self,
4198    ) -> (
4199        Scene,
4200        Vec<(ImageHandle, PaintImageResource)>,
4201        HashMap<WidgetId, Rect>,
4202        Option<Rect>,
4203    ) {
4204        (
4205            self.scene,
4206            self.images,
4207            self.widget_paint_bounds,
4208            self.ime_composition_rect,
4209        )
4210    }
4211}
4212
4213fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
4214    let mut hasher = DefaultHasher::new();
4215    run.text.hash(&mut hasher);
4216    run.rect.size.width.to_bits().hash(&mut hasher);
4217    run.rect.size.height.to_bits().hash(&mut hasher);
4218    run.style.font.map(|font| font.get()).hash(&mut hasher);
4219    run.style.font_size.to_bits().hash(&mut hasher);
4220    run.style.line_height.to_bits().hash(&mut hasher);
4221    run.style.weight.value().hash(&mut hasher);
4222    run.style.style.hash(&mut hasher);
4223    run.style.stretch.hash(&mut hasher);
4224    run.style.features.hash(&mut hasher);
4225    TextLayoutHandle::new(hasher.finish().max(1))
4226}
4227
4228#[derive(Debug, Clone)]
4229pub struct SemanticsCtx {
4230    pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
4231    output_reusable: bool,
4232    window_id: WindowId,
4233    widget_id: WidgetId,
4234    root_widget_id: WidgetId,
4235    focused_widget_id: Option<WidgetId>,
4236    bounds: Rect,
4237    presentation_transform: Transform,
4238    nodes: Vec<SemanticsNode>,
4239}
4240
4241impl SemanticsCtx {
4242    pub(crate) fn new(
4243        window_id: WindowId,
4244        widget_id: WidgetId,
4245        root_widget_id: WidgetId,
4246        bounds: Rect,
4247        focused_widget_id: Option<WidgetId>,
4248    ) -> Self {
4249        Self::new_with_transform(
4250            window_id,
4251            widget_id,
4252            root_widget_id,
4253            bounds,
4254            focused_widget_id,
4255            Transform::IDENTITY,
4256        )
4257    }
4258
4259    pub(crate) fn new_with_transform(
4260        window_id: WindowId,
4261        widget_id: WidgetId,
4262        root_widget_id: WidgetId,
4263        bounds: Rect,
4264        focused_widget_id: Option<WidgetId>,
4265        presentation_transform: Transform,
4266    ) -> Self {
4267        Self {
4268            output_cache: None,
4269            output_reusable: true,
4270            window_id,
4271            widget_id,
4272            root_widget_id,
4273            focused_widget_id,
4274            bounds,
4275            presentation_transform,
4276            nodes: Vec::new(),
4277        }
4278    }
4279
4280    pub const fn window_id(&self) -> WindowId {
4281        self.window_id
4282    }
4283
4284    pub const fn widget_id(&self) -> WidgetId {
4285        self.widget_id
4286    }
4287
4288    /// Read an observable whose changes affect semantics.
4289    pub fn observe<T, O>(&self, observable: &O) -> T
4290    where
4291        O: Observable<T> + ?Sized,
4292    {
4293        self.observe_with(observable, InvalidationKind::Semantics)
4294    }
4295
4296    /// Read an observable and explicitly declare the resulting invalidation.
4297    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
4298    where
4299        O: Observable<T> + ?Sized,
4300    {
4301        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
4302    }
4303
4304    pub const fn root_widget_id(&self) -> WidgetId {
4305        self.root_widget_id
4306    }
4307
4308    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
4309        self.focused_widget_id
4310    }
4311
4312    pub fn is_focused(&self) -> bool {
4313        self.focused_widget_id == Some(self.widget_id)
4314    }
4315
4316    pub const fn bounds(&self) -> Rect {
4317        self.bounds
4318    }
4319
4320    pub const fn presentation_transform(&self) -> Transform {
4321        self.presentation_transform
4322    }
4323
4324    pub fn push(&mut self, node: SemanticsNode) {
4325        self.nodes.push(node);
4326    }
4327
4328    pub fn nodes(&self) -> &[SemanticsNode] {
4329        &self.nodes
4330    }
4331
4332    pub(crate) fn extend_nodes(&mut self, nodes: impl IntoIterator<Item = SemanticsNode>) {
4333        self.nodes.extend(nodes);
4334    }
4335
4336    pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
4337        self.nodes
4338    }
4339}
4340
4341#[cfg(test)]
4342mod tests {
4343    use std::sync::Arc;
4344
4345    use crate::CommandSender;
4346
4347    use super::{
4348        ArrangeCtx, EventCtx, EventPhase, KeyedChildren, MeasureCtx, MeasureScope, PaintCtx,
4349        SemanticsCtx, SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod,
4350        WidgetPodMutVisitor, WidgetPodVisitor, relative_transform,
4351    };
4352    use std::cell::Cell;
4353    use std::collections::{HashMap, HashSet};
4354    use std::rc::Rc;
4355    use sui_core::{
4356        Clipboard, Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode,
4357        SemanticsRole, Size, Transform, Vector, WidgetId, WindowId,
4358    };
4359
4360    #[test]
4361    fn relative_transform_canonicalizes_shared_transform_roundoff() {
4362        let parent = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.0, 510.0);
4363        let roundoff = Transform::new(0.32000002, 0.0, 0.0, 0.31999996, 1430.0001, 509.99994);
4364        assert_eq!(relative_transform(roundoff, parent), Transform::IDENTITY);
4365
4366        let translated = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.01, 510.0);
4367        assert!(!relative_transform(translated, parent).is_identity());
4368    }
4369    use sui_layout::{Constraints, LayoutContext};
4370    use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
4371    use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
4372
4373    fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
4374        MeasureCtx::new(
4375            window_id,
4376            widget_id,
4377            Rect::ZERO,
4378            DpiInfo::default(),
4379            std::sync::Arc::new(TextSystem::new()),
4380            std::sync::Arc::new(FontRegistry::new()),
4381            std::sync::Arc::new(ImageRegistry::new()),
4382        )
4383    }
4384
4385    #[test]
4386    fn measure_ctx_wraps_reusable_layout_context() {
4387        let mut images = ImageRegistry::new();
4388        images.insert(
4389            ImageHandle::new(9),
4390            RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
4391        );
4392        let layout = LayoutContext::new(
4393            DpiInfo::new(
4394                1.5,
4395                Some(144.0),
4396                Size::new(200.0, 100.0),
4397                Size::new(300.0, 150.0),
4398            ),
4399            Arc::new(TextSystem::new()),
4400            Arc::new(FontRegistry::new()),
4401            Arc::new(images),
4402        );
4403
4404        let measure = MeasureCtx::with_layout(
4405            WindowId::new(1),
4406            WidgetId::new(2),
4407            Rect::new(4.0, 6.0, 32.0, 18.0),
4408            layout.clone(),
4409        );
4410
4411        assert_eq!(measure.dpi(), layout.dpi());
4412        assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
4413        assert_eq!(
4414            measure.layout().image_size(ImageHandle::new(9)),
4415            Some(Size::new(3.0, 2.0))
4416        );
4417    }
4418
4419    #[test]
4420    fn measure_and_paint_ctx_expose_dpi_info() {
4421        let dpi = DpiInfo::new(
4422            2.0,
4423            Some(192.0),
4424            sui_core::Size::new(320.0, 180.0),
4425            sui_core::Size::new(640.0, 360.0),
4426        );
4427
4428        let measure = MeasureCtx::new(
4429            WindowId::new(1),
4430            WidgetId::new(2),
4431            Rect::ZERO,
4432            dpi,
4433            std::sync::Arc::new(TextSystem::new()),
4434            std::sync::Arc::new(FontRegistry::new()),
4435            std::sync::Arc::new(ImageRegistry::new()),
4436        );
4437        let paint = PaintCtx::new(
4438            WindowId::new(1),
4439            WidgetId::new(2),
4440            Rect::new(0.0, 0.0, 120.0, 60.0),
4441            None,
4442            dpi,
4443            Arc::new(TextSystem::new()),
4444            Arc::new(FontRegistry::new()),
4445            Arc::new(ImageRegistry::new()),
4446        );
4447        let event = EventCtx::new(
4448            WindowId::new(1),
4449            WidgetId::new(2),
4450            Rect::new(0.0, 0.0, 120.0, 60.0),
4451            dpi,
4452            0.0,
4453            EventPhase::Target,
4454            None,
4455            Clipboard::new(),
4456            CommandSender::new(),
4457        );
4458
4459        assert_eq!(measure.dpi(), dpi);
4460        assert_eq!(paint.dpi(), dpi);
4461        assert_eq!(event.dpi(), dpi);
4462    }
4463
4464    struct LabelWidget;
4465
4466    impl Widget for LabelWidget {
4467        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4468            constraints.clamp(sui_core::Size::new(48.0, 20.0))
4469        }
4470
4471        fn paint(&self, ctx: &mut PaintCtx) {
4472            ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
4473        }
4474
4475        fn semantics(&self, ctx: &mut SemanticsCtx) {
4476            ctx.push(SemanticsNode::new(
4477                ctx.widget_id(),
4478                SemanticsRole::Text,
4479                ctx.bounds(),
4480            ));
4481        }
4482    }
4483
4484    struct BoundsLeaf;
4485
4486    impl Widget for BoundsLeaf {
4487        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4488            constraints.max
4489        }
4490
4491        fn paint(&self, ctx: &mut PaintCtx) {
4492            ctx.fill_rect(
4493                Rect::new(10.0, 10.0, 80.0, 50.0),
4494                Color::rgba(0.2, 0.3, 0.4, 1.0),
4495            );
4496        }
4497    }
4498
4499    struct BoundsWrapper {
4500        child: WidgetPod,
4501        clip: Option<Rect>,
4502        translation: Vector,
4503    }
4504
4505    impl BoundsWrapper {
4506        fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
4507            Self {
4508                child: WidgetPod::new(child),
4509                clip,
4510                translation,
4511            }
4512        }
4513    }
4514
4515    impl Widget for BoundsWrapper {
4516        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4517            self.child.measure(ctx, constraints)
4518        }
4519
4520        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4521            self.child.arrange(ctx, bounds);
4522        }
4523
4524        fn paint(&self, ctx: &mut PaintCtx) {
4525            if let Some(clip) = self.clip {
4526                ctx.push_clip_rect(clip);
4527            }
4528            if self.translation != Vector::ZERO {
4529                ctx.translate(self.translation);
4530            }
4531
4532            self.child.paint(ctx);
4533
4534            if self.translation != Vector::ZERO {
4535                ctx.pop_transform();
4536            }
4537            if self.clip.is_some() {
4538                ctx.pop_clip();
4539            }
4540        }
4541
4542        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4543            visitor.visit(&self.child);
4544        }
4545
4546        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4547            visitor.visit(&mut self.child);
4548        }
4549    }
4550
4551    #[test]
4552    fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
4553        let mut ctx = EventCtx::new(
4554            WindowId::new(1),
4555            WidgetId::new(2),
4556            Rect::new(8.0, 12.0, 24.0, 36.0),
4557            DpiInfo::default(),
4558            0.0,
4559            EventPhase::Target,
4560            None,
4561            Clipboard::new(),
4562            CommandSender::new(),
4563        );
4564
4565        ctx.request_measure();
4566        ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
4567        ctx.request_transform();
4568        ctx.request_effect();
4569        ctx.request_visibility();
4570        ctx.request_animation_frame();
4571        ctx.request_focus();
4572        ctx.set_handled();
4573
4574        assert!(ctx.is_handled());
4575        assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
4576        assert_eq!(ctx.invalidations().len(), 5);
4577        assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
4578        assert_eq!(
4579            ctx.invalidations()[1].region,
4580            Some(Rect::new(8.0, 12.0, 24.0, 36.0))
4581        );
4582        assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
4583        assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
4584        assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
4585        assert_eq!(
4586            ctx.take_wake_requests(),
4587            vec![WakeRequest::RequestAnimationFrame {
4588                target: WidgetId::new(2)
4589            }]
4590        );
4591    }
4592
4593    #[test]
4594    fn request_animation_frame_enqueues_widget_for_next_frame() {
4595        let mut ctx = EventCtx::new(
4596            WindowId::new(4),
4597            WidgetId::new(9),
4598            Rect::new(0.0, 0.0, 20.0, 10.0),
4599            DpiInfo::default(),
4600            16.0,
4601            EventPhase::Target,
4602            None,
4603            Clipboard::new(),
4604            CommandSender::new(),
4605        );
4606
4607        ctx.request_animation_frame();
4608
4609        assert_eq!(
4610            ctx.take_wake_requests(),
4611            vec![WakeRequest::RequestAnimationFrame {
4612                target: WidgetId::new(9)
4613            }]
4614        );
4615    }
4616
4617    struct CountingChild {
4618        measures: Rc<Cell<u32>>,
4619    }
4620
4621    impl Widget for CountingChild {
4622        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4623            self.measures.set(self.measures.get() + 1);
4624            constraints.clamp(sui_core::Size::new(10.0, 10.0))
4625        }
4626    }
4627
4628    struct PassthroughParent {
4629        child: WidgetPod,
4630    }
4631
4632    impl Widget for PassthroughParent {
4633        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4634            self.child.measure(ctx, constraints)
4635        }
4636
4637        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4638            visitor.visit(&self.child);
4639        }
4640
4641        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4642            visitor.visit(&mut self.child);
4643        }
4644    }
4645
4646    fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
4647        MeasureCtx::new_scoped_at(
4648            WindowId::new(1),
4649            root_id,
4650            Rect::ZERO,
4651            DpiInfo::default(),
4652            Arc::new(TextSystem::new()),
4653            Arc::new(FontRegistry::new()),
4654            Arc::new(ImageRegistry::new()),
4655            Rc::new(scope),
4656            0.0,
4657        )
4658    }
4659
4660    #[test]
4661    fn scalar_probes_preserve_final_state_and_have_bounded_storage() {
4662        struct Probe {
4663            calls: Rc<Cell<u32>>,
4664            width: Rc<Cell<f32>>,
4665        }
4666        impl Widget for Probe {
4667            fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
4668                self.calls.set(self.calls.get() + 1);
4669                self.width.set(constraints.max.width);
4670                constraints.clamp(Size::new(30.0, 10.0))
4671            }
4672        }
4673        let calls = Rc::new(Cell::new(0));
4674        let width = Rc::new(Cell::new(0.0));
4675        let mut pod = WidgetPod::new(Probe {
4676            calls: calls.clone(),
4677            width: width.clone(),
4678        });
4679        let root = WidgetId::new(u64::MAX);
4680        let constraint = |width| Constraints::tight(Size::new(width, 10.0));
4681        let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4682        pod.probe_measure(&mut clean, constraint(10.0));
4683        pod.probe_measure(&mut clean, constraint(20.0));
4684        pod.measure(&mut clean, constraint(100.0));
4685        let before = calls.get();
4686        assert_eq!(pod.probe_measure(&mut clean, constraint(10.0)).width, 10.0);
4687        pod.measure(&mut clean, constraint(100.0));
4688        assert_eq!(calls.get(), before);
4689        assert_eq!(width.get(), 100.0);
4690        assert_eq!(pod.measured_size().width, 100.0);
4691        pod.probe_measure(&mut clean, constraint(30.0));
4692        pod.probe_measure(&mut clean, constraint(40.0));
4693        pod.probe_measure(&mut clean, constraint(50.0));
4694        pod.probe_measure(&mut clean, constraint(10.0)); // oldest entry was evicted
4695        assert_eq!(calls.get(), before + 4);
4696        assert_eq!(
4697            pod.probe_cache
4698                .as_ref()
4699                .unwrap()
4700                .measurements
4701                .iter()
4702                .flatten()
4703                .count(),
4704            4
4705        );
4706    }
4707
4708    #[test]
4709    fn size_only_hooks_require_explicit_forwarding_and_final_commit() {
4710        struct Leaf {
4711            queries: Rc<Cell<u32>>,
4712            commits: Rc<Cell<u32>>,
4713            width: Rc<Cell<f32>>,
4714        }
4715        impl Widget for Leaf {
4716            fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4717                self.queries.set(self.queries.get() + 1);
4718                c.clamp(Size::new(20.0, 10.0))
4719            }
4720            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4721                self.commits.set(self.commits.get() + 1);
4722                self.width.set(c.max.width);
4723                c.clamp(Size::new(20.0, 10.0))
4724            }
4725        }
4726        struct Forwarder(WidgetPod);
4727        impl Widget for Forwarder {
4728            fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4729                self.0.probe_measure(ctx, c)
4730            }
4731            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4732                self.0.measure(ctx, c);
4733                self.0.measured_size()
4734            }
4735        }
4736        let queries = Rc::new(Cell::new(0));
4737        let commits = Rc::new(Cell::new(0));
4738        let width = Rc::new(Cell::new(0.0));
4739        let mut pod = WidgetPod::new(Forwarder(WidgetPod::new(Leaf {
4740            queries: queries.clone(),
4741            commits: commits.clone(),
4742            width: width.clone(),
4743        })));
4744        let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4745        let c = Constraints::tight(Size::new(100.0, 10.0));
4746        assert_eq!(pod.probe_measure(&mut ctx, c), c.max);
4747        assert_eq!(queries.get(), 1);
4748        assert_eq!(commits.get(), 0);
4749        assert_eq!(width.get(), 0.0);
4750        assert_eq!(pod.measure(&mut ctx, c), c.max);
4751        assert_eq!(
4752            commits.get(),
4753            1,
4754            "a size probe cannot satisfy final measurement"
4755        );
4756        pod.probe_measure(&mut ctx, Constraints::tight(Size::new(50.0, 10.0)));
4757        pod.measure(&mut ctx, c);
4758        assert_eq!(commits.get(), 2);
4759        assert_eq!(width.get(), 100.0);
4760    }
4761
4762    #[test]
4763    fn default_size_hook_preserves_stateful_child_measure_contract() {
4764        struct Leaf(Rc<Cell<f32>>);
4765        impl Widget for Leaf {
4766            fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4767                Size::new(c.max.width, 10.0)
4768            }
4769            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4770                self.0.set(c.max.width);
4771                Size::new(c.max.width, 10.0)
4772            }
4773        }
4774        struct Legacy {
4775            child: WidgetPod,
4776            width: Rc<Cell<f32>>,
4777        }
4778        impl Widget for Legacy {
4779            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4780                self.child.measure(ctx, c);
4781                // Custom containers can consume state committed by child.measure.
4782                Size::new(self.width.get(), 10.0)
4783            }
4784        }
4785        let width = Rc::new(Cell::new(0.0));
4786        let mut pod = WidgetPod::new(Legacy {
4787            child: WidgetPod::new(Leaf(width.clone())),
4788            width: width.clone(),
4789        });
4790        let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4791        let c = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4792        assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4793        assert_eq!(pod.probe_measure(&mut ctx, c(200.0)).width, 200.0);
4794        assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4795        assert_eq!(pod.measure(&mut ctx, c(100.0)).width, 100.0);
4796        assert_eq!(width.get(), 100.0);
4797    }
4798
4799    #[test]
4800    fn axis_queries_are_distinct_and_invalidate_with_the_window_context() {
4801        use sui_layout::Axis;
4802        struct Leaf(Rc<Cell<u32>>, Rc<Cell<f32>>);
4803        impl Widget for Leaf {
4804            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4805                self.0.set(self.0.get() + 1);
4806                c.clamp(Size::new(self.1.get(), 13.0))
4807            }
4808        }
4809        let calls = Rc::new(Cell::new(0));
4810        let value = Rc::new(Cell::new(27.0));
4811        let mut pod = WidgetPod::new(Leaf(calls.clone(), value.clone()));
4812        let shared = crate::measure_cache::MeasureQueryCache::shared();
4813        let root = WidgetId::new(u64::MAX);
4814        let mut ctx = scoped_measure_ctx(root, MeasureScope::default());
4815        ctx.set_query_cache(shared.clone());
4816        let c = Constraints::new(Size::ZERO, Size::new(100.0, 100.0));
4817        for width in 100..110 {
4818            let c = Constraints::new(Size::ZERO, Size::new(width as f32, 100.0));
4819            assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4820            assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4821            assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4822        }
4823        let before = calls.get();
4824        assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4825        assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4826        assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4827        assert_eq!(
4828            calls.get(),
4829            before,
4830            "overflow hits must preserve query kind"
4831        );
4832        assert_eq!(pod.measure(&mut ctx, c), Size::new(27.0, 13.0));
4833        assert_eq!(calls.get(), before + 1, "axis hits cannot commit layout");
4834        value.set(41.0);
4835        shared.borrow_mut().invalidate_context();
4836        let mut next = scoped_measure_ctx(root, MeasureScope::default());
4837        next.set_query_cache(shared);
4838        assert_eq!(pod.probe_measure_axis(&mut next, c, Axis::Horizontal), 41.0);
4839        assert_eq!(pod.measure(&mut next, c), Size::new(41.0, 13.0));
4840    }
4841
4842    #[test]
4843    fn window_query_cache_reuses_evicted_local_entries_and_respects_all_invalidations() {
4844        struct Leaf(Rc<Cell<f32>>, Rc<Cell<u32>>);
4845        impl Widget for Leaf {
4846            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4847                self.1.set(self.1.get() + 1);
4848                c.clamp(Size::new(self.0.get(), 10.0))
4849            }
4850        }
4851        let value = Rc::new(Cell::new(20.0));
4852        let calls = Rc::new(Cell::new(0));
4853        let mut pod = WidgetPod::new(Leaf(value.clone(), calls.clone()));
4854        let shared = crate::measure_cache::MeasureQueryCache::shared();
4855        let root = WidgetId::new(u64::MAX);
4856        let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4857        clean.set_query_cache(shared.clone());
4858        let constraint = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4859        for width in 100..104 {
4860            pod.probe_measure(&mut clean, constraint(width as f32));
4861        }
4862        for width in 100..104 {
4863            let key = crate::measure_cache::QueryKey::new(
4864                pod.id(),
4865                pod.probe_cache.as_ref().unwrap().revision,
4866                constraint(width as f32),
4867            )
4868            .unwrap();
4869            let mut window = shared.borrow_mut();
4870            let context = window.context();
4871            assert!(
4872                window.get(context, &key).is_none(),
4873                "small query sets should stay in the local cache"
4874            );
4875        }
4876        for width in 104..110 {
4877            pod.probe_measure(&mut clean, constraint(width as f32));
4878        }
4879        let before = calls.get();
4880        assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 20.0);
4881        assert_eq!(
4882            calls.get(),
4883            before,
4884            "the window cache should survive local eviction"
4885        );
4886        value.set(30.0);
4887        let mut dirty = scoped_measure_ctx(
4888            root,
4889            MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4890        );
4891        dirty.set_query_cache(shared.clone());
4892        assert_eq!(pod.probe_measure(&mut dirty, constraint(100.0)).width, 30.0);
4893        pod.measure(&mut clean, constraint(100.0));
4894        value.set(40.0);
4895        shared.borrow_mut().invalidate_context(); // Pod not visited during invalidation.
4896        clean.set_query_cache(shared.clone()); // Start a pass in the new context.
4897        assert_eq!(pod.measure(&mut clean, constraint(100.0)).width, 40.0);
4898        let mut external =
4899            MeasureCtx::with_layout(clean.window_id(), root, Rect::ZERO, clean.layout().clone());
4900        value.set(50.0);
4901        assert_eq!(
4902            pod.probe_measure(&mut external, constraint(100.0)).width,
4903            50.0
4904        );
4905        value.set(60.0);
4906        assert_eq!(
4907            pod.probe_measure(&mut external, constraint(100.0)).width,
4908            60.0
4909        );
4910        assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 60.0);
4911        // Crossing into another window/context also invalidates committed state.
4912        let mut other = scoped_measure_ctx(root, MeasureScope::default());
4913        other.set_query_cache(crate::measure_cache::MeasureQueryCache::shared());
4914        value.set(70.0);
4915        assert_eq!(pod.measure(&mut other, constraint(100.0)).width, 70.0);
4916    }
4917
4918    #[test]
4919    fn probe_invalidation_discards_all_constraints_and_preserves_forced_callbacks() {
4920        struct Probe(Rc<Cell<u32>>);
4921        impl Widget for Probe {
4922            fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4923                self.0.set(self.0.get() + 1);
4924                ctx.request_paint();
4925                ctx.request_animation_frame();
4926                constraints.clamp(Size::new(self.0.get() as f32, 10.0))
4927            }
4928        }
4929        let calls = Rc::new(Cell::new(0));
4930        let mut pod = WidgetPod::new(Probe(calls.clone()));
4931        let root = WidgetId::new(u64::MAX);
4932        let a = Constraints::new(Size::ZERO, Size::new(100.0, 10.0));
4933        let b = Constraints::new(Size::ZERO, Size::new(200.0, 10.0));
4934        let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
4935        pod.probe_measure(&mut initial, a);
4936        pod.probe_measure(&mut initial, b);
4937        let mut dirty = scoped_measure_ctx(
4938            root,
4939            MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4940        );
4941        pod.probe_measure(&mut dirty, a);
4942        pod.measure(&mut dirty, a);
4943        pod.measure(&mut dirty, a);
4944        assert_eq!(
4945            calls.get(),
4946            5,
4947            "forced ordinary callbacks must still execute"
4948        );
4949        assert_eq!(dirty.invalidations.len(), 3);
4950        assert_eq!(dirty.wake_requests.len(), 3);
4951        let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4952        pod.probe_measure(&mut clean, b);
4953        assert_eq!(
4954            calls.get(),
4955            6,
4956            "an unqueried constraint survived invalidation"
4957        );
4958        let mut subtree = scoped_measure_ctx(
4959            root,
4960            MeasureScope::scoped(HashSet::new(), HashSet::from([root])),
4961        );
4962        pod.probe_measure(&mut subtree, b);
4963        assert_eq!(calls.get(), 7);
4964        let mut resized = scoped_measure_ctx(root, MeasureScope::force_all());
4965        pod.probe_measure(&mut resized, b);
4966        assert_eq!(calls.get(), 8);
4967    }
4968
4969    #[test]
4970    fn external_measure_context_keeps_full_measure_semantics_when_reused() {
4971        struct Leaf(Rc<Cell<f32>>);
4972        impl Widget for Leaf {
4973            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4974                c.clamp(Size::new(self.0.get(), 10.0))
4975            }
4976        }
4977        struct Parent(WidgetPod);
4978        impl Widget for Parent {
4979            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4980                let natural = self.0.probe_measure(ctx, Constraints::UNBOUNDED);
4981                self.0.measure(ctx, c);
4982                c.clamp(natural)
4983            }
4984        }
4985        let value = Rc::new(Cell::new(20.0));
4986        let mut pod = WidgetPod::new(Parent(WidgetPod::new(Leaf(value.clone()))));
4987        let root = WidgetId::new(u64::MAX);
4988        let template = scoped_measure_ctx(root, MeasureScope::force_all());
4989        let mut ctx = MeasureCtx::with_layout(
4990            template.window_id(),
4991            root,
4992            Rect::ZERO,
4993            template.layout().clone(),
4994        );
4995        let constraints = Constraints::new(Size::ZERO, Size::new(100.0, 20.0));
4996        assert_eq!(pod.measure(&mut ctx, constraints).width, 20.0);
4997        value.set(40.0);
4998        assert_eq!(pod.measure(&mut ctx, constraints).width, 40.0);
4999    }
5000
5001    #[test]
5002    fn dirty_probes_reuse_results_within_a_pass_but_final_measurement_still_executes() {
5003        let calls = Rc::new(Cell::new(0));
5004        let mut pod = WidgetPod::new(CountingChild {
5005            measures: calls.clone(),
5006        });
5007        let root = WidgetId::new(u64::MAX);
5008        let constraints = Constraints::tight(Size::new(100.0, 10.0));
5009        let mut pass = scoped_measure_ctx(root, MeasureScope::force_all());
5010        pod.probe_measure(&mut pass, constraints);
5011        pod.probe_measure(&mut pass, constraints);
5012        assert_eq!(calls.get(), 1);
5013        pod.measure(&mut pass, constraints);
5014        pod.measure(&mut pass, constraints);
5015        assert_eq!(calls.get(), 3);
5016        pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
5017        pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
5018        assert_eq!(calls.get(), 4);
5019        let mut next = scoped_measure_ctx(root, MeasureScope::force_all());
5020        pod.probe_measure(&mut next, constraints);
5021        assert_eq!(
5022            calls.get(),
5023            5,
5024            "a new dirty pass must invalidate the previous queries"
5025        );
5026    }
5027
5028    #[test]
5029    fn intrinsic_cache_keys_include_axis_and_cross_extent() {
5030        struct Probe(Rc<Cell<u32>>);
5031        impl Widget for Probe {
5032            fn intrinsic_size(
5033                &mut self,
5034                _: &mut MeasureCtx,
5035                axis: sui_layout::Axis,
5036                cross: f32,
5037            ) -> sui_layout::IntrinsicSize {
5038                self.0.set(self.0.get() + 1);
5039                let offset = if axis == sui_layout::Axis::Horizontal {
5040                    1.0
5041                } else {
5042                    2.0
5043                };
5044                sui_layout::IntrinsicSize::fixed(cross + offset)
5045            }
5046        }
5047        let calls = Rc::new(Cell::new(0));
5048        let mut pod = WidgetPod::new(Probe(calls.clone()));
5049        let root = WidgetId::new(u64::MAX);
5050        let mut clean = scoped_measure_ctx(root, MeasureScope::default());
5051        for _ in 0..2 {
5052            assert_eq!(
5053                pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 10.0)
5054                    .natural,
5055                11.0
5056            );
5057            assert_eq!(
5058                pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0)
5059                    .natural,
5060                12.0
5061            );
5062        }
5063        assert_eq!(calls.get(), 2);
5064        assert_eq!(
5065            pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0)
5066                .natural,
5067            21.0
5068        );
5069        assert_eq!(calls.get(), 3);
5070        let mut dirty = scoped_measure_ctx(
5071            root,
5072            MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
5073        );
5074        pod.measure(&mut dirty, Constraints::tight(Size::new(10.0, 10.0)));
5075        pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0);
5076        assert_eq!(
5077            calls.get(),
5078            4,
5079            "ordinary dirty measurement must also clear intrinsic probes"
5080        );
5081    }
5082
5083    #[test]
5084    fn intrinsic_probe_cannot_leave_a_cached_final_layout_in_the_wrong_state() {
5085        struct StatefulMeasure(Rc<Cell<f32>>);
5086        impl Widget for StatefulMeasure {
5087            fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5088                self.0.set(constraints.max.width);
5089                constraints.clamp(Size::new(20.0, 20.0))
5090            }
5091        }
5092        let committed_width = Rc::new(Cell::new(0.0));
5093        let mut pod = WidgetPod::new(StatefulMeasure(committed_width.clone()));
5094        let root = WidgetId::new(u64::MAX);
5095        let final_constraints = Constraints::tight(Size::new(100.0, 20.0));
5096        let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
5097        pod.measure(&mut initial, final_constraints);
5098        let mut clean =
5099            scoped_measure_ctx(root, MeasureScope::scoped(HashSet::new(), HashSet::new()));
5100        pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0);
5101        pod.measure(&mut clean, final_constraints);
5102        assert_eq!(
5103            committed_width.get(),
5104            100.0,
5105            "a scalar cache hit did not restore the final layout state"
5106        );
5107    }
5108
5109    #[test]
5110    fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
5111        let measures = Rc::new(Cell::new(0u32));
5112        let child = WidgetPod::new(CountingChild {
5113            measures: Rc::clone(&measures),
5114        });
5115        let mut parent = WidgetPod::new(PassthroughParent { child });
5116        let parent_id = parent.id();
5117        let outside = WidgetId::new(u64::MAX);
5118        let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
5119
5120        // 1. First pass (force_all) measures everything, populating caches.
5121        let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
5122        parent.measure(&mut ctx, constraints);
5123        assert_eq!(measures.get(), 1, "initial pass must measure the child");
5124
5125        // 2. A pass where nothing is dirty short-circuits the clean parent before
5126        //    it ever recurses, so the child is not re-measured.
5127        let mut ctx = scoped_measure_ctx(
5128            outside,
5129            MeasureScope::scoped(HashSet::new(), HashSet::new()),
5130        );
5131        parent.measure(&mut ctx, constraints);
5132        assert_eq!(measures.get(), 1, "clean subtree must be skipped");
5133
5134        // 3. Re-measuring only the parent (ancestor) without marking it a subtree
5135        //    root recomputes the parent but lets the clean child short-circuit.
5136        let mut dirty = HashSet::new();
5137        dirty.insert(parent_id);
5138        let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
5139        parent.measure(&mut ctx, constraints);
5140        assert_eq!(
5141            measures.get(),
5142            1,
5143            "ancestor-only re-measure must not force the subtree"
5144        );
5145
5146        // 4. Marking the parent a subtree root forces its whole subtree to
5147        //    re-measure even though the child was never individually invalidated.
5148        //    This is the case that the popover/stack-surface regression needed.
5149        let mut dirty = HashSet::new();
5150        dirty.insert(parent_id);
5151        let mut roots = HashSet::new();
5152        roots.insert(parent_id);
5153        let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
5154        parent.measure(&mut ctx, constraints);
5155        assert_eq!(
5156            measures.get(),
5157            2,
5158            "a changed widget must force its descendants to re-measure"
5159        );
5160    }
5161
5162    #[test]
5163    fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
5164        let mut pod = WidgetPod::new(LabelWidget);
5165        pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
5166
5167        let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
5168        let size = pod.measure(
5169            &mut measure,
5170            Constraints::tight(sui_core::Size::new(64.0, 32.0)),
5171        );
5172        let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
5173        pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
5174
5175        let mut paint = PaintCtx::new(
5176            WindowId::new(3),
5177            WidgetId::new(4),
5178            Rect::new(0.0, 0.0, 120.0, 60.0),
5179            None,
5180            DpiInfo::default(),
5181            Arc::new(TextSystem::new()),
5182            Arc::new(FontRegistry::new()),
5183            Arc::new(ImageRegistry::new()),
5184        );
5185        pod.paint(&mut paint);
5186
5187        let mut semantics = SemanticsCtx::new(
5188            WindowId::new(3),
5189            WidgetId::new(4),
5190            WidgetId::new(4),
5191            Rect::new(0.0, 0.0, 120.0, 60.0),
5192            None,
5193        );
5194        pod.semantics(&mut semantics);
5195
5196        assert_eq!(size, sui_core::Size::new(64.0, 32.0));
5197        assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
5198        assert_eq!(paint.scene().commands().len(), 1);
5199        assert!(matches!(
5200            paint.scene().commands()[0],
5201            SceneCommand::FillRect { .. }
5202        ));
5203        assert_eq!(semantics.nodes().len(), 1);
5204    }
5205
5206    #[test]
5207    fn remeasured_subtree_arranges_children_outside_the_dirty_scope() {
5208        let window_id = WindowId::new(1);
5209        let parent_id = WidgetId::new(2);
5210        struct ArrangedBounds(Rc<std::cell::Cell<Rect>>);
5211        impl Widget for ArrangedBounds {
5212            fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5213                constraints.max
5214            }
5215            fn arrange(&mut self, _: &mut ArrangeCtx, bounds: Rect) {
5216                self.0.set(bounds);
5217            }
5218        }
5219        let actual = Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0)));
5220        let mut pod = WidgetPod::new(BoundsWrapper::new(
5221            ArrangedBounds(actual.clone()),
5222            None,
5223            Vector::ZERO,
5224        ));
5225        let mut measure = measure_ctx(window_id, parent_id);
5226        pod.measure(&mut measure, Constraints::tight(Size::new(100.0, 80.0)));
5227        let mut arrange = ArrangeCtx::new(window_id, parent_id, DpiInfo::default());
5228        pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 100.0, 80.0));
5229        // A splitter measures this clean sibling with new constraints. Its own
5230        // ID is deliberately absent from the scoped arrangement invalidation.
5231        pod.measure(&mut measure, Constraints::tight(Size::new(180.0, 80.0)));
5232        let mut arrange = ArrangeCtx::new_scoped_at(
5233            window_id,
5234            parent_id,
5235            DpiInfo::default(),
5236            0.0,
5237            Rc::new(super::ArrangeScope::scoped(
5238                [parent_id].into_iter().collect(),
5239            )),
5240        );
5241        pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 180.0, 80.0));
5242        struct BoundsVisitor(Vec<Rect>);
5243        impl WidgetPodVisitor for BoundsVisitor {
5244            fn visit(&mut self, child: &WidgetPod) {
5245                self.0.push(child.bounds());
5246            }
5247        }
5248        let mut visitor = BoundsVisitor(Vec::new());
5249        pod.visit_children(&mut visitor);
5250        assert_eq!(visitor.0, vec![Rect::new(0.0, 0.0, 180.0, 80.0)]);
5251        assert_eq!(actual.get(), Rect::new(0.0, 0.0, 180.0, 80.0));
5252    }
5253
5254    #[test]
5255    fn single_child_wraps_measure_arrange_and_visitation() {
5256        struct CaptureVisitor {
5257            ids: Vec<WidgetId>,
5258        }
5259
5260        impl WidgetPodVisitor for CaptureVisitor {
5261            fn visit(&mut self, child: &WidgetPod) {
5262                self.ids.push(child.id());
5263            }
5264        }
5265
5266        impl WidgetPodMutVisitor for CaptureVisitor {
5267            fn visit(&mut self, child: &mut WidgetPod) {
5268                self.ids.push(child.id());
5269            }
5270        }
5271
5272        let mut child = SingleChild::new(LabelWidget);
5273        let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
5274        let size = child.measure(
5275            &mut measure,
5276            Constraints::tight(sui_core::Size::new(80.0, 24.0)),
5277        );
5278        let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
5279        child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
5280
5281        let mut visitor = CaptureVisitor { ids: Vec::new() };
5282        child.visit_children(&mut visitor);
5283        child.visit_children_mut(&mut visitor);
5284
5285        assert_eq!(size, sui_core::Size::new(80.0, 24.0));
5286        assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
5287        assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
5288    }
5289
5290    #[test]
5291    fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
5292        let mut children = WidgetChildren::with_capacity(2);
5293        children.push(LabelWidget);
5294        children.push(LabelWidget);
5295
5296        let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
5297        children.measure_child(
5298            0,
5299            &mut measure,
5300            Constraints::tight(sui_core::Size::new(40.0, 18.0)),
5301        );
5302        children.measure_child(
5303            1,
5304            &mut measure,
5305            Constraints::tight(sui_core::Size::new(60.0, 18.0)),
5306        );
5307        let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
5308        children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
5309        children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
5310
5311        let mut paint = PaintCtx::new(
5312            WindowId::new(9),
5313            WidgetId::new(10),
5314            Rect::new(0.0, 0.0, 120.0, 40.0),
5315            None,
5316            DpiInfo::default(),
5317            Arc::new(TextSystem::new()),
5318            Arc::new(FontRegistry::new()),
5319            Arc::new(ImageRegistry::new()),
5320        );
5321        children.paint(&mut paint);
5322
5323        let mut semantics = SemanticsCtx::new(
5324            WindowId::new(9),
5325            WidgetId::new(10),
5326            WidgetId::new(10),
5327            Rect::new(0.0, 0.0, 120.0, 40.0),
5328            None,
5329        );
5330        children.semantics(&mut semantics);
5331
5332        assert_eq!(children.len(), 2);
5333        assert_eq!(paint.scene().commands().len(), 2);
5334        assert_eq!(semantics.nodes().len(), 2);
5335    }
5336
5337    #[test]
5338    fn keyed_children_preserve_pods_and_update_item_signals() {
5339        let mut children = KeyedChildren::<u64, (u64, String)>::new();
5340        let first = children.reconcile(
5341            [(1, "one".to_string()), (2, "two".to_string())],
5342            |item| item.0,
5343            |_key, _value| LabelWidget,
5344        );
5345        assert_eq!(first.inserted, 2);
5346        let first_ids = children
5347            .iter()
5348            .map(|(key, _, child)| (*key, child.id()))
5349            .collect::<HashMap<_, _>>();
5350
5351        let second = children.reconcile(
5352            [
5353                (2, "two updated".to_string()),
5354                (1, "one".to_string()),
5355                (3, "three".to_string()),
5356            ],
5357            |item| item.0,
5358            |_key, _value| LabelWidget,
5359        );
5360        assert_eq!(second.inserted, 1);
5361        assert_eq!(second.removed, 0);
5362        assert_eq!(second.moved, 2);
5363        assert_eq!(second.updated, 1);
5364        assert_eq!(second.unchanged, 1);
5365
5366        let entries = children
5367            .iter()
5368            .map(|(key, value, child)| (*key, value.get(), child.id()))
5369            .collect::<Vec<_>>();
5370        assert_eq!(
5371            entries.iter().map(|(key, _, _)| *key).collect::<Vec<_>>(),
5372            vec![2, 1, 3]
5373        );
5374        assert_eq!(entries[0].1.1, "two updated");
5375        assert_eq!(entries[0].2, first_ids[&2]);
5376        assert_eq!(entries[1].2, first_ids[&1]);
5377    }
5378
5379    #[test]
5380    fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
5381        let inner = BoundsWrapper::new(
5382            BoundsLeaf,
5383            Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
5384            Vector::new(0.0, 7.0),
5385        );
5386        let outer = BoundsWrapper::new(
5387            inner,
5388            Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
5389            Vector::new(5.0, 0.0),
5390        );
5391        // This pass-through level exercises the balanced Scene::append summary path
5392        // after the clipped/transformed child stream has returned to identity state.
5393        let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
5394        let window_id = WindowId::new(17);
5395        let root_id = WidgetId::new(18);
5396        let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
5397        let mut measure = measure_ctx(window_id, root_id);
5398        root.measure(&mut measure, Constraints::tight(bounds.size));
5399        let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
5400        root.arrange(&mut arrange, bounds);
5401
5402        let mut paint = PaintCtx::new(
5403            window_id,
5404            root_id,
5405            bounds,
5406            None,
5407            DpiInfo::default(),
5408            Arc::new(TextSystem::new()),
5409            Arc::new(FontRegistry::new()),
5410            Arc::new(ImageRegistry::new()),
5411        );
5412        root.paint(&mut paint);
5413
5414        assert_eq!(
5415            paint.scene().content_bounds(),
5416            Some(Rect::new(15.0, 17.0, 80.0, 50.0))
5417        );
5418        assert_eq!(
5419            paint.scene().paint_bounds(),
5420            Some(Rect::new(15.0, 17.0, 50.0, 43.0))
5421        );
5422        assert_eq!(
5423            paint.scene().paint_bounds(),
5424            paint.scene().clone().paint_bounds()
5425        );
5426    }
5427
5428    #[test]
5429    fn paint_ctx_emits_extended_scene_commands() {
5430        let mut paint = PaintCtx::new(
5431            WindowId::new(11),
5432            WidgetId::new(12),
5433            Rect::new(0.0, 0.0, 120.0, 60.0),
5434            None,
5435            DpiInfo::default(),
5436            Arc::new(TextSystem::new()),
5437            Arc::new(FontRegistry::new()),
5438            Arc::new(ImageRegistry::new()),
5439        );
5440
5441        let mut path = sui_core::Path::builder();
5442        path.move_to(Point::new(4.0, 5.0))
5443            .line_to(Point::new(24.0, 5.0))
5444            .line_to(Point::new(14.0, 15.0))
5445            .close();
5446        paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
5447        paint.draw_text(
5448            Rect::new(8.0, 10.0, 80.0, 20.0),
5449            "hello",
5450            TextStyle::new(Color::BLACK),
5451        );
5452        paint.draw_image(
5453            Rect::new(0.0, 0.0, 16.0, 16.0),
5454            sui_core::ImageHandle::new(3),
5455        );
5456        paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
5457        paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
5458        paint.translate(Vector::new(3.0, 4.0));
5459        paint.pop_transform();
5460        paint.pop_clip();
5461        paint.pop_clip();
5462
5463        assert!(matches!(
5464            paint.scene().commands()[0],
5465            SceneCommand::StrokePath { .. }
5466        ));
5467        assert!(matches!(
5468            paint.scene().commands()[1],
5469            SceneCommand::DrawShapedText(_)
5470        ));
5471        assert!(matches!(
5472            paint.scene().commands()[2],
5473            SceneCommand::DrawImage { .. }
5474        ));
5475        assert!(matches!(
5476            paint.scene().commands()[3],
5477            SceneCommand::PushClipPath { .. }
5478        ));
5479        assert!(matches!(
5480            paint.scene().commands()[4],
5481            SceneCommand::PushClip { .. }
5482        ));
5483        assert!(matches!(
5484            paint.scene().commands()[5],
5485            SceneCommand::PushTransform { .. }
5486        ));
5487        assert!(matches!(
5488            paint.scene().commands()[6],
5489            SceneCommand::PopTransform
5490        ));
5491        assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
5492        assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
5493    }
5494
5495    #[test]
5496    fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
5497        let run = TextRun {
5498            rect: Rect::new(8.0, 10.0, 80.0, 20.0),
5499            text: "hello".to_string(),
5500            style: TextStyle::new(Color::BLACK),
5501        };
5502        let mut recolored = run.clone();
5503        recolored.style.color = Color::WHITE;
5504        let mut bold = run.clone();
5505        bold.style.weight = FontWeight::BOLD;
5506
5507        assert_eq!(
5508            super::stable_text_run_handle(&run),
5509            super::stable_text_run_handle(&recolored)
5510        );
5511        assert_ne!(
5512            super::stable_text_run_handle(&run),
5513            super::stable_text_run_handle(&bold)
5514        );
5515    }
5516
5517    #[test]
5518    fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
5519        let text_system = Arc::new(TextSystem::new());
5520        let mut paint = PaintCtx::new(
5521            WindowId::new(12),
5522            WidgetId::new(13),
5523            Rect::new(0.0, 0.0, 120.0, 60.0),
5524            None,
5525            DpiInfo::default(),
5526            Arc::clone(&text_system),
5527            Arc::new(FontRegistry::new()),
5528            Arc::new(ImageRegistry::new()),
5529        );
5530        let paint_color = Color::BLACK;
5531        paint.draw_text(
5532            Rect::new(8.0, 10.0, 80.0, 20.0),
5533            "hello",
5534            TextStyle::new(paint_color),
5535        );
5536
5537        let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
5538            panic!("draw_text should emit shaped text when layout succeeds");
5539        };
5540        assert_eq!(text.color_override, Some(paint_color));
5541
5542        let registry = text_system.text_layout_registry();
5543        let layout = text
5544            .resolve(registry.as_ref())
5545            .expect("drawn shaped text should resolve from the registry");
5546        assert_eq!(layout.style().color, Color::WHITE);
5547    }
5548
5549    #[test]
5550    fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
5551        let text_system = Arc::new(TextSystem::new());
5552        let layout = text_system
5553            .shape_text_persistent(
5554                None,
5555                "held",
5556                Size::new(80.0, 20.0),
5557                TextStyle::new(Color::WHITE),
5558                &FontRegistry::new(),
5559            )
5560            .unwrap();
5561        text_system.retain_persistent_layouts(&std::collections::HashSet::new());
5562        assert!(!text_system.text_layout_registry().contains(layout.handle()));
5563
5564        let mut paint = PaintCtx::new(
5565            WindowId::new(12),
5566            WidgetId::new(13),
5567            Rect::new(0.0, 0.0, 120.0, 60.0),
5568            None,
5569            DpiInfo::default(),
5570            Arc::clone(&text_system),
5571            Arc::new(FontRegistry::new()),
5572            Arc::new(ImageRegistry::new()),
5573        );
5574        paint.draw_persistent_text_layout(Point::ZERO, &layout);
5575
5576        assert!(text_system.text_layout_registry().contains(layout.handle()));
5577        assert!(matches!(
5578            paint.scene().commands()[0],
5579            SceneCommand::DrawShapedText(_)
5580        ));
5581    }
5582
5583    #[test]
5584    fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
5585        let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
5586            .layout()
5587            .shape_text(
5588                "hello",
5589                sui_core::Size::new(80.0, 20.0),
5590                TextStyle::new(Color::BLACK),
5591            )
5592            .unwrap();
5593
5594        let mut paint = PaintCtx::new(
5595            WindowId::new(13),
5596            WidgetId::new(14),
5597            Rect::new(0.0, 0.0, 120.0, 60.0),
5598            None,
5599            DpiInfo::default(),
5600            Arc::new(TextSystem::new()),
5601            Arc::new(FontRegistry::new()),
5602            Arc::new(ImageRegistry::new()),
5603        );
5604        let origin = Point::new(8.0, 10.0);
5605        paint.draw_text_layout(origin, &layout);
5606        paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
5607
5608        assert!(matches!(
5609            paint.scene().commands()[0],
5610            SceneCommand::DrawShapedText(_)
5611        ));
5612        assert!(paint.ime_composition_rect().is_some());
5613        assert!(!layout.selection_rects(1..4).is_empty());
5614    }
5615}