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