Skip to main content

sui_runtime/
widget.rs

1#![allow(clippy::too_many_arguments, clippy::type_complexity)]
2
3use std::{
4    collections::{HashMap, HashSet, hash_map::DefaultHasher},
5    hash::{Hash, Hasher},
6    rc::Rc,
7    sync::{
8        Arc, Mutex,
9        atomic::{AtomicU64, Ordering},
10    },
11};
12
13use crate::{
14    Command, CommandDelivery, CommandKey, CommandSender, CommandTarget,
15    command::{QueuedCommand, queued_command},
16    diagnostics::{WidgetTimingPhase, record_widget_timing},
17    overlay::OverlayOptions,
18};
19
20use sui_core::{
21    AsyncWakeToken, Clipboard, Color, DpiInfo, DragPayload, DragScopeId, DragSessionId, DropEffect,
22    Event, ImageHandle, InvalidationKind, InvalidationRequest, InvalidationTarget, Path, Point,
23    Rect, SemanticsNode, Size, TimerToken, Transform, Vector, WakeEvent, WidgetId, WindowId,
24};
25use sui_layout::{Axis, Constraints, IntrinsicSize, LayoutContext};
26use sui_reactive::{Observable, Signal};
27use sui_scene::{
28    Border, Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
29    RegisteredExternalImage, RegisteredImage, Scene, SceneCommand, SceneLayer,
30    SceneLayerDescriptor, SceneLayerId, ShadowParams, StrokeStyle, TextRenderPolicy, WidgetShader,
31};
32use sui_text::{
33    FontRegistry, PersistentTextLayout, ShapedText, ShapedTextWindow, TextLayout, TextLayoutHandle,
34    TextLayoutRequest, TextMeasurement, TextRun, TextStyle, TextSystem,
35};
36use web_time::Instant;
37
38static NEXT_WIDGET_ID: AtomicU64 = AtomicU64::new(1);
39static NEXT_TIMER_TOKEN: AtomicU64 = AtomicU64::new(1);
40static NEXT_ASYNC_WAKE_TOKEN: AtomicU64 = AtomicU64::new(1);
41static NEXT_DRAG_SESSION_ID: AtomicU64 = AtomicU64::new(1);
42const WIDGET_IMAGE_HANDLE_NAMESPACE: u64 = 1 << 63;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum EventPhase {
46    Capture,
47    Target,
48    Bubble,
49}
50
51pub trait WidgetPodVisitor {
52    fn visit(&mut self, child: &WidgetPod);
53}
54
55pub trait WidgetPodMutVisitor {
56    fn visit(&mut self, child: &mut WidgetPod);
57}
58
59/// One opt-in diagnostic value published by a widget for live inspection.
60///
61/// Values are deliberately presentation-neutral strings. Widgets should expose
62/// compact operational state here (cache sizes, visible ranges, parser
63/// revisions, and similar data), never user content or other sensitive data.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct WidgetDiagnostic {
66    pub name: String,
67    pub value: String,
68}
69
70/// Collector passed to [`Widget::diagnostics`].
71#[derive(Debug, Default)]
72pub struct WidgetDiagnosticsCtx {
73    entries: Vec<WidgetDiagnostic>,
74}
75
76impl WidgetDiagnosticsCtx {
77    pub fn record(&mut self, name: impl Into<String>, value: impl Into<String>) {
78        self.entries.push(WidgetDiagnostic {
79            name: name.into(),
80            value: value.into(),
81        });
82    }
83
84    fn into_entries(self) -> Vec<WidgetDiagnostic> {
85        self.entries
86    }
87}
88
89/// On-demand widget-specific state included in an inspector snapshot.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct WidgetDiagnosticsSnapshot {
92    pub widget_id: WidgetId,
93    pub widget_name: &'static str,
94    pub entries: Vec<WidgetDiagnostic>,
95}
96
97pub trait Widget {
98    fn event(&mut self, _ctx: &mut EventCtx, _event: &Event) {}
99
100    /// Receive a typed command addressed directly to this widget. Commands are
101    /// target-only and do not capture or bubble through the widget tree.
102    fn command(&mut self, _ctx: &mut EventCtx, _command: &Command<'_>) {}
103
104    fn debug_name(&self) -> &'static str {
105        std::any::type_name::<Self>()
106    }
107
108    /// Publish widget-specific state for an inspector snapshot.
109    ///
110    /// The runtime only calls this while explicitly capturing a snapshot, so
111    /// normal event, layout, and paint passes pay no cost for this hook.
112    fn diagnostics(&self, _ctx: &mut WidgetDiagnosticsCtx) {}
113
114    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
115        constraints.max
116    }
117
118    /// Report the smallest and preferred extent along one axis.
119    ///
120    /// The conservative default treats the ordinary natural measurement as
121    /// unbreakable. Text and other shrinkable widgets can override this to
122    /// expose a smaller minimum without changing the normal measure contract.
123    fn intrinsic_size(
124        &mut self,
125        ctx: &mut MeasureCtx,
126        axis: Axis,
127        available_cross: f32,
128    ) -> IntrinsicSize {
129        let cross = if available_cross.is_finite() {
130            available_cross.max(0.0)
131        } else {
132            f32::INFINITY
133        };
134        let constraints = match axis {
135            Axis::Horizontal => Constraints::new(Size::ZERO, Size::new(f32::INFINITY, cross)),
136            Axis::Vertical => Constraints::new(Size::ZERO, Size::new(cross, f32::INFINITY)),
137        };
138        let size = self.measure(ctx, constraints);
139        IntrinsicSize::fixed(match axis {
140            Axis::Horizontal => size.width,
141            Axis::Vertical => size.height,
142        })
143    }
144
145    fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
146
147    fn paint(&self, _ctx: &mut PaintCtx) {}
148
149    fn layer_options(&self) -> LayerOptions {
150        LayerOptions::default()
151    }
152
153    fn layer_properties(&self) -> LayerProperties {
154        LayerProperties::default()
155    }
156
157    fn stack_host_options(&self) -> Option<StackHostOptions> {
158        None
159    }
160
161    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
162        None
163    }
164
165    /// Describe this widget as the logical owner of a presented overlay.
166    ///
167    /// The overlay's rendered surfaces may be retained descendants. Returning
168    /// options here lets the window runtime coordinate nesting, focus,
169    /// dismissal, modality, and diagnostics independently of paint ownership.
170    fn overlay_options(&self) -> Option<OverlayOptions> {
171        None
172    }
173
174    fn semantics(&self, _ctx: &mut SemanticsCtx) {}
175
176    fn accepts_focus(&self) -> bool {
177        false
178    }
179
180    fn focus_changed(&mut self, _ctx: &mut EventCtx, _focused: bool) {}
181
182    /// Visit this widget's logical children.
183    ///
184    /// The children do not need to correspond to every piece of state or every
185    /// visual element a widget owns internally. A widget may expose retained
186    /// local children, generated/virtual children, remote children represented
187    /// by local pods, or only the subset that should cooperate with the SUI
188    /// runtime for this pass.
189    fn visit_children(&self, _visitor: &mut dyn WidgetPodVisitor) {}
190
191    /// Mutably visit this widget's logical children.
192    ///
193    /// This is the mutable counterpart to [`Widget::visit_children`]; SUI uses
194    /// it as a cooperation point for the retained runtime, not as ownership of
195    /// a widget's complete internal model.
196    fn visit_children_mut(&mut self, _visitor: &mut dyn WidgetPodMutVisitor) {}
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub enum PaintBoundaryMode {
201    Flat,
202    Explicit,
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub struct LayerOptions {
207    pub paint_boundary: PaintBoundaryMode,
208    pub composition_mode: LayerCompositionMode,
209}
210
211impl LayerOptions {
212    pub const fn emits_layer(self) -> bool {
213        matches!(self.paint_boundary, PaintBoundaryMode::Explicit)
214    }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum StackOrderPolicy {
219    Stable,
220    FocusFronted,
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224pub struct StackHostOptions {
225    pub order_policy: StackOrderPolicy,
226}
227
228impl Default for StackHostOptions {
229    fn default() -> Self {
230        Self {
231            order_policy: StackOrderPolicy::Stable,
232        }
233    }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub struct StackSurfaceOptions {
238    pub dynamic_ordering: bool,
239    pub transient: bool,
240    pub hit_test: bool,
241}
242
243impl Default for StackSurfaceOptions {
244    fn default() -> Self {
245        Self {
246            dynamic_ordering: true,
247            transient: false,
248            hit_test: true,
249        }
250    }
251}
252
253impl Default for LayerOptions {
254    fn default() -> Self {
255        Self {
256            paint_boundary: PaintBoundaryMode::Flat,
257            composition_mode: LayerCompositionMode::Normal,
258        }
259    }
260}
261
262pub struct SingleChild {
263    child: WidgetPod,
264}
265
266impl SingleChild {
267    pub fn new<W>(child: W) -> Self
268    where
269        W: Widget + 'static,
270    {
271        Self::from_pod(WidgetPod::new(child))
272    }
273
274    /// Creates a child whose scene is retained behind an explicit paint boundary.
275    ///
276    /// This is useful for containers that move their complete child subtree as a
277    /// unit. The child's own composition mode and layer properties are preserved;
278    /// only a flat paint boundary is promoted to an explicit one.
279    pub fn new_with_paint_boundary<W>(child: W) -> Self
280    where
281        W: Widget + 'static,
282    {
283        let mut child = WidgetPod::new(child);
284        child.force_paint_boundary = true;
285        Self::from_pod(child)
286    }
287
288    /// Returns this child wrapper with an explicit paint boundary forced on.
289    /// The consuming form keeps layer-topology changes in builder flows.
290    pub fn with_paint_boundary(mut self) -> Self {
291        self.child.force_paint_boundary = true;
292        self
293    }
294
295    pub fn from_pod(child: WidgetPod) -> Self {
296        Self { child }
297    }
298
299    pub fn child(&self) -> &WidgetPod {
300        &self.child
301    }
302
303    pub fn child_mut(&mut self) -> &mut WidgetPod {
304        &mut self.child
305    }
306
307    pub fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
308        self.child.measure(ctx, constraints)
309    }
310
311    pub fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
312        self.child.arrange(ctx, bounds);
313    }
314
315    pub fn set_bounds(&mut self, bounds: Rect) {
316        self.child.set_bounds(bounds);
317    }
318
319    pub fn paint(&self, ctx: &mut PaintCtx) {
320        self.child.paint(ctx);
321    }
322
323    pub fn semantics(&self, ctx: &mut SemanticsCtx) {
324        self.child.semantics(ctx);
325    }
326
327    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
328        visitor.visit(&self.child);
329    }
330
331    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
332        visitor.visit(&mut self.child);
333    }
334}
335
336#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
337pub enum FocusRestorePolicy {
338    /// Restore only a descendant that previously held focus.
339    LastFocused,
340    /// Focus the first currently mounted focusable descendant.
341    FirstFocusable,
342    /// Prefer the last focused descendant, falling back to the first focusable one.
343    #[default]
344    LastFocusedOrFirstFocusable,
345}
346
347#[derive(Debug, Default)]
348struct FocusScopeStateInner {
349    last_focused: Option<WidgetId>,
350    restore_requested: bool,
351}
352
353/// Shared retained focus history for a [`FocusScope`].
354///
355/// Presentation policies call [`Self::request_restore`] when a previously
356/// hidden pane or route becomes visible. The associated scope performs the
357/// focus change on its next runtime wake without rebuilding its child subtree.
358#[derive(Clone, Debug)]
359pub struct FocusScopeState {
360    inner: Arc<Mutex<FocusScopeStateInner>>,
361    restore_revision: Signal<u64>,
362}
363
364impl FocusScopeState {
365    pub fn new() -> Self {
366        Self {
367            inner: Arc::new(Mutex::new(FocusScopeStateInner::default())),
368            restore_revision: Signal::named("FocusScopeState::restore", 0),
369        }
370    }
371
372    pub fn last_focused(&self) -> Option<WidgetId> {
373        self.lock_inner().last_focused
374    }
375
376    pub fn request_restore(&self) -> bool {
377        let changed = {
378            let mut inner = self.lock_inner();
379            if inner.restore_requested {
380                false
381            } else {
382                inner.restore_requested = true;
383                true
384            }
385        };
386        if changed {
387            self.restore_revision
388                .update(|revision| *revision = revision.wrapping_add(1));
389        }
390        changed
391    }
392
393    pub fn clear(&self) {
394        let restore_was_requested = {
395            let mut inner = self.lock_inner();
396            let restore_was_requested = inner.restore_requested;
397            inner.last_focused = None;
398            inner.restore_requested = false;
399            restore_was_requested
400        };
401        if restore_was_requested {
402            self.restore_revision
403                .update(|revision| *revision = revision.wrapping_add(1));
404        }
405    }
406
407    fn remember(&self, widget_id: WidgetId) {
408        self.lock_inner().last_focused = Some(widget_id);
409    }
410
411    fn restore_requested(&self) -> bool {
412        self.lock_inner().restore_requested
413    }
414
415    fn complete_restore(&self) {
416        self.lock_inner().restore_requested = false;
417    }
418
419    fn lock_inner(&self) -> std::sync::MutexGuard<'_, FocusScopeStateInner> {
420        self.inner
421            .lock()
422            .unwrap_or_else(std::sync::PoisonError::into_inner)
423    }
424}
425
426impl Default for FocusScopeState {
427    fn default() -> Self {
428        Self::new()
429    }
430}
431
432/// Retains focus history for a stable child subtree.
433///
434/// The scope does not impose visibility or navigation behavior. Adaptive
435/// containers keep the scope and its child mounted, then request restoration
436/// through [`FocusScopeState`] when the subtree is presented again.
437pub struct FocusScope {
438    state: FocusScopeState,
439    restore_policy: FocusRestorePolicy,
440    child: SingleChild,
441}
442
443impl FocusScope {
444    pub fn new<W>(child: W) -> Self
445    where
446        W: Widget + 'static,
447    {
448        Self {
449            state: FocusScopeState::new(),
450            restore_policy: FocusRestorePolicy::default(),
451            child: SingleChild::new(child),
452        }
453    }
454
455    pub fn state(mut self, state: FocusScopeState) -> Self {
456        self.state = state;
457        self
458    }
459
460    pub fn restore_policy(mut self, restore_policy: FocusRestorePolicy) -> Self {
461        self.restore_policy = restore_policy;
462        self
463    }
464
465    pub fn child(&self) -> &WidgetPod {
466        self.child.child()
467    }
468
469    pub fn child_mut(&mut self) -> &mut WidgetPod {
470        self.child.child_mut()
471    }
472
473    fn restore_target(&self) -> Option<WidgetId> {
474        let last_focused = self
475            .state
476            .last_focused()
477            .filter(|target| pod_contains(self.child.child(), *target));
478        match self.restore_policy {
479            FocusRestorePolicy::LastFocused => last_focused,
480            FocusRestorePolicy::FirstFocusable => first_focusable(self.child.child()),
481            FocusRestorePolicy::LastFocusedOrFirstFocusable => {
482                last_focused.or_else(|| first_focusable(self.child.child()))
483            }
484        }
485    }
486
487    fn remember_current_focus(&self, focused_widget_id: Option<WidgetId>) {
488        if let Some(focused) = focused_widget_id
489            && pod_contains(self.child.child(), focused)
490        {
491            self.state.remember(focused);
492        }
493    }
494}
495
496impl Widget for FocusScope {
497    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
498        self.remember_current_focus(ctx.focused_widget_id());
499        if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. }))
500            && self.state.restore_requested()
501        {
502            let target = self.restore_target();
503            self.state.complete_restore();
504            if let Some(target) = target {
505                ctx.request_focus_for(target);
506                ctx.request_paint();
507                ctx.request_semantics();
508                ctx.set_handled();
509            }
510        }
511    }
512
513    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
514        let _ = ctx.observe(&self.state.restore_revision);
515        if self.state.restore_requested() {
516            ctx.request_animation_frame();
517        }
518        self.child.measure(ctx, constraints)
519    }
520
521    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
522        self.child.arrange(ctx, bounds);
523    }
524
525    fn paint(&self, ctx: &mut PaintCtx) {
526        self.remember_current_focus(ctx.focused_widget_id());
527        self.child.paint(ctx);
528    }
529
530    fn semantics(&self, ctx: &mut SemanticsCtx) {
531        self.remember_current_focus(ctx.focused_widget_id());
532        self.child.semantics(ctx);
533    }
534
535    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
536        self.child.visit_children(visitor);
537    }
538
539    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
540        self.child.visit_children_mut(visitor);
541    }
542}
543
544fn pod_contains(root: &WidgetPod, target: WidgetId) -> bool {
545    if root.id() == target {
546        return true;
547    }
548
549    struct Finder {
550        target: WidgetId,
551        found: bool,
552    }
553
554    impl WidgetPodVisitor for Finder {
555        fn visit(&mut self, child: &WidgetPod) {
556            if self.found {
557                return;
558            }
559            if child.id() == self.target {
560                self.found = true;
561            } else {
562                child.visit_children(self);
563            }
564        }
565    }
566
567    let mut finder = Finder {
568        target,
569        found: false,
570    };
571    root.visit_children(&mut finder);
572    finder.found
573}
574
575fn first_focusable(root: &WidgetPod) -> Option<WidgetId> {
576    if root.accepts_focus() {
577        return Some(root.id());
578    }
579
580    struct Finder {
581        target: Option<WidgetId>,
582    }
583
584    impl WidgetPodVisitor for Finder {
585        fn visit(&mut self, child: &WidgetPod) {
586            if self.target.is_some() {
587                return;
588            }
589            if child.accepts_focus() {
590                self.target = Some(child.id());
591            } else {
592                child.visit_children(self);
593            }
594        }
595    }
596
597    let mut finder = Finder { target: None };
598    root.visit_children(&mut finder);
599    finder.target
600}
601
602#[derive(Default)]
603pub struct WidgetChildren {
604    children: Vec<WidgetPod>,
605}
606
607impl WidgetChildren {
608    pub fn new() -> Self {
609        Self::default()
610    }
611
612    pub fn with_capacity(capacity: usize) -> Self {
613        Self {
614            children: Vec::with_capacity(capacity),
615        }
616    }
617
618    pub fn push<W>(&mut self, child: W)
619    where
620        W: Widget + 'static,
621    {
622        self.push_pod(WidgetPod::new(child));
623    }
624
625    pub fn push_pod(&mut self, child: WidgetPod) {
626        self.children.push(child);
627    }
628
629    pub fn len(&self) -> usize {
630        self.children.len()
631    }
632
633    pub fn is_empty(&self) -> bool {
634        self.children.is_empty()
635    }
636
637    pub fn as_slice(&self) -> &[WidgetPod] {
638        &self.children
639    }
640
641    pub fn as_mut_slice(&mut self) -> &mut [WidgetPod] {
642        &mut self.children
643    }
644
645    pub fn measure_child(
646        &mut self,
647        index: usize,
648        ctx: &mut MeasureCtx,
649        constraints: Constraints,
650    ) -> Size {
651        self.children[index].measure(ctx, constraints)
652    }
653
654    pub fn intrinsic_size_child(
655        &mut self,
656        index: usize,
657        ctx: &mut MeasureCtx,
658        axis: Axis,
659        available_cross: f32,
660    ) -> IntrinsicSize {
661        self.children[index].intrinsic_size(ctx, axis, available_cross)
662    }
663
664    pub fn arrange_child(&mut self, index: usize, ctx: &mut ArrangeCtx, bounds: Rect) {
665        self.children[index].arrange(ctx, bounds);
666    }
667
668    pub fn paint(&self, ctx: &mut PaintCtx) {
669        for child in &self.children {
670            child.paint(ctx);
671        }
672    }
673
674    pub fn semantics(&self, ctx: &mut SemanticsCtx) {
675        for child in &self.children {
676            child.semantics(ctx);
677        }
678    }
679
680    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
681        for child in &self.children {
682            visitor.visit(child);
683        }
684    }
685
686    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
687        for child in &mut self.children {
688            visitor.visit(child);
689        }
690    }
691}
692
693#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
694pub struct KeyedReconcile {
695    pub inserted: usize,
696    pub removed: usize,
697    pub moved: usize,
698    pub updated: usize,
699    pub unchanged: usize,
700    pub duplicate_keys: usize,
701}
702
703struct KeyedChild<K, T> {
704    key: K,
705    value: Signal<T>,
706    child: WidgetPod,
707}
708
709/// Layout-neutral retained child collection reconciled by stable application
710/// keys.
711///
712/// Existing [`WidgetPod`] instances are moved rather than recreated. Each
713/// child also receives a per-item [`Signal`] so changing item data can update
714/// the retained widget without replacing it.
715pub struct KeyedChildren<K, T> {
716    entries: Vec<KeyedChild<K, T>>,
717}
718
719impl<K, T> KeyedChildren<K, T> {
720    pub const fn new() -> Self {
721        Self {
722            entries: Vec::new(),
723        }
724    }
725
726    pub fn len(&self) -> usize {
727        self.entries.len()
728    }
729
730    pub fn is_empty(&self) -> bool {
731        self.entries.is_empty()
732    }
733
734    pub fn iter(&self) -> impl Iterator<Item = (&K, &Signal<T>, &WidgetPod)> {
735        self.entries
736            .iter()
737            .map(|entry| (&entry.key, &entry.value, &entry.child))
738    }
739
740    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &Signal<T>, &mut WidgetPod)> {
741        self.entries
742            .iter_mut()
743            .map(|entry| (&entry.key, &entry.value, &mut entry.child))
744    }
745
746    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
747        for entry in &self.entries {
748            visitor.visit(&entry.child);
749        }
750    }
751
752    pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
753        for entry in &mut self.entries {
754            visitor.visit(&mut entry.child);
755        }
756    }
757}
758
759impl<K, T> KeyedChildren<K, T>
760where
761    K: Clone + Eq + Hash,
762    T: Clone + PartialEq + 'static,
763{
764    pub fn reconcile<I, KF, B, W>(
765        &mut self,
766        items: I,
767        mut key_for: KF,
768        mut build: B,
769    ) -> KeyedReconcile
770    where
771        I: IntoIterator<Item = T>,
772        KF: FnMut(&T) -> K,
773        B: FnMut(&K, Signal<T>) -> W,
774        W: Widget + 'static,
775    {
776        let previous_len = self.entries.len();
777        let mut previous = std::mem::take(&mut self.entries)
778            .into_iter()
779            .enumerate()
780            .map(|(index, entry)| (entry.key.clone(), (index, entry)))
781            .collect::<HashMap<_, _>>();
782        let mut seen = HashSet::new();
783        let mut next = Vec::new();
784        let mut report = KeyedReconcile::default();
785
786        for item in items {
787            let key = key_for(&item);
788            if !seen.insert(key.clone()) {
789                report.duplicate_keys += 1;
790                continue;
791            }
792
793            let next_index = next.len();
794            if let Some((previous_index, entry)) = previous.remove(&key) {
795                if previous_index != next_index {
796                    report.moved += 1;
797                }
798                if entry.value.set(item) {
799                    report.updated += 1;
800                } else {
801                    report.unchanged += 1;
802                }
803                next.push(entry);
804            } else {
805                let value = Signal::named("Keyed item", item);
806                let child = WidgetPod::new(build(&key, value.clone()));
807                next.push(KeyedChild { key, value, child });
808                report.inserted += 1;
809            }
810        }
811
812        report.removed = previous.len();
813        debug_assert_eq!(previous_len + report.inserted, next.len() + report.removed);
814        self.entries = next;
815        report
816    }
817}
818
819impl<K, T> Default for KeyedChildren<K, T> {
820    fn default() -> Self {
821        Self::new()
822    }
823}
824
825/// Standard retained-widget adapter used by the SUI runtime.
826///
827/// `WidgetPod` gives a `Widget` stable identity, cached layout state, event
828/// routing participation, and scene/semantics cooperation. It is the default
829/// local retained model, but a widget's own internals may still use custom
830/// state, virtualization, worker threads, or remote systems before rejoining
831/// SUI through widget contexts and scene output.
832pub struct WidgetPod {
833    id: WidgetId,
834    layout_state: LayoutState,
835    force_paint_boundary: bool,
836    widget: Box<dyn Widget>,
837}
838
839impl Drop for WidgetPod {
840    fn drop(&mut self) {
841        crate::reactive::clear_widget(self.id);
842    }
843}
844
845#[derive(Debug, Clone, Copy, PartialEq)]
846struct LayoutState {
847    measured_size: Size,
848    arranged_bounds: Rect,
849    last_constraints: Constraints,
850    measure_valid: bool,
851    arrange_valid: bool,
852}
853
854impl Default for LayoutState {
855    fn default() -> Self {
856        Self {
857            measured_size: Size::ZERO,
858            arranged_bounds: Rect::ZERO,
859            last_constraints: Constraints::default(),
860            measure_valid: false,
861            arrange_valid: false,
862        }
863    }
864}
865
866impl WidgetPod {
867    pub fn new<W>(widget: W) -> Self
868    where
869        W: Widget + 'static,
870    {
871        Self {
872            id: WidgetId::new(NEXT_WIDGET_ID.fetch_add(1, Ordering::Relaxed)),
873            layout_state: LayoutState::default(),
874            force_paint_boundary: false,
875            widget: Box::new(widget),
876        }
877    }
878
879    pub const fn id(&self) -> WidgetId {
880        self.id
881    }
882
883    pub fn debug_name(&self) -> &'static str {
884        self.widget.debug_name()
885    }
886
887    pub fn diagnostics_snapshot(&self) -> WidgetDiagnosticsSnapshot {
888        let mut ctx = WidgetDiagnosticsCtx::default();
889        self.widget.diagnostics(&mut ctx);
890        WidgetDiagnosticsSnapshot {
891            widget_id: self.id,
892            widget_name: self.widget.debug_name(),
893            entries: ctx.into_entries(),
894        }
895    }
896
897    pub fn collect_diagnostics(&self, output: &mut Vec<WidgetDiagnosticsSnapshot>) {
898        let snapshot = self.diagnostics_snapshot();
899        if !snapshot.entries.is_empty() {
900            output.push(snapshot);
901        }
902        let mut visitor = CollectDiagnosticsVisitor { output };
903        self.visit_children(&mut visitor);
904    }
905
906    pub const fn bounds(&self) -> Rect {
907        self.layout_state.arranged_bounds
908    }
909
910    pub const fn measured_size(&self) -> Size {
911        self.layout_state.measured_size
912    }
913
914    pub fn set_bounds(&mut self, bounds: Rect) {
915        let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
916        self.layout_state.arranged_bounds = bounds;
917        self.layout_state.measured_size = bounds.size;
918        self.layout_state.arrange_valid = true;
919        self.translate_descendants(delta);
920    }
921
922    pub fn measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
923        // Incremental-layout fast path. Cache invalidation is driven entirely by
924        // the measure recursion (never a separate tree walk), so it cannot diverge
925        // from how parents actually reach their children:
926        //
927        // - `force` is true when this pod sits inside a subtree rooted at a widget
928        //   that changed this frame; such a pod always re-measures (which also
929        //   preserves any side effects of measuring more than once per pass).
930        // - otherwise a pod whose own id is listed dirty re-measures, while a clean
931        //   pod measured before under identical constraints returns its cached size
932        //   without recursing.
933        let force = parent_ctx.child_force();
934        let must_remeasure = force || parent_ctx.scope().must_remeasure(self.id);
935        if !must_remeasure
936            && self.layout_state.measure_valid
937            && self.layout_state.last_constraints == constraints
938        {
939            return self.layout_state.measured_size;
940        }
941
942        let origin = self.layout_state.arranged_bounds.origin;
943        let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
944        let started = Instant::now();
945        let size = self.widget.measure(&mut child_ctx, constraints);
946        record_widget_timing(
947            self.id,
948            self.widget.debug_name(),
949            WidgetTimingPhase::Measure,
950            started.elapsed(),
951        );
952        self.layout_state.measured_size = size;
953        self.layout_state.last_constraints = constraints;
954        self.layout_state.measure_valid = true;
955        self.layout_state.arranged_bounds = Rect::from_origin_size(origin, size);
956        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
957        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
958        size
959    }
960
961    pub fn intrinsic_size(
962        &mut self,
963        parent_ctx: &mut MeasureCtx,
964        axis: Axis,
965        available_cross: f32,
966    ) -> IntrinsicSize {
967        let force = parent_ctx.child_force();
968        let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
969        let started = Instant::now();
970        let intrinsic = self
971            .widget
972            .intrinsic_size(&mut child_ctx, axis, available_cross);
973        record_widget_timing(
974            self.id,
975            self.widget.debug_name(),
976            WidgetTimingPhase::Measure,
977            started.elapsed(),
978        );
979        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
980        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
981        IntrinsicSize::new(intrinsic.minimum, intrinsic.natural)
982    }
983
984    pub fn arrange(&mut self, parent_ctx: &mut ArrangeCtx, bounds: Rect) {
985        let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
986        self.layout_state.arranged_bounds = bounds;
987        self.layout_state.arrange_valid = true;
988        self.translate_descendants(delta);
989
990        let mut child_ctx = ArrangeCtx::new_at(
991            parent_ctx.window_id(),
992            self.id,
993            parent_ctx.dpi(),
994            parent_ctx.current_time(),
995        );
996        let started = Instant::now();
997        self.widget.arrange(&mut child_ctx, bounds);
998        record_widget_timing(
999            self.id,
1000            self.widget.debug_name(),
1001            WidgetTimingPhase::Arrange,
1002            started.elapsed(),
1003        );
1004        parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1005        parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1006    }
1007
1008    pub fn paint(&self, parent_ctx: &mut PaintCtx) {
1009        let mut child_ctx = PaintCtx::new(
1010            parent_ctx.window_id(),
1011            self.id,
1012            self.layout_state.arranged_bounds,
1013            parent_ctx.focused_widget_id(),
1014            parent_ctx.dpi(),
1015            Arc::clone(&parent_ctx.text_system),
1016            Arc::clone(&parent_ctx.font_registry),
1017            Arc::clone(&parent_ctx.image_registry),
1018        );
1019        let started = Instant::now();
1020        self.widget.paint(&mut child_ctx);
1021        record_widget_timing(
1022            self.id,
1023            self.widget.debug_name(),
1024            WidgetTimingPhase::Paint,
1025            started.elapsed(),
1026        );
1027
1028        let (scene, images, widget_paint_bounds, invalidations, ime_composition_rect) =
1029            child_ctx.into_parts();
1030        let paint_bounds = scene
1031            .paint_bounds()
1032            .unwrap_or(self.layout_state.arranged_bounds);
1033        parent_ctx.record_widget_paint_bounds(self.id, paint_bounds);
1034        if self.current_layer_options().emits_layer() {
1035            parent_ctx.push_layer(self.build_layer_descriptor(&scene), scene);
1036        } else {
1037            parent_ctx.append_scene(scene);
1038        }
1039        parent_ctx.extend_widget_paint_bounds(widget_paint_bounds);
1040        parent_ctx.extend_images(images);
1041        parent_ctx.extend_invalidations(invalidations);
1042        parent_ctx.extend_ime_composition_rect(ime_composition_rect);
1043    }
1044
1045    pub(crate) fn paint_layer_contents_for(
1046        &mut self,
1047        target: WidgetId,
1048        parent_ctx: &mut PaintCtx,
1049    ) -> bool {
1050        self.find_mut(target, &mut |pod| {
1051            let started = Instant::now();
1052            pod.widget.paint(parent_ctx);
1053            record_widget_timing(
1054                pod.id,
1055                pod.widget.debug_name(),
1056                WidgetTimingPhase::Paint,
1057                started.elapsed(),
1058            );
1059            let paint_bounds = parent_ctx
1060                .scene()
1061                .paint_bounds()
1062                .unwrap_or(pod.layout_state.arranged_bounds);
1063            parent_ctx.record_widget_paint_bounds(pod.id, paint_bounds);
1064        })
1065        .is_some()
1066    }
1067
1068    pub(crate) fn layer_descriptor_for(
1069        &mut self,
1070        target: WidgetId,
1071        scene: &Scene,
1072    ) -> Option<SceneLayerDescriptor> {
1073        self.find_mut(target, &mut |pod| pod.build_layer_descriptor(scene))
1074    }
1075
1076    pub fn semantics(&self, parent_ctx: &mut SemanticsCtx) {
1077        let mut child_ctx = SemanticsCtx::new(
1078            parent_ctx.window_id(),
1079            self.id,
1080            parent_ctx.root_widget_id(),
1081            self.layout_state.arranged_bounds,
1082            parent_ctx.focused_widget_id(),
1083        );
1084        let started = Instant::now();
1085        self.widget.semantics(&mut child_ctx);
1086        record_widget_timing(
1087            self.id,
1088            self.widget.debug_name(),
1089            WidgetTimingPhase::Semantics,
1090            started.elapsed(),
1091        );
1092        parent_ctx.extend_nodes(child_ctx.into_nodes());
1093    }
1094
1095    /// Return whether this retained widget is a focus target.
1096    ///
1097    /// Adaptive containers use this while selecting a restoration fallback for
1098    /// a subtree that has just become visible again.
1099    pub fn accepts_focus(&self) -> bool {
1100        self.widget.accepts_focus()
1101    }
1102
1103    /// Visit this pod's direct children. Public so container widgets can walk
1104    /// their own subtree (e.g. to derive a focus-within visual by comparing
1105    /// descendant ids against the focused widget id — sui has no focus-within
1106    /// event, and any focus change repaints every window, so polling at paint
1107    /// time stays correct).
1108    pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1109        self.widget.visit_children(visitor);
1110    }
1111
1112    pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1113        self.widget.visit_children_mut(visitor);
1114    }
1115
1116    #[allow(clippy::too_many_arguments)]
1117    pub(crate) fn dispatch_event_for_path(
1118        &mut self,
1119        path: &[WidgetId],
1120        window_id: WindowId,
1121        dpi_info: DpiInfo,
1122        current_time: f64,
1123        phase: EventPhase,
1124        focused_widget: Option<WidgetId>,
1125        clipboard: &Clipboard,
1126        command_sender: &CommandSender,
1127        event: &Event,
1128    ) -> Option<EventDispatch> {
1129        self.find_mut_path(path, &mut |pod| {
1130            pod.dispatch_event(
1131                window_id,
1132                dpi_info,
1133                current_time,
1134                phase,
1135                focused_widget,
1136                clipboard,
1137                command_sender,
1138                event,
1139            )
1140        })
1141    }
1142
1143    #[allow(clippy::too_many_arguments)]
1144    pub(crate) fn dispatch_event_for(
1145        &mut self,
1146        target: WidgetId,
1147        window_id: WindowId,
1148        dpi_info: DpiInfo,
1149        current_time: f64,
1150        phase: EventPhase,
1151        focused_widget: Option<WidgetId>,
1152        clipboard: &Clipboard,
1153        command_sender: &CommandSender,
1154        event: &Event,
1155    ) -> Option<EventDispatch> {
1156        self.find_mut(target, &mut |pod| {
1157            pod.dispatch_event(
1158                window_id,
1159                dpi_info,
1160                current_time,
1161                phase,
1162                focused_widget,
1163                clipboard,
1164                command_sender,
1165                event,
1166            )
1167        })
1168    }
1169
1170    #[allow(clippy::too_many_arguments)]
1171    pub(crate) fn dispatch_command_for_path(
1172        &mut self,
1173        path: &[WidgetId],
1174        window_id: WindowId,
1175        dpi_info: DpiInfo,
1176        current_time: f64,
1177        focused_widget: Option<WidgetId>,
1178        clipboard: &Clipboard,
1179        command_sender: &CommandSender,
1180        command: &Command<'_>,
1181    ) -> Option<EventDispatch> {
1182        self.find_mut_path(path, &mut |pod| {
1183            pod.dispatch_command(
1184                window_id,
1185                dpi_info,
1186                current_time,
1187                focused_widget,
1188                clipboard,
1189                command_sender,
1190                command,
1191            )
1192        })
1193    }
1194
1195    #[allow(clippy::too_many_arguments)]
1196    pub(crate) fn dispatch_command_for(
1197        &mut self,
1198        target: WidgetId,
1199        window_id: WindowId,
1200        dpi_info: DpiInfo,
1201        current_time: f64,
1202        focused_widget: Option<WidgetId>,
1203        clipboard: &Clipboard,
1204        command_sender: &CommandSender,
1205        command: &Command<'_>,
1206    ) -> Option<EventDispatch> {
1207        self.find_mut(target, &mut |pod| {
1208            pod.dispatch_command(
1209                window_id,
1210                dpi_info,
1211                current_time,
1212                focused_widget,
1213                clipboard,
1214                command_sender,
1215                command,
1216            )
1217        })
1218    }
1219
1220    #[allow(clippy::too_many_arguments)]
1221    pub(crate) fn notify_focus_change_for(
1222        &mut self,
1223        target: WidgetId,
1224        window_id: WindowId,
1225        dpi_info: DpiInfo,
1226        current_time: f64,
1227        focused_widget: Option<WidgetId>,
1228        clipboard: &Clipboard,
1229        command_sender: &CommandSender,
1230        focused: bool,
1231    ) -> Option<EventDispatch> {
1232        self.find_mut(target, &mut |pod| {
1233            pod.focus_changed(
1234                window_id,
1235                dpi_info,
1236                current_time,
1237                focused_widget,
1238                clipboard,
1239                command_sender,
1240                focused,
1241            )
1242        })
1243    }
1244
1245    #[allow(clippy::too_many_arguments)]
1246    pub(crate) fn notify_focus_change_for_path(
1247        &mut self,
1248        path: &[WidgetId],
1249        window_id: WindowId,
1250        dpi_info: DpiInfo,
1251        current_time: f64,
1252        focused_widget: Option<WidgetId>,
1253        clipboard: &Clipboard,
1254        command_sender: &CommandSender,
1255        focused: bool,
1256    ) -> Option<EventDispatch> {
1257        self.find_mut_path(path, &mut |pod| {
1258            pod.focus_changed(
1259                window_id,
1260                dpi_info,
1261                current_time,
1262                focused_widget,
1263                clipboard,
1264                command_sender,
1265                focused,
1266            )
1267        })
1268    }
1269
1270    #[allow(clippy::too_many_arguments)]
1271    fn dispatch_event(
1272        &mut self,
1273        window_id: WindowId,
1274        dpi_info: DpiInfo,
1275        current_time: f64,
1276        phase: EventPhase,
1277        focused_widget: Option<WidgetId>,
1278        clipboard: &Clipboard,
1279        command_sender: &CommandSender,
1280        event: &Event,
1281    ) -> EventDispatch {
1282        let mut ctx = EventCtx::new(
1283            window_id,
1284            self.id,
1285            self.layout_state.arranged_bounds,
1286            dpi_info,
1287            current_time,
1288            phase,
1289            focused_widget,
1290            clipboard.clone(),
1291            command_sender.clone(),
1292        );
1293        self.widget.event(&mut ctx, event);
1294        EventDispatch {
1295            handled: ctx.is_handled(),
1296            invalidations: ctx.take_invalidations(),
1297            focus_request: ctx.take_focus_request(),
1298            wake_requests: ctx.take_wake_requests(),
1299            pointer_capture_requests: ctx.take_pointer_capture_requests(),
1300            drag_requests: ctx.take_drag_requests(),
1301            drop_acceptances: ctx.take_drop_acceptances(),
1302            posted_events: ctx.take_posted_events(),
1303            posted_commands: ctx.take_posted_commands(),
1304        }
1305    }
1306
1307    #[allow(clippy::too_many_arguments)]
1308    fn dispatch_command(
1309        &mut self,
1310        window_id: WindowId,
1311        dpi_info: DpiInfo,
1312        current_time: f64,
1313        focused_widget: Option<WidgetId>,
1314        clipboard: &Clipboard,
1315        command_sender: &CommandSender,
1316        command: &Command<'_>,
1317    ) -> EventDispatch {
1318        let mut ctx = EventCtx::new(
1319            window_id,
1320            self.id,
1321            self.layout_state.arranged_bounds,
1322            dpi_info,
1323            current_time,
1324            EventPhase::Target,
1325            focused_widget,
1326            clipboard.clone(),
1327            command_sender.clone(),
1328        );
1329        self.widget.command(&mut ctx, command);
1330        ctx.into_dispatch()
1331    }
1332
1333    fn focus_changed(
1334        &mut self,
1335        window_id: WindowId,
1336        dpi_info: DpiInfo,
1337        current_time: f64,
1338        focused_widget: Option<WidgetId>,
1339        clipboard: &Clipboard,
1340        command_sender: &CommandSender,
1341        focused: bool,
1342    ) -> EventDispatch {
1343        let mut ctx = EventCtx::new(
1344            window_id,
1345            self.id,
1346            self.layout_state.arranged_bounds,
1347            dpi_info,
1348            current_time,
1349            EventPhase::Target,
1350            focused_widget,
1351            clipboard.clone(),
1352            command_sender.clone(),
1353        );
1354        self.widget.focus_changed(&mut ctx, focused);
1355        EventDispatch {
1356            handled: ctx.is_handled(),
1357            invalidations: ctx.take_invalidations(),
1358            focus_request: ctx.take_focus_request(),
1359            wake_requests: ctx.take_wake_requests(),
1360            pointer_capture_requests: ctx.take_pointer_capture_requests(),
1361            drag_requests: ctx.take_drag_requests(),
1362            drop_acceptances: ctx.take_drop_acceptances(),
1363            posted_events: ctx.take_posted_events(),
1364            posted_commands: ctx.take_posted_commands(),
1365        }
1366    }
1367
1368    fn find_mut<R, F>(&mut self, target: WidgetId, f: &mut F) -> Option<R>
1369    where
1370        F: FnMut(&mut WidgetPod) -> R,
1371    {
1372        if self.id == target {
1373            return Some(f(self));
1374        }
1375
1376        let mut result = None;
1377        let mut visitor = FindMutVisitor {
1378            target,
1379            callback: f,
1380            result: &mut result,
1381        };
1382        self.visit_children_mut(&mut visitor);
1383        result
1384    }
1385
1386    fn find_mut_path<R, F>(&mut self, path: &[WidgetId], f: &mut F) -> Option<R>
1387    where
1388        F: FnMut(&mut WidgetPod) -> R,
1389    {
1390        let (&current, rest) = path.split_first()?;
1391        if current != self.id {
1392            return None;
1393        }
1394
1395        if rest.is_empty() {
1396            return Some(f(self));
1397        }
1398
1399        let mut result = None;
1400        let mut visitor = FindPathMutVisitor {
1401            path: rest,
1402            callback: f,
1403            result: &mut result,
1404        };
1405        self.visit_children_mut(&mut visitor);
1406        result
1407    }
1408
1409    fn translate_descendants(&mut self, delta: Vector) {
1410        if delta == Vector::ZERO {
1411            return;
1412        }
1413
1414        let mut visitor = TranslateVisitor { delta };
1415        self.visit_children_mut(&mut visitor);
1416    }
1417
1418    fn translate_subtree(&mut self, delta: Vector) {
1419        if delta == Vector::ZERO {
1420            return;
1421        }
1422
1423        self.layout_state.arranged_bounds = self.layout_state.arranged_bounds.translate(delta);
1424        self.translate_descendants(delta);
1425    }
1426
1427    pub(crate) fn build_layer_descriptor(&self, scene: &Scene) -> SceneLayerDescriptor {
1428        let options = self.current_layer_options();
1429        SceneLayerDescriptor::new(
1430            SceneLayerId::from_widget(self.id),
1431            self.id,
1432            self.layout_state.arranged_bounds,
1433        )
1434        .with_content_bounds(
1435            scene
1436                .content_bounds()
1437                .unwrap_or(self.layout_state.arranged_bounds),
1438        )
1439        .with_paint_bounds(
1440            scene
1441                .paint_bounds()
1442                .unwrap_or(self.layout_state.arranged_bounds),
1443        )
1444        .with_properties(self.current_layer_properties())
1445        .with_clip_to_ancestors(matches!(
1446            options.composition_mode,
1447            LayerCompositionMode::Normal
1448        ))
1449        .with_composition_mode(options.composition_mode)
1450    }
1451
1452    pub(crate) fn current_layer_options(&self) -> LayerOptions {
1453        let mut options = self.widget.layer_options();
1454        if self.force_paint_boundary {
1455            options.paint_boundary = PaintBoundaryMode::Explicit;
1456        }
1457        options
1458    }
1459
1460    pub(crate) fn current_layer_properties(&self) -> LayerProperties {
1461        self.widget.layer_properties()
1462    }
1463
1464    pub(crate) fn current_paint_boundary_mode(&self) -> PaintBoundaryMode {
1465        self.current_layer_options().paint_boundary
1466    }
1467
1468    pub(crate) fn current_stack_host_options(&self) -> Option<StackHostOptions> {
1469        self.widget.stack_host_options()
1470    }
1471
1472    pub(crate) fn current_stack_surface_options(&self) -> Option<StackSurfaceOptions> {
1473        self.widget.stack_surface_options()
1474    }
1475
1476    pub(crate) fn current_overlay_options(&self) -> Option<OverlayOptions> {
1477        self.widget.overlay_options()
1478    }
1479
1480    pub(crate) fn layer_composition_mode_for(
1481        &mut self,
1482        target: WidgetId,
1483    ) -> Option<LayerCompositionMode> {
1484        self.find_mut(target, &mut |pod| {
1485            pod.current_layer_options().composition_mode
1486        })
1487    }
1488}
1489
1490struct TranslateVisitor {
1491    delta: Vector,
1492}
1493
1494impl WidgetPodMutVisitor for TranslateVisitor {
1495    fn visit(&mut self, child: &mut WidgetPod) {
1496        child.translate_subtree(self.delta);
1497    }
1498}
1499
1500struct CollectDiagnosticsVisitor<'a> {
1501    output: &'a mut Vec<WidgetDiagnosticsSnapshot>,
1502}
1503
1504impl WidgetPodVisitor for CollectDiagnosticsVisitor<'_> {
1505    fn visit(&mut self, child: &WidgetPod) {
1506        child.collect_diagnostics(self.output);
1507    }
1508}
1509
1510struct FindMutVisitor<'a, F, R>
1511where
1512    F: FnMut(&mut WidgetPod) -> R,
1513{
1514    target: WidgetId,
1515    callback: &'a mut F,
1516    result: &'a mut Option<R>,
1517}
1518
1519impl<F, R> WidgetPodMutVisitor for FindMutVisitor<'_, F, R>
1520where
1521    F: FnMut(&mut WidgetPod) -> R,
1522{
1523    fn visit(&mut self, child: &mut WidgetPod) {
1524        if self.result.is_none() {
1525            *self.result = child.find_mut(self.target, self.callback);
1526        }
1527    }
1528}
1529
1530struct FindPathMutVisitor<'a, F, R>
1531where
1532    F: FnMut(&mut WidgetPod) -> R,
1533{
1534    path: &'a [WidgetId],
1535    callback: &'a mut F,
1536    result: &'a mut Option<R>,
1537}
1538
1539impl<F, R> WidgetPodMutVisitor for FindPathMutVisitor<'_, F, R>
1540where
1541    F: FnMut(&mut WidgetPod) -> R,
1542{
1543    fn visit(&mut self, child: &mut WidgetPod) {
1544        if self.result.is_none() && self.path.first().copied() == Some(child.id) {
1545            *self.result = child.find_mut_path(self.path, self.callback);
1546        }
1547    }
1548}
1549
1550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1551pub(crate) enum FocusRequest {
1552    Focus(WidgetId),
1553    Clear,
1554}
1555
1556#[derive(Debug, Clone, Copy, PartialEq)]
1557pub(crate) enum WakeRequest {
1558    ScheduleTimer {
1559        token: TimerToken,
1560        deadline: f64,
1561        target: WidgetId,
1562    },
1563    CancelTimer {
1564        token: TimerToken,
1565    },
1566    RegisterAsync {
1567        token: AsyncWakeToken,
1568        target: WidgetId,
1569    },
1570    UnregisterAsync {
1571        token: AsyncWakeToken,
1572    },
1573    RequestAnimationFrame {
1574        target: WidgetId,
1575    },
1576}
1577
1578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1579pub(crate) enum PointerCaptureRequest {
1580    Capture { pointer_id: u64, target: WidgetId },
1581    Release { pointer_id: u64 },
1582}
1583
1584#[derive(Debug, Clone)]
1585pub(crate) struct BeginDragRequest {
1586    pub session_id: DragSessionId,
1587    pub scope_id: DragScopeId,
1588    pub pointer_id: u64,
1589    pub source: WidgetId,
1590    pub position: Point,
1591    pub payload: DragPayload,
1592    pub allowed_effect: DropEffect,
1593    pub preview_label: Option<String>,
1594}
1595
1596#[derive(Debug, Clone)]
1597pub(crate) enum DragRequest {
1598    Begin(BeginDragRequest),
1599}
1600
1601#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1602pub(crate) struct DropAcceptanceRequest {
1603    pub target: WidgetId,
1604    pub effect: DropEffect,
1605}
1606
1607/// An event queued by a widget for delivery to another widget once the
1608/// current dispatch finishes.
1609#[derive(Debug, Clone)]
1610pub(crate) struct PostedEventRequest {
1611    pub target: WidgetId,
1612    pub event: Event,
1613}
1614
1615/// A typed, target-only command posted during widget dispatch.
1616#[derive(Debug, Clone)]
1617pub(crate) struct PostedCommandRequest {
1618    pub command: QueuedCommand,
1619}
1620
1621#[derive(Debug, Clone)]
1622pub(crate) struct EventDispatch {
1623    pub handled: bool,
1624    pub invalidations: Vec<InvalidationRequest>,
1625    pub focus_request: Option<FocusRequest>,
1626    pub wake_requests: Vec<WakeRequest>,
1627    pub pointer_capture_requests: Vec<PointerCaptureRequest>,
1628    pub drag_requests: Vec<DragRequest>,
1629    pub drop_acceptances: Vec<DropAcceptanceRequest>,
1630    pub posted_events: Vec<PostedEventRequest>,
1631    pub posted_commands: Vec<PostedCommandRequest>,
1632}
1633
1634#[derive(Debug, Clone)]
1635pub struct EventCtx {
1636    window_id: WindowId,
1637    widget_id: WidgetId,
1638    bounds: Rect,
1639    dpi_info: DpiInfo,
1640    current_time: f64,
1641    phase: EventPhase,
1642    focused_widget_id: Option<WidgetId>,
1643    clipboard: Clipboard,
1644    command_sender: CommandSender,
1645    handled: bool,
1646    invalidations: Vec<InvalidationRequest>,
1647    focus_request: Option<FocusRequest>,
1648    wake_requests: Vec<WakeRequest>,
1649    pointer_capture_requests: Vec<PointerCaptureRequest>,
1650    drag_requests: Vec<DragRequest>,
1651    drop_acceptances: Vec<DropAcceptanceRequest>,
1652    posted_events: Vec<PostedEventRequest>,
1653    posted_commands: Vec<PostedCommandRequest>,
1654}
1655
1656impl EventCtx {
1657    #[allow(clippy::too_many_arguments)]
1658    pub(crate) fn new(
1659        window_id: WindowId,
1660        widget_id: WidgetId,
1661        bounds: Rect,
1662        dpi_info: DpiInfo,
1663        current_time: f64,
1664        phase: EventPhase,
1665        focused_widget_id: Option<WidgetId>,
1666        clipboard: Clipboard,
1667        command_sender: CommandSender,
1668    ) -> Self {
1669        Self {
1670            window_id,
1671            widget_id,
1672            bounds,
1673            dpi_info,
1674            current_time,
1675            phase,
1676            focused_widget_id,
1677            clipboard,
1678            command_sender,
1679            handled: false,
1680            invalidations: Vec::new(),
1681            focus_request: None,
1682            wake_requests: Vec::new(),
1683            pointer_capture_requests: Vec::new(),
1684            drag_requests: Vec::new(),
1685            drop_acceptances: Vec::new(),
1686            posted_events: Vec::new(),
1687            posted_commands: Vec::new(),
1688        }
1689    }
1690
1691    fn into_dispatch(mut self) -> EventDispatch {
1692        EventDispatch {
1693            handled: self.is_handled(),
1694            invalidations: self.take_invalidations(),
1695            focus_request: self.take_focus_request(),
1696            wake_requests: self.take_wake_requests(),
1697            pointer_capture_requests: self.take_pointer_capture_requests(),
1698            drag_requests: self.take_drag_requests(),
1699            drop_acceptances: self.take_drop_acceptances(),
1700            posted_events: self.take_posted_events(),
1701            posted_commands: self.take_posted_commands(),
1702        }
1703    }
1704
1705    pub const fn window_id(&self) -> WindowId {
1706        self.window_id
1707    }
1708
1709    pub const fn widget_id(&self) -> WidgetId {
1710        self.widget_id
1711    }
1712
1713    /// Read an observable and subscribe this widget to the requested
1714    /// invalidation kind.
1715    pub fn observe<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
1716    where
1717        O: Observable<T> + ?Sized,
1718    {
1719        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
1720    }
1721
1722    /// Record a development diagnostic explaining a structural widget rebuild.
1723    pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
1724        crate::diagnostics::record_widget_rebuild(
1725            self.window_id,
1726            self.widget_id,
1727            widget_name,
1728            reason,
1729        );
1730    }
1731
1732    pub const fn bounds(&self) -> Rect {
1733        self.bounds
1734    }
1735
1736    pub const fn dpi(&self) -> DpiInfo {
1737        self.dpi_info
1738    }
1739
1740    pub const fn current_time(&self) -> f64 {
1741        self.current_time
1742    }
1743
1744    pub const fn phase(&self) -> EventPhase {
1745        self.phase
1746    }
1747
1748    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
1749        self.focused_widget_id
1750    }
1751
1752    pub fn is_focused(&self) -> bool {
1753        self.focused_widget_id == Some(self.widget_id)
1754    }
1755
1756    pub const fn is_handled(&self) -> bool {
1757        self.handled
1758    }
1759
1760    pub fn set_handled(&mut self) {
1761        self.handled = true;
1762    }
1763
1764    /// Shared clipboard service for this window. Backed by the OS clipboard
1765    /// when the platform installed a native backend, otherwise by in-process
1766    /// storage shared across the runtime.
1767    pub fn clipboard(&self) -> &Clipboard {
1768        &self.clipboard
1769    }
1770
1771    pub fn clipboard_text(&self) -> Option<String> {
1772        self.clipboard.text()
1773    }
1774
1775    pub fn set_clipboard_text(&mut self, text: impl AsRef<str>) {
1776        self.clipboard.set_text(text);
1777    }
1778
1779    /// Return the runtime's cloneable typed command producer.
1780    ///
1781    /// Widget callbacks can use this to address window or application
1782    /// controllers without routing through an ancestor widget. Delivery is
1783    /// queued until the current event dispatch completes.
1784    pub fn command_sender(&self) -> &CommandSender {
1785        &self.command_sender
1786    }
1787
1788    /// Queue an event for delivery to `target` after the current dispatch
1789    /// completes. Used to route commands (for example clipboard actions from
1790    /// a context menu) to a specific widget outside the normal hit-test or
1791    /// focus routing.
1792    pub fn post_event(&mut self, target: WidgetId, event: Event) {
1793        self.posted_events
1794            .push(PostedEventRequest { target, event });
1795    }
1796
1797    /// Queue a typed command for target-only delivery after the current widget
1798    /// dispatch completes.
1799    pub fn post_command<T>(&mut self, target: WidgetId, key: CommandKey<T>, payload: T)
1800    where
1801        T: Send + Sync + 'static,
1802    {
1803        self.posted_commands.push(PostedCommandRequest {
1804            command: queued_command(
1805                CommandTarget::Widget {
1806                    window_id: self.window_id,
1807                    widget_id: target,
1808                },
1809                CommandDelivery::Directed,
1810                key,
1811                payload,
1812            ),
1813        });
1814    }
1815
1816    pub fn request_focus(&mut self) {
1817        self.focus_request = Some(FocusRequest::Focus(self.widget_id));
1818    }
1819
1820    /// Request focus for a retained widget in the current window.
1821    ///
1822    /// Containers use this to restore focus to a descendant after adaptive
1823    /// presentation changes. The target must be mounted in the widget graph by
1824    /// the time the current event dispatch completes.
1825    pub fn request_focus_for(&mut self, widget_id: WidgetId) {
1826        self.focus_request = Some(FocusRequest::Focus(widget_id));
1827    }
1828
1829    pub fn clear_focus(&mut self) {
1830        self.focus_request = Some(FocusRequest::Clear);
1831    }
1832
1833    pub fn schedule_timer_at(&mut self, deadline: f64) -> TimerToken {
1834        let token = TimerToken::new(NEXT_TIMER_TOKEN.fetch_add(1, Ordering::Relaxed));
1835        self.wake_requests.push(WakeRequest::ScheduleTimer {
1836            token,
1837            deadline,
1838            target: self.widget_id,
1839        });
1840        token
1841    }
1842
1843    pub fn schedule_timer_after(&mut self, delay: f64) -> TimerToken {
1844        self.schedule_timer_at(self.current_time + delay)
1845    }
1846
1847    pub fn cancel_timer(&mut self, token: TimerToken) {
1848        self.wake_requests.push(WakeRequest::CancelTimer { token });
1849    }
1850
1851    pub fn register_async_wakeup(&mut self) -> AsyncWakeToken {
1852        let token = AsyncWakeToken::new(NEXT_ASYNC_WAKE_TOKEN.fetch_add(1, Ordering::Relaxed));
1853        self.wake_requests.push(WakeRequest::RegisterAsync {
1854            token,
1855            target: self.widget_id,
1856        });
1857        token
1858    }
1859
1860    pub fn unregister_async_wakeup(&mut self, token: AsyncWakeToken) {
1861        self.wake_requests
1862            .push(WakeRequest::UnregisterAsync { token });
1863    }
1864
1865    pub fn request_animation_frame(&mut self) {
1866        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
1867            target: self.widget_id,
1868        });
1869    }
1870
1871    pub fn request_pointer_capture(&mut self, pointer_id: u64) {
1872        self.pointer_capture_requests
1873            .push(PointerCaptureRequest::Capture {
1874                pointer_id,
1875                target: self.widget_id,
1876            });
1877    }
1878
1879    pub fn release_pointer_capture(&mut self, pointer_id: u64) {
1880        self.pointer_capture_requests
1881            .push(PointerCaptureRequest::Release { pointer_id });
1882    }
1883
1884    pub fn begin_drag(
1885        &mut self,
1886        scope_id: DragScopeId,
1887        pointer_id: u64,
1888        position: Point,
1889        payload: DragPayload,
1890        allowed_effect: DropEffect,
1891        preview_label: Option<String>,
1892    ) -> DragSessionId {
1893        let session_id = DragSessionId::new(NEXT_DRAG_SESSION_ID.fetch_add(1, Ordering::Relaxed));
1894        self.drag_requests
1895            .push(DragRequest::Begin(BeginDragRequest {
1896                session_id,
1897                scope_id,
1898                pointer_id,
1899                source: self.widget_id,
1900                position,
1901                payload,
1902                allowed_effect,
1903                preview_label,
1904            }));
1905        session_id
1906    }
1907
1908    pub fn accept_drop(&mut self, effect: DropEffect) {
1909        if effect.is_none() {
1910            return;
1911        }
1912        self.drop_acceptances.push(DropAcceptanceRequest {
1913            target: self.widget_id,
1914            effect,
1915        });
1916    }
1917
1918    pub fn request(&mut self, request: InvalidationRequest) {
1919        self.invalidations.push(request);
1920    }
1921
1922    pub fn request_measure(&mut self) {
1923        self.request_widget(InvalidationKind::Measure);
1924    }
1925
1926    pub fn request_arrange(&mut self) {
1927        self.request_widget(InvalidationKind::Arrange);
1928    }
1929
1930    pub fn request_ordering(&mut self) {
1931        self.request_widget(InvalidationKind::Ordering);
1932    }
1933
1934    pub fn request_paint(&mut self) {
1935        self.request_widget(InvalidationKind::Paint);
1936    }
1937
1938    pub fn request_paint_rect(&mut self, rect: Rect) {
1939        self.request(
1940            InvalidationRequest::new(
1941                InvalidationTarget::Widget(self.widget_id),
1942                InvalidationKind::Paint,
1943            )
1944            .with_region(rect),
1945        );
1946    }
1947
1948    pub fn request_transform(&mut self) {
1949        self.request_widget(InvalidationKind::Transform);
1950    }
1951
1952    pub fn request_effect(&mut self) {
1953        self.request_widget(InvalidationKind::Effect);
1954    }
1955
1956    pub fn request_visibility(&mut self) {
1957        self.request_widget(InvalidationKind::Visibility);
1958    }
1959
1960    pub fn request_hit_test(&mut self) {
1961        self.request_widget(InvalidationKind::HitTest);
1962    }
1963
1964    pub fn request_text(&mut self) {
1965        self.request_widget(InvalidationKind::Text);
1966    }
1967
1968    pub fn request_semantics(&mut self) {
1969        self.request_widget(InvalidationKind::Semantics);
1970    }
1971
1972    pub fn request_resources(&mut self) {
1973        self.request_widget(InvalidationKind::Resources);
1974    }
1975
1976    pub fn invalidations(&self) -> &[InvalidationRequest] {
1977        &self.invalidations
1978    }
1979
1980    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
1981        std::mem::take(&mut self.invalidations)
1982    }
1983
1984    pub(crate) fn take_focus_request(&mut self) -> Option<FocusRequest> {
1985        self.focus_request.take()
1986    }
1987
1988    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
1989        std::mem::take(&mut self.wake_requests)
1990    }
1991
1992    pub(crate) fn take_pointer_capture_requests(&mut self) -> Vec<PointerCaptureRequest> {
1993        std::mem::take(&mut self.pointer_capture_requests)
1994    }
1995
1996    pub(crate) fn take_drag_requests(&mut self) -> Vec<DragRequest> {
1997        std::mem::take(&mut self.drag_requests)
1998    }
1999
2000    pub(crate) fn take_drop_acceptances(&mut self) -> Vec<DropAcceptanceRequest> {
2001        std::mem::take(&mut self.drop_acceptances)
2002    }
2003
2004    pub(crate) fn take_posted_events(&mut self) -> Vec<PostedEventRequest> {
2005        std::mem::take(&mut self.posted_events)
2006    }
2007
2008    pub(crate) fn take_posted_commands(&mut self) -> Vec<PostedCommandRequest> {
2009        std::mem::take(&mut self.posted_commands)
2010    }
2011
2012    fn request_widget(&mut self, kind: InvalidationKind) {
2013        self.request(InvalidationRequest::new(
2014            InvalidationTarget::Widget(self.widget_id),
2015            kind,
2016        ));
2017    }
2018}
2019
2020/// Per-measure-pass invalidation scope, shared (via `Rc`) by every `MeasureCtx`
2021/// in a single pass. Drives which pods may reuse their cached measure.
2022///
2023/// - `force_all`: ignore all caches and re-measure everything (bootstrap, resize,
2024///   or any frame whose dirty set could not be resolved to concrete widgets).
2025/// - `dirty`: pods that must recompute their own measure — the changed widgets
2026///   plus every ancestor on the path from the root (an ancestor's layout can
2027///   depend on a descendant's size).
2028/// - `subtree_roots`: the changed widgets themselves; entering their children
2029///   forces the whole subtree to re-measure, because the change is inside them.
2030#[derive(Debug, Default)]
2031pub(crate) struct MeasureScope {
2032    force_all: bool,
2033    dirty: HashSet<WidgetId>,
2034    subtree_roots: HashSet<WidgetId>,
2035}
2036
2037impl MeasureScope {
2038    pub(crate) fn force_all() -> Self {
2039        Self {
2040            force_all: true,
2041            dirty: HashSet::new(),
2042            subtree_roots: HashSet::new(),
2043        }
2044    }
2045
2046    pub(crate) fn scoped(dirty: HashSet<WidgetId>, subtree_roots: HashSet<WidgetId>) -> Self {
2047        Self {
2048            force_all: false,
2049            dirty,
2050            subtree_roots,
2051        }
2052    }
2053
2054    fn must_remeasure(&self, widget_id: WidgetId) -> bool {
2055        self.force_all || self.dirty.contains(&widget_id)
2056    }
2057
2058    fn forces_subtree(&self, widget_id: WidgetId) -> bool {
2059        self.subtree_roots.contains(&widget_id)
2060    }
2061}
2062
2063#[derive(Debug, Clone)]
2064pub struct MeasureCtx {
2065    window_id: WindowId,
2066    widget_id: WidgetId,
2067    bounds: Rect,
2068    layout: LayoutContext,
2069    current_time: f64,
2070    invalidations: Vec<InvalidationRequest>,
2071    wake_requests: Vec<WakeRequest>,
2072    scope: Rc<MeasureScope>,
2073    /// Whether the pod this ctx belongs to is inside a forced subtree.
2074    force: bool,
2075}
2076
2077impl MeasureCtx {
2078    pub fn with_layout(
2079        window_id: WindowId,
2080        widget_id: WidgetId,
2081        bounds: Rect,
2082        layout: LayoutContext,
2083    ) -> Self {
2084        // External / test callers get full-measure semantics by default.
2085        Self::with_layout_scoped(
2086            window_id,
2087            widget_id,
2088            bounds,
2089            layout,
2090            0.0,
2091            Rc::new(MeasureScope::force_all()),
2092            true,
2093        )
2094    }
2095
2096    pub(crate) fn with_layout_scoped(
2097        window_id: WindowId,
2098        widget_id: WidgetId,
2099        bounds: Rect,
2100        layout: LayoutContext,
2101        current_time: f64,
2102        scope: Rc<MeasureScope>,
2103        force: bool,
2104    ) -> Self {
2105        Self {
2106            window_id,
2107            widget_id,
2108            bounds,
2109            layout,
2110            current_time,
2111            invalidations: Vec::new(),
2112            wake_requests: Vec::new(),
2113            scope,
2114            force,
2115        }
2116    }
2117
2118    #[cfg(test)]
2119    pub(crate) fn new(
2120        window_id: WindowId,
2121        widget_id: WidgetId,
2122        bounds: Rect,
2123        dpi_info: DpiInfo,
2124        text_system: Arc<TextSystem>,
2125        font_registry: Arc<FontRegistry>,
2126        image_registry: Arc<ImageRegistry>,
2127    ) -> Self {
2128        Self::with_layout(
2129            window_id,
2130            widget_id,
2131            bounds,
2132            LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
2133        )
2134    }
2135
2136    pub(crate) fn new_scoped_at(
2137        window_id: WindowId,
2138        widget_id: WidgetId,
2139        bounds: Rect,
2140        dpi_info: DpiInfo,
2141        text_system: Arc<TextSystem>,
2142        font_registry: Arc<FontRegistry>,
2143        image_registry: Arc<ImageRegistry>,
2144        scope: Rc<MeasureScope>,
2145        current_time: f64,
2146    ) -> Self {
2147        Self::with_layout_scoped(
2148            window_id,
2149            widget_id,
2150            bounds,
2151            LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
2152            current_time,
2153            scope,
2154            false,
2155        )
2156    }
2157
2158    pub(crate) fn scope(&self) -> &MeasureScope {
2159        &self.scope
2160    }
2161
2162    /// Whether the *children* of this pod must be force-remeasured: either this
2163    /// pod is already inside a forced subtree, or this pod is itself a changed
2164    /// widget whose subtree must be rebuilt.
2165    pub(crate) fn child_force(&self) -> bool {
2166        self.force || self.scope.forces_subtree(self.widget_id)
2167    }
2168
2169    /// Build the measure ctx for a child pod, carrying the shared scope and the
2170    /// child's resolved force flag.
2171    pub(crate) fn child(&self, widget_id: WidgetId, bounds: Rect, force: bool) -> Self {
2172        Self::with_layout_scoped(
2173            self.window_id,
2174            widget_id,
2175            bounds,
2176            self.layout.clone(),
2177            self.current_time,
2178            Rc::clone(&self.scope),
2179            force,
2180        )
2181    }
2182
2183    pub const fn window_id(&self) -> WindowId {
2184        self.window_id
2185    }
2186
2187    pub const fn widget_id(&self) -> WidgetId {
2188        self.widget_id
2189    }
2190
2191    /// Read an observable whose changes affect measurement.
2192    pub fn observe<T, O>(&self, observable: &O) -> T
2193    where
2194        O: Observable<T> + ?Sized,
2195    {
2196        self.observe_with(observable, InvalidationKind::Measure)
2197    }
2198
2199    /// Read an observable and explicitly declare the resulting invalidation.
2200    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2201    where
2202        O: Observable<T> + ?Sized,
2203    {
2204        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2205    }
2206
2207    /// Record a development diagnostic explaining a structural widget rebuild.
2208    pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
2209        crate::diagnostics::record_widget_rebuild(
2210            self.window_id,
2211            self.widget_id,
2212            widget_name,
2213            reason,
2214        );
2215    }
2216
2217    pub const fn bounds(&self) -> Rect {
2218        self.bounds
2219    }
2220
2221    pub const fn layout(&self) -> &LayoutContext {
2222        &self.layout
2223    }
2224
2225    pub const fn dpi(&self) -> DpiInfo {
2226        self.layout.dpi()
2227    }
2228
2229    pub const fn current_time(&self) -> f64 {
2230        self.current_time
2231    }
2232
2233    pub fn request(&mut self, request: InvalidationRequest) {
2234        self.invalidations.push(request);
2235    }
2236
2237    pub fn request_measure(&mut self) {
2238        self.request_widget(InvalidationKind::Measure);
2239    }
2240
2241    pub fn request_arrange(&mut self) {
2242        self.request_widget(InvalidationKind::Arrange);
2243    }
2244
2245    pub fn request_ordering(&mut self) {
2246        self.request_widget(InvalidationKind::Ordering);
2247    }
2248
2249    pub fn request_paint(&mut self) {
2250        self.request_widget(InvalidationKind::Paint);
2251    }
2252
2253    pub fn request_semantics(&mut self) {
2254        self.request_widget(InvalidationKind::Semantics);
2255    }
2256
2257    pub fn request_animation_frame(&mut self) {
2258        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
2259            target: self.widget_id,
2260        });
2261    }
2262
2263    pub fn invalidations(&self) -> &[InvalidationRequest] {
2264        &self.invalidations
2265    }
2266
2267    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
2268        std::mem::take(&mut self.invalidations)
2269    }
2270
2271    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
2272        std::mem::take(&mut self.wake_requests)
2273    }
2274
2275    pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
2276        self.invalidations.extend(invalidations);
2277    }
2278
2279    pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
2280        self.wake_requests.extend(wake_requests);
2281    }
2282
2283    fn request_widget(&mut self, kind: InvalidationKind) {
2284        self.request(InvalidationRequest::new(
2285            InvalidationTarget::Widget(self.widget_id),
2286            kind,
2287        ));
2288    }
2289}
2290
2291#[derive(Debug, Clone)]
2292pub struct ArrangeCtx {
2293    window_id: WindowId,
2294    widget_id: WidgetId,
2295    dpi_info: DpiInfo,
2296    current_time: f64,
2297    invalidations: Vec<InvalidationRequest>,
2298    wake_requests: Vec<WakeRequest>,
2299}
2300
2301impl ArrangeCtx {
2302    #[cfg(test)]
2303    pub(crate) fn new(window_id: WindowId, widget_id: WidgetId, dpi_info: DpiInfo) -> Self {
2304        Self::new_at(window_id, widget_id, dpi_info, 0.0)
2305    }
2306
2307    pub(crate) fn new_at(
2308        window_id: WindowId,
2309        widget_id: WidgetId,
2310        dpi_info: DpiInfo,
2311        current_time: f64,
2312    ) -> Self {
2313        Self {
2314            window_id,
2315            widget_id,
2316            dpi_info,
2317            current_time,
2318            invalidations: Vec::new(),
2319            wake_requests: Vec::new(),
2320        }
2321    }
2322
2323    pub const fn window_id(&self) -> WindowId {
2324        self.window_id
2325    }
2326
2327    pub const fn widget_id(&self) -> WidgetId {
2328        self.widget_id
2329    }
2330
2331    /// Read an observable whose changes affect arrangement.
2332    pub fn observe<T, O>(&self, observable: &O) -> T
2333    where
2334        O: Observable<T> + ?Sized,
2335    {
2336        self.observe_with(observable, InvalidationKind::Arrange)
2337    }
2338
2339    /// Read an observable and explicitly declare the resulting invalidation.
2340    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2341    where
2342        O: Observable<T> + ?Sized,
2343    {
2344        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2345    }
2346
2347    pub const fn dpi(&self) -> DpiInfo {
2348        self.dpi_info
2349    }
2350
2351    pub const fn current_time(&self) -> f64 {
2352        self.current_time
2353    }
2354
2355    pub fn request(&mut self, request: InvalidationRequest) {
2356        self.invalidations.push(request);
2357    }
2358
2359    pub fn request_arrange(&mut self) {
2360        self.request_widget(InvalidationKind::Arrange);
2361    }
2362
2363    pub fn request_ordering(&mut self) {
2364        self.request_widget(InvalidationKind::Ordering);
2365    }
2366
2367    pub fn request_paint(&mut self) {
2368        self.request_widget(InvalidationKind::Paint);
2369    }
2370
2371    pub fn request_semantics(&mut self) {
2372        self.request_widget(InvalidationKind::Semantics);
2373    }
2374
2375    pub fn request_transform(&mut self) {
2376        self.request_widget(InvalidationKind::Transform);
2377    }
2378
2379    /// Schedule an animation frame for this widget after arrangement.
2380    ///
2381    /// This is useful for retained layout transitions, which discover their
2382    /// new destination during arrange rather than during event delivery.
2383    pub fn request_animation_frame(&mut self) {
2384        self.wake_requests.push(WakeRequest::RequestAnimationFrame {
2385            target: self.widget_id,
2386        });
2387    }
2388
2389    pub fn invalidations(&self) -> &[InvalidationRequest] {
2390        &self.invalidations
2391    }
2392
2393    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
2394        std::mem::take(&mut self.invalidations)
2395    }
2396
2397    pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
2398        std::mem::take(&mut self.wake_requests)
2399    }
2400
2401    pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
2402        self.invalidations.extend(invalidations);
2403    }
2404
2405    pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
2406        self.wake_requests.extend(wake_requests);
2407    }
2408
2409    fn request_widget(&mut self, kind: InvalidationKind) {
2410        self.request(InvalidationRequest::new(
2411            InvalidationTarget::Widget(self.widget_id),
2412            kind,
2413        ));
2414    }
2415}
2416
2417#[derive(Debug, Clone)]
2418pub struct PaintCtx {
2419    window_id: WindowId,
2420    widget_id: WidgetId,
2421    focused_widget_id: Option<WidgetId>,
2422    bounds: Rect,
2423    dpi_info: DpiInfo,
2424    text_system: Arc<TextSystem>,
2425    font_registry: Arc<FontRegistry>,
2426    image_registry: Arc<ImageRegistry>,
2427    scene: Scene,
2428    images: Vec<(ImageHandle, PaintImageResource)>,
2429    widget_paint_bounds: HashMap<WidgetId, Rect>,
2430    invalidations: Vec<InvalidationRequest>,
2431    ime_composition_rect: Option<Rect>,
2432}
2433
2434#[derive(Debug, Clone)]
2435pub(crate) enum PaintImageResource {
2436    Cpu(RegisteredImage),
2437    External(RegisteredExternalImage),
2438}
2439
2440impl PaintCtx {
2441    pub(crate) fn new(
2442        window_id: WindowId,
2443        widget_id: WidgetId,
2444        bounds: Rect,
2445        focused_widget_id: Option<WidgetId>,
2446        dpi_info: DpiInfo,
2447        text_system: Arc<TextSystem>,
2448        font_registry: Arc<FontRegistry>,
2449        image_registry: Arc<ImageRegistry>,
2450    ) -> Self {
2451        Self {
2452            window_id,
2453            widget_id,
2454            focused_widget_id,
2455            bounds,
2456            dpi_info,
2457            text_system,
2458            font_registry,
2459            image_registry,
2460            scene: Scene::new(),
2461            images: Vec::new(),
2462            widget_paint_bounds: HashMap::new(),
2463            invalidations: Vec::new(),
2464            ime_composition_rect: None,
2465        }
2466    }
2467
2468    pub const fn window_id(&self) -> WindowId {
2469        self.window_id
2470    }
2471
2472    pub const fn widget_id(&self) -> WidgetId {
2473        self.widget_id
2474    }
2475
2476    /// Read an observable whose changes affect painting.
2477    pub fn observe<T, O>(&self, observable: &O) -> T
2478    where
2479        O: Observable<T> + ?Sized,
2480    {
2481        self.observe_with(observable, InvalidationKind::Paint)
2482    }
2483
2484    /// Read an observable and explicitly declare the resulting invalidation.
2485    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2486    where
2487        O: Observable<T> + ?Sized,
2488    {
2489        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2490    }
2491
2492    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
2493        self.focused_widget_id
2494    }
2495
2496    pub fn is_focused(&self) -> bool {
2497        self.focused_widget_id == Some(self.widget_id)
2498    }
2499
2500    pub const fn bounds(&self) -> Rect {
2501        self.bounds
2502    }
2503
2504    pub const fn dpi(&self) -> DpiInfo {
2505        self.dpi_info
2506    }
2507
2508    pub fn measure_text(
2509        &self,
2510        text: impl Into<String>,
2511        style: TextStyle,
2512    ) -> sui_core::Result<TextMeasurement> {
2513        self.text_system
2514            .measure_text(text, style, self.font_registry.as_ref())
2515    }
2516
2517    pub fn shape_text(
2518        &self,
2519        text: impl Into<String>,
2520        box_size: Size,
2521        style: TextStyle,
2522    ) -> sui_core::Result<TextLayout> {
2523        self.text_system
2524            .shape_text(text, box_size, style, self.font_registry.as_ref())
2525    }
2526
2527    pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
2528        self.text_system
2529            .layout_document(request, self.font_registry.as_ref())
2530    }
2531
2532    pub fn clear(&mut self, color: Color) {
2533        self.scene.push(SceneCommand::Clear(color));
2534    }
2535
2536    pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
2537        self.scene.push(SceneCommand::FillPath {
2538            path: path.into(),
2539            brush: brush.into(),
2540        });
2541    }
2542
2543    pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
2544        self.scene.push(SceneCommand::FillRect {
2545            rect,
2546            brush: brush.into(),
2547        });
2548    }
2549
2550    pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
2551        self.fill_rect(self.bounds, brush);
2552    }
2553
2554    pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
2555        self.scene.push(SceneCommand::StrokePath {
2556            path: path.into(),
2557            brush: brush.into(),
2558            stroke,
2559        });
2560    }
2561
2562    pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
2563        self.scene.push(SceneCommand::StrokeRect {
2564            rect,
2565            brush: brush.into(),
2566            stroke,
2567        });
2568    }
2569
2570    pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
2571        self.stroke_rect(self.bounds, brush, stroke);
2572    }
2573
2574    pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
2575        let text = text.into();
2576        let paint_color = style.color;
2577        let mut layout_style = style.clone();
2578        layout_style.color = Color::WHITE;
2579        let layout_run = TextRun {
2580            rect,
2581            text: text.clone(),
2582            style: layout_style,
2583        };
2584        let fallback_run = TextRun { rect, text, style };
2585
2586        match self.text_system.shape_text_run_persistent(
2587            Some(stable_text_run_handle(&layout_run)),
2588            &layout_run,
2589            self.font_registry.as_ref(),
2590        ) {
2591            Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
2592                ShapedText::new(rect.origin, &layout).with_color(paint_color),
2593            )),
2594            Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
2595        }
2596    }
2597
2598    pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
2599        let persistent = self.text_system.adopt_layout(layout.clone());
2600        self.draw_persistent_text_layout(origin, &persistent);
2601    }
2602
2603    pub fn draw_text_layout_with_color(
2604        &mut self,
2605        origin: Point,
2606        layout: &TextLayout,
2607        color: Color,
2608    ) {
2609        let persistent = self.text_system.adopt_layout(layout.clone());
2610        self.draw_persistent_text_layout_with_color(origin, &persistent, color);
2611    }
2612
2613    pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
2614        self.text_system.touch_persistent_layout(layout);
2615        self.scene
2616            .push(SceneCommand::DrawShapedText(ShapedText::new(
2617                origin, layout,
2618            )));
2619    }
2620
2621    pub fn draw_persistent_text_layout_with_color(
2622        &mut self,
2623        origin: Point,
2624        layout: &PersistentTextLayout,
2625        color: Color,
2626    ) {
2627        self.text_system.touch_persistent_layout(layout);
2628        self.scene.push(SceneCommand::DrawShapedText(
2629            ShapedText::new(origin, layout).with_color(color),
2630        ));
2631    }
2632
2633    pub fn draw_persistent_text_layout_window(
2634        &mut self,
2635        origin: Point,
2636        layout: &PersistentTextLayout,
2637        line_range: std::ops::Range<usize>,
2638    ) {
2639        self.text_system.touch_persistent_layout(layout);
2640        self.scene
2641            .push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
2642                origin, layout, line_range,
2643            )));
2644    }
2645
2646    pub fn draw_persistent_text_layout_window_with_color(
2647        &mut self,
2648        origin: Point,
2649        layout: &PersistentTextLayout,
2650        line_range: std::ops::Range<usize>,
2651        color: Color,
2652    ) {
2653        self.text_system.touch_persistent_layout(layout);
2654        self.scene.push(SceneCommand::DrawShapedTextWindow(
2655            ShapedTextWindow::new(origin, layout, line_range).with_color(color),
2656        ));
2657    }
2658
2659    pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
2660        self.draw_text(rect, text, TextStyle::new(color));
2661    }
2662
2663    pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
2664        self.scene.push(SceneCommand::PushTextRenderPolicy {
2665            policy: policy.normalized(),
2666        });
2667    }
2668
2669    pub fn pop_text_render_policy(&mut self) {
2670        self.scene.push(SceneCommand::PopTextRenderPolicy);
2671    }
2672
2673    pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
2674        self.scene.push(SceneCommand::DrawImage {
2675            rect,
2676            source: ImageSource::new(image),
2677        });
2678    }
2679
2680    pub fn image_registered(&self, image: ImageHandle) -> bool {
2681        self.image_registry.contains(image)
2682            || self.images.iter().any(|(handle, _)| *handle == image)
2683    }
2684
2685    pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
2686        self.scene.push(SceneCommand::DrawImage { rect, source });
2687    }
2688
2689    pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
2690        self.draw_image_quad_source(points, ImageSource::new(image));
2691    }
2692
2693    pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
2694        self.scene
2695            .push(SceneCommand::DrawImageQuad { points, source });
2696    }
2697
2698    pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
2699        let mut hasher = DefaultHasher::new();
2700        self.widget_id.hash(&mut hasher);
2701        slot.hash(&mut hasher);
2702        ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
2703    }
2704
2705    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
2706        self.images.push((handle, PaintImageResource::Cpu(image)));
2707    }
2708
2709    /// Register renderer-neutral metadata for an externally owned image.
2710    ///
2711    /// The active renderer must have a matching backend resource registered
2712    /// for `handle`. The external resource remains app-owned; this only makes
2713    /// its dimensions available to layout and scene construction for the
2714    /// current frame.
2715    pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
2716        self.images
2717            .push((handle, PaintImageResource::External(image)));
2718    }
2719
2720    pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
2721        self.scene
2722            .push(SceneCommand::DrawShaderRect { rect, shader });
2723    }
2724
2725    /// Fill a rounded rectangle (per-corner radii `[tl, tr, br, bl]`) with a brush.
2726    pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
2727        self.scene.push(SceneCommand::FillRoundedRect {
2728            rect,
2729            radii,
2730            brush: brush.into(),
2731            border: None,
2732            shadow: None,
2733        });
2734    }
2735
2736    /// Fill a rounded rectangle with a brush and stroke an inset border.
2737    pub fn fill_rrect_bordered(
2738        &mut self,
2739        rect: Rect,
2740        radii: [f32; 4],
2741        brush: impl Into<Brush>,
2742        border: Border,
2743    ) {
2744        self.scene.push(SceneCommand::FillRoundedRect {
2745            rect,
2746            radii,
2747            brush: brush.into(),
2748            border: Some(border),
2749            shadow: None,
2750        });
2751    }
2752
2753    /// Paint just a soft drop shadow for a rounded rectangle (no fill).
2754    pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
2755        self.scene.push(SceneCommand::FillRoundedRect {
2756            rect,
2757            radii,
2758            brush: Brush::Solid(Color::TRANSPARENT),
2759            border: None,
2760            shadow: Some(shadow),
2761        });
2762    }
2763
2764    /// Fill a rounded rectangle with a brush behind a soft drop shadow.
2765    pub fn fill_rrect_with_shadow(
2766        &mut self,
2767        rect: Rect,
2768        radii: [f32; 4],
2769        brush: impl Into<Brush>,
2770        shadow: ShadowParams,
2771    ) {
2772        self.scene.push(SceneCommand::FillRoundedRect {
2773            rect,
2774            radii,
2775            brush: brush.into(),
2776            border: None,
2777            shadow: Some(shadow),
2778        });
2779    }
2780
2781    pub fn push_clip(&mut self, path: impl Into<Path>) {
2782        self.scene
2783            .push(SceneCommand::PushClipPath { path: path.into() });
2784    }
2785
2786    pub fn push_clip_rect(&mut self, rect: Rect) {
2787        self.scene.push(SceneCommand::PushClip { rect });
2788    }
2789
2790    pub fn pop_clip(&mut self) {
2791        self.scene.push(SceneCommand::PopClip);
2792    }
2793
2794    pub fn push_transform(&mut self, transform: Transform) {
2795        self.scene.push(SceneCommand::PushTransform { transform });
2796    }
2797
2798    pub fn translate(&mut self, delta: Vector) {
2799        self.push_transform(Transform::translation_vector(delta));
2800    }
2801
2802    pub fn pop_transform(&mut self) {
2803        self.scene.push(SceneCommand::PopTransform);
2804    }
2805
2806    pub fn push(&mut self, command: SceneCommand) {
2807        self.scene.push(command);
2808    }
2809
2810    pub fn scene(&self) -> &Scene {
2811        &self.scene
2812    }
2813
2814    pub fn scene_mut(&mut self) -> &mut Scene {
2815        &mut self.scene
2816    }
2817
2818    pub fn request(&mut self, request: InvalidationRequest) {
2819        self.invalidations.push(request);
2820    }
2821
2822    pub fn request_paint(&mut self) {
2823        self.request_widget(InvalidationKind::Paint);
2824    }
2825
2826    pub fn request_paint_rect(&mut self, rect: Rect) {
2827        self.request(
2828            InvalidationRequest::new(
2829                InvalidationTarget::Widget(self.widget_id),
2830                InvalidationKind::Paint,
2831            )
2832            .with_region(rect),
2833        );
2834    }
2835
2836    pub fn invalidations(&self) -> &[InvalidationRequest] {
2837        &self.invalidations
2838    }
2839
2840    pub fn set_ime_composition_rect(&mut self, rect: Rect) {
2841        self.ime_composition_rect = Some(rect);
2842    }
2843
2844    pub fn clear_ime_composition_rect(&mut self) {
2845        self.ime_composition_rect = None;
2846    }
2847
2848    pub const fn ime_composition_rect(&self) -> Option<Rect> {
2849        self.ime_composition_rect
2850    }
2851
2852    pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
2853        self.scene
2854            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
2855                descriptor, scene,
2856            )));
2857    }
2858
2859    pub(crate) fn append_scene(&mut self, scene: Scene) {
2860        self.scene.append(scene);
2861    }
2862
2863    pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
2864        self.widget_paint_bounds.insert(widget_id, paint_bounds);
2865    }
2866
2867    pub(crate) fn extend_widget_paint_bounds(
2868        &mut self,
2869        widget_paint_bounds: HashMap<WidgetId, Rect>,
2870    ) {
2871        self.widget_paint_bounds.extend(widget_paint_bounds);
2872    }
2873
2874    pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
2875        self.images.extend(images);
2876    }
2877
2878    pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
2879        self.invalidations.extend(invalidations);
2880    }
2881
2882    pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
2883        if ime_composition_rect.is_some() {
2884            self.ime_composition_rect = ime_composition_rect;
2885        }
2886    }
2887
2888    pub(crate) fn into_parts(
2889        self,
2890    ) -> (
2891        Scene,
2892        Vec<(ImageHandle, PaintImageResource)>,
2893        HashMap<WidgetId, Rect>,
2894        Vec<InvalidationRequest>,
2895        Option<Rect>,
2896    ) {
2897        (
2898            self.scene,
2899            self.images,
2900            self.widget_paint_bounds,
2901            self.invalidations,
2902            self.ime_composition_rect,
2903        )
2904    }
2905
2906    fn request_widget(&mut self, kind: InvalidationKind) {
2907        self.request(InvalidationRequest::new(
2908            InvalidationTarget::Widget(self.widget_id),
2909            kind,
2910        ));
2911    }
2912}
2913
2914fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
2915    let mut hasher = DefaultHasher::new();
2916    run.text.hash(&mut hasher);
2917    run.rect.size.width.to_bits().hash(&mut hasher);
2918    run.rect.size.height.to_bits().hash(&mut hasher);
2919    run.style.font.map(|font| font.get()).hash(&mut hasher);
2920    run.style.font_size.to_bits().hash(&mut hasher);
2921    run.style.line_height.to_bits().hash(&mut hasher);
2922    run.style.weight.value().hash(&mut hasher);
2923    run.style.style.hash(&mut hasher);
2924    run.style.stretch.hash(&mut hasher);
2925    run.style.features.hash(&mut hasher);
2926    TextLayoutHandle::new(hasher.finish().max(1))
2927}
2928
2929#[derive(Debug, Clone)]
2930pub struct SemanticsCtx {
2931    window_id: WindowId,
2932    widget_id: WidgetId,
2933    root_widget_id: WidgetId,
2934    focused_widget_id: Option<WidgetId>,
2935    bounds: Rect,
2936    nodes: Vec<SemanticsNode>,
2937}
2938
2939impl SemanticsCtx {
2940    pub(crate) fn new(
2941        window_id: WindowId,
2942        widget_id: WidgetId,
2943        root_widget_id: WidgetId,
2944        bounds: Rect,
2945        focused_widget_id: Option<WidgetId>,
2946    ) -> Self {
2947        Self {
2948            window_id,
2949            widget_id,
2950            root_widget_id,
2951            focused_widget_id,
2952            bounds,
2953            nodes: Vec::new(),
2954        }
2955    }
2956
2957    pub const fn window_id(&self) -> WindowId {
2958        self.window_id
2959    }
2960
2961    pub const fn widget_id(&self) -> WidgetId {
2962        self.widget_id
2963    }
2964
2965    /// Read an observable whose changes affect semantics.
2966    pub fn observe<T, O>(&self, observable: &O) -> T
2967    where
2968        O: Observable<T> + ?Sized,
2969    {
2970        self.observe_with(observable, InvalidationKind::Semantics)
2971    }
2972
2973    /// Read an observable and explicitly declare the resulting invalidation.
2974    pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2975    where
2976        O: Observable<T> + ?Sized,
2977    {
2978        crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2979    }
2980
2981    pub const fn root_widget_id(&self) -> WidgetId {
2982        self.root_widget_id
2983    }
2984
2985    pub const fn focused_widget_id(&self) -> Option<WidgetId> {
2986        self.focused_widget_id
2987    }
2988
2989    pub fn is_focused(&self) -> bool {
2990        self.focused_widget_id == Some(self.widget_id)
2991    }
2992
2993    pub const fn bounds(&self) -> Rect {
2994        self.bounds
2995    }
2996
2997    pub fn push(&mut self, node: SemanticsNode) {
2998        self.nodes.push(node);
2999    }
3000
3001    pub fn nodes(&self) -> &[SemanticsNode] {
3002        &self.nodes
3003    }
3004
3005    pub(crate) fn extend_nodes(&mut self, nodes: Vec<SemanticsNode>) {
3006        self.nodes.extend(nodes);
3007    }
3008
3009    pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
3010        self.nodes
3011    }
3012}
3013
3014#[cfg(test)]
3015mod tests {
3016    use std::sync::Arc;
3017
3018    use crate::CommandSender;
3019
3020    use super::{
3021        ArrangeCtx, EventCtx, EventPhase, KeyedChildren, MeasureCtx, MeasureScope, PaintCtx,
3022        SemanticsCtx, SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod,
3023        WidgetPodMutVisitor, WidgetPodVisitor,
3024    };
3025    use std::cell::Cell;
3026    use std::collections::{HashMap, HashSet};
3027    use std::rc::Rc;
3028    use sui_core::{
3029        Clipboard, Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode,
3030        SemanticsRole, Size, Vector, WidgetId, WindowId,
3031    };
3032    use sui_layout::{Constraints, LayoutContext};
3033    use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
3034    use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
3035
3036    fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
3037        MeasureCtx::new(
3038            window_id,
3039            widget_id,
3040            Rect::ZERO,
3041            DpiInfo::default(),
3042            std::sync::Arc::new(TextSystem::new()),
3043            std::sync::Arc::new(FontRegistry::new()),
3044            std::sync::Arc::new(ImageRegistry::new()),
3045        )
3046    }
3047
3048    #[test]
3049    fn measure_ctx_wraps_reusable_layout_context() {
3050        let mut images = ImageRegistry::new();
3051        images.insert(
3052            ImageHandle::new(9),
3053            RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
3054        );
3055        let layout = LayoutContext::new(
3056            DpiInfo::new(
3057                1.5,
3058                Some(144.0),
3059                Size::new(200.0, 100.0),
3060                Size::new(300.0, 150.0),
3061            ),
3062            Arc::new(TextSystem::new()),
3063            Arc::new(FontRegistry::new()),
3064            Arc::new(images),
3065        );
3066
3067        let measure = MeasureCtx::with_layout(
3068            WindowId::new(1),
3069            WidgetId::new(2),
3070            Rect::new(4.0, 6.0, 32.0, 18.0),
3071            layout.clone(),
3072        );
3073
3074        assert_eq!(measure.dpi(), layout.dpi());
3075        assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
3076        assert_eq!(
3077            measure.layout().image_size(ImageHandle::new(9)),
3078            Some(Size::new(3.0, 2.0))
3079        );
3080    }
3081
3082    #[test]
3083    fn measure_and_paint_ctx_expose_dpi_info() {
3084        let dpi = DpiInfo::new(
3085            2.0,
3086            Some(192.0),
3087            sui_core::Size::new(320.0, 180.0),
3088            sui_core::Size::new(640.0, 360.0),
3089        );
3090
3091        let measure = MeasureCtx::new(
3092            WindowId::new(1),
3093            WidgetId::new(2),
3094            Rect::ZERO,
3095            dpi,
3096            std::sync::Arc::new(TextSystem::new()),
3097            std::sync::Arc::new(FontRegistry::new()),
3098            std::sync::Arc::new(ImageRegistry::new()),
3099        );
3100        let paint = PaintCtx::new(
3101            WindowId::new(1),
3102            WidgetId::new(2),
3103            Rect::new(0.0, 0.0, 120.0, 60.0),
3104            None,
3105            dpi,
3106            Arc::new(TextSystem::new()),
3107            Arc::new(FontRegistry::new()),
3108            Arc::new(ImageRegistry::new()),
3109        );
3110        let event = EventCtx::new(
3111            WindowId::new(1),
3112            WidgetId::new(2),
3113            Rect::new(0.0, 0.0, 120.0, 60.0),
3114            dpi,
3115            0.0,
3116            EventPhase::Target,
3117            None,
3118            Clipboard::new(),
3119            CommandSender::new(),
3120        );
3121
3122        assert_eq!(measure.dpi(), dpi);
3123        assert_eq!(paint.dpi(), dpi);
3124        assert_eq!(event.dpi(), dpi);
3125    }
3126
3127    struct LabelWidget;
3128
3129    impl Widget for LabelWidget {
3130        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
3131            constraints.clamp(sui_core::Size::new(48.0, 20.0))
3132        }
3133
3134        fn paint(&self, ctx: &mut PaintCtx) {
3135            ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
3136        }
3137
3138        fn semantics(&self, ctx: &mut SemanticsCtx) {
3139            ctx.push(SemanticsNode::new(
3140                ctx.widget_id(),
3141                SemanticsRole::Text,
3142                ctx.bounds(),
3143            ));
3144        }
3145    }
3146
3147    struct BoundsLeaf;
3148
3149    impl Widget for BoundsLeaf {
3150        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3151            constraints.max
3152        }
3153
3154        fn paint(&self, ctx: &mut PaintCtx) {
3155            ctx.fill_rect(
3156                Rect::new(10.0, 10.0, 80.0, 50.0),
3157                Color::rgba(0.2, 0.3, 0.4, 1.0),
3158            );
3159        }
3160    }
3161
3162    struct BoundsWrapper {
3163        child: WidgetPod,
3164        clip: Option<Rect>,
3165        translation: Vector,
3166    }
3167
3168    impl BoundsWrapper {
3169        fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
3170            Self {
3171                child: WidgetPod::new(child),
3172                clip,
3173                translation,
3174            }
3175        }
3176    }
3177
3178    impl Widget for BoundsWrapper {
3179        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3180            self.child.measure(ctx, constraints)
3181        }
3182
3183        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3184            self.child.arrange(ctx, bounds);
3185        }
3186
3187        fn paint(&self, ctx: &mut PaintCtx) {
3188            if let Some(clip) = self.clip {
3189                ctx.push_clip_rect(clip);
3190            }
3191            if self.translation != Vector::ZERO {
3192                ctx.translate(self.translation);
3193            }
3194
3195            self.child.paint(ctx);
3196
3197            if self.translation != Vector::ZERO {
3198                ctx.pop_transform();
3199            }
3200            if self.clip.is_some() {
3201                ctx.pop_clip();
3202            }
3203        }
3204
3205        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3206            visitor.visit(&self.child);
3207        }
3208
3209        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3210            visitor.visit(&mut self.child);
3211        }
3212    }
3213
3214    #[test]
3215    fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
3216        let mut ctx = EventCtx::new(
3217            WindowId::new(1),
3218            WidgetId::new(2),
3219            Rect::new(8.0, 12.0, 24.0, 36.0),
3220            DpiInfo::default(),
3221            0.0,
3222            EventPhase::Target,
3223            None,
3224            Clipboard::new(),
3225            CommandSender::new(),
3226        );
3227
3228        ctx.request_measure();
3229        ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
3230        ctx.request_transform();
3231        ctx.request_effect();
3232        ctx.request_visibility();
3233        ctx.request_animation_frame();
3234        ctx.request_focus();
3235        ctx.set_handled();
3236
3237        assert!(ctx.is_handled());
3238        assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
3239        assert_eq!(ctx.invalidations().len(), 5);
3240        assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
3241        assert_eq!(
3242            ctx.invalidations()[1].region,
3243            Some(Rect::new(8.0, 12.0, 24.0, 36.0))
3244        );
3245        assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
3246        assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
3247        assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
3248        assert_eq!(
3249            ctx.take_wake_requests(),
3250            vec![WakeRequest::RequestAnimationFrame {
3251                target: WidgetId::new(2)
3252            }]
3253        );
3254    }
3255
3256    #[test]
3257    fn request_animation_frame_enqueues_widget_for_next_frame() {
3258        let mut ctx = EventCtx::new(
3259            WindowId::new(4),
3260            WidgetId::new(9),
3261            Rect::new(0.0, 0.0, 20.0, 10.0),
3262            DpiInfo::default(),
3263            16.0,
3264            EventPhase::Target,
3265            None,
3266            Clipboard::new(),
3267            CommandSender::new(),
3268        );
3269
3270        ctx.request_animation_frame();
3271
3272        assert_eq!(
3273            ctx.take_wake_requests(),
3274            vec![WakeRequest::RequestAnimationFrame {
3275                target: WidgetId::new(9)
3276            }]
3277        );
3278    }
3279
3280    struct CountingChild {
3281        measures: Rc<Cell<u32>>,
3282    }
3283
3284    impl Widget for CountingChild {
3285        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
3286            self.measures.set(self.measures.get() + 1);
3287            constraints.clamp(sui_core::Size::new(10.0, 10.0))
3288        }
3289    }
3290
3291    struct PassthroughParent {
3292        child: WidgetPod,
3293    }
3294
3295    impl Widget for PassthroughParent {
3296        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
3297            self.child.measure(ctx, constraints)
3298        }
3299
3300        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3301            visitor.visit(&self.child);
3302        }
3303
3304        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3305            visitor.visit(&mut self.child);
3306        }
3307    }
3308
3309    fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
3310        MeasureCtx::new_scoped_at(
3311            WindowId::new(1),
3312            root_id,
3313            Rect::ZERO,
3314            DpiInfo::default(),
3315            Arc::new(TextSystem::new()),
3316            Arc::new(FontRegistry::new()),
3317            Arc::new(ImageRegistry::new()),
3318            Rc::new(scope),
3319            0.0,
3320        )
3321    }
3322
3323    #[test]
3324    fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
3325        let measures = Rc::new(Cell::new(0u32));
3326        let child = WidgetPod::new(CountingChild {
3327            measures: Rc::clone(&measures),
3328        });
3329        let mut parent = WidgetPod::new(PassthroughParent { child });
3330        let parent_id = parent.id();
3331        let outside = WidgetId::new(u64::MAX);
3332        let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
3333
3334        // 1. First pass (force_all) measures everything, populating caches.
3335        let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
3336        parent.measure(&mut ctx, constraints);
3337        assert_eq!(measures.get(), 1, "initial pass must measure the child");
3338
3339        // 2. A pass where nothing is dirty short-circuits the clean parent before
3340        //    it ever recurses, so the child is not re-measured.
3341        let mut ctx = scoped_measure_ctx(
3342            outside,
3343            MeasureScope::scoped(HashSet::new(), HashSet::new()),
3344        );
3345        parent.measure(&mut ctx, constraints);
3346        assert_eq!(measures.get(), 1, "clean subtree must be skipped");
3347
3348        // 3. Re-measuring only the parent (ancestor) without marking it a subtree
3349        //    root recomputes the parent but lets the clean child short-circuit.
3350        let mut dirty = HashSet::new();
3351        dirty.insert(parent_id);
3352        let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
3353        parent.measure(&mut ctx, constraints);
3354        assert_eq!(
3355            measures.get(),
3356            1,
3357            "ancestor-only re-measure must not force the subtree"
3358        );
3359
3360        // 4. Marking the parent a subtree root forces its whole subtree to
3361        //    re-measure even though the child was never individually invalidated.
3362        //    This is the case that the popover/stack-surface regression needed.
3363        let mut dirty = HashSet::new();
3364        dirty.insert(parent_id);
3365        let mut roots = HashSet::new();
3366        roots.insert(parent_id);
3367        let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
3368        parent.measure(&mut ctx, constraints);
3369        assert_eq!(
3370            measures.get(),
3371            2,
3372            "a changed widget must force its descendants to re-measure"
3373        );
3374    }
3375
3376    #[test]
3377    fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
3378        let mut pod = WidgetPod::new(LabelWidget);
3379        pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
3380
3381        let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
3382        let size = pod.measure(
3383            &mut measure,
3384            Constraints::tight(sui_core::Size::new(64.0, 32.0)),
3385        );
3386        let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
3387        pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
3388
3389        let mut paint = PaintCtx::new(
3390            WindowId::new(3),
3391            WidgetId::new(4),
3392            Rect::new(0.0, 0.0, 120.0, 60.0),
3393            None,
3394            DpiInfo::default(),
3395            Arc::new(TextSystem::new()),
3396            Arc::new(FontRegistry::new()),
3397            Arc::new(ImageRegistry::new()),
3398        );
3399        pod.paint(&mut paint);
3400
3401        let mut semantics = SemanticsCtx::new(
3402            WindowId::new(3),
3403            WidgetId::new(4),
3404            WidgetId::new(4),
3405            Rect::new(0.0, 0.0, 120.0, 60.0),
3406            None,
3407        );
3408        pod.semantics(&mut semantics);
3409
3410        assert_eq!(size, sui_core::Size::new(64.0, 32.0));
3411        assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
3412        assert_eq!(paint.scene().commands().len(), 1);
3413        assert!(matches!(
3414            paint.scene().commands()[0],
3415            SceneCommand::FillRect { .. }
3416        ));
3417        assert_eq!(semantics.nodes().len(), 1);
3418    }
3419
3420    #[test]
3421    fn single_child_wraps_measure_arrange_and_visitation() {
3422        struct CaptureVisitor {
3423            ids: Vec<WidgetId>,
3424        }
3425
3426        impl WidgetPodVisitor for CaptureVisitor {
3427            fn visit(&mut self, child: &WidgetPod) {
3428                self.ids.push(child.id());
3429            }
3430        }
3431
3432        impl WidgetPodMutVisitor for CaptureVisitor {
3433            fn visit(&mut self, child: &mut WidgetPod) {
3434                self.ids.push(child.id());
3435            }
3436        }
3437
3438        let mut child = SingleChild::new(LabelWidget);
3439        let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
3440        let size = child.measure(
3441            &mut measure,
3442            Constraints::tight(sui_core::Size::new(80.0, 24.0)),
3443        );
3444        let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
3445        child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
3446
3447        let mut visitor = CaptureVisitor { ids: Vec::new() };
3448        child.visit_children(&mut visitor);
3449        child.visit_children_mut(&mut visitor);
3450
3451        assert_eq!(size, sui_core::Size::new(80.0, 24.0));
3452        assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
3453        assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
3454    }
3455
3456    #[test]
3457    fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
3458        let mut children = WidgetChildren::with_capacity(2);
3459        children.push(LabelWidget);
3460        children.push(LabelWidget);
3461
3462        let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
3463        children.measure_child(
3464            0,
3465            &mut measure,
3466            Constraints::tight(sui_core::Size::new(40.0, 18.0)),
3467        );
3468        children.measure_child(
3469            1,
3470            &mut measure,
3471            Constraints::tight(sui_core::Size::new(60.0, 18.0)),
3472        );
3473        let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
3474        children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
3475        children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
3476
3477        let mut paint = PaintCtx::new(
3478            WindowId::new(9),
3479            WidgetId::new(10),
3480            Rect::new(0.0, 0.0, 120.0, 40.0),
3481            None,
3482            DpiInfo::default(),
3483            Arc::new(TextSystem::new()),
3484            Arc::new(FontRegistry::new()),
3485            Arc::new(ImageRegistry::new()),
3486        );
3487        children.paint(&mut paint);
3488
3489        let mut semantics = SemanticsCtx::new(
3490            WindowId::new(9),
3491            WidgetId::new(10),
3492            WidgetId::new(10),
3493            Rect::new(0.0, 0.0, 120.0, 40.0),
3494            None,
3495        );
3496        children.semantics(&mut semantics);
3497
3498        assert_eq!(children.len(), 2);
3499        assert_eq!(paint.scene().commands().len(), 2);
3500        assert_eq!(semantics.nodes().len(), 2);
3501    }
3502
3503    #[test]
3504    fn keyed_children_preserve_pods_and_update_item_signals() {
3505        let mut children = KeyedChildren::<u64, (u64, String)>::new();
3506        let first = children.reconcile(
3507            [(1, "one".to_string()), (2, "two".to_string())],
3508            |item| item.0,
3509            |_key, _value| LabelWidget,
3510        );
3511        assert_eq!(first.inserted, 2);
3512        let first_ids = children
3513            .iter()
3514            .map(|(key, _, child)| (*key, child.id()))
3515            .collect::<HashMap<_, _>>();
3516
3517        let second = children.reconcile(
3518            [
3519                (2, "two updated".to_string()),
3520                (1, "one".to_string()),
3521                (3, "three".to_string()),
3522            ],
3523            |item| item.0,
3524            |_key, _value| LabelWidget,
3525        );
3526        assert_eq!(second.inserted, 1);
3527        assert_eq!(second.removed, 0);
3528        assert_eq!(second.moved, 2);
3529        assert_eq!(second.updated, 1);
3530        assert_eq!(second.unchanged, 1);
3531
3532        let entries = children
3533            .iter()
3534            .map(|(key, value, child)| (*key, value.get(), child.id()))
3535            .collect::<Vec<_>>();
3536        assert_eq!(
3537            entries.iter().map(|(key, _, _)| *key).collect::<Vec<_>>(),
3538            vec![2, 1, 3]
3539        );
3540        assert_eq!(entries[0].1.1, "two updated");
3541        assert_eq!(entries[0].2, first_ids[&2]);
3542        assert_eq!(entries[1].2, first_ids[&1]);
3543    }
3544
3545    #[test]
3546    fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
3547        let inner = BoundsWrapper::new(
3548            BoundsLeaf,
3549            Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
3550            Vector::new(0.0, 7.0),
3551        );
3552        let outer = BoundsWrapper::new(
3553            inner,
3554            Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
3555            Vector::new(5.0, 0.0),
3556        );
3557        // This pass-through level exercises the balanced Scene::append summary path
3558        // after the clipped/transformed child stream has returned to identity state.
3559        let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
3560        let window_id = WindowId::new(17);
3561        let root_id = WidgetId::new(18);
3562        let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
3563        let mut measure = measure_ctx(window_id, root_id);
3564        root.measure(&mut measure, Constraints::tight(bounds.size));
3565        let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
3566        root.arrange(&mut arrange, bounds);
3567
3568        let mut paint = PaintCtx::new(
3569            window_id,
3570            root_id,
3571            bounds,
3572            None,
3573            DpiInfo::default(),
3574            Arc::new(TextSystem::new()),
3575            Arc::new(FontRegistry::new()),
3576            Arc::new(ImageRegistry::new()),
3577        );
3578        root.paint(&mut paint);
3579
3580        assert_eq!(
3581            paint.scene().content_bounds(),
3582            Some(Rect::new(15.0, 17.0, 80.0, 50.0))
3583        );
3584        assert_eq!(
3585            paint.scene().paint_bounds(),
3586            Some(Rect::new(15.0, 17.0, 50.0, 43.0))
3587        );
3588        assert_eq!(
3589            paint.scene().paint_bounds(),
3590            paint.scene().clone().paint_bounds()
3591        );
3592    }
3593
3594    #[test]
3595    fn paint_ctx_emits_extended_scene_commands() {
3596        let mut paint = PaintCtx::new(
3597            WindowId::new(11),
3598            WidgetId::new(12),
3599            Rect::new(0.0, 0.0, 120.0, 60.0),
3600            None,
3601            DpiInfo::default(),
3602            Arc::new(TextSystem::new()),
3603            Arc::new(FontRegistry::new()),
3604            Arc::new(ImageRegistry::new()),
3605        );
3606
3607        let mut path = sui_core::Path::builder();
3608        path.move_to(Point::new(4.0, 5.0))
3609            .line_to(Point::new(24.0, 5.0))
3610            .line_to(Point::new(14.0, 15.0))
3611            .close();
3612        paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
3613        paint.draw_text(
3614            Rect::new(8.0, 10.0, 80.0, 20.0),
3615            "hello",
3616            TextStyle::new(Color::BLACK),
3617        );
3618        paint.draw_image(
3619            Rect::new(0.0, 0.0, 16.0, 16.0),
3620            sui_core::ImageHandle::new(3),
3621        );
3622        paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
3623        paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
3624        paint.translate(Vector::new(3.0, 4.0));
3625        paint.pop_transform();
3626        paint.pop_clip();
3627        paint.pop_clip();
3628
3629        assert!(matches!(
3630            paint.scene().commands()[0],
3631            SceneCommand::StrokePath { .. }
3632        ));
3633        assert!(matches!(
3634            paint.scene().commands()[1],
3635            SceneCommand::DrawShapedText(_)
3636        ));
3637        assert!(matches!(
3638            paint.scene().commands()[2],
3639            SceneCommand::DrawImage { .. }
3640        ));
3641        assert!(matches!(
3642            paint.scene().commands()[3],
3643            SceneCommand::PushClipPath { .. }
3644        ));
3645        assert!(matches!(
3646            paint.scene().commands()[4],
3647            SceneCommand::PushClip { .. }
3648        ));
3649        assert!(matches!(
3650            paint.scene().commands()[5],
3651            SceneCommand::PushTransform { .. }
3652        ));
3653        assert!(matches!(
3654            paint.scene().commands()[6],
3655            SceneCommand::PopTransform
3656        ));
3657        assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
3658        assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
3659    }
3660
3661    #[test]
3662    fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
3663        let run = TextRun {
3664            rect: Rect::new(8.0, 10.0, 80.0, 20.0),
3665            text: "hello".to_string(),
3666            style: TextStyle::new(Color::BLACK),
3667        };
3668        let mut recolored = run.clone();
3669        recolored.style.color = Color::WHITE;
3670        let mut bold = run.clone();
3671        bold.style.weight = FontWeight::BOLD;
3672
3673        assert_eq!(
3674            super::stable_text_run_handle(&run),
3675            super::stable_text_run_handle(&recolored)
3676        );
3677        assert_ne!(
3678            super::stable_text_run_handle(&run),
3679            super::stable_text_run_handle(&bold)
3680        );
3681    }
3682
3683    #[test]
3684    fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
3685        let text_system = Arc::new(TextSystem::new());
3686        let mut paint = PaintCtx::new(
3687            WindowId::new(12),
3688            WidgetId::new(13),
3689            Rect::new(0.0, 0.0, 120.0, 60.0),
3690            None,
3691            DpiInfo::default(),
3692            Arc::clone(&text_system),
3693            Arc::new(FontRegistry::new()),
3694            Arc::new(ImageRegistry::new()),
3695        );
3696        let paint_color = Color::BLACK;
3697        paint.draw_text(
3698            Rect::new(8.0, 10.0, 80.0, 20.0),
3699            "hello",
3700            TextStyle::new(paint_color),
3701        );
3702
3703        let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
3704            panic!("draw_text should emit shaped text when layout succeeds");
3705        };
3706        assert_eq!(text.color_override, Some(paint_color));
3707
3708        let registry = text_system.text_layout_registry();
3709        let layout = text
3710            .resolve(registry.as_ref())
3711            .expect("drawn shaped text should resolve from the registry");
3712        assert_eq!(layout.style().color, Color::WHITE);
3713    }
3714
3715    #[test]
3716    fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
3717        let text_system = Arc::new(TextSystem::new());
3718        let layout = text_system
3719            .shape_text_persistent(
3720                None,
3721                "held",
3722                Size::new(80.0, 20.0),
3723                TextStyle::new(Color::WHITE),
3724                &FontRegistry::new(),
3725            )
3726            .unwrap();
3727        text_system.retain_persistent_layouts(&std::collections::HashSet::new());
3728        assert!(!text_system.text_layout_registry().contains(layout.handle()));
3729
3730        let mut paint = PaintCtx::new(
3731            WindowId::new(12),
3732            WidgetId::new(13),
3733            Rect::new(0.0, 0.0, 120.0, 60.0),
3734            None,
3735            DpiInfo::default(),
3736            Arc::clone(&text_system),
3737            Arc::new(FontRegistry::new()),
3738            Arc::new(ImageRegistry::new()),
3739        );
3740        paint.draw_persistent_text_layout(Point::ZERO, &layout);
3741
3742        assert!(text_system.text_layout_registry().contains(layout.handle()));
3743        assert!(matches!(
3744            paint.scene().commands()[0],
3745            SceneCommand::DrawShapedText(_)
3746        ));
3747    }
3748
3749    #[test]
3750    fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
3751        let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
3752            .layout()
3753            .shape_text(
3754                "hello",
3755                sui_core::Size::new(80.0, 20.0),
3756                TextStyle::new(Color::BLACK),
3757            )
3758            .unwrap();
3759
3760        let mut paint = PaintCtx::new(
3761            WindowId::new(13),
3762            WidgetId::new(14),
3763            Rect::new(0.0, 0.0, 120.0, 60.0),
3764            None,
3765            DpiInfo::default(),
3766            Arc::new(TextSystem::new()),
3767            Arc::new(FontRegistry::new()),
3768            Arc::new(ImageRegistry::new()),
3769        );
3770        let origin = Point::new(8.0, 10.0);
3771        paint.draw_text_layout(origin, &layout);
3772        paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
3773
3774        assert!(matches!(
3775            paint.scene().commands()[0],
3776            SceneCommand::DrawShapedText(_)
3777        ));
3778        assert!(paint.ime_composition_rect().is_some());
3779        assert!(!layout.selection_rects(1..4).is_empty());
3780    }
3781}