Skip to main content

waft_widgets/widgets/
overlay.rs

1//! Flutter counterpart: `widgets/overlay.dart`.
2
3use std::any::{Any, TypeId};
4use std::cell::Cell;
5use std::fmt::{self, Debug, Display};
6use std::panic::Location;
7use std::rc::Rc;
8
9use waft_embedder::{Clip, Matrix4, Offset, Rect, Size, TextDirection};
10use waft_foundation::{
11    App, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty, DiagnosticsTreeStyle,
12    EnumProperty, Handle, IntProperty, ListenableObject, Listener, OptionRetained, Retained,
13    ValueNotifier, message,
14};
15use waft_painting::{Alignment, AlignmentGeometry};
16use waft_rendering::{
17    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ClipRectLayer, Constraints,
18    ContainerBoxParentData, ContainerParentData, ContainerParentDataMixin,
19    ContainerRenderObjectData, ContainerRenderObjectMixin, LayerHandle, PaintingContext,
20    ParentData, PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject,
21    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
22    RenderObjectWithLayoutCallbackData, RenderObjectWithLayoutCallbackMixin, RenderProxyBoxMixin,
23    StackParentData,
24};
25use waft_scheduler::{
26    FrameCallback, SchedulerBinding, SchedulerPhase, Ticker, TickerCallback, TickerProviderObject,
27};
28
29use crate::framework::{
30    AnyElement, BuildContext, BuildScope, BuildScopeCallback, CreationLocation, Element,
31    ElementData, GlobalKey, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectElementBase,
32    MultiChildRenderObjectElementData, MultiChildRenderObjectWidget, RenderObjectElement,
33    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
34    SingleChildRenderObjectWidget, Slot, State, StateData, StatefulWidget, Widget, WidgetKind,
35    WidgetRef, downcast_widget,
36};
37use crate::view::View;
38use crate::widgets::basic::{Builder, Directionality, WidgetBuilder};
39use crate::widgets::lookup_boundary::LookupBoundary;
40use crate::widgets::media_query::MediaQuery;
41use crate::widgets::ticker_provider::{
42    TickerMode, TickerProviderStateMixin, TickerProviderStateMixinData,
43};
44use waft_foundation::Ref;
45
46/// The signature of the widget builder callback used in
47/// [`OverlayPortal::overlay_child_layout_builder`].
48pub type OverlayChildLayoutBuilder =
49    Rc<dyn Fn(&mut App, BuildContext, OverlayChildLayoutInfo) -> WidgetRef>;
50
51/// The additional layout information available to the
52/// [`OverlayPortal::overlay_child_layout_builder`] callback.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct OverlayChildLayoutInfo {
55    child_size: Size,
56    child_paint_transform: Matrix4,
57    overlay_size: Size,
58}
59
60impl OverlayChildLayoutInfo {
61    /// The size of [`OverlayPortal::child`] in its own coordinates.
62    pub fn child_size(&self) -> Size {
63        self.child_size
64    }
65
66    /// The paint transform of [`OverlayPortal::child`], in the target [`Overlay`]'s
67    /// coordinates.
68    pub fn child_paint_transform(&self) -> Matrix4 {
69        self.child_paint_transform
70    }
71
72    /// The size of the target [`Overlay`] in its own coordinates.
73    pub fn overlay_size(&self) -> Size {
74        self.overlay_size
75    }
76}
77
78// * OverlayEntry Implementation
79
80/// A place in an [`Overlay`] that can contain a widget.
81///
82/// Overlay entries are inserted into an [`Overlay`] using the [`OverlayState::insert`] or
83/// [`OverlayState::insert_all`] functions. To find the closest enclosing overlay for a given
84/// [`BuildContext`], use the [`Overlay::of`] function.
85///
86/// An overlay entry can be in at most one overlay at a time. To remove an entry from its
87/// overlay, call the [`remove`](Self::remove) function on the overlay entry.
88///
89/// Because an [`Overlay`] uses a stack layout, overlay entries can use `Positioned` to
90/// position themselves within the overlay.
91///
92/// By default, if there is an entirely [`opaque`](Self::opaque) entry over this one, then this
93/// one will not be included in the widget tree (in particular, stateful widgets within the
94/// overlay entry will not be instantiated). To ensure that your overlay entry is still built
95/// even if it is not visible, set [`maintain_state`](Self::maintain_state) to true. This is
96/// more expensive, so should be done with care.
97///
98/// `Handle<OverlayEntry>` is a [`Listenable`](waft_foundation::Listenable) that notifies
99/// when the widget built by [`builder`](Self::builder) is mounted or unmounted, whose exact
100/// state can be queried by [`mounted`](Self::mounted). After the owner of the [`OverlayEntry`] calls
101/// [`remove`](Self::remove) and then [`dispose`](Self::dispose), the widget may not be
102/// immediately removed from the widget tree. As a result listeners of the [`OverlayEntry`] can
103/// get notified for one last time after the `dispose` call, when the widget is eventually
104/// unmounted.
105///
106/// See also:
107///
108///  * [`Overlay`], a stack of entries that can be managed independently.
109///  * [`OverlayState`], the current state of an Overlay.
110pub struct OverlayEntry {
111    /// This entry will include the widget built by this builder in the overlay at the entry's
112    /// position.
113    ///
114    /// To cause this builder to be called again, call [`mark_needs_build`] on this overlay
115    /// entry.
116    ///
117    /// [`mark_needs_build`]: Self::mark_needs_build
118    pub builder: WidgetBuilder,
119    opaque: bool,
120    maintain_state: bool,
121    can_size_overlay: bool,
122    /// The currently mounted [`OverlayEntryWidgetState`] built using this [`OverlayEntry`].
123    overlay_entry_state_notifier:
124        Option<Ref<ValueNotifier<Option<Handle<OverlayEntryWidgetState>>>>>,
125    overlay: Option<Handle<OverlayState>>,
126    key: GlobalKey,
127    disposed_by_owner: bool,
128}
129
130impl OverlayEntry {
131    /// Creates an overlay entry.
132    ///
133    /// To insert the entry into an [`Overlay`], first find the overlay using [`Overlay::of`]
134    /// and then call [`OverlayState::insert`]. To remove the entry, call
135    /// [`remove`](Self::remove) on the overlay entry itself.
136    ///
137    /// Dart's defaults: `opaque` false, `maintain_state` false, `can_size_overlay` false.
138    pub fn new(
139        app: &mut App,
140        builder: WidgetBuilder,
141        opaque: bool,
142        maintain_state: bool,
143        can_size_overlay: bool,
144    ) -> Ref<OverlayEntry> {
145        let notifier = app.create(ValueNotifier::new(None));
146        app.create(OverlayEntry {
147            builder,
148            opaque,
149            maintain_state,
150            can_size_overlay,
151            overlay_entry_state_notifier: Some(notifier),
152            overlay: None,
153            key: GlobalKey::new(),
154            disposed_by_owner: false,
155        })
156    }
157
158    /// Whether this entry occludes the entire overlay.
159    ///
160    /// If an entry claims to be opaque, then, for efficiency, the overlay will skip building
161    /// entries below that entry unless they have [`maintain_state`](Self::maintain_state) set.
162    pub fn opaque(self: Handle<Self>, app: &App) -> bool {
163        app.get(self).opaque
164    }
165
166    /// Sets [`opaque`](Self::opaque).
167    pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
168        debug_assert!(!app.get(self).disposed_by_owner);
169        if app.get(self).opaque == value {
170            return;
171        }
172        app.get_mut(self).opaque = value;
173        if let Some(overlay) = app.get(self).overlay {
174            overlay.did_change_entry_opacity(app);
175        }
176    }
177
178    /// Whether this entry must be included in the tree even if there is a fully
179    /// [`opaque`](Self::opaque) entry above it.
180    ///
181    /// By default, if there is an entirely opaque entry over this one, then this one will not
182    /// be included in the widget tree (in particular, stateful widgets within the overlay
183    /// entry will not be instantiated). To ensure that your overlay entry is still built even
184    /// if it is not visible, set this to true. This is more expensive, so should be done with
185    /// care.
186    ///
187    /// This is used by the `Navigator` and `Route` objects to ensure that routes are kept
188    /// around even when in the background.
189    pub fn maintain_state(self: Handle<Self>, app: &App) -> bool {
190        app.get(self).maintain_state
191    }
192
193    /// Sets [`maintain_state`](Self::maintain_state).
194    pub fn set_maintain_state(self: Handle<Self>, app: &mut App, value: bool) {
195        debug_assert!(!app.get(self).disposed_by_owner);
196        if app.get(self).maintain_state == value {
197            return;
198        }
199        app.get_mut(self).maintain_state = value;
200        let overlay = app.get(self).overlay.expect("inserted into an Overlay");
201        overlay.did_change_entry_opacity(app);
202    }
203
204    /// Whether the content of this [`OverlayEntry`] can be used to size the [`Overlay`].
205    ///
206    /// In most situations the overlay sizes itself based on its incoming constraints to be as
207    /// large as possible. However, if that would result in an infinite size, it has to rely on
208    /// one of its children to size itself. In this situation, the overlay will consult the
209    /// topmost non-positioned overlay entry that has this property set to true, lay it out with
210    /// the incoming [`BoxConstraints`] of the overlay, and force all other non-positioned
211    /// overlay entries to have the same size.
212    ///
213    /// Overlay entries that set this to true must be able to handle unconstrained
214    /// [`BoxConstraints`].
215    pub fn can_size_overlay(self: Handle<Self>, app: &App) -> bool {
216        app.get(self).can_size_overlay
217    }
218
219    /// Whether the [`OverlayEntry`] is currently mounted in the widget tree.
220    ///
221    /// The [`OverlayEntry`] notifies its listeners when this value changes.
222    pub fn mounted(self: Handle<Self>, app: &App) -> bool {
223        app.get(self)
224            .overlay_entry_state_notifier
225            .as_ref()
226            .is_some_and(|notifier| app.get(notifier).value().is_some())
227    }
228
229    /// Remove this entry from the overlay.
230    ///
231    /// This should only be called once.
232    ///
233    /// This method removes this overlay entry from the overlay immediately. The UI will be
234    /// updated in the same frame if this method is called before the overlay rebuild in this
235    /// frame; otherwise, the UI will be updated in the next frame.
236    pub fn remove(self: Handle<Self>, app: &mut App) {
237        let overlay = app
238            .get(self)
239            .overlay
240            .expect("An OverlayEntry should be removed only once.");
241        debug_assert!(!app.get(self).disposed_by_owner);
242        app.get_mut(self).overlay = None;
243        if !overlay.mounted(app) {
244            return;
245        }
246
247        app.get_mut(overlay).entries.retain(|entry| entry != self);
248        if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
249            SchedulerBinding::add_post_frame_callback(
250                app,
251                FrameCallback::handle_method(overlay, OverlayState::mark_dirty_after_frame),
252                View::maybe_id_of(app, overlay.context(app)),
253            );
254        } else {
255            overlay.mark_dirty(app);
256        }
257    }
258
259    /// Cause this entry to rebuild during the next pipeline flush.
260    ///
261    /// You need to call this function if the output of [`builder`](Self::builder) has changed.
262    pub fn mark_needs_build(self: Handle<Self>, app: &mut App) {
263        debug_assert!(!app.get(self).disposed_by_owner);
264        let key = app.get(self).key.clone();
265        if let Some(state) = key.current_state::<OverlayEntryWidgetState>(app) {
266            state.mark_needs_build(app);
267        }
268    }
269
270    fn did_unmount(self: Handle<Self>, app: &mut App) {
271        debug_assert!(!self.mounted(app));
272        if app.get(self).disposed_by_owner {
273            self.dispose_notifier(app);
274        }
275    }
276
277    fn dispose_notifier(self: Handle<Self>, app: &mut App) {
278        if let Some(notifier) = app.get_mut(self).overlay_entry_state_notifier.take() {
279            notifier.dispose(app);
280        }
281    }
282
283    /// Discards any resources used by this [`OverlayEntry`].
284    ///
285    /// The [`remove`](Self::remove) method must be called before this method if the
286    /// [`OverlayEntry`] is inserted into an [`Overlay`].
287    ///
288    /// After this is called, the object is not in a usable state and should be discarded.
289    /// However, the listeners registered may not be immediately released until the widget built
290    /// using this [`OverlayEntry`] is unmounted from the widget tree.
291    ///
292    /// This method should only be called by the object's owner.
293    pub fn dispose(self: Handle<Self>, app: &mut App) {
294        debug_assert!(!app.get(self).disposed_by_owner);
295        debug_assert!(
296            app.get(self).overlay.is_none(),
297            "An OverlayEntry must first be removed from the Overlay before dispose is called."
298        );
299        app.get_mut(self).disposed_by_owner = true;
300        if !self.mounted(app) {
301            // If we're still mounted when disposed, then this will be disposed in did_unmount,
302            // to allow notifications to occur until the entry is unmounted.
303            self.dispose_notifier(app);
304        }
305    }
306}
307
308impl ListenableObject for OverlayEntry {
309    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
310        debug_assert!(!app.get(self).disposed_by_owner);
311        if let Some(notifier) = app.get(self).overlay_entry_state_notifier.handle() {
312            notifier.add_listener(app, listener);
313        }
314    }
315
316    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
317        if let Some(notifier) = app.get(self).overlay_entry_state_notifier.handle() {
318            notifier.remove_listener(app, listener);
319        }
320    }
321}
322
323impl Debug for OverlayEntry {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        write!(
326            f,
327            "OverlayEntry(opaque: {}; maintainState: {}){}",
328            self.opaque,
329            self.maintain_state,
330            if self.disposed_by_owner {
331                "(DISPOSED)"
332            } else {
333                ""
334            }
335        )
336    }
337}
338
339/// Dart's `_OverlayEntryWidget`: the tree node one [`OverlayEntry`] builds into.
340#[derive(Debug)]
341struct OverlayEntryWidget {
342    key: KeyRef,
343    entry: Ref<OverlayEntry>,
344    overlay_state: Handle<OverlayState>,
345    ticker_enabled: bool,
346}
347
348impl StatefulWidget for OverlayEntryWidget {
349    type State = OverlayEntryWidgetState;
350
351    fn key(&self) -> Option<&KeyRef> {
352        Some(&self.key)
353    }
354
355    fn create_state(&self) -> OverlayEntryWidgetState {
356        OverlayEntryWidgetState {
357            state: StateData::new(),
358            theater: None,
359            sorted_theater_siblings: None,
360        }
361    }
362}
363
364/// Dart's `_OverlayEntryWidgetState`.
365struct OverlayEntryWidgetState {
366    state: StateData<OverlayEntryWidget>,
367    theater: Option<RenderHandle<RenderTheater>>,
368    // Manages the stack of theater children whose paint order is sorted by their
369    // z_order_index. The children added by OverlayPortal are added to this list, and they
370    // will be shown *above* the OverlayEntry tied to this widget. The children with larger
371    // z_order_index values (that is, those `show`n recently) will be painted last.
372    //
373    // This list is lazily created in `add`, and the entries are added/removed via
374    // `add`/`remove`, called by OverlayPortals lower in the tree. `add` or `remove` does not
375    // cause this widget to rebuild, the list will be read by RenderTheater as part of its
376    // render child model. This would ideally be in a RenderObject but there may not be
377    // RenderObjects between RenderTheater and the render subtree OverlayEntry builds.
378    sorted_theater_siblings: Option<Vec<Ref<OverlayEntryLocation>>>,
379}
380
381impl OverlayEntryWidgetState {
382    fn theater(self: Handle<Self>, app: &App) -> RenderHandle<RenderTheater> {
383        app.get(self).theater.expect("mounted under an Overlay")
384    }
385
386    // Worst-case O(N), N being the number of children added to the top spot in the same
387    // frame. This can be a bit expensive when there's a lot of global key reparenting in the
388    // same frame but N is usually a small number.
389    fn add(self: Handle<Self>, app: &mut App, child: Ref<OverlayEntryLocation>) {
390        debug_assert!(self.mounted(app));
391        let z_order_index = app.get(&child).z_order_index;
392        let existing = app
393            .get(self)
394            .sorted_theater_siblings
395            .clone()
396            .unwrap_or_default();
397        debug_assert!(!existing.contains(&child));
398        let mut insert_position = existing.len();
399        while insert_position > 0
400            && app.get(&existing[insert_position - 1]).z_order_index > z_order_index
401        {
402            insert_position -= 1;
403        }
404        app.get_mut(self)
405            .sorted_theater_siblings
406            .get_or_insert_with(Vec::new)
407            .insert(insert_position, child);
408    }
409
410    fn remove(self: Handle<Self>, app: &mut App, child: Handle<OverlayEntryLocation>) {
411        let children = app.get_mut(self).sorted_theater_siblings.as_mut();
412        debug_assert!(children.is_some());
413        let Some(children) = children else { return };
414        let position = children.iter().position(|other| other == child);
415        debug_assert!(position.is_some(), "the child was in the collection");
416        if let Some(position) = position {
417            children.remove(position);
418        }
419    }
420
421    // The children in the child model in paint order (from farthest to the user to the
422    // closest to the user).
423    fn paint_order_children(
424        self: Handle<Self>,
425        app: &App,
426    ) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
427        self.create_child_list(app, false)
428    }
429
430    fn create_child_list(
431        self: Handle<Self>,
432        app: &App,
433        reversed: bool,
434    ) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
435        let Some(children) = app.get(self).sorted_theater_siblings.as_ref() else {
436            return Vec::new();
437        };
438        let mut boxes: Vec<RenderHandle<RenderDeferredLayoutBox>> = children
439            .iter()
440            .filter_map(|candidate| app.get(candidate).overlay_child_render_box)
441            .collect();
442        if reversed {
443            boxes.reverse();
444        }
445        boxes
446    }
447
448    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
449        // The state that changed is in the builder.
450        self.set_state(app, |_state| {});
451    }
452}
453
454impl State for OverlayEntryWidgetState {
455    type Widget = OverlayEntryWidget;
456
457    crate::state_accessors!();
458
459    fn init_state(self: Handle<Self>, app: &mut App) {
460        let entry = self.widget(app).entry.handle();
461        let notifier = app
462            .get(entry)
463            .overlay_entry_state_notifier
464            .handle()
465            .expect("a live OverlayEntry");
466        notifier.set_value(app, Some(self));
467        let context = self.context(app);
468        let theater = context
469            .find_ancestor_render_object_of_type::<RenderTheater>(app)
470            .expect("an _OverlayEntryWidget is built by an Overlay");
471        app.get_mut(self).theater = Some(theater);
472        debug_assert!(app.get(self).sorted_theater_siblings.is_none());
473    }
474
475    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &OverlayEntryWidget) {
476        // OverlayState's build method always returns a RenderObjectWidget Theater, so it is
477        // safe to assume that state equality implies render object equality.
478        debug_assert!(old_widget.entry == self.widget(app).entry);
479        let changed = old_widget.overlay_state != self.widget(app).overlay_state;
480        if changed {
481            let context = self.context(app);
482            let new_theater = context
483                .find_ancestor_render_object_of_type::<RenderTheater>(app)
484                .expect("an _OverlayEntryWidget is built by an Overlay");
485            debug_assert!(app.get(self).theater != Some(new_theater));
486            app.get_mut(self).theater = Some(new_theater);
487        }
488    }
489
490    fn dispose(self: Handle<Self>, app: &mut App) {
491        let entry = self.widget(app).entry.handle();
492        if let Some(notifier) = app.get(entry).overlay_entry_state_notifier.handle() {
493            notifier.set_value(app, None);
494        }
495        entry.did_unmount(app);
496        app.get_mut(self).sorted_theater_siblings = None;
497    }
498
499    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
500        let widget = self.widget(app);
501        let (ticker_enabled, entry) = (widget.ticker_enabled, widget.entry.handle());
502        let theater = self.theater(app);
503        let builder = Rc::clone(&app.get(entry).builder);
504        TickerMode::new(
505            ticker_enabled,
506            // Use a Builder so that `entry.builder` can have access to RenderTheaterMarker::of.
507            RenderTheaterMarker {
508                theater,
509                overlay_entry_widget_state: self,
510                child: Builder { key: None, builder }.into_widget(),
511            },
512        )
513        .into_widget()
514    }
515}
516
517/// A stack of entries that can be managed independently.
518///
519/// Overlays let independent child widgets "float" visual elements on top of other widgets by
520/// inserting them into the overlay's stack. The overlay lets each of these widgets manage their
521/// participation in the overlay using [`OverlayEntry`] objects.
522///
523/// Although you can create an [`Overlay`] directly, it's most common to use the overlay created
524/// by the `Navigator`. The navigator uses its overlay to manage the visual appearance of its
525/// routes.
526///
527/// The [`Overlay`] widget uses a custom stack implementation, which is very similar to the
528/// `Stack` widget. The main use case of [`Overlay`] is related to navigation and being able to
529/// insert widgets on top of the pages in an app. For layout purposes unrelated to navigation,
530/// consider using `Stack` instead.
531///
532/// An [`Overlay`] widget requires a [`Directionality`] widget to be in scope, so that it can
533/// resolve direction-sensitive coordinates of any `Positioned::directional` children.
534///
535/// See also:
536///
537///  * [`OverlayEntry`], the class that is used for describing the overlay entries.
538///  * [`OverlayState`], which is used to insert the entries into the overlay.
539#[derive(Debug)]
540pub struct Overlay {
541    /// See [`Widget::key`].
542    pub key: Option<KeyRef>,
543    /// The entries to include in the overlay initially.
544    ///
545    /// These entries are only used when the [`OverlayState`] is initialized. If you are
546    /// providing a new [`Overlay`] description for an overlay that's already in the tree, then
547    /// the new entries are ignored.
548    ///
549    /// To add entries to an [`Overlay`] that is already in the tree, use [`Overlay::of`] to
550    /// obtain the [`OverlayState`], and then use [`OverlayState::insert`] or
551    /// [`OverlayState::insert_all`].
552    ///
553    /// To remove an entry from an [`Overlay`], use [`OverlayEntry::remove`].
554    pub initial_entries: Vec<Ref<OverlayEntry>>,
555    /// How to clip the entries that overflow the overlay.
556    ///
557    /// Defaults to [`Clip::HardEdge`].
558    pub clip_behavior: Clip,
559    /// Determines that the overlay should always size itself to content.
560    ///
561    /// Normally overlay will only size itself to content if the incoming constraints are
562    /// infinite and there is an [`OverlayEntry`] that can size the overlay. Setting this to
563    /// `true` will force this behavior even for finite (but possibly loose) constraints.
564    ///
565    /// Setting this to true requires an [`OverlayEntry`] that can size the overlay based on
566    /// itself ([`OverlayEntry::can_size_overlay`] set to true). If not provided the overlay
567    /// panics.
568    pub always_size_to_content: bool,
569}
570
571impl Overlay {
572    /// Creates an overlay; Dart's named arguments are the setters.
573    ///
574    /// The initial entries will be inserted into the overlay when its associated
575    /// [`OverlayState`] is initialized.
576    pub fn new() -> Overlay {
577        Overlay::default()
578    }
579
580    /// Dart `Overlay(key:)`.
581    pub fn key(mut self, key: KeyRef) -> Overlay {
582        self.key = Some(key);
583        self
584    }
585
586    /// Dart `Overlay(initialEntries:)`.
587    pub fn initial_entries(
588        mut self,
589        entries: impl IntoIterator<Item = Ref<OverlayEntry>>,
590    ) -> Overlay {
591        self.initial_entries = entries.into_iter().collect();
592        self
593    }
594
595    /// Dart `Overlay(clipBehavior:)`.
596    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Overlay {
597        self.clip_behavior = clip_behavior;
598        self
599    }
600
601    /// Dart `Overlay(alwaysSizeToContent:)`.
602    pub fn always_size_to_content(mut self, always_size_to_content: bool) -> Overlay {
603        self.always_size_to_content = always_size_to_content;
604        self
605    }
606
607    /// Wrap the provided `child` in an [`Overlay`] to allow other visual elements (packed in
608    /// [`OverlayEntry`]s) to float on top of the child.
609    ///
610    /// This is a convenience method over the regular [`Overlay`] constructor: it creates an
611    /// [`Overlay`] and puts the provided `child` in an [`OverlayEntry`] at the bottom of that
612    /// newly created Overlay.
613    #[cfg_attr(debug_assertions, track_caller)]
614    pub fn wrap<K>(child: impl IntoWidget<K>) -> WrappingOverlay {
615        WrappingOverlay {
616            key: None,
617            clip_behavior: Clip::HardEdge,
618            always_size_to_content: false,
619            child: child.into_widget(),
620        }
621    }
622
623    /// The [`OverlayState`] from the closest instance of [`Overlay`] that encloses the given
624    /// context, and panics if one is not found.
625    ///
626    /// If `root_overlay` is set to true, the state from the furthest instance of this class is
627    /// given instead. Useful for installing overlay entries above all subsequent instances of
628    /// [`Overlay`].
629    ///
630    /// See also:
631    ///
632    /// * [`Overlay::maybe_of`] for a similar function that returns `None` if an [`Overlay`] is
633    ///   not found.
634    pub fn of(app: &mut App, context: BuildContext, root_overlay: bool) -> Handle<OverlayState> {
635        Overlay::maybe_of(app, context, root_overlay).expect(
636            "No Overlay widget found. Some widgets require an Overlay widget ancestor for \
637             correct operation. The most common way to add an Overlay to an application is to \
638             include a WidgetsApp or Navigator widget in the run_app() call.",
639        )
640    }
641
642    /// The [`OverlayState`] from the closest instance of [`Overlay`] that encloses the given
643    /// context, if any.
644    ///
645    /// If `root_overlay` is set to true, the state from the furthest instance of this class is
646    /// given instead.
647    ///
648    /// See also:
649    ///
650    ///  * [`Overlay::of`] for a similar function that panics if an [`Overlay`] is not found.
651    pub fn maybe_of(
652        app: &mut App,
653        context: BuildContext,
654        root_overlay: bool,
655    ) -> Option<Handle<OverlayState>> {
656        let marker = RenderTheaterMarker::maybe_of(app, context, root_overlay, false)?;
657        Some(marker.overlay_entry_widget_state.widget(app).overlay_state)
658    }
659}
660
661impl Default for Overlay {
662    fn default() -> Overlay {
663        Overlay {
664            key: None,
665            initial_entries: Vec::new(),
666            clip_behavior: Clip::HardEdge,
667            always_size_to_content: false,
668        }
669    }
670}
671
672impl StatefulWidget for Overlay {
673    type State = OverlayState;
674
675    fn key(&self) -> Option<&KeyRef> {
676        self.key.as_ref()
677    }
678
679    fn create_state(&self) -> OverlayState {
680        OverlayState {
681            state: StateData::new(),
682            ticker_provider: TickerProviderStateMixinData::new(),
683            entries: Vec::new(),
684        }
685    }
686}
687
688/// The current state of an [`Overlay`].
689///
690/// Used to insert [`OverlayEntry`]s into the overlay using the [`insert`](Self::insert) and
691/// [`insert_all`](Self::insert_all) functions.
692pub struct OverlayState {
693    state: StateData<Overlay>,
694    ticker_provider: TickerProviderStateMixinData,
695    entries: Vec<Ref<OverlayEntry>>,
696}
697
698impl OverlayState {
699    fn insertion_index(
700        self: Handle<Self>,
701        app: &App,
702        below: Option<Handle<OverlayEntry>>,
703        above: Option<Handle<OverlayEntry>>,
704    ) -> usize {
705        debug_assert!(above.is_none() || below.is_none());
706        let entries = &app.get(self).entries;
707        if let Some(below) = below {
708            return entries
709                .iter()
710                .position(|entry| entry == below)
711                .expect("`below` is in this Overlay");
712        }
713        if let Some(above) = above {
714            return entries
715                .iter()
716                .position(|entry| entry == above)
717                .expect("`above` is in this Overlay")
718                + 1;
719        }
720        entries.len()
721    }
722
723    fn debug_can_insert_entry(self: Handle<Self>, app: &App, entry: Handle<OverlayEntry>) -> bool {
724        assert!(
725            self.mounted(app),
726            "Attempted to insert an OverlayEntry to an already disposed Overlay."
727        );
728        let current_overlay = app.get(entry).overlay;
729        assert!(
730            !app.get(self).entries.iter().any(|kept| kept == entry),
731            "The specified entry is already present in the target Overlay. Consider calling \
732             remove on the OverlayEntry before inserting it to a different Overlay."
733        );
734        assert!(
735            current_overlay.is_none(),
736            "The specified entry is already present in a different Overlay. Consider calling \
737             remove on the OverlayEntry before inserting it to a different Overlay."
738        );
739        true
740    }
741
742    /// Insert the given entry into the overlay.
743    ///
744    /// If `below` is non-`None`, the entry is inserted just below `below`. If `above` is
745    /// non-`None`, the entry is inserted just above `above`. Otherwise, the entry is inserted
746    /// on top.
747    ///
748    /// It is an error to specify both `above` and `below`.
749    pub fn insert(
750        self: Handle<Self>,
751        app: &mut App,
752        entry: Ref<OverlayEntry>,
753        below: Option<Handle<OverlayEntry>>,
754        above: Option<Handle<OverlayEntry>>,
755    ) {
756        debug_assert!(self.debug_verify_insert_position(app, above, below, None));
757        debug_assert!(self.debug_can_insert_entry(app, entry.handle()));
758        app.get_mut(&entry).overlay = Some(self);
759        let index = self.insertion_index(app, below, above);
760        self.set_state(app, |state| state.entries.insert(index, entry));
761    }
762
763    /// Insert all the entries in the given iterable.
764    ///
765    /// If `below` is non-`None`, the entries are inserted just below `below`. If `above` is
766    /// non-`None`, the entries are inserted just above `above`. Otherwise, the entries are
767    /// inserted on top.
768    ///
769    /// It is an error to specify both `above` and `below`.
770    pub fn insert_all(
771        self: Handle<Self>,
772        app: &mut App,
773        entries: Vec<Ref<OverlayEntry>>,
774        below: Option<Handle<OverlayEntry>>,
775        above: Option<Handle<OverlayEntry>>,
776    ) {
777        debug_assert!(self.debug_verify_insert_position(app, above, below, None));
778        if cfg!(debug_assertions) {
779            for entry in &entries {
780                assert!(self.debug_can_insert_entry(app, entry.handle()));
781            }
782        }
783        if entries.is_empty() {
784            return;
785        }
786        for entry in &entries {
787            debug_assert!(app.get(entry).overlay.is_none());
788            app.get_mut(entry).overlay = Some(self);
789        }
790        let index = self.insertion_index(app, below, above);
791        self.set_state(app, move |state| {
792            state.entries.splice(index..index, entries);
793        });
794    }
795
796    fn debug_verify_insert_position(
797        self: Handle<Self>,
798        app: &App,
799        above: Option<Handle<OverlayEntry>>,
800        below: Option<Handle<OverlayEntry>>,
801        new_entries: Option<&[Ref<OverlayEntry>]>,
802    ) -> bool {
803        assert!(
804            above.is_none() || below.is_none(),
805            "Only one of `above` and `below` may be specified."
806        );
807        let present = |entry: Handle<OverlayEntry>| {
808            app.get(entry).overlay == Some(self)
809                && app.get(self).entries.iter().any(|kept| kept == entry)
810                && new_entries.is_none_or(|entries| entries.iter().any(|kept| kept == entry))
811        };
812        assert!(
813            above.is_none_or(present),
814            "The provided entry used for `above` must be present in the Overlay."
815        );
816        assert!(
817            below.is_none_or(present),
818            "The provided entry used for `below` must be present in the Overlay."
819        );
820        true
821    }
822
823    /// Remove all the entries listed in the given iterable, then reinsert them into the overlay
824    /// in the given order.
825    ///
826    /// Entries mentioned in `new_entries` but absent from the overlay are inserted as if with
827    /// [`insert_all`](Self::insert_all).
828    ///
829    /// Entries not mentioned in `new_entries` but present in the overlay are positioned as a
830    /// group in the resulting list relative to the entries that were moved, as specified by one
831    /// of `below` or `above`, which, if specified, must be one of the entries in `new_entries`:
832    ///
833    /// If `below` is non-`None`, the group is positioned just below `below`. If `above` is
834    /// non-`None`, the group is positioned just above `above`. Otherwise, the group is left on
835    /// top, with all the rearranged entries below.
836    ///
837    /// It is an error to specify both `above` and `below`.
838    pub fn rearrange(
839        self: Handle<Self>,
840        app: &mut App,
841        new_entries: Vec<Ref<OverlayEntry>>,
842        below: Option<Handle<OverlayEntry>>,
843        above: Option<Handle<OverlayEntry>>,
844    ) {
845        debug_assert!(self.debug_verify_insert_position(app, above, below, Some(&new_entries)));
846        debug_assert!(
847            new_entries.iter().all(|entry| {
848                let overlay = app.get(entry).overlay;
849                overlay.is_none() || overlay == Some(self)
850            }),
851            "One or more of the specified entries are already present in another Overlay."
852        );
853        debug_assert!(
854            new_entries.iter().all(|entry| {
855                let entries = &app.get(self).entries;
856                entries.iter().position(|other| other == entry)
857                    == entries.iter().rposition(|other| other == entry)
858            }),
859            "One or more of the specified entries are specified multiple times."
860        );
861        if new_entries.is_empty() {
862            return;
863        }
864        if app.get(self).entries == new_entries {
865            return;
866        }
867        let old: Vec<Ref<OverlayEntry>> = app
868            .get(self)
869            .entries
870            .iter()
871            .filter(|entry| !new_entries.contains(entry))
872            .cloned()
873            .collect();
874        for entry in &new_entries {
875            if app.get(entry).overlay.is_none() {
876                app.get_mut(entry).overlay = Some(self);
877            }
878        }
879        let index = {
880            let entries = &new_entries;
881            if let Some(below) = below {
882                entries
883                    .iter()
884                    .position(|entry| entry == below)
885                    .expect("`below` is in `new_entries`")
886            } else if let Some(above) = above {
887                entries
888                    .iter()
889                    .position(|entry| entry == above)
890                    .expect("`above` is in `new_entries`")
891                    + 1
892            } else {
893                entries.len()
894            }
895        };
896        self.set_state(app, move |state| {
897            state.entries.clear();
898            state.entries.extend(new_entries);
899            state.entries.splice(index..index, old);
900        });
901    }
902
903    fn mark_dirty(self: Handle<Self>, app: &mut App) {
904        if self.mounted(app) {
905            self.set_state(app, |_state| {});
906        }
907    }
908
909    fn mark_dirty_after_frame(self: Handle<Self>, app: &mut App, _time_stamp: std::time::Duration) {
910        self.mark_dirty(app);
911    }
912
913    /// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an opaque entry).
914    ///
915    /// This is an O(N) algorithm, and should not be necessary except for debug asserts. To
916    /// avoid people depending on it, this function is implemented only in debug mode, and
917    /// always returns false in release mode.
918    pub fn debug_is_visible(self: Handle<Self>, app: &App, entry: Handle<OverlayEntry>) -> bool {
919        let mut result = false;
920        debug_assert!(app.get(self).entries.iter().any(|kept| kept == entry));
921        if cfg!(debug_assertions) {
922            let entries = app.get(self).entries.clone();
923            for index in (1..entries.len()).rev() {
924                let candidate = entries[index].handle();
925                if candidate == entry {
926                    result = true;
927                    break;
928                }
929                if candidate.opaque(app) {
930                    break;
931                }
932            }
933        }
934        result
935    }
936
937    fn did_change_entry_opacity(self: Handle<Self>, app: &mut App) {
938        // We use the opacity of the entry in our build function, which means our state has
939        // changed.
940        self.set_state(app, |_state| {});
941    }
942}
943
944impl TickerProviderStateMixin for OverlayState {
945    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
946        &app.get(self).ticker_provider
947    }
948
949    fn ticker_provider_data_mut(
950        self: Handle<Self>,
951        app: &mut App,
952    ) -> &mut TickerProviderStateMixinData {
953        &mut app.get_mut(self).ticker_provider
954    }
955}
956
957impl TickerProviderObject for OverlayState {
958    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
959        TickerProviderStateMixin::create_ticker(self, app, on_tick)
960    }
961}
962
963impl State for OverlayState {
964    type Widget = Overlay;
965
966    crate::state_accessors!();
967
968    fn debug_fill_properties(
969        self: Handle<Self>,
970        app: &App,
971        properties: &mut DiagnosticPropertiesBuilder,
972    ) {
973        let entries: Vec<String> = app
974            .get(self)
975            .entries
976            .iter()
977            .map(|entry| format!("{:?}", app.get(entry.handle())))
978            .collect();
979        properties.add(DiagnosticsProperty::<String>::new(
980            "entries",
981            Some(format!("[{}]", entries.join(", "))),
982        ));
983    }
984
985    fn init_state(self: Handle<Self>, app: &mut App) {
986        let initial = self.widget(app).initial_entries.clone();
987        self.insert_all(app, initial, None, None);
988    }
989
990    fn activate(self: Handle<Self>, app: &mut App) {
991        TickerProviderStateMixin::activate(self, app);
992    }
993
994    fn dispose(self: Handle<Self>, app: &mut App) {
995        TickerProviderStateMixin::dispose(self, app);
996    }
997
998    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
999        // This list is filled backwards and then reversed below before it is added to the tree.
1000        let mut children: Vec<WidgetRef> = Vec::new();
1001        let mut onstage = true;
1002        let mut onstage_count = 0usize;
1003        for entry in app.get(self).entries.clone().into_iter().rev() {
1004            let key: KeyRef = app.get(&entry).key.clone().into();
1005            let (opaque, maintain_state) = (app.get(&entry).opaque, app.get(&entry).maintain_state);
1006            if onstage {
1007                onstage_count += 1;
1008                children.push(
1009                    OverlayEntryWidget {
1010                        key,
1011                        overlay_state: self,
1012                        entry,
1013                        ticker_enabled: true,
1014                    }
1015                    .into_widget(),
1016                );
1017                if opaque {
1018                    onstage = false;
1019                }
1020            } else if maintain_state {
1021                children.push(
1022                    OverlayEntryWidget {
1023                        key,
1024                        overlay_state: self,
1025                        entry,
1026                        ticker_enabled: false,
1027                    }
1028                    .into_widget(),
1029                );
1030            }
1031        }
1032        let skip_count = children.len() - onstage_count;
1033        children.reverse();
1034        let widget = self.widget(app);
1035        Theater {
1036            skip_count,
1037            clip_behavior: widget.clip_behavior,
1038            always_size_to_content: widget.always_size_to_content,
1039            children,
1040        }
1041        .into_widget()
1042    }
1043}
1044
1045/// Dart's `_WrappingOverlay`: the widget [`Overlay::wrap`] returns.
1046#[derive(Debug)]
1047pub struct WrappingOverlay {
1048    /// See [`Widget::key`].
1049    pub key: Option<KeyRef>,
1050    /// See [`Overlay::clip_behavior`].
1051    pub clip_behavior: Clip,
1052    /// See [`Overlay::always_size_to_content`].
1053    pub always_size_to_content: bool,
1054    /// The widget the created [`Overlay`]'s bottom entry builds.
1055    pub child: WidgetRef,
1056}
1057
1058impl WrappingOverlay {
1059    /// Dart `Overlay.wrap(key:)`.
1060    pub fn key(mut self, key: KeyRef) -> WrappingOverlay {
1061        self.key = Some(key);
1062        self
1063    }
1064
1065    /// Dart `Overlay.wrap(clipBehavior:)`.
1066    pub fn clip_behavior(mut self, clip_behavior: Clip) -> WrappingOverlay {
1067        self.clip_behavior = clip_behavior;
1068        self
1069    }
1070
1071    /// Dart `Overlay.wrap(alwaysSizeToContent:)`.
1072    pub fn always_size_to_content(mut self, always_size_to_content: bool) -> WrappingOverlay {
1073        self.always_size_to_content = always_size_to_content;
1074        self
1075    }
1076}
1077
1078impl StatefulWidget for WrappingOverlay {
1079    type State = WrappingOverlayState;
1080
1081    fn key(&self) -> Option<&KeyRef> {
1082        self.key.as_ref()
1083    }
1084
1085    fn create_state(&self) -> WrappingOverlayState {
1086        WrappingOverlayState {
1087            state: StateData::new(),
1088            entry: None,
1089        }
1090    }
1091}
1092
1093/// Dart's `_WrappingOverlayState`.
1094pub struct WrappingOverlayState {
1095    state: StateData<WrappingOverlay>,
1096    entry: Option<Ref<OverlayEntry>>,
1097}
1098
1099impl WrappingOverlayState {
1100    /// Dart's `late final _entry`, created on its first use.
1101    fn entry(self: Handle<Self>, app: &mut App) -> Ref<OverlayEntry> {
1102        if let Some(entry) = app.get(self).entry.clone() {
1103            return entry;
1104        }
1105        let entry = OverlayEntry::new(
1106            app,
1107            Rc::new(move |app: &mut App, _context| self.widget(app).child.clone()),
1108            true,
1109            false,
1110            true,
1111        );
1112        app.get_mut(self).entry = Some(entry.clone());
1113        entry
1114    }
1115}
1116
1117impl State for WrappingOverlayState {
1118    type Widget = WrappingOverlay;
1119
1120    crate::state_accessors!();
1121
1122    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &WrappingOverlay) {
1123        let entry = self.entry(app);
1124        entry.mark_needs_build(app);
1125    }
1126
1127    fn dispose(self: Handle<Self>, app: &mut App) {
1128        let entry = self.entry(app);
1129        entry.remove(app);
1130        entry.dispose(app);
1131    }
1132
1133    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1134        let entry = self.entry(app);
1135        let widget = self.widget(app);
1136        Overlay {
1137            key: None,
1138            initial_entries: vec![entry],
1139            clip_behavior: widget.clip_behavior,
1140            always_size_to_content: widget.always_size_to_content,
1141        }
1142        .into_widget()
1143    }
1144}
1145
1146/// Special version of a stack that doesn't lay out and render the first
1147/// [`skip_count`](Self::skip_count) children.
1148///
1149/// The first `skip_count` children are considered "offstage".
1150#[derive(Debug)]
1151struct Theater {
1152    skip_count: usize,
1153    clip_behavior: Clip,
1154    always_size_to_content: bool,
1155    children: Vec<WidgetRef>,
1156}
1157
1158impl RenderObjectWidget for Theater {
1159    type RenderObject = RenderTheater;
1160
1161    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1162        properties.add(IntProperty::<usize>::new(
1163            "skipCount",
1164            Some(self.skip_count),
1165        ));
1166    }
1167
1168    fn debug_check_constructor(&self) {
1169        debug_assert!(self.children.len() >= self.skip_count);
1170    }
1171
1172    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1173        let text_direction = Directionality::of(app, context);
1174        let render_object = RenderTheater::new(
1175            app,
1176            text_direction,
1177            self.skip_count,
1178            self.clip_behavior,
1179            self.always_size_to_content,
1180        );
1181        render_object.as_object()
1182    }
1183
1184    fn update_render_object(
1185        &self,
1186        app: &mut App,
1187        context: BuildContext,
1188        render_object: RenderHandle<RenderTheater>,
1189    ) {
1190        render_object.set_skip_count(app, self.skip_count);
1191        let text_direction = Directionality::of(app, context);
1192        render_object.set_text_direction(app, text_direction);
1193        render_object.set_clip_behavior(app, self.clip_behavior);
1194        render_object.set_always_size_to_content(app, self.always_size_to_content);
1195    }
1196}
1197
1198impl MultiChildRenderObjectWidget for Theater {
1199    fn children(&self) -> &[WidgetRef] {
1200        &self.children
1201    }
1202
1203    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1204        TheaterElement::new(app, this).as_element()
1205    }
1206}
1207
1208/// Dart's `_TheaterElement`: stamps each child's [`TheaterParentData`] with the
1209/// [`OverlayEntry`] that built it.
1210struct TheaterElement {
1211    element: ElementData,
1212    render_object_element: RenderObjectElementData,
1213    multi_child: MultiChildRenderObjectElementData,
1214}
1215
1216impl TheaterElement {
1217    fn new(app: &mut App, widget: WidgetRef) -> Handle<TheaterElement> {
1218        debug_assert!(downcast_widget::<Theater>(&*widget).is_some());
1219        app.create(TheaterElement {
1220            element: ElementData::new(widget),
1221            render_object_element: RenderObjectElementData::default(),
1222            multi_child: MultiChildRenderObjectElementData::default(),
1223        })
1224        .into_tree_node(app)
1225    }
1226
1227    /// The [`OverlayEntry`] of the `OverlayEntryWidget` at the given slot's index.
1228    fn entry_at_slot(self: Handle<Self>, app: &App, slot: Option<&Slot>) -> Handle<OverlayEntry> {
1229        let index = <Self as MultiChildRenderObjectElementBase>::indexed_slot(slot).index;
1230        let widget = Self::widget_of(self.as_element().widget(app));
1231        downcast_widget::<OverlayEntryWidget>(&*widget.children[index])
1232            .expect("a Theater's children are _OverlayEntryWidgets")
1233            .entry
1234            .handle()
1235    }
1236}
1237
1238impl RenderObjectElementWidget for TheaterElement {
1239    type Widget = Theater;
1240
1241    fn widget_of(widget: &WidgetRef) -> &Theater {
1242        downcast_widget::<Theater>(&**widget).expect("a _TheaterElement holds a _Theater")
1243    }
1244}
1245
1246impl RenderObjectElement for TheaterElement {
1247    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
1248        &app.get(self).render_object_element
1249    }
1250
1251    fn render_object_element_data_mut(
1252        self: Handle<Self>,
1253        app: &mut App,
1254    ) -> &mut RenderObjectElementData {
1255        &mut app.get_mut(self).render_object_element
1256    }
1257}
1258
1259impl MultiChildRenderObjectElementBase for TheaterElement {
1260    fn multi_child_data(self: Handle<Self>, app: &App) -> &MultiChildRenderObjectElementData {
1261        &app.get(self).multi_child
1262    }
1263
1264    fn multi_child_data_mut(
1265        self: Handle<Self>,
1266        app: &mut App,
1267    ) -> &mut MultiChildRenderObjectElementData {
1268        &mut app.get_mut(self).multi_child
1269    }
1270}
1271
1272impl Element for TheaterElement {
1273    crate::element_accessors!();
1274
1275    const IS_RENDER_OBJECT_ELEMENT: bool = true;
1276
1277    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
1278        self.render_object_element_data(app).render_object()
1279    }
1280
1281    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
1282        None
1283    }
1284
1285    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
1286        self.render_object_element_data(app).debug_doing_build()
1287    }
1288
1289    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
1290        RenderObjectElement::perform_rebuild(self, app);
1291    }
1292
1293    fn deactivate(self: Handle<Self>, app: &mut App) {
1294        RenderObjectElement::deactivate(self, app);
1295    }
1296
1297    fn unmount(self: Handle<Self>, app: &mut App) {
1298        RenderObjectElement::unmount(self, app);
1299    }
1300
1301    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
1302        RenderObjectElement::update_parent_data(self, app, parent_data_element);
1303    }
1304
1305    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
1306        RenderObjectElement::update_slot(self, app, new_slot);
1307    }
1308
1309    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
1310        RenderObjectElement::attach_render_object(self, app, new_slot);
1311    }
1312
1313    fn detach_render_object(self: Handle<Self>, app: &mut App) {
1314        RenderObjectElement::detach_render_object(self, app);
1315    }
1316
1317    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1318        MultiChildRenderObjectElementBase::visit_children(self, app, visitor);
1319    }
1320
1321    /// Dart's `_TheaterElement.debugVisitOnstageChildren`: the children after the theater's
1322    /// `skip_count`, the entries the overlay keeps onstage.
1323    fn debug_visit_onstage_children(
1324        self: Handle<Self>,
1325        app: &App,
1326        visitor: &mut dyn FnMut(AnyElement),
1327    ) {
1328        let skip_count = Self::widget_of(self.as_element().widget(app)).skip_count;
1329        let mut children = Vec::new();
1330        MultiChildRenderObjectElementBase::visit_children(self, app, &mut |child| {
1331            children.push(child);
1332        });
1333        debug_assert!(children.len() >= skip_count);
1334        children.into_iter().skip(skip_count).for_each(visitor);
1335    }
1336
1337    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
1338        MultiChildRenderObjectElementBase::forget_child(self, app, child);
1339    }
1340
1341    fn mount(
1342        self: Handle<Self>,
1343        app: &mut App,
1344        parent: Option<AnyElement>,
1345        new_slot: Option<Slot>,
1346    ) {
1347        MultiChildRenderObjectElementBase::mount(self, app, parent, new_slot);
1348    }
1349
1350    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
1351        MultiChildRenderObjectElementBase::update(self, app, new_widget);
1352    }
1353
1354    fn insert_render_object_child(
1355        self: Handle<Self>,
1356        app: &mut App,
1357        child: AnyRenderObject,
1358        slot: Option<Slot>,
1359    ) {
1360        MultiChildRenderObjectElementBase::insert_render_object_child(
1361            self,
1362            app,
1363            child,
1364            slot.clone(),
1365        );
1366        let entry = self.entry_at_slot(app, slot.as_ref()).keep(app);
1367        child
1368            .parent_data_of_mut::<TheaterParentData>(app)
1369            .overlay_entry = Some(entry);
1370    }
1371
1372    fn move_render_object_child(
1373        self: Handle<Self>,
1374        app: &mut App,
1375        child: AnyRenderObject,
1376        old_slot: Option<Slot>,
1377        new_slot: Option<Slot>,
1378    ) {
1379        MultiChildRenderObjectElementBase::move_render_object_child(
1380            self,
1381            app,
1382            child,
1383            old_slot,
1384            new_slot.clone(),
1385        );
1386        if cfg!(debug_assertions) {
1387            let entry_at_new_slot = self.entry_at_slot(app, new_slot.as_ref());
1388            let parent_data = child.parent_data_of::<TheaterParentData>(app);
1389            assert!(parent_data.overlay_entry.handle() == Some(entry_at_new_slot));
1390        }
1391    }
1392
1393    fn remove_render_object_child(
1394        self: Handle<Self>,
1395        app: &mut App,
1396        child: AnyRenderObject,
1397        slot: Option<Slot>,
1398    ) {
1399        MultiChildRenderObjectElementBase::remove_render_object_child(self, app, child, slot);
1400    }
1401}
1402
1403/// Dart's `_TheaterParentData`: [`StackParentData`] plus the entry that created the child.
1404#[derive(Debug, Default)]
1405pub struct TheaterParentData {
1406    stack: StackParentData,
1407    /// The [`OverlayEntry`] that directly created this child.
1408    overlay_entry: Option<Ref<OverlayEntry>>,
1409}
1410
1411impl TheaterParentData {
1412    /// Parent data for a child of a [`RenderTheater`] that no entry has claimed yet.
1413    pub fn new() -> TheaterParentData {
1414        TheaterParentData {
1415            stack: StackParentData::new(),
1416            overlay_entry: None,
1417        }
1418    }
1419
1420    /// The stack half: the positioning a `Positioned` child writes.
1421    pub fn stack(&self) -> &StackParentData {
1422        &self.stack
1423    }
1424
1425    /// See [`stack`](Self::stack).
1426    pub fn stack_mut(&mut self) -> &mut StackParentData {
1427        &mut self.stack
1428    }
1429
1430    // An [`OverlayPortal`] makes its overlay child a render child of an ancestor
1431    // [`Overlay`]. Currently, to make sure the overlay child is painted after its
1432    // [`OverlayPortal`], and before the next [`OverlayEntry`] (which could be something that
1433    // should obstruct the overlay child, such as a `ModalRoute`) in the host [`Overlay`], the
1434    // paint order of each overlay child is managed by the [`OverlayEntry`] that hosts its
1435    // [`OverlayPortal`].
1436    //
1437    // The following methods are exposed to allow easy access to the overlay children's render
1438    // objects whose order is managed by `overlay_entry`, in the right order.
1439
1440    // The entry's notifier is cleared in OverlayEntryWidgetState's dispose method. These are
1441    // only accessed during layout, paint and hit-test so the `expect` is safe.
1442    fn paint_order_children(&self, app: &App) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
1443        match self.child_model(app) {
1444            Some(child_model) => child_model.paint_order_children(app),
1445            None => Vec::new(),
1446        }
1447    }
1448
1449    fn child_model(&self, app: &App) -> Option<Handle<OverlayEntryWidgetState>> {
1450        let notifier = app
1451            .get(self.overlay_entry.as_ref()?)
1452            .overlay_entry_state_notifier
1453            .handle()?;
1454        Some((*app.get(notifier).value()).expect("the entry is mounted"))
1455    }
1456
1457    // A convenience method for traversing `paint_order_children` with a render object
1458    // visitor.
1459    fn visit_overlay_portal_children_on_overlay_entry(
1460        &self,
1461        app: &App,
1462        visitor: &mut dyn FnMut(AnyRenderObject),
1463    ) {
1464        for child in self.paint_order_children(app) {
1465            visitor(child.as_object());
1466        }
1467    }
1468}
1469
1470impl ParentData for TheaterParentData {
1471    fn detach(&mut self) {
1472        ContainerParentDataMixin::detach(self);
1473    }
1474
1475    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1476        if id == TypeId::of::<TheaterParentData>() {
1477            return Some(self);
1478        }
1479        self.stack.provide(id)
1480    }
1481
1482    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1483        if id == TypeId::of::<TheaterParentData>() {
1484            return Some(self);
1485        }
1486        self.stack.provide_mut(id)
1487    }
1488}
1489
1490impl ContainerParentDataMixin for TheaterParentData {
1491    type ChildType = AnyRenderBox;
1492
1493    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
1494        self.stack.container_parent_data()
1495    }
1496
1497    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
1498        self.stack.container_parent_data_mut()
1499    }
1500}
1501
1502impl ContainerBoxParentData for TheaterParentData {
1503    fn box_parent_data(&self) -> &waft_rendering::BoxParentData {
1504        ContainerBoxParentData::box_parent_data(&self.stack)
1505    }
1506
1507    fn box_parent_data_mut(&mut self) -> &mut waft_rendering::BoxParentData {
1508        ContainerBoxParentData::box_parent_data_mut(&mut self.stack)
1509    }
1510}
1511
1512impl Display for TheaterParentData {
1513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514        Display::fmt(&self.stack, f)
1515    }
1516}
1517
1518/// `RenderStack.layoutPositionedChild` for a child whose parent data is a
1519/// [`TheaterParentData`].
1520fn layout_positioned_theater_child(
1521    app: &mut App,
1522    child: AnyRenderBox,
1523    size: Size,
1524    alignment: Alignment,
1525) {
1526    let child_constraints = {
1527        let parent_data = child.as_object().parent_data_of::<TheaterParentData>(app);
1528        debug_assert!(parent_data.stack.is_positioned());
1529        parent_data.stack.positioned_child_constraints(size)
1530    };
1531    child.layout(app, child_constraints, true);
1532
1533    let child_size = child.size(app);
1534    let parent_data = child.as_object().parent_data_of::<TheaterParentData>(app);
1535    let x = match (parent_data.stack.left, parent_data.stack.right) {
1536        (Some(left), _) => left,
1537        (None, Some(right)) => size.width() - right - child_size.width(),
1538        (None, None) => alignment.along_offset(size - child_size).dx(),
1539    };
1540    let y = match (parent_data.stack.top, parent_data.stack.bottom) {
1541        (Some(top), _) => top,
1542        (None, Some(bottom)) => size.height() - bottom - child_size.height(),
1543        (None, None) => alignment.along_offset(size - child_size).dy(),
1544    };
1545    child
1546        .as_object()
1547        .parent_data_of_mut::<TheaterParentData>(app)
1548        .set_offset(Offset::new(x, y));
1549}
1550
1551/// An App-aware cursor for Flutter's lazy theater child generators.
1552///
1553/// Entry layout can mutate its portal list, so that list is opened only after
1554/// yielding the entry. Portal candidates advance before yielding, as in Dart.
1555pub struct TheaterChildren {
1556    /// The owning theater; absent for a deferred box's single normal child.
1557    theater: Option<RenderHandle<RenderTheater>>,
1558
1559    /// The current entry, kept until its portal children have been traversed.
1560    entry: Option<AnyRenderBox>,
1561
1562    /// Hit testing traverses portals before entries, from front to back.
1563    reversed: bool,
1564
1565    /// Hit-test entries left before reaching the offstage prefix.
1566    remaining: usize,
1567
1568    /// The source generator's suspension point between child operations.
1569    phase: TheaterChildrenPhase,
1570
1571    /// The next portal location, advanced before yielding its render box.
1572    candidate: Option<Handle<OverlayEntryLocation>>,
1573}
1574
1575/// Suspension points in Flutter's paint-order and hit-test-order generators.
1576enum TheaterChildrenPhase {
1577    /// Yields the entry first when traversing in paint order.
1578    Entry,
1579
1580    /// Opens the current portal list after the previous yield has completed.
1581    OpenPortals,
1582
1583    /// Yields portal boxes while reading links from the current child model.
1584    Portals,
1585
1586    /// Advances to the adjacent entry after its portals and entry were yielded.
1587    NextEntry,
1588}
1589
1590impl TheaterChildren {
1591    /// Creates the one-child generator used by deferred layout boxes.
1592    fn single(child: Option<AnyRenderBox>) -> Self {
1593        Self {
1594            theater: None,
1595            entry: child,
1596            reversed: false,
1597            remaining: 0,
1598            phase: TheaterChildrenPhase::Entry,
1599            candidate: None,
1600        }
1601    }
1602
1603    /// Starts at the first or last onstage entry without reading its portals.
1604    fn theater(theater: RenderHandle<RenderTheater>, app: &App, reversed: bool) -> Self {
1605        Self {
1606            theater: Some(theater),
1607            entry: if reversed {
1608                theater.last_onstage_child(app)
1609            } else {
1610                theater.first_onstage_child(app)
1611            },
1612            reversed,
1613            remaining: theater.child_count(app) - theater.get(app).skip_count,
1614            phase: TheaterChildrenPhase::Entry,
1615            candidate: None,
1616        }
1617    }
1618
1619    /// Advances after the caller has finished operating on the previous child.
1620    pub fn next(&mut self, app: &App) -> Option<AnyRenderBox> {
1621        let Some(theater) = self.theater else {
1622            return self.entry.take();
1623        };
1624        loop {
1625            let entry = self.entry?;
1626            match self.phase {
1627                TheaterChildrenPhase::Entry => {
1628                    self.phase = TheaterChildrenPhase::OpenPortals;
1629                    if !self.reversed {
1630                        return Some(entry);
1631                    }
1632                }
1633                TheaterChildrenPhase::OpenPortals => {
1634                    let model = entry
1635                        .as_object()
1636                        .parent_data_of::<TheaterParentData>(app)
1637                        .child_model(app);
1638                    self.candidate = model.and_then(|model| {
1639                        let list = app.get(model).sorted_theater_siblings.as_ref()?;
1640                        if self.reversed {
1641                            list.last().map(Retained::handle)
1642                        } else {
1643                            list.first().map(Retained::handle)
1644                        }
1645                    });
1646                    self.phase = TheaterChildrenPhase::Portals;
1647                }
1648                TheaterChildrenPhase::Portals => {
1649                    if let Some(candidate) = self.candidate {
1650                        let render_box = app.get(candidate).overlay_child_render_box;
1651                        self.candidate = (|| {
1652                            let model = app.get(candidate).child_model;
1653                            let list = app.get(model).sorted_theater_siblings.as_ref()?;
1654                            let index = list.iter().position(|value| value == candidate)?;
1655                            let next = if self.reversed {
1656                                index.checked_sub(1).and_then(|i| list.get(i))
1657                            } else {
1658                                list.get(index + 1)
1659                            };
1660                            next.map(Retained::handle)
1661                        })();
1662                        if let Some(render_box) = render_box {
1663                            return Some(render_box.as_box());
1664                        }
1665                    } else {
1666                        self.phase = TheaterChildrenPhase::NextEntry;
1667                        if self.reversed {
1668                            return Some(entry);
1669                        }
1670                    }
1671                }
1672                TheaterChildrenPhase::NextEntry => {
1673                    self.entry = if self.reversed {
1674                        self.remaining -= 1;
1675                        if self.remaining == 0 {
1676                            None
1677                        } else {
1678                            theater.child_before(app, entry)
1679                        }
1680                    } else {
1681                        theater.child_after(app, entry)
1682                    };
1683                    self.phase = TheaterChildrenPhase::Entry;
1684                }
1685            }
1686        }
1687    }
1688
1689    /// Collects a snapshot for tests that do not mutate children between yields.
1690    #[cfg(test)]
1691    fn collect(mut self, app: &App) -> Vec<AnyRenderBox> {
1692        let mut children = Vec::new();
1693        while let Some(child) = self.next(app) {
1694            children.push(child);
1695        }
1696        children
1697    }
1698}
1699
1700/// A `RenderBox` that sizes itself to its parent's size, implements the stack layout algorithm
1701/// and renders its children in the given [`theater`](Self::theater).
1702///
1703/// Flutter's `_RenderTheaterMixin`.
1704pub trait RenderTheaterMixin: RenderBox {
1705    /// The theater whose child model this box paints from.
1706    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater>;
1707
1708    /// The children in paint order: from farthest to the user to the closest to the user.
1709    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;
1710
1711    /// The children in hit-test order: from closest to the user to the farthest.
1712    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;
1713
1714    /// The body of Flutter's `setupParentData` override.
1715    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1716        if !child.parent_data_is::<TheaterParentData>(app) {
1717            child.set_parent_data(app, TheaterParentData::new());
1718        }
1719    }
1720
1721    /// Lays one child out with the stack layout algorithm.
1722    fn layout_child(
1723        self: RenderHandle<Self>,
1724        app: &mut App,
1725        child: AnyRenderBox,
1726        non_positioned_child_constraints: BoxConstraints,
1727    ) {
1728        let alignment = self.theater(app).resolved_alignment(app);
1729        let is_positioned = child
1730            .as_object()
1731            .parent_data_of::<TheaterParentData>(app)
1732            .stack
1733            .is_positioned();
1734        if !is_positioned {
1735            // Dart dispatches this through `RenderObject.layout`, which
1736            // `_RenderDeferredLayoutBox` overrides to hand its subtree to the pipeline
1737            // owner's dirty list instead of laying it out inside this tree walk.
1738            match child.as_object().downcast::<RenderDeferredLayoutBox>(app) {
1739                Some(deferred) => {
1740                    let parent = child
1741                        .as_object()
1742                        .parent(app)
1743                        .expect("a child being laid out has a parent");
1744                    deferred.do_layout_from(app, parent, non_positioned_child_constraints);
1745                }
1746                None => child.layout(app, non_positioned_child_constraints, true),
1747            }
1748            child
1749                .as_object()
1750                .parent_data_of_mut::<TheaterParentData>(app)
1751                .set_offset(Offset::ZERO);
1752        } else {
1753            debug_assert!(
1754                child
1755                    .as_object()
1756                    .downcast::<RenderDeferredLayoutBox>(app)
1757                    .is_none(),
1758                "all deferred layout boxes must be non-positioned children."
1759            );
1760            let size = self.size(app);
1761            layout_positioned_theater_child(app, child, size, alignment);
1762        }
1763    }
1764
1765    /// The body of Flutter's `hitTestChildren` override.
1766    fn hit_test_children(
1767        self: RenderHandle<Self>,
1768        app: &mut App,
1769        result: &mut BoxHitTestResult<'_>,
1770        position: Offset,
1771    ) -> bool {
1772        let mut children = self.children_in_hit_test_order(app);
1773        while let Some(child) = children.next(app) {
1774            let offset = child
1775                .as_object()
1776                .parent_data_of::<TheaterParentData>(app)
1777                .offset();
1778            let is_hit = result.add_with_paint_offset(Some(offset), position, |result, local| {
1779                child.hit_test(app, result, local)
1780            });
1781            if is_hit {
1782                return true;
1783            }
1784        }
1785        false
1786    }
1787
1788    /// The body of Flutter's `paint` override.
1789    fn paint(
1790        self: RenderHandle<Self>,
1791        app: &mut App,
1792        context: &mut PaintingContext,
1793        offset: Offset,
1794    ) {
1795        let mut children = self.children_in_paint_order(app);
1796        while let Some(child) = children.next(app) {
1797            let child_offset = child
1798                .as_object()
1799                .parent_data_of::<TheaterParentData>(app)
1800                .offset();
1801            context.paint_child(app, child.as_object(), child_offset + offset);
1802        }
1803    }
1804}
1805
1806/// The render object of an [`Overlay`]: a stack that skips its first
1807/// [`skip_count`](Self::skip_count) children.
1808///
1809/// Flutter's `_RenderTheater`.
1810pub struct RenderTheater {
1811    render_object: RenderObjectData,
1812    render_box: RenderBoxData,
1813    container: ContainerRenderObjectData<AnyRenderBox>,
1814    alignment_cache: Option<Alignment>,
1815    text_direction: TextDirection,
1816    skip_count: usize,
1817    clip_behavior: Clip,
1818    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
1819    always_size_to_content: bool,
1820    laying_out_size_determining_child: bool,
1821}
1822
1823impl RenderTheater {
1824    /// Creates the render object of an [`Overlay`]. Add children with
1825    /// [`add`](ContainerRenderObjectMixin::add); Dart's constructor takes them.
1826    pub fn new(
1827        app: &mut App,
1828        text_direction: TextDirection,
1829        skip_count: usize,
1830        clip_behavior: Clip,
1831        always_size_to_content: bool,
1832    ) -> RenderHandle<RenderTheater> {
1833        RenderHandle::new_box(
1834            app,
1835            RenderTheater {
1836                render_object: RenderObjectData::new(),
1837                render_box: RenderBoxData::new(),
1838                container: ContainerRenderObjectData::new(),
1839                alignment_cache: None,
1840                text_direction,
1841                skip_count,
1842                clip_behavior,
1843                clip_rect_layer: LayerHandle::new(),
1844                always_size_to_content,
1845                laying_out_size_determining_child: false,
1846            },
1847        )
1848    }
1849
1850    /// `AlignmentDirectional.topStart` resolved against
1851    /// [`text_direction`](Self::text_direction), cached until it changes.
1852    pub fn resolved_alignment(self: RenderHandle<Self>, app: &mut App) -> Alignment {
1853        if let Some(cached) = self.get(app).alignment_cache {
1854            return cached;
1855        }
1856        let resolved = AlignmentGeometry::TOP_START.resolve(Some(self.get(app).text_direction));
1857        self.get_mut(app).alignment_cache = Some(resolved);
1858        resolved
1859    }
1860
1861    fn mark_need_resolution(self: RenderHandle<Self>, app: &mut App) {
1862        self.get_mut(app).alignment_cache = None;
1863        self.mark_needs_layout(app);
1864    }
1865
1866    /// The text direction with which the stack alignment is resolved.
1867    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
1868        self.get(app).text_direction
1869    }
1870
1871    /// Sets [`text_direction`](Self::text_direction).
1872    pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
1873        if self.get(app).text_direction == value {
1874            return;
1875        }
1876        self.get_mut(app).text_direction = value;
1877        self.mark_need_resolution(app);
1878    }
1879
1880    /// How many children at the start of the child list are offstage.
1881    pub fn skip_count(self: RenderHandle<Self>, app: &App) -> usize {
1882        self.get(app).skip_count
1883    }
1884
1885    /// Sets [`skip_count`](Self::skip_count).
1886    pub fn set_skip_count(self: RenderHandle<Self>, app: &mut App, value: usize) {
1887        if self.get(app).skip_count != value {
1888            self.get_mut(app).skip_count = value;
1889            self.mark_needs_layout(app);
1890        }
1891    }
1892
1893    /// How to clip the children that overflow the overlay.
1894    ///
1895    /// Defaults to [`Clip::HardEdge`].
1896    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
1897        self.get(app).clip_behavior
1898    }
1899
1900    /// Sets [`clip_behavior`](Self::clip_behavior).
1901    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
1902        if value != self.get(app).clip_behavior {
1903            self.get_mut(app).clip_behavior = value;
1904            self.mark_needs_paint(app);
1905        }
1906    }
1907
1908    /// See [`Overlay::always_size_to_content`].
1909    pub fn always_size_to_content(self: RenderHandle<Self>, app: &App) -> bool {
1910        self.get(app).always_size_to_content
1911    }
1912
1913    /// Sets [`always_size_to_content`](Self::always_size_to_content).
1914    pub fn set_always_size_to_content(self: RenderHandle<Self>, app: &mut App, value: bool) {
1915        if self.get(app).always_size_to_content != value {
1916            self.get_mut(app).always_size_to_content = value;
1917            self.mark_needs_layout(app);
1918        }
1919    }
1920
1921    // Adding/removing a deferred child does not affect the layout of the other children, or
1922    // that of the Overlay. Flutter suppresses the `markNeedsLayout` that `adoptChild` and
1923    // `dropChild` do here; `RenderBox::mark_needs_layout` has no callable base body outside
1924    // `waft-rendering`, so the Overlay is relaid out instead (see `PORTING.md`).
1925    fn add_deferred_child(
1926        self: RenderHandle<Self>,
1927        app: &mut App,
1928        child: RenderHandle<RenderDeferredLayoutBox>,
1929    ) {
1930        self.adopt_child(app, child.as_object());
1931        // The Overlay still needs repainting when a deferred child is added.
1932        self.mark_needs_paint(app);
1933
1934        // After adding `child` to the render tree, we want to make sure it will be laid out
1935        // in the same frame. This is done by calling mark_needs_layout on the layout
1936        // surrogate. This ensures `child` is added to the dirty list (see
1937        // RenderLayoutSurrogateProxyBox's perform_layout).
1938        let surrogate = child.get(app).layout_surrogate;
1939        surrogate.as_object().mark_needs_layout(app);
1940    }
1941
1942    fn remove_deferred_child(
1943        self: RenderHandle<Self>,
1944        app: &mut App,
1945        child: RenderHandle<RenderDeferredLayoutBox>,
1946    ) {
1947        self.drop_child(app, child.as_object());
1948        // The Overlay still needs repainting when a deferred child is dropped. See the
1949        // comment in `add_deferred_child`.
1950        self.mark_needs_paint(app);
1951    }
1952
1953    fn first_onstage_child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
1954        let skip_count = self.get(app).skip_count;
1955        if skip_count == self.child_count(app) {
1956            return None;
1957        }
1958        let mut child = self.first_child(app);
1959        for _ in 0..skip_count {
1960            let current = child.expect("skip_count is at most child_count");
1961            child = self.child_after(app, current);
1962        }
1963        child
1964    }
1965
1966    fn last_onstage_child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
1967        if self.get(app).skip_count == self.child_count(app) {
1968            None
1969        } else {
1970            self.last_child(app)
1971        }
1972    }
1973
1974    fn find_size_determining_child(self: RenderHandle<Self>, app: &App) -> AnyRenderBox {
1975        let mut child = self.last_onstage_child(app);
1976        while let Some(current) = child {
1977            let parent_data = current.as_object().parent_data_of::<TheaterParentData>(app);
1978            let can_size = parent_data
1979                .overlay_entry
1980                .as_ref()
1981                .is_some_and(|entry| app.get(entry).can_size_overlay);
1982            if can_size && !parent_data.stack.is_positioned() {
1983                return current;
1984            }
1985            child = self.child_before(app, current);
1986        }
1987        assert!(
1988            !self.get(app).always_size_to_content,
1989            "Overlay was asked to size itself to content but does not have a suitable child. \
1990             When `always_size_to_content` is true, the Overlay requires at least one \
1991             non-positioned `OverlayEntry` with `can_size_overlay` set to true to determine its \
1992             size."
1993        );
1994        panic!(
1995            "Overlay was given infinite constraints and cannot be sized by a suitable child. \
1996             The constraints given to the overlay would result in an illegal infinite size. To \
1997             avoid that, the Overlay tried to size itself to one of its children, but no \
1998             suitable non-positioned child that belongs to an OverlayEntry with \
1999             can_size_overlay set to true could be found."
2000        );
2001    }
2002}
2003
2004impl ContainerRenderObjectMixin for RenderTheater {
2005    type ChildType = AnyRenderBox;
2006    type ParentDataType = TheaterParentData;
2007
2008    fn container_data(
2009        self: RenderHandle<Self>,
2010        app: &App,
2011    ) -> &ContainerRenderObjectData<AnyRenderBox> {
2012        &self.get(app).container
2013    }
2014
2015    fn container_data_mut(
2016        self: RenderHandle<Self>,
2017        app: &mut App,
2018    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
2019        &mut self.get_mut(app).container
2020    }
2021}
2022
2023impl RenderTheaterMixin for RenderTheater {
2024    fn theater(self: RenderHandle<Self>, _app: &App) -> RenderHandle<RenderTheater> {
2025        self
2026    }
2027
2028    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
2029        TheaterChildren::theater(self, app, false)
2030    }
2031
2032    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
2033        TheaterChildren::theater(self, app, true)
2034    }
2035}
2036
2037impl RenderObject for RenderTheater {
2038    waft_rendering::render_object_accessors!();
2039
2040    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2041        let constraints = self.constraints(app);
2042        let mut size_determining_child = None;
2043        if !self.get(app).always_size_to_content && constraints.biggest().is_finite() {
2044            self.set_size(app, constraints.biggest());
2045        } else {
2046            let child = self.find_size_determining_child(app);
2047            size_determining_child = Some(child);
2048            self.get_mut(app).laying_out_size_determining_child = true;
2049            self.layout_child(app, child, constraints);
2050            self.get_mut(app).laying_out_size_determining_child = false;
2051            let size = child.size(app);
2052            self.set_size(app, size);
2053        }
2054
2055        // Equivalent to the BoxConstraints RenderStack uses for StackFit.expand.
2056        let non_positioned_child_constraints = BoxConstraints::tight(self.size(app));
2057        let mut children = self.children_in_paint_order(app);
2058        while let Some(child) = children.next(app) {
2059            if Some(child) != size_determining_child {
2060                self.layout_child(app, child, non_positioned_child_constraints);
2061            }
2062        }
2063    }
2064
2065    fn visit_children(
2066        self: RenderHandle<Self>,
2067        app: &App,
2068        visitor: &mut dyn FnMut(AnyRenderObject),
2069    ) {
2070        let mut child = self.first_child(app);
2071        while let Some(current) = child {
2072            visitor(current.as_object());
2073            current
2074                .as_object()
2075                .parent_data_of::<TheaterParentData>(app)
2076                .visit_overlay_portal_children_on_overlay_entry(app, visitor);
2077            child = self.child_after(app, current);
2078        }
2079    }
2080
2081    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
2082        ContainerRenderObjectMixin::did_attach(self, app, owner);
2083        let mut child = self.first_child(app);
2084        while let Some(current) = child {
2085            let deferred = current
2086                .as_object()
2087                .parent_data_of::<TheaterParentData>(app)
2088                .paint_order_children(app);
2089            for deferred_child in deferred {
2090                deferred_child.as_object().attach(app, owner);
2091            }
2092            child = self.child_after(app, current);
2093        }
2094    }
2095
2096    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2097        ContainerRenderObjectMixin::did_detach(self, app);
2098        let mut child = self.first_child(app);
2099        while let Some(current) = child {
2100            let deferred = current
2101                .as_object()
2102                .parent_data_of::<TheaterParentData>(app)
2103                .paint_order_children(app);
2104            for deferred_child in deferred {
2105                deferred_child.as_object().detach(app);
2106            }
2107            child = self.child_after(app, current);
2108        }
2109    }
2110
2111    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
2112        let mut children = Vec::new();
2113        RenderObject::visit_children(self, app, &mut |child| children.push(child));
2114        for child in children {
2115            self.as_object().redepth_child(app, child);
2116        }
2117    }
2118
2119    fn paint(
2120        self: RenderHandle<Self>,
2121        app: &mut App,
2122        context: &mut PaintingContext,
2123        offset: Offset,
2124    ) {
2125        let clip_behavior = self.clip_behavior(app);
2126        if clip_behavior != Clip::None {
2127            let size = self.size(app);
2128            let old = self.get(app).clip_rect_layer.layer();
2129            let layer = context.push_clip_rect(
2130                app,
2131                self.as_object().needs_compositing(app),
2132                offset,
2133                Offset::ZERO & size,
2134                |app, context, offset| RenderTheaterMixin::paint(self, app, context, offset),
2135                clip_behavior,
2136                old,
2137            );
2138            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
2139        } else {
2140            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
2141            RenderTheaterMixin::paint(self, app, context, offset);
2142        }
2143    }
2144
2145    fn debug_fill_properties(
2146        self: RenderHandle<Self>,
2147        app: &App,
2148        properties: &mut DiagnosticPropertiesBuilder,
2149    ) {
2150        let this = self.get(app);
2151        properties.add(IntProperty::<usize>::new(
2152            "skipCount",
2153            Some(this.skip_count),
2154        ));
2155        properties.add(EnumProperty::<TextDirection>::new(
2156            "textDirection",
2157            Some(this.text_direction),
2158        ));
2159    }
2160
2161    fn debug_describe_children(
2162        self: RenderHandle<Self>,
2163        app: &App,
2164    ) -> Vec<Rc<dyn DiagnosticsNode>> {
2165        let mut offstage_children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
2166        let mut onstage_children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
2167
2168        let mut count = 1;
2169        let mut onstage = false;
2170        let first_onstage_child = self.first_onstage_child(app);
2171        let mut child = self.first_child(app);
2172        while let Some(current) = child {
2173            let child_parent_data = current.as_object().parent_data_of::<TheaterParentData>(app);
2174            if Some(current) == first_onstage_child {
2175                onstage = true;
2176                count = 1;
2177            }
2178
2179            if onstage {
2180                onstage_children.push(Rc::new(
2181                    current
2182                        .as_object()
2183                        .to_diagnostics_node(app, format!("onstage {count}")),
2184                ));
2185            } else {
2186                offstage_children.push(Rc::new(
2187                    current
2188                        .as_object()
2189                        .to_diagnostics_node(app, format!("offstage {count}"))
2190                        .with_style(DiagnosticsTreeStyle::Offstage),
2191                ));
2192            }
2193
2194            let mut portal_children = Vec::new();
2195            child_parent_data
2196                .visit_overlay_portal_children_on_overlay_entry(app, &mut |render_object| {
2197                    portal_children.push(render_object)
2198                });
2199            for (index, render_object) in portal_children.into_iter().enumerate() {
2200                let subcount = index + 1;
2201                if onstage {
2202                    onstage_children.push(Rc::new(
2203                        render_object
2204                            .to_diagnostics_node(app, format!("onstage {count} - {subcount}")),
2205                    ));
2206                } else {
2207                    offstage_children.push(Rc::new(
2208                        render_object
2209                            .to_diagnostics_node(app, format!("offstage {count} - {subcount}"))
2210                            .with_style(DiagnosticsTreeStyle::Offstage),
2211                    ));
2212                }
2213            }
2214
2215            child = child_parent_data.next_sibling();
2216            count += 1;
2217        }
2218
2219        let mut result = onstage_children;
2220        if offstage_children.is_empty() {
2221            result.push(Rc::new(
2222                message("no offstage children").with_style(DiagnosticsTreeStyle::Offstage),
2223            ));
2224        } else {
2225            result.extend(offstage_children);
2226        }
2227        result
2228    }
2229
2230    fn dispose(self: RenderHandle<Self>, app: &mut App) {
2231        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
2232        waft_rendering::RenderObjectBase::dispose(self, app);
2233    }
2234
2235    /// Dart's `describeApproximatePaintClip`: the theater clips every entry to its bounds
2236    /// unless [`clip_behavior`](Self::clip_behavior) is [`Clip::None`].
2237    fn describe_approximate_paint_clip(
2238        self: RenderHandle<Self>,
2239        app: &App,
2240        _child: AnyRenderObject,
2241    ) -> Option<Rect> {
2242        match self.clip_behavior(app) {
2243            Clip::None => None,
2244            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
2245                Some(Offset::ZERO & self.size(app))
2246            }
2247        }
2248    }
2249}
2250
2251impl RenderBox for RenderTheater {
2252    waft_rendering::render_box_accessors!();
2253
2254    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2255        RenderTheaterMixin::setup_parent_data(self, app, child)
2256    }
2257
2258    fn hit_test_children(
2259        self: RenderHandle<Self>,
2260        app: &mut App,
2261        result: &mut BoxHitTestResult<'_>,
2262        position: Offset,
2263    ) -> bool {
2264        RenderTheaterMixin::hit_test_children(self, app, result, position)
2265    }
2266}
2267
2268/// Dart's `_RenderTheaterMarker`: the [`RenderTheater`] and the entry state an
2269/// [`Overlay`]'s subtree builds under.
2270#[derive(Debug)]
2271struct RenderTheaterMarker {
2272    theater: RenderHandle<RenderTheater>,
2273    overlay_entry_widget_state: Handle<OverlayEntryWidgetState>,
2274    child: WidgetRef,
2275}
2276
2277/// The two fields of a [`RenderTheaterMarker`], copied out of the tree.
2278#[derive(Clone, Copy)]
2279struct TheaterLocation {
2280    theater: RenderHandle<RenderTheater>,
2281    overlay_entry_widget_state: Handle<OverlayEntryWidgetState>,
2282}
2283
2284impl RenderTheaterMarker {
2285    fn of(app: &mut App, context: BuildContext, target_root_overlay: bool) -> TheaterLocation {
2286        RenderTheaterMarker::maybe_of(app, context, target_root_overlay, true).unwrap_or_else(
2287            || {
2288                panic!(
2289                    "No Overlay widget found.\n{} widgets require an Overlay widget ancestor.\n\
2290                     An overlay lets widgets float on top of other widget children.\n\
2291                     To introduce an Overlay widget, you can either directly include one, or \
2292                     use a widget that contains an Overlay itself, such as a Navigator or \
2293                     WidgetsApp.",
2294                    context.widget(app).type_name()
2295                )
2296            },
2297        )
2298    }
2299
2300    fn maybe_of(
2301        app: &mut App,
2302        context: BuildContext,
2303        target_root_overlay: bool,
2304        create_dependency: bool,
2305    ) -> Option<TheaterLocation> {
2306        let read = |app: &App, element: AnyElement| {
2307            let widget = element.widget(app);
2308            let marker = downcast_widget::<RenderTheaterMarker>(&**widget)
2309                .expect("a _RenderTheaterMarker element holds a _RenderTheaterMarker");
2310            TheaterLocation {
2311                theater: marker.theater,
2312                overlay_entry_widget_state: marker.overlay_entry_widget_state,
2313            }
2314        };
2315
2316        if target_root_overlay {
2317            let nearest = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
2318                RenderTheaterMarker,
2319            >(app, context);
2320            let ancestor = RenderTheaterMarker::root_marker_of(app, nearest)?;
2321            if create_dependency {
2322                context.depend_on_inherited_element(app, ancestor, None);
2323            }
2324            return Some(read(app, ancestor));
2325        }
2326
2327        if create_dependency {
2328            LookupBoundary::depend_on_inherited_widget_of_exact_type::<RenderTheaterMarker>(
2329                app, context,
2330            )?;
2331        }
2332        let element = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
2333            RenderTheaterMarker,
2334        >(app, context)?;
2335        Some(read(app, element))
2336    }
2337
2338    fn root_marker_of(app: &App, marker_element: Option<AnyElement>) -> Option<AnyElement> {
2339        let marker_element = marker_element?;
2340        let mut ancestor = None;
2341        marker_element.visit_ancestor_elements(app, &mut |element| {
2342            ancestor = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
2343                RenderTheaterMarker,
2344            >(app, element);
2345            false
2346        });
2347        match ancestor {
2348            None => Some(marker_element),
2349            Some(ancestor) => RenderTheaterMarker::root_marker_of(app, Some(ancestor)),
2350        }
2351    }
2352}
2353
2354impl InheritedWidget for RenderTheaterMarker {
2355    fn child(&self) -> &WidgetRef {
2356        &self.child
2357    }
2358
2359    fn update_should_notify(&self, old_widget: &RenderTheaterMarker) -> bool {
2360        old_widget.theater != self.theater
2361            || old_widget.overlay_entry_widget_state != self.overlay_entry_widget_state
2362    }
2363}
2364
2365// * OverlayPortal Implementation
2366//  OverlayPortal is inspired by the
2367//  [flutter_portal](https://pub.dev/packages/flutter_portal) package.
2368//
2369// ** RenderObject hierarchy
2370// The widget works by inserting its overlay child's render subtree directly under
2371// [`Overlay`]'s render object ([`RenderTheater`]).
2372//
2373// To ensure the overlay child render subtree does not do layout twice, the subtree must only
2374// perform layout after both its RenderTheater and the OverlayPortal's render object
2375// (RenderLayoutSurrogateProxyBox) have finished layout. This is handled by
2376// RenderDeferredLayoutBox.
2377//
2378// ** Z-Index of an overlay child
2379// OverlayEntryLocation is a (private) interface that allows an OverlayPortal to insert its
2380// overlay child into a specific Overlay, as well as specifying the paint order between the
2381// overlay child and other children of the RenderTheater.
2382//
2383// Since OverlayPortal is only allowed to target ancestor Overlays (RenderTheater must finish
2384// doing layout before RenderDeferredLayoutBox), the RenderTheater should typically be
2385// acquired using an InheritedWidget (currently, RenderTheaterMarker) in case the
2386// OverlayPortal gets reparented.
2387
2388thread_local! {
2389    /// Dart's `OverlayPortalController._wallTime`.
2390    static WALL_TIME: Cell<i64> = const { Cell::new(i64::MIN) };
2391}
2392
2393/// A class to show, hide and bring to top an [`OverlayPortal`]'s overlay child in the target
2394/// [`Overlay`].
2395///
2396/// An [`OverlayPortalController`] can only be given to at most one [`OverlayPortal`] at a
2397/// time. When an [`OverlayPortalController`] is moved from one [`OverlayPortal`] to another,
2398/// its [`is_showing`](Self::is_showing) state does not carry over.
2399///
2400/// [`show`](Self::show) and [`hide`](Self::hide) can be called even before the controller is
2401/// assigned to any [`OverlayPortal`], but they typically should not be called while the
2402/// widget tree is being rebuilt.
2403pub struct OverlayPortalController {
2404    attach_target: Option<Handle<OverlayPortalState>>,
2405    // A separate z_order_index to allow `show` or `hide` to be called when the controller is
2406    // not yet attached. Once this controller is attached, the attach target's z_order_index
2407    // will be used as the source of truth, and this variable will be set to None.
2408    z_order_index: Option<i64>,
2409    debug_label: Option<String>,
2410}
2411
2412impl OverlayPortalController {
2413    /// Creates an [`OverlayPortalController`], optionally with a `debug_label`.
2414    pub fn new(app: &mut App, debug_label: Option<String>) -> Ref<OverlayPortalController> {
2415        app.create(OverlayPortalController {
2416            attach_target: None,
2417            z_order_index: None,
2418            debug_label,
2419        })
2420    }
2421
2422    // Returns a unique and monotonically increasing timestamp that represents now.
2423    //
2424    // The value this method returns increments after each call.
2425    fn now(self: Handle<Self>, app: &App) -> i64 {
2426        let now = WALL_TIME.get() + 1;
2427        WALL_TIME.set(now);
2428        debug_assert!(app.get(self).z_order_index.is_none_or(|index| index < now));
2429        debug_assert!(
2430            app.get(self)
2431                .attach_target
2432                .and_then(|target| app.get(target).z_order_index)
2433                .is_none_or(|index| index < now)
2434        );
2435        now
2436    }
2437
2438    /// Show the overlay child of the [`OverlayPortal`] this controller is attached to, at the
2439    /// top of the target [`Overlay`].
2440    ///
2441    /// When there is more than one [`OverlayPortal`] that targets the same [`Overlay`], the
2442    /// overlay child of the last [`OverlayPortal`] to have called
2443    /// [`show`](Self::show) appears at the top level, unobstructed.
2444    ///
2445    /// If [`is_showing`](Self::is_showing) is already true, calling this method brings the
2446    /// overlay child it controls to the top.
2447    ///
2448    /// This method should typically not be called while the widget tree is being rebuilt.
2449    pub fn show(self: Handle<Self>, app: &mut App) {
2450        let now = self.now(app);
2451        match app.get(self).attach_target {
2452            Some(state) => state.show(app, now),
2453            None => app.get_mut(self).z_order_index = Some(now),
2454        }
2455    }
2456
2457    /// Hide the [`OverlayPortal`]'s overlay child.
2458    ///
2459    /// Once hidden, the overlay child will be removed from the widget tree the next time the
2460    /// widget tree rebuilds, and stateful widgets in the overlay child may lose state as a
2461    /// result.
2462    ///
2463    /// This method should typically not be called while the widget tree is being rebuilt.
2464    pub fn hide(self: Handle<Self>, app: &mut App) {
2465        match app.get(self).attach_target {
2466            Some(state) => state.hide(app),
2467            None => {
2468                debug_assert!(app.get(self).z_order_index.is_some());
2469                app.get_mut(self).z_order_index = None;
2470            }
2471        }
2472    }
2473
2474    /// Whether the associated [`OverlayPortal`] should build and show its overlay child,
2475    /// using its [`overlay_child_builder`](OverlayPortal::overlay_child_builder).
2476    pub fn is_showing(self: Handle<Self>, app: &App) -> bool {
2477        match app.get(self).attach_target {
2478            Some(state) => app.get(state).z_order_index.is_some(),
2479            None => app.get(self).z_order_index.is_some(),
2480        }
2481    }
2482
2483    /// Convenience method for toggling the current [`is_showing`](Self::is_showing) status.
2484    ///
2485    /// This method should typically not be called while the widget tree is being rebuilt.
2486    pub fn toggle(self: Handle<Self>, app: &mut App) {
2487        if self.is_showing(app) {
2488            self.hide(app);
2489        } else {
2490            self.show(app);
2491        }
2492    }
2493}
2494
2495impl Debug for OverlayPortalController {
2496    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2497        write!(f, "OverlayPortalController")?;
2498        if let Some(label) = &self.debug_label {
2499            write!(f, "({label})")?;
2500        }
2501        if self.attach_target.is_none() {
2502            write!(f, " DETACHED")?;
2503        }
2504        Ok(())
2505    }
2506}
2507
2508/// The location of the [`Overlay`] that an [`OverlayPortal`] renders its overlay child on.
2509///
2510/// This is typically used in [`OverlayPortal`].
2511#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2512pub enum OverlayChildLocation {
2513    /// The [`OverlayPortal`] renders its overlay child on the closest ancestor [`Overlay`]
2514    /// above the widget tree.
2515    NearestOverlay,
2516
2517    /// The [`OverlayPortal`] renders its overlay child on the root [`Overlay`] above the
2518    /// widget tree.
2519    ///
2520    /// In case of multi-view apps, the root [`Overlay`] refers to the first Overlay below the
2521    /// `View`.
2522    RootOverlay,
2523}
2524
2525/// A widget that renders its overlay child on an [`Overlay`].
2526///
2527/// The overlay child is initially hidden until [`OverlayPortalController::show`] is called on
2528/// the associated [`controller`](Self::controller). The [`OverlayPortal`] uses
2529/// [`overlay_child_builder`](Self::overlay_child_builder) to build its overlay child and
2530/// renders it on the specified [`Overlay`] as if it was inserted using an [`OverlayEntry`],
2531/// while it can depend on the same set of `InheritedWidget`s that this widget can depend on.
2532///
2533/// This widget requires an [`Overlay`] ancestor in the widget tree when its overlay child is
2534/// showing. The overlay child is rendered by the [`Overlay`] ancestor, not by the widget
2535/// itself. This allows the overlay child to float above other widgets, independent of its
2536/// position in the widget tree.
2537///
2538/// When [`OverlayPortalController::hide`] is called, the widget built using
2539/// [`overlay_child_builder`](Self::overlay_child_builder) will be removed from the widget
2540/// tree the next time the widget rebuilds. Stateful descendants in the overlay child subtree
2541/// may lose state as a result.
2542///
2543/// ### Paint Order
2544///
2545/// In an [`Overlay`], an overlay child is painted after the [`OverlayEntry`] associated with
2546/// its [`OverlayPortal`] (that is, the [`OverlayEntry`] closest to the [`OverlayPortal`] in
2547/// the widget tree, which usually represents the enclosing `Route`), and before the next
2548/// [`OverlayEntry`].
2549///
2550/// When an [`OverlayEntry`] has multiple associated [`OverlayPortal`]s, the paint order
2551/// between their overlay children is the order in which [`OverlayPortalController::show`] was
2552/// called. The last [`OverlayPortal`] to have called `show` gets to paint its overlay child
2553/// in the foreground.
2554///
2555/// ### Differences between [`OverlayPortal`] and [`OverlayEntry`]
2556///
2557/// The main difference between [`OverlayEntry`] and [`OverlayPortal`] is that [`OverlayEntry`]
2558/// builds its widget subtree as a child of the target [`Overlay`], while [`OverlayPortal`]
2559/// uses [`overlay_child_builder`](Self::overlay_child_builder) to build a child widget of
2560/// itself. This allows [`OverlayPortal`]'s overlay child to depend on the same set of
2561/// `InheritedWidget`s as [`OverlayPortal`], and it's also guaranteed that the overlay child
2562/// will not outlive its [`OverlayPortal`].
2563///
2564/// On the other hand, [`OverlayPortal`]'s implementation is more complex. For instance, it
2565/// does a bit more work than a regular widget during global key reparenting. If the content
2566/// to be shown on the [`Overlay`] doesn't benefit from being a part of [`OverlayPortal`]'s
2567/// subtree, consider using an [`OverlayEntry`] instead.
2568///
2569/// See also:
2570///
2571///  * [`OverlayEntry`], an alternative API for inserting widgets into an [`Overlay`].
2572///  * `Positioned`, which can be used to size and position the overlay child in relation to
2573///    the target [`Overlay`]'s boundaries.
2574pub struct OverlayPortal {
2575    /// See [`Widget::key`].
2576    pub key: Option<KeyRef>,
2577    /// The controller to show, hide and bring to top the overlay child.
2578    pub controller: Ref<OverlayPortalController>,
2579    /// A [`WidgetBuilder`] used to build a widget below this widget in the tree, that renders
2580    /// on the closest [`Overlay`].
2581    ///
2582    /// The said widget will only be built and shown in the closest [`Overlay`] once
2583    /// [`OverlayPortalController::show`] is called on the associated
2584    /// [`controller`](Self::controller). It will be painted in front of the [`OverlayEntry`]
2585    /// closest to this widget in the widget tree (which is usually the enclosing `Route`).
2586    ///
2587    /// The built overlay child widget is inserted below this widget in the widget tree,
2588    /// allowing it to depend on `InheritedWidget`s above it, and be notified when the
2589    /// `InheritedWidget`s change.
2590    ///
2591    /// Unlike [`child`](Self::child), the built overlay child can visually extend outside the
2592    /// bounds of this widget without being clipped, and receive hit-test events outside of
2593    /// this widget's bounds, as long as it does not extend outside of the [`Overlay`] on
2594    /// which it is rendered.
2595    pub overlay_child_builder: WidgetBuilder,
2596    /// A widget below this widget in the tree.
2597    pub child: Option<WidgetRef>,
2598    /// The [`Overlay`] that the widget returned from
2599    /// [`overlay_child_builder`](Self::overlay_child_builder) is attached to.
2600    pub overlay_location: OverlayChildLocation,
2601}
2602
2603impl OverlayPortal {
2604    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
2605    /// the closest [`Overlay`] when [`OverlayPortalController::show`] is called.
2606    ///
2607    /// The [`overlay_location`](Self::overlay_location) sets which [`Overlay`] this widget
2608    /// attaches the widget returned by `overlay_child_builder` to. Defaults to
2609    /// [`OverlayChildLocation::NearestOverlay`].
2610    pub fn new(
2611        controller: Ref<OverlayPortalController>,
2612        overlay_child_builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
2613    ) -> OverlayPortal {
2614        OverlayPortal {
2615            key: None,
2616            controller,
2617            overlay_child_builder: Rc::new(overlay_child_builder),
2618            child: None,
2619            overlay_location: OverlayChildLocation::NearestOverlay,
2620        }
2621    }
2622
2623    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
2624    /// the root [`Overlay`] when [`OverlayPortalController::show`] is called.
2625    ///
2626    /// Deprecated in Flutter after v3.33.0-0.0.pre: use [`OverlayPortal::new`] with
2627    /// [`overlay_location`](Self::overlay_location) set to
2628    /// [`OverlayChildLocation::RootOverlay`] instead.
2629    #[deprecated(note = "Use OverlayPortal::new with an overlay_location of \
2630                OverlayChildLocation::RootOverlay instead. This feature was deprecated \
2631                after v3.33.0-0.0.pre.")]
2632    pub fn targets_root_overlay(
2633        controller: Ref<OverlayPortalController>,
2634        overlay_child_builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
2635    ) -> OverlayPortal {
2636        OverlayPortal {
2637            key: None,
2638            controller,
2639            overlay_child_builder: Rc::new(overlay_child_builder),
2640            child: None,
2641            overlay_location: OverlayChildLocation::RootOverlay,
2642        }
2643    }
2644
2645    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
2646    /// the closest [`Overlay`] when [`OverlayPortalController::show`] is called.
2647    ///
2648    /// Developers can use `overlay_child_builder` to configure the overlay child based on the
2649    /// size and the location of [`child`](Self::child) within the target [`Overlay`], as well
2650    /// as the size of the [`Overlay`] itself. This allows the overlay child to, for example,
2651    /// always follow [`child`](Self::child) and at the same time resize itself based on how
2652    /// close it is to the edges of the [`Overlay`].
2653    ///
2654    /// The `overlay_child_builder` callback is called during layout. To ensure the paint
2655    /// transform of [`child`](Self::child) in relation to the target [`Overlay`] is
2656    /// up-to-date by then, all render objects between the [`OverlayPortal`] and the target
2657    /// [`Overlay`] must establish their paint transform during the layout phase, which most
2658    /// render objects do.
2659    ///
2660    /// The [`overlay_location`](Self::overlay_location) sets which [`Overlay`] this widget
2661    /// attaches the widget returned by `overlay_child_builder` to. Defaults to
2662    /// [`OverlayChildLocation::NearestOverlay`].
2663    pub fn overlay_child_layout_builder(
2664        controller: Ref<OverlayPortalController>,
2665        overlay_child_builder: impl Fn(&mut App, BuildContext, OverlayChildLayoutInfo) -> WidgetRef
2666        + 'static,
2667    ) -> OverlayPortal {
2668        let builder: OverlayChildLayoutBuilder = Rc::new(overlay_child_builder);
2669        OverlayPortal::new(controller, move |_app, _context| {
2670            OverlayChildLayoutBuilderWidget {
2671                builder: Rc::clone(&builder),
2672                created: None,
2673            }
2674            .into_widget()
2675        })
2676    }
2677
2678    /// Dart `OverlayPortal(key:)`.
2679    pub fn key(mut self, key: KeyRef) -> OverlayPortal {
2680        self.key = Some(key);
2681        self
2682    }
2683
2684    /// Dart `OverlayPortal(child:)`.
2685    #[cfg_attr(debug_assertions, track_caller)]
2686    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> OverlayPortal {
2687        self.child = Some(child.into_widget());
2688        self
2689    }
2690
2691    /// Dart `OverlayPortal(overlayLocation:)`.
2692    pub fn overlay_location(mut self, overlay_location: OverlayChildLocation) -> OverlayPortal {
2693        self.overlay_location = overlay_location;
2694        self
2695    }
2696}
2697
2698impl Debug for OverlayPortal {
2699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2700        f.debug_struct("OverlayPortal")
2701            .field("overlayLocation", &self.overlay_location)
2702            .finish_non_exhaustive()
2703    }
2704}
2705
2706impl StatefulWidget for OverlayPortal {
2707    type State = OverlayPortalState;
2708
2709    fn key(&self) -> Option<&KeyRef> {
2710        self.key.as_ref()
2711    }
2712
2713    fn create_state(&self) -> OverlayPortalState {
2714        OverlayPortalState {
2715            state: StateData::new(),
2716            z_order_index: None,
2717            child_model_may_have_changed: true,
2718            location_cache: None,
2719        }
2720    }
2721}
2722
2723/// Dart's `_OverlayPortalState`.
2724pub struct OverlayPortalState {
2725    state: StateData<OverlayPortal>,
2726    z_order_index: Option<i64>,
2727    // The location of the overlay child within the overlay. This object will be used as the
2728    // slot of the overlay child widget.
2729    //
2730    // The developer must call `show` to reveal the overlay so we can get a unique timestamp of
2731    // the user interaction for determining the z-index of the overlay child in the overlay.
2732    //
2733    // Avoid invalidating the cache if possible, since the framework uses identity to compare
2734    // slots, and OverlayEntryLocation is mutable. Changing slots can be relatively slow.
2735    child_model_may_have_changed: bool,
2736    location_cache: Option<Ref<OverlayEntryLocation>>,
2737}
2738
2739impl OverlayPortalState {
2740    fn is_the_same_location(
2741        app: &App,
2742        location_cache: Handle<OverlayEntryLocation>,
2743        marker: &TheaterLocation,
2744    ) -> bool {
2745        let cached = app.get(location_cache);
2746        cached.child_model == marker.overlay_entry_widget_state && cached.theater == marker.theater
2747    }
2748
2749    fn get_location(
2750        self: Handle<Self>,
2751        app: &mut App,
2752        z_order_index: i64,
2753        overlay_location: OverlayChildLocation,
2754    ) -> Ref<OverlayEntryLocation> {
2755        let cached_location = app.get(self).location_cache.clone();
2756        let context = self.context(app);
2757        let target_root_overlay = overlay_location == OverlayChildLocation::RootOverlay;
2758        // Dart's `late final marker`: reading it depends on an inherited widget, which the
2759        // valid-cache path must not do.
2760        let mut marker = None;
2761        let is_cache_valid = cached_location.as_ref().is_some_and(|cached| {
2762            !app.get(self).child_model_may_have_changed || {
2763                let found = RenderTheaterMarker::of(app, context, target_root_overlay);
2764                marker = Some(found);
2765                OverlayPortalState::is_the_same_location(app, cached.handle(), &found)
2766            }
2767        });
2768        app.get_mut(self).child_model_may_have_changed = false;
2769        if is_cache_valid {
2770            let cached = cached_location.expect("a valid cache holds a location");
2771            debug_assert!(app.get(&cached).z_order_index == z_order_index);
2772            debug_assert!(cached.debug_is_location_valid(app));
2773            return cached;
2774        }
2775        // Otherwise invalidate the cache and create a new location.
2776        if let Some(cached) = &cached_location {
2777            cached.debug_mark_location_invalid(app);
2778        }
2779        let marker = match marker {
2780            Some(marker) => marker,
2781            None => RenderTheaterMarker::of(app, context, target_root_overlay),
2782        };
2783        let new_location = OverlayEntryLocation::new(
2784            app,
2785            z_order_index,
2786            marker.overlay_entry_widget_state,
2787            marker.theater,
2788        );
2789        app.get_mut(self).location_cache = Some(new_location.clone());
2790        new_location
2791    }
2792
2793    fn setup_controller(
2794        self: Handle<Self>,
2795        app: &mut App,
2796        controller: Handle<OverlayPortalController>,
2797    ) {
2798        debug_assert!(
2799            app.get(controller).attach_target == Some(self)
2800                || !app
2801                    .get(controller)
2802                    .attach_target
2803                    .is_some_and(|target| target.mounted(app)),
2804            "Failed to attach the controller: it is already attached to another OverlayPortal."
2805        );
2806        let controller_z_order_index = app.get(controller).z_order_index;
2807        let z_order_index = app.get(self).z_order_index;
2808        let takes_controller_index = match (controller_z_order_index, z_order_index) {
2809            (_, None) => true,
2810            (Some(controller_index), Some(index)) => controller_index > index,
2811            (None, Some(_)) => false,
2812        };
2813        if takes_controller_index {
2814            app.get_mut(self).z_order_index = controller_z_order_index;
2815        }
2816        let controller_state = app.get_mut(controller);
2817        controller_state.z_order_index = None;
2818        controller_state.attach_target = Some(self);
2819    }
2820
2821    fn show(self: Handle<Self>, app: &mut App, z_order_index: i64) {
2822        debug_assert!(
2823            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
2824            "OverlayPortalController::show should not be called during build."
2825        );
2826        self.set_state(app, |state| state.z_order_index = Some(z_order_index));
2827        if let Some(cached) = app.get(self).location_cache.handle() {
2828            cached.debug_mark_location_invalid(app);
2829        }
2830        app.get_mut(self).location_cache = None;
2831    }
2832
2833    fn hide(self: Handle<Self>, app: &mut App) {
2834        debug_assert!(
2835            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
2836            "OverlayPortalController::hide should not be called during build."
2837        );
2838        self.set_state(app, |state| state.z_order_index = None);
2839        if let Some(cached) = app.get(self).location_cache.handle() {
2840            cached.debug_mark_location_invalid(app);
2841        }
2842        app.get_mut(self).location_cache = None;
2843    }
2844}
2845
2846impl State for OverlayPortalState {
2847    type Widget = OverlayPortal;
2848
2849    crate::state_accessors!();
2850
2851    fn init_state(self: Handle<Self>, app: &mut App) {
2852        let controller = self.widget(app).controller.handle();
2853        self.setup_controller(app, controller);
2854    }
2855
2856    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2857        app.get_mut(self).child_model_may_have_changed = true;
2858    }
2859
2860    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &OverlayPortal) {
2861        let (old_location, old_controller) =
2862            (old_widget.overlay_location, old_widget.controller.handle());
2863        let widget = self.widget(app);
2864        let (new_location, new_controller) = (widget.overlay_location, widget.controller.handle());
2865        let state = app.get_mut(self);
2866        state.child_model_may_have_changed =
2867            state.child_model_may_have_changed || old_location != new_location;
2868        if old_controller != new_controller {
2869            app.get_mut(old_controller).attach_target = None;
2870            self.setup_controller(app, new_controller);
2871        }
2872    }
2873
2874    fn activate(self: Handle<Self>, app: &mut App) {
2875        debug_assert!(app.get(&self.widget(app).controller).attach_target == Some(self));
2876    }
2877
2878    fn dispose(self: Handle<Self>, app: &mut App) {
2879        let controller = self.widget(app).controller.handle();
2880        app.get_mut(controller).attach_target = None;
2881        if let Some(cached) = app.get(self).location_cache.handle() {
2882            cached.debug_mark_location_invalid(app);
2883        }
2884        app.get_mut(self).location_cache = None;
2885    }
2886
2887    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2888        let child = self.widget(app).child.clone();
2889        let Some(z_order_index) = app.get(self).z_order_index else {
2890            return RawOverlayPortal {
2891                overlay_location: None,
2892                overlay_child: None,
2893                child,
2894                created: None,
2895            }
2896            .into_widget();
2897        };
2898
2899        let widget_location = self.widget(app).overlay_location;
2900        let overlay_location = self.get_location(app, z_order_index, widget_location);
2901        let child_model_context = app.get(&overlay_location).child_model.context(app);
2902        let overlay_data = MediaQuery::of(app, child_model_context);
2903        let data = MediaQuery::of(app, context)
2904            .copy_with()
2905            .padding(overlay_data.padding)
2906            .view_insets(overlay_data.view_insets)
2907            .view_padding(overlay_data.view_padding);
2908        let builder = Rc::clone(&self.widget(app).overlay_child_builder);
2909        RawOverlayPortal {
2910            overlay_location: Some(overlay_location),
2911            created: None,
2912            overlay_child: Some(
2913                DeferredLayout {
2914                    child: MediaQuery::new(data, Builder { key: None, builder }).into_widget(),
2915                }
2916                .into_widget(),
2917            ),
2918            child,
2919        }
2920        .into_widget()
2921    }
2922}
2923
2924/// A location in an [`Overlay`].
2925///
2926/// An [`OverlayEntryLocation`] determines the [`Overlay`] the associated [`OverlayPortal`]
2927/// should put its overlay child onto, as well as the overlay child's paint order in relation
2928/// to other contents painted on the [`Overlay`].
2929//
2930// An OverlayEntryLocation is a cursor pointing to a location in a particular Overlay's child
2931// model, and provides methods to insert/remove/move a RenderDeferredLayoutBox to/from its
2932// target theater.
2933//
2934// The occupant (a `RenderBox`) will be painted above the associated OverlayEntry, but below
2935// the OverlayEntry above that OverlayEntry.
2936//
2937// Additionally, `reattach_from_layout_surrogate` and `detach_from_layout_surrogate` are
2938// called when the overlay child's RawOverlayPortalElement activates/deactivates (for instance,
2939// during global key reparenting). RawOverlayPortalElement removes its overlay child's render
2940// object from the target RenderTheater when it deactivates and puts it back on activation.
2941// These two methods can be used to "hide" a child in the child model without removing it, when
2942// the child is expensive/difficult to re-insert at the correct location on activation.
2943//
2944// ### Equality
2945//
2946// An OverlayEntryLocation is used as an Element's slot. These three parts uniquely identify a
2947// place in an overlay's child model:
2948// - theater
2949// - child_model (the OverlayEntry)
2950// - z_order_index
2951//
2952// Since it is mutable, slots compare it by identity, and the same OverlayEntryLocation must
2953// not be used to represent more than one location.
2954struct OverlayEntryLocation {
2955    z_order_index: i64,
2956    child_model: Handle<OverlayEntryWidgetState>,
2957    theater: RenderHandle<RenderTheater>,
2958    overlay_child_render_box: Option<RenderHandle<RenderDeferredLayoutBox>>,
2959    // The identity a `Slot::Custom` compares: created with the location and never replaced.
2960    slot_token: Option<Rc<dyn Any>>,
2961    // Dart records the `StackTrace` of the first `_debugMarkLocationInvalid` call; only the
2962    // flag is kept here (see `PORTING.md`). The effect is not reversible: once marked invalid,
2963    // this object cannot be marked valid again.
2964    debug_location_invalid: bool,
2965}
2966
2967impl OverlayEntryLocation {
2968    fn new(
2969        app: &mut App,
2970        z_order_index: i64,
2971        child_model: Handle<OverlayEntryWidgetState>,
2972        theater: RenderHandle<RenderTheater>,
2973    ) -> Ref<OverlayEntryLocation> {
2974        let this = app.create(OverlayEntryLocation {
2975            z_order_index,
2976            child_model,
2977            theater,
2978            overlay_child_render_box: None,
2979            slot_token: None,
2980            debug_location_invalid: false,
2981        });
2982        app.get_mut(&this).slot_token = Some(Rc::new(this.handle()));
2983        this
2984    }
2985
2986    /// The slot the overlay child element occupies: this location, compared by identity.
2987    fn slot(self: Handle<Self>, app: &App) -> Slot {
2988        Slot::Custom(Rc::clone(
2989            app.get(self)
2990                .slot_token
2991                .as_ref()
2992                .expect("the token is created with the location"),
2993        ))
2994    }
2995
2996    /// The location a slot names, if it names one.
2997    fn from_slot(slot: &Slot) -> Option<Handle<OverlayEntryLocation>> {
2998        match slot {
2999            Slot::Custom(token) => token
3000                .downcast_ref::<Handle<OverlayEntryLocation>>()
3001                .copied(),
3002            _ => None,
3003        }
3004    }
3005
3006    fn add_to_child_model(
3007        self: Handle<Self>,
3008        app: &mut App,
3009        child: RenderHandle<RenderDeferredLayoutBox>,
3010    ) {
3011        debug_assert!(
3012            app.get(self).overlay_child_render_box.is_none(),
3013            "Failed to add the child: this location is already occupied."
3014        );
3015        app.get_mut(self).overlay_child_render_box = Some(child);
3016        let (child_model, theater) = {
3017            let location = app.get(self);
3018            (location.child_model, location.theater)
3019        };
3020        let kept = self.keep(app);
3021        child_model.add(app, kept);
3022        theater.mark_needs_paint(app);
3023    }
3024
3025    fn remove_from_child_model(
3026        self: Handle<Self>,
3027        app: &mut App,
3028        child: RenderHandle<RenderDeferredLayoutBox>,
3029    ) {
3030        debug_assert!(app.get(self).overlay_child_render_box == Some(child));
3031        app.get_mut(self).overlay_child_render_box = None;
3032        let (child_model, theater) = {
3033            let location = app.get(self);
3034            (location.child_model, location.theater)
3035        };
3036        child_model.remove(app, self);
3037        theater.mark_needs_paint(app);
3038    }
3039
3040    fn add_child(self: Handle<Self>, app: &mut App, child: RenderHandle<RenderDeferredLayoutBox>) {
3041        debug_assert!(self.debug_is_location_valid(app));
3042        self.add_to_child_model(app, child);
3043        let theater = app.get(self).theater;
3044        theater.add_deferred_child(app, child);
3045        debug_assert!(child.parent(app) == Some(theater.as_object()));
3046    }
3047
3048    fn remove_child(
3049        self: Handle<Self>,
3050        app: &mut App,
3051        child: RenderHandle<RenderDeferredLayoutBox>,
3052    ) {
3053        // This call is allowed even when this location is disposed.
3054        self.remove_from_child_model(app, child);
3055        let theater = app.get(self).theater;
3056        theater.remove_deferred_child(app, child);
3057        debug_assert!(child.parent(app).is_none());
3058    }
3059
3060    fn move_child(
3061        self: Handle<Self>,
3062        app: &mut App,
3063        child: RenderHandle<RenderDeferredLayoutBox>,
3064        from_location: Handle<OverlayEntryLocation>,
3065    ) {
3066        debug_assert!(from_location != self);
3067        debug_assert!(self.debug_is_location_valid(app));
3068        let from_theater = app.get(from_location).theater;
3069        let from_model = app.get(from_location).child_model;
3070        let theater = app.get(self).theater;
3071
3072        if from_theater != theater {
3073            from_theater.remove_deferred_child(app, child);
3074            theater.add_deferred_child(app, child);
3075        }
3076
3077        if from_model != app.get(self).child_model
3078            || app.get(from_location).z_order_index != app.get(self).z_order_index
3079        {
3080            from_location.remove_from_child_model(app, child);
3081            self.add_to_child_model(app, child);
3082        }
3083    }
3084
3085    /// Undoes [`detach_from_layout_surrogate`](Self::detach_from_layout_surrogate) by adding
3086    /// the given `child` back to the theater.
3087    ///
3088    /// This is called when the [`OverlayPortal`] is activated. This call is allowed even when
3089    /// this location is invalidated.
3090    fn reattach_from_layout_surrogate(
3091        self: Handle<Self>,
3092        app: &mut App,
3093        child: RenderHandle<RenderDeferredLayoutBox>,
3094    ) {
3095        debug_assert!(
3096            app.get(self).overlay_child_render_box.is_none(),
3097            "failed to reattach: detach_from_layout_surrogate must be called before \
3098             reattach_from_layout_surrogate."
3099        );
3100        let theater = app.get(self).theater;
3101        theater.add_deferred_child(app, child);
3102        app.get_mut(self).overlay_child_render_box = Some(child);
3103    }
3104
3105    /// Removes the given `child` from the theater but keeps it in the child list (unlike
3106    /// [`remove_child`](Self::remove_child)).
3107    ///
3108    /// This is typically called when the [`OverlayPortal`] deactivates. Since every render
3109    /// object in the render tree must be attached, when an [`OverlayPortal`] deactivates, it
3110    /// must remove the overlay child from the render tree instead of just detaching it.
3111    ///
3112    /// This call is allowed even when this location is invalidated.
3113    fn detach_from_layout_surrogate(
3114        self: Handle<Self>,
3115        app: &mut App,
3116        child: RenderHandle<RenderDeferredLayoutBox>,
3117    ) {
3118        let theater = app.get(self).theater;
3119        theater.remove_deferred_child(app, child);
3120        app.get_mut(self).overlay_child_render_box = None;
3121    }
3122
3123    // Panics if this location is already invalidated and shouldn't be used as an OverlayPortal
3124    // slot. Must be used in asserts.
3125    //
3126    // Generally, `debug_assert!(location.debug_is_location_valid(app))` should be used to
3127    // prevent invalid accesses to an invalid location. Exceptions to this rule are
3128    // `remove_child` and `detach_from_layout_surrogate`, which are called when the
3129    // OverlayPortal is being removed from the widget tree and may use the location information
3130    // to perform cleanup tasks.
3131    //
3132    // Another exception is `reattach_from_layout_surrogate`, which is called shortly after the
3133    // OverlayPortal activates because it's possible that the widget subtree hasn't been
3134    // rebuilt at that point, so we'll have to re-attach the overlay child render object using
3135    // a potentially outdated location.
3136    fn debug_is_location_valid(self: Handle<Self>, app: &App) -> bool {
3137        assert!(
3138            !app.get(self).debug_location_invalid,
3139            "this OverlayPortal location is already disposed."
3140        );
3141        true
3142    }
3143
3144    fn debug_mark_location_invalid(self: Handle<Self>, app: &mut App) {
3145        debug_assert!(self.debug_is_location_valid(app));
3146        if cfg!(debug_assertions) {
3147            app.get_mut(self).debug_location_invalid = true;
3148        }
3149    }
3150}
3151
3152/// Dart's `_OverlayPortal`: the render object widget an [`OverlayPortal`] builds.
3153#[derive(Debug)]
3154struct RawOverlayPortal {
3155    overlay_child: Option<WidgetRef>,
3156    /// A widget below this widget in the tree.
3157    child: Option<WidgetRef>,
3158    overlay_location: Option<Ref<OverlayEntryLocation>>,
3159    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
3160    created: Option<CreationLocation>,
3161}
3162
3163impl RawOverlayPortal {
3164    /// The tree node: a render object widget with its own element, outside the `IntoWidget`
3165    /// kinds.
3166    #[cfg_attr(debug_assertions, track_caller)]
3167    fn into_widget(mut self) -> WidgetRef {
3168        debug_assert!(self.overlay_child.is_none() || self.overlay_location.is_some());
3169        self.created = Some(CreationLocation::of_caller());
3170        Rc::new(self)
3171    }
3172}
3173
3174impl Widget for RawOverlayPortal {
3175    fn key(&self) -> Option<&KeyRef> {
3176        None
3177    }
3178
3179    fn creation_location(&self) -> Option<&'static Location<'static>> {
3180        self.created.and_then(CreationLocation::location)
3181    }
3182
3183    fn record_creation_location(&mut self, location: CreationLocation) {
3184        self.created = Some(location);
3185    }
3186
3187    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
3188        RawOverlayPortalElement::new(app, this).as_element()
3189    }
3190
3191    fn as_any(&self) -> &dyn Any {
3192        self
3193    }
3194
3195    fn widget_type(&self) -> std::any::TypeId {
3196        std::any::TypeId::of::<RawOverlayPortal>()
3197    }
3198
3199    fn kind(&self) -> WidgetKind {
3200        WidgetKind::Other
3201    }
3202}
3203
3204impl RenderObjectWidget for RawOverlayPortal {
3205    type RenderObject = RenderLayoutSurrogateProxyBox;
3206
3207    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
3208        RenderLayoutSurrogateProxyBox::new(app, self.overlay_location.clone()).as_object()
3209    }
3210
3211    fn update_render_object(
3212        &self,
3213        app: &mut App,
3214        _context: BuildContext,
3215        render_object: RenderHandle<RenderLayoutSurrogateProxyBox>,
3216    ) {
3217        render_object.get_mut(app).overlay_location = self.overlay_location.clone();
3218    }
3219}
3220
3221/// Dart's `_OverlayPortalElement`: it holds the regular child and the overlay child, whose
3222/// slot is its [`OverlayEntryLocation`].
3223struct RawOverlayPortalElement {
3224    element: ElementData,
3225    render_object_element: RenderObjectElementData,
3226    overlay_child: Option<AnyElement>,
3227    child: Option<AnyElement>,
3228}
3229
3230impl RawOverlayPortalElement {
3231    fn new(app: &mut App, widget: WidgetRef) -> Handle<RawOverlayPortalElement> {
3232        debug_assert!(downcast_widget::<RawOverlayPortal>(&*widget).is_some());
3233        app.create(RawOverlayPortalElement {
3234            element: ElementData::new(widget),
3235            render_object_element: RenderObjectElementData::default(),
3236            overlay_child: None,
3237            child: None,
3238        })
3239        .into_tree_node(app)
3240    }
3241
3242    fn update_children(self: Handle<Self>, app: &mut App) {
3243        let this = self.as_element();
3244        let (child_widget, overlay_child_widget, overlay_location) = {
3245            let widget = Self::widget_of(this.widget(app));
3246            (
3247                widget.child.clone(),
3248                widget.overlay_child.clone(),
3249                widget.overlay_location.handle(),
3250            )
3251        };
3252        let child = app.get(self).child;
3253        let child = this.update_child(app, child, child_widget, None);
3254        app.get_mut(self).child = child;
3255        let slot = overlay_location.map(|location| location.slot(app));
3256        let overlay_child = app.get(self).overlay_child;
3257        let overlay_child = this.update_child(app, overlay_child, overlay_child_widget, slot);
3258        app.get_mut(self).overlay_child = overlay_child;
3259    }
3260
3261    fn surrogate(self: Handle<Self>, app: &App) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
3262        self.typed_render_object(app)
3263    }
3264}
3265
3266impl RenderObjectElementWidget for RawOverlayPortalElement {
3267    type Widget = RawOverlayPortal;
3268
3269    fn widget_of(widget: &WidgetRef) -> &RawOverlayPortal {
3270        downcast_widget::<RawOverlayPortal>(&**widget)
3271            .expect("a RawOverlayPortalElement holds a RawOverlayPortal")
3272    }
3273}
3274
3275impl RenderObjectElement for RawOverlayPortalElement {
3276    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
3277        &app.get(self).render_object_element
3278    }
3279
3280    fn render_object_element_data_mut(
3281        self: Handle<Self>,
3282        app: &mut App,
3283    ) -> &mut RenderObjectElementData {
3284        &mut app.get_mut(self).render_object_element
3285    }
3286}
3287
3288impl Element for RawOverlayPortalElement {
3289    crate::element_accessors!();
3290
3291    const IS_RENDER_OBJECT_ELEMENT: bool = true;
3292
3293    fn debug_fill_properties(
3294        self: Handle<Self>,
3295        app: &App,
3296        properties: &mut DiagnosticPropertiesBuilder,
3297    ) {
3298        let state = app.get(self);
3299        properties.add(
3300            DiagnosticsProperty::<String>::new(
3301                "child",
3302                state.child.map(|child| child.to_string_short(app)),
3303            )
3304            .default_value(None),
3305        );
3306        properties.add(
3307            DiagnosticsProperty::<String>::new(
3308                "overlayChild",
3309                state.overlay_child.map(|child| child.to_string_short(app)),
3310            )
3311            .default_value(None),
3312        );
3313        properties.add(
3314            DiagnosticsProperty::<String>::new(
3315                "overlayLocation",
3316                state
3317                    .overlay_child
3318                    .and_then(|child| child.slot(app))
3319                    .map(|slot| format!("{slot:?}")),
3320            )
3321            .default_value(None),
3322        );
3323    }
3324
3325    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
3326        self.render_object_element_data(app).render_object()
3327    }
3328
3329    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
3330        None
3331    }
3332
3333    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
3334        self.render_object_element_data(app).debug_doing_build()
3335    }
3336
3337    fn mount(
3338        self: Handle<Self>,
3339        app: &mut App,
3340        parent: Option<AnyElement>,
3341        new_slot: Option<Slot>,
3342    ) {
3343        RenderObjectElement::mount(self, app, parent, new_slot);
3344        self.update_children(app);
3345    }
3346
3347    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
3348        RenderObjectElement::update(self, app, new_widget);
3349        self.update_children(app);
3350    }
3351
3352    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
3353        // The overlay child element does not have a key because the DeferredLayout widget does
3354        // not take a Key, so only the regular child can be taken during global key
3355        // reparenting.
3356        debug_assert!(app.get(self).child == Some(child));
3357        app.get_mut(self).child = None;
3358    }
3359
3360    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
3361        let state = app.get(self);
3362        let (child, overlay_child) = (state.child, state.overlay_child);
3363        if let Some(child) = child {
3364            visitor(child);
3365        }
3366        if let Some(overlay_child) = overlay_child {
3367            visitor(overlay_child);
3368        }
3369    }
3370
3371    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
3372        RenderObjectElement::perform_rebuild(self, app);
3373    }
3374
3375    fn deactivate(self: Handle<Self>, app: &mut App) {
3376        RenderObjectElement::deactivate(self, app);
3377    }
3378
3379    fn unmount(self: Handle<Self>, app: &mut App) {
3380        RenderObjectElement::unmount(self, app);
3381    }
3382
3383    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
3384        RenderObjectElement::update_parent_data(self, app, parent_data_element);
3385    }
3386
3387    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
3388        RenderObjectElement::update_slot(self, app, new_slot);
3389    }
3390
3391    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
3392        RenderObjectElement::attach_render_object(self, app, new_slot);
3393    }
3394
3395    fn detach_render_object(self: Handle<Self>, app: &mut App) {
3396        RenderObjectElement::detach_render_object(self, app);
3397    }
3398
3399    fn insert_render_object_child(
3400        self: Handle<Self>,
3401        app: &mut App,
3402        child: AnyRenderObject,
3403        slot: Option<Slot>,
3404    ) {
3405        debug_assert!(child.parent(app).is_none());
3406        let surrogate = self.surrogate(app);
3407        match slot.as_ref().and_then(OverlayEntryLocation::from_slot) {
3408            Some(location) => {
3409                let deferred = child
3410                    .downcast::<RenderDeferredLayoutBox>(app)
3411                    .expect("an overlay child is a DeferredLayout");
3412                // The deferred child is assigned in DeferredLayout's create_render_object.
3413                debug_assert!(surrogate.get(app).deferred_layout_child == Some(deferred));
3414                location.add_child(app, deferred);
3415            }
3416            None => surrogate.set_child(app, Some(child.as_box().expect("a box child"))),
3417        }
3418    }
3419
3420    // The DeferredLayout widget does not have a key so there will be no reparenting between
3421    // the overlay child and the child, hence the non-null slots.
3422    fn move_render_object_child(
3423        self: Handle<Self>,
3424        app: &mut App,
3425        child: AnyRenderObject,
3426        old_slot: Option<Slot>,
3427        new_slot: Option<Slot>,
3428    ) {
3429        let old_location = old_slot
3430            .as_ref()
3431            .and_then(OverlayEntryLocation::from_slot)
3432            .expect("an overlay child moves between locations");
3433        let new_location = new_slot
3434            .as_ref()
3435            .and_then(OverlayEntryLocation::from_slot)
3436            .expect("an overlay child moves between locations");
3437        debug_assert!(new_location.debug_is_location_valid(app));
3438        let deferred = child
3439            .downcast::<RenderDeferredLayoutBox>(app)
3440            .expect("an overlay child is a DeferredLayout");
3441        new_location.move_child(app, deferred, old_location);
3442    }
3443
3444    fn remove_render_object_child(
3445        self: Handle<Self>,
3446        app: &mut App,
3447        child: AnyRenderObject,
3448        slot: Option<Slot>,
3449    ) {
3450        let surrogate = self.surrogate(app);
3451        let Some(location) = slot.as_ref().and_then(OverlayEntryLocation::from_slot) else {
3452            surrogate.set_child(app, None);
3453            return;
3454        };
3455        let deferred = child
3456            .downcast::<RenderDeferredLayoutBox>(app)
3457            .expect("an overlay child is a DeferredLayout");
3458        debug_assert!(surrogate.get(app).deferred_layout_child == Some(deferred));
3459        location.remove_child(app, deferred);
3460        surrogate.get_mut(app).deferred_layout_child = None;
3461    }
3462}
3463
3464/// Dart's `_DeferredLayout`: the overlay child's own render object widget.
3465#[derive(Debug)]
3466struct DeferredLayout {
3467    // This widget must not be given a key: reparenting between the overlay child and the child
3468    // is not supported.
3469    child: WidgetRef,
3470}
3471
3472impl DeferredLayout {
3473    fn layout_parent(
3474        app: &App,
3475        context: BuildContext,
3476    ) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
3477        context
3478            .find_ancestor_render_object_of_type::<RenderLayoutSurrogateProxyBox>(app)
3479            .expect("a _DeferredLayout is built by an OverlayPortal")
3480    }
3481}
3482
3483impl RenderObjectWidget for DeferredLayout {
3484    type RenderObject = RenderDeferredLayoutBox;
3485
3486    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
3487        let parent = DeferredLayout::layout_parent(app, context);
3488        let render_object = RenderDeferredLayoutBox::new(app, parent);
3489        parent.get_mut(app).deferred_layout_child = Some(render_object);
3490        render_object.as_object()
3491    }
3492
3493    fn update_render_object(
3494        &self,
3495        app: &mut App,
3496        context: BuildContext,
3497        render_object: RenderHandle<RenderDeferredLayoutBox>,
3498    ) {
3499        debug_assert!(
3500            render_object.get(app).layout_surrogate == DeferredLayout::layout_parent(app, context)
3501        );
3502        debug_assert!(
3503            DeferredLayout::layout_parent(app, context)
3504                .get(app)
3505                .deferred_layout_child
3506                == Some(render_object)
3507        );
3508    }
3509}
3510
3511impl SingleChildRenderObjectWidget for DeferredLayout {
3512    fn child(&self) -> Option<&WidgetRef> {
3513        Some(&self.child)
3514    }
3515}
3516
3517// This render object must be a child of a [`RenderTheater`]. It guarantees that it only does
3518// layout after the sizes of the render objects from its `layout_surrogate` (which must be a
3519// descendant of this object's parent) through the parent RenderTheater are known. To this end:
3520//
3521// 1. It's a relayout boundary, and adding it to the RenderTheater as a child never dirties its
3522//    RenderTheater. Instead, it is always added to the PipelineOwner's dirty list when it
3523//    needs layout (even for the initial layout when it is first added to the tree).
3524//
3525// 2. Its layout is driven through `do_layout_from` such that `perform_layout` does not do
3526//    anything when it is called from the tree walk, preventing the parent RenderTheater from
3527//    laying out this subtree prematurely (but this object may still be resized). Instead,
3528//    `mark_needs_layout` is called from within `do_layout_from` to schedule a layout update for
3529//    this relayout boundary when needed.
3530//
3531// When invoked from `PipelineOwner::flush_layout`, this object behaves like an [`Overlay`] that
3532// has only one entry.
3533struct RenderDeferredLayoutBox {
3534    render_object: RenderObjectData,
3535    render_box: RenderBoxData,
3536    child: RenderObjectWithChildData<AnyRenderBox>,
3537    layout_surrogate: RenderHandle<RenderLayoutSurrogateProxyBox>,
3538    /// Whether this box's layout is currently being driven by the theater's or the layout
3539    /// surrogate's `perform_layout`.
3540    doing_layout_from_tree_walk: bool,
3541    debug_mutations_locked: bool,
3542}
3543
3544impl RenderDeferredLayoutBox {
3545    fn new(
3546        app: &mut App,
3547        layout_surrogate: RenderHandle<RenderLayoutSurrogateProxyBox>,
3548    ) -> RenderHandle<RenderDeferredLayoutBox> {
3549        RenderHandle::new_box(
3550            app,
3551            RenderDeferredLayoutBox {
3552                render_object: RenderObjectData::new(),
3553                render_box: RenderBoxData::new(),
3554                child: RenderObjectWithChildData::new(),
3555                layout_surrogate,
3556                doing_layout_from_tree_walk: false,
3557                debug_mutations_locked: false,
3558            },
3559        )
3560    }
3561
3562    fn do_layout_from(
3563        self: RenderHandle<Self>,
3564        app: &mut App,
3565        treewalk_parent: AnyRenderObject,
3566        constraints: BoxConstraints,
3567    ) {
3568        debug_assert!(!self.get(app).doing_layout_from_tree_walk);
3569        self.get_mut(app).doing_layout_from_tree_walk = true;
3570        self.as_box().layout(app, constraints, false);
3571        debug_assert!(self.get(app).doing_layout_from_tree_walk);
3572        self.get_mut(app).doing_layout_from_tree_walk = false;
3573        debug_assert!(!self.as_object().debug_needs_layout(app));
3574
3575        // Instead of laying out this subtree via tree walk, add it to the dirty list. This
3576        // ensures:
3577        //
3578        //  1. this node will be laid out by the PipelineOwner *after* the two nodes it depends
3579        //     on (the theater and the layout surrogate) are laid out, as it has a greater
3580        //     depth value than its dependencies.
3581        //
3582        //  2. when the deferred child's child starts to do layout, the nodes from the layout
3583        //     surrogate to the theater (exclusive) have finished doing layout, so the deferred
3584        //     child's child can read their sizes and (usually) compute the paint transform of
3585        //     the regular child within the Overlay.
3586        //
3587        // Invoking mark_needs_layout as a layout callback allows this node to be merged back
3588        // to the PipelineOwner's dirty list in the right order, if it's not already dirty,
3589        // such that this subtree does not get laid out twice.
3590        //
3591        // Flutter skips this when the subtree is clean and the constraints did not change;
3592        // `RenderObject`'s dirty flag is not readable outside `waft-rendering` (see
3593        // `PORTING.md`), so the subtree is always re-scheduled.
3594        treewalk_parent.invoke_layout_callback(app, |app| {
3595            RenderBox::mark_needs_layout(self, app);
3596        });
3597    }
3598}
3599
3600impl RenderObjectWithChildMixin for RenderDeferredLayoutBox {
3601    type ChildType = AnyRenderBox;
3602
3603    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3604        &self.get(app).child
3605    }
3606
3607    fn child_data_mut(
3608        self: RenderHandle<Self>,
3609        app: &mut App,
3610    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3611        &mut self.get_mut(app).child
3612    }
3613}
3614
3615impl RenderProxyBoxMixin for RenderDeferredLayoutBox {}
3616
3617impl RenderTheaterMixin for RenderDeferredLayoutBox {
3618    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater> {
3619        self.parent(app)
3620            .and_then(|parent| parent.downcast::<RenderTheater>(app))
3621            .expect("the parent of a deferred layout box is a RenderTheater")
3622    }
3623
3624    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
3625        TheaterChildren::single(self.child(app))
3626    }
3627
3628    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
3629        RenderTheaterMixin::children_in_paint_order(self, app)
3630    }
3631}
3632
3633impl RenderObject for RenderDeferredLayoutBox {
3634    waft_rendering::render_object_accessors!();
3635
3636    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
3637        true
3638    }
3639
3640    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3641        debug_assert!(!self.get(app).debug_mutations_locked);
3642        if self.get(app).doing_layout_from_tree_walk {
3643            return;
3644        }
3645        if cfg!(debug_assertions) {
3646            self.get_mut(app).debug_mutations_locked = true;
3647        }
3648        // This method is directly being invoked from `PipelineOwner::flush_layout`, or from
3649        // the layout surrogate's perform_layout.
3650        debug_assert!(self.parent(app).is_some());
3651        let Some(child) = self.child(app) else {
3652            return;
3653        };
3654        let constraints = self.constraints(app);
3655        debug_assert!(constraints.is_tight());
3656        self.layout_child(app, child, constraints);
3657        if cfg!(debug_assertions) {
3658            self.get_mut(app).debug_mutations_locked = false;
3659        }
3660    }
3661
3662    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
3663        // The layout surrogate can be adopted after this box enters the theater. Until then,
3664        // the surrogate has no owner and cannot redepth this child. Once the surrogate is
3665        // adopted, its own redepth_children will restore the depth invariant.
3666        let surrogate = self.get(app).layout_surrogate;
3667        if surrogate.as_object().attached(app) {
3668            surrogate.as_object().redepth_child(app, self.as_object());
3669        }
3670        if let Some(child) = self.child(app) {
3671            self.as_object().redepth_child(app, child.as_object());
3672        }
3673    }
3674
3675    fn visit_children(
3676        self: RenderHandle<Self>,
3677        app: &App,
3678        visitor: &mut dyn FnMut(AnyRenderObject),
3679    ) {
3680        if let Some(child) = self.child(app) {
3681            visitor(child.as_object());
3682        }
3683    }
3684
3685    fn paint(
3686        self: RenderHandle<Self>,
3687        app: &mut App,
3688        context: &mut PaintingContext,
3689        offset: Offset,
3690    ) {
3691        RenderTheaterMixin::paint(self, app, context, offset);
3692    }
3693}
3694
3695impl RenderBox for RenderDeferredLayoutBox {
3696    waft_rendering::render_box_accessors!();
3697
3698    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
3699        let size = self.constraints(app).biggest();
3700        self.set_size(app, size);
3701    }
3702
3703    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
3704        RenderTheaterMixin::setup_parent_data(self, app, child);
3705    }
3706
3707    // Flutter's override translates by the child's parent-data offset, which is what
3708    // `RenderBox::apply_paint_transform` already does; `RenderProxyBoxMixin`'s no-op one is
3709    // not used here.
3710
3711    fn hit_test_children(
3712        self: RenderHandle<Self>,
3713        app: &mut App,
3714        result: &mut BoxHitTestResult<'_>,
3715        position: Offset,
3716    ) -> bool {
3717        RenderTheaterMixin::hit_test_children(self, app, result, position)
3718    }
3719
3720    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3721        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
3722    }
3723
3724    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3725        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
3726    }
3727
3728    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3729        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
3730    }
3731
3732    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3733        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
3734    }
3735
3736    fn compute_dry_layout(
3737        self: RenderHandle<Self>,
3738        app: &mut App,
3739        constraints: BoxConstraints,
3740    ) -> Size {
3741        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
3742    }
3743}
3744
3745// A proxy box that makes sure its deferred layout child has a greater depth than itself.
3746//
3747// This render object also conditionally attaches and detaches the associated
3748// RenderDeferredLayoutBox when itself attaches and detaches from its PipelineOwner. This
3749// guarantees that the deferred box's attached status is always kept in sync with both the
3750// surrogate and its parent theater.
3751struct RenderLayoutSurrogateProxyBox {
3752    render_object: RenderObjectData,
3753    render_box: RenderBoxData,
3754    child: RenderObjectWithChildData<AnyRenderBox>,
3755    // This variable is set as soon as the DeferredLayout widget creates it, and it is only set
3756    // to None when the DeferredLayout widget is being removed from the tree.
3757    deferred_layout_child: Option<RenderHandle<RenderDeferredLayoutBox>>,
3758    overlay_location: Option<Ref<OverlayEntryLocation>>,
3759    debug_is_first_attach: bool,
3760    did_detach_deferred_child: bool,
3761}
3762
3763impl RenderLayoutSurrogateProxyBox {
3764    fn new(
3765        app: &mut App,
3766        overlay_location: Option<Ref<OverlayEntryLocation>>,
3767    ) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
3768        RenderHandle::new_box(
3769            app,
3770            RenderLayoutSurrogateProxyBox {
3771                render_object: RenderObjectData::new(),
3772                render_box: RenderBoxData::new(),
3773                child: RenderObjectWithChildData::new(),
3774                deferred_layout_child: None,
3775                overlay_location,
3776                debug_is_first_attach: true,
3777                did_detach_deferred_child: false,
3778            },
3779        )
3780    }
3781}
3782
3783impl RenderObjectWithChildMixin for RenderLayoutSurrogateProxyBox {
3784    type ChildType = AnyRenderBox;
3785
3786    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3787        &self.get(app).child
3788    }
3789
3790    fn child_data_mut(
3791        self: RenderHandle<Self>,
3792        app: &mut App,
3793    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3794        &mut self.get_mut(app).child
3795    }
3796}
3797
3798impl RenderProxyBoxMixin for RenderLayoutSurrogateProxyBox {}
3799
3800impl RenderObject for RenderLayoutSurrogateProxyBox {
3801    waft_rendering::render_object_accessors!();
3802
3803    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
3804        if let Some(child) = self.child(app) {
3805            child.as_object().attach(app, owner);
3806        }
3807        // If did_attach runs after did_detach_deferred_child is set to true then it is always
3808        // safe to put the deferred child back because the theater must be an ancestor of both
3809        // render objects.
3810        if self.get(app).did_detach_deferred_child {
3811            self.get_mut(app).did_detach_deferred_child = false;
3812            let deferred = self
3813                .get(app)
3814                .deferred_layout_child
3815                .expect("a detached deferred child was recorded");
3816            debug_assert!(!self.get(app).debug_is_first_attach);
3817            let location = self
3818                .get(app)
3819                .overlay_location
3820                .handle()
3821                .expect("a deferred child has a location");
3822            location.reattach_from_layout_surrogate(app, deferred);
3823        }
3824        if cfg!(debug_assertions) {
3825            self.get_mut(app).debug_is_first_attach = false;
3826        }
3827    }
3828
3829    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
3830        // Detaches the deferred child if this node is being detached, but only if the theater
3831        // isn't already detached (so the deferred child will be detached by the theater).
3832        if let Some(deferred) = self.get(app).deferred_layout_child
3833            && deferred.theater(app).as_object().attached(app)
3834        {
3835            let location = self
3836                .get(app)
3837                .overlay_location
3838                .handle()
3839                .expect("a deferred child has a location");
3840            location.detach_from_layout_surrogate(app, deferred);
3841            self.get_mut(app).did_detach_deferred_child = true;
3842        }
3843        if let Some(child) = self.child(app) {
3844            child.as_object().detach(app);
3845        }
3846    }
3847
3848    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
3849        if let Some(child) = self.child(app) {
3850            self.as_object().redepth_child(app, child.as_object());
3851        }
3852        // If the child is not attached yet, this method will be invoked by the child's real
3853        // parent (the theater) when it becomes attached.
3854        if let Some(deferred) = self.get(app).deferred_layout_child
3855            && deferred.as_object().attached(app)
3856        {
3857            self.as_object().redepth_child(app, deferred.as_object());
3858        }
3859    }
3860
3861    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3862        RenderProxyBoxMixin::perform_layout(self, app);
3863        let Some(deferred_child) = self.get(app).deferred_layout_child else {
3864            return;
3865        };
3866        // To make sure all ancestors' perform_layout calls have returned when the deferred
3867        // child does layout, the deferred child needs to be put in the dirty list if it is
3868        // dirty, and the deferred child subtree made unreachable via the layout tree walk.
3869        let theater = deferred_child.theater(app);
3870        // If the theater is laying out the size-determining child, its size is not available
3871        // yet. Since the theater always lays out the size-determining child first and the
3872        // deferred child can never be size-determining, this method does not have to do
3873        // anything: the theater will update the constraints of the deferred child and resize
3874        // it or put it in the dirty list if needed.
3875        if !theater.get(app).laying_out_size_determining_child {
3876            let theater_constraints = theater.constraints(app);
3877            let box_size = if theater_constraints.biggest().is_finite() {
3878                theater_constraints.biggest()
3879            } else {
3880                theater.size(app)
3881            };
3882            deferred_child.do_layout_from(app, self.as_object(), BoxConstraints::tight(box_size));
3883        }
3884    }
3885
3886    fn visit_children(
3887        self: RenderHandle<Self>,
3888        app: &App,
3889        visitor: &mut dyn FnMut(AnyRenderObject),
3890    ) {
3891        if let Some(child) = self.child(app) {
3892            visitor(child.as_object());
3893        }
3894    }
3895
3896    fn paint(
3897        self: RenderHandle<Self>,
3898        app: &mut App,
3899        context: &mut PaintingContext,
3900        offset: Offset,
3901    ) {
3902        RenderProxyBoxMixin::paint(self, app, context, offset);
3903    }
3904}
3905
3906impl RenderBox for RenderLayoutSurrogateProxyBox {
3907    waft_rendering::render_box_accessors!();
3908
3909    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
3910        RenderProxyBoxMixin::setup_parent_data(self, app, child);
3911    }
3912
3913    fn apply_paint_transform(
3914        self: RenderHandle<Self>,
3915        app: &App,
3916        child: AnyRenderObject,
3917        transform: &mut Matrix4,
3918    ) {
3919        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
3920    }
3921
3922    fn hit_test_children(
3923        self: RenderHandle<Self>,
3924        app: &mut App,
3925        result: &mut BoxHitTestResult<'_>,
3926        position: Offset,
3927    ) -> bool {
3928        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
3929    }
3930
3931    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3932        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
3933    }
3934
3935    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3936        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
3937    }
3938
3939    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3940        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
3941    }
3942
3943    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3944        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
3945    }
3946
3947    fn compute_dry_layout(
3948        self: RenderHandle<Self>,
3949        app: &mut App,
3950        constraints: BoxConstraints,
3951    ) -> Size {
3952        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
3953    }
3954}
3955
3956/// Dart's `_OverlayChildLayoutBuilder`: the widget
3957/// [`OverlayPortal::overlay_child_layout_builder`] builds as its overlay child.
3958///
3959/// Dart derives it from `AbstractLayoutBuilder<OverlayChildLayoutInfo>` and reuses
3960/// `layout_builder.dart`'s element; the crate's `LayoutBuilder` is not generic over the
3961/// layout information, so this is a concrete pair of its own (see `PORTING.md`).
3962struct OverlayChildLayoutBuilderWidget {
3963    builder: OverlayChildLayoutBuilder,
3964    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
3965    created: Option<CreationLocation>,
3966}
3967
3968impl OverlayChildLayoutBuilderWidget {
3969    /// The tree node: a render object widget with its own element, outside the `IntoWidget`
3970    /// kinds.
3971    #[cfg_attr(debug_assertions, track_caller)]
3972    fn into_widget(mut self) -> WidgetRef {
3973        self.created = Some(CreationLocation::of_caller());
3974        Rc::new(self)
3975    }
3976
3977    /// Whether the builder needs to be called again even if the layout information is the
3978    /// same.
3979    fn update_should_rebuild(&self, old_widget: &OverlayChildLayoutBuilderWidget) -> bool {
3980        let _ = old_widget;
3981        true
3982    }
3983}
3984
3985impl Debug for OverlayChildLayoutBuilderWidget {
3986    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3987        f.debug_struct("OverlayChildLayoutBuilder")
3988            .finish_non_exhaustive()
3989    }
3990}
3991
3992impl Widget for OverlayChildLayoutBuilderWidget {
3993    fn key(&self) -> Option<&KeyRef> {
3994        None
3995    }
3996
3997    fn creation_location(&self) -> Option<&'static Location<'static>> {
3998        self.created.and_then(CreationLocation::location)
3999    }
4000
4001    fn record_creation_location(&mut self, location: CreationLocation) {
4002        self.created = Some(location);
4003    }
4004
4005    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
4006        OverlayChildLayoutBuilderElement::new(app, this).as_element()
4007    }
4008
4009    fn as_any(&self) -> &dyn Any {
4010        self
4011    }
4012
4013    fn widget_type(&self) -> std::any::TypeId {
4014        std::any::TypeId::of::<OverlayChildLayoutBuilderWidget>()
4015    }
4016
4017    fn kind(&self) -> WidgetKind {
4018        WidgetKind::Other
4019    }
4020}
4021
4022impl RenderObjectWidget for OverlayChildLayoutBuilderWidget {
4023    type RenderObject = RenderOverlayChildLayoutBuilder;
4024
4025    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4026        RenderOverlayChildLayoutBuilder::new(app).as_object()
4027    }
4028
4029    // update_render_object is redundant with the logic in the element below.
4030    fn update_render_object(
4031        &self,
4032        _app: &mut App,
4033        _context: BuildContext,
4034        _render_object: RenderHandle<RenderOverlayChildLayoutBuilder>,
4035    ) {
4036    }
4037
4038    fn did_unmount_render_object(
4039        &self,
4040        app: &mut App,
4041        render_object: RenderHandle<RenderOverlayChildLayoutBuilder>,
4042    ) {
4043        // Flutter cancels the per-frame callback in the render object's `dispose`, which is
4044        // not an override point here.
4045        render_object.cancel_frame_callback(app);
4046    }
4047}
4048
4049/// The element of an [`OverlayChildLayoutBuilderWidget`]: it builds its child from within the
4050/// render object's layout, as `LayoutBuilderElement` does.
4051struct OverlayChildLayoutBuilderElement {
4052    element: ElementData,
4053    render_object_element: RenderObjectElementData,
4054    child: Option<AnyElement>,
4055    /// Dart's `late final _buildScope`, created right after the element so its
4056    /// `scheduleRebuild` can name it.
4057    build_scope: Option<Ref<BuildScope>>,
4058    deferred_callback_scheduled: bool,
4059    previous_layout_info: Option<OverlayChildLayoutInfo>,
4060    needs_build: bool,
4061}
4062
4063impl OverlayChildLayoutBuilderElement {
4064    fn new(app: &mut App, widget: WidgetRef) -> Handle<OverlayChildLayoutBuilderElement> {
4065        debug_assert!(downcast_widget::<OverlayChildLayoutBuilderWidget>(&*widget).is_some());
4066        let this = app
4067            .create(OverlayChildLayoutBuilderElement {
4068                element: ElementData::new(widget),
4069                render_object_element: RenderObjectElementData::default(),
4070                child: None,
4071                build_scope: None,
4072                deferred_callback_scheduled: false,
4073                previous_layout_info: None,
4074                needs_build: true,
4075            })
4076            .into_tree_node(app);
4077        let build_scope = BuildScope::new(
4078            app,
4079            Some(Listener::handle_method(this, Self::schedule_rebuild)),
4080        );
4081        app.get_mut(this).build_scope = Some(build_scope);
4082        this
4083    }
4084
4085    fn render_layout_builder(
4086        self: Handle<Self>,
4087        app: &App,
4088    ) -> RenderHandle<RenderOverlayChildLayoutBuilder> {
4089        self.typed_render_object(app)
4090    }
4091
4092    fn schedule_rebuild(self: Handle<Self>, app: &mut App) {
4093        if app.get(self).deferred_callback_scheduled {
4094            return;
4095        }
4096        let defer_mark_needs_layout = match SchedulerBinding::scheduler_phase(app) {
4097            SchedulerPhase::Idle | SchedulerPhase::PostFrameCallbacks => true,
4098            SchedulerPhase::TransientCallbacks
4099            | SchedulerPhase::MidFrameMicrotasks
4100            | SchedulerPhase::PersistentCallbacks => false,
4101        };
4102        if !defer_mark_needs_layout {
4103            self.render_layout_builder(app)
4104                .schedule_layout_callback(app);
4105            return;
4106        }
4107        app.get_mut(self).deferred_callback_scheduled = true;
4108        SchedulerBinding::schedule_frame_callback(
4109            app,
4110            FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
4111            View::maybe_id_of(app, self.as_element()),
4112            false,
4113            true,
4114        );
4115    }
4116
4117    fn frame_callback(self: Handle<Self>, app: &mut App) {
4118        app.get_mut(self).deferred_callback_scheduled = false;
4119        if self.as_element().mounted(app) {
4120            self.render_layout_builder(app)
4121                .schedule_layout_callback(app);
4122        }
4123    }
4124
4125    fn rebuild_with_constraints(self: Handle<Self>, app: &mut App) {
4126        let render_object = self.render_layout_builder(app);
4127        let layout_info = render_object.layout_info(app);
4128        let this = self.as_element();
4129        let needs_callback =
4130            app.get(self).needs_build || Some(layout_info) != app.get(self).previous_layout_info;
4131        let callback: Option<BuildScopeCallback> = needs_callback.then(|| {
4132            Box::new(move |app: &mut App| {
4133                debug_assert!(layout_info == render_object.layout_info(app));
4134                let builder = Rc::clone(&Self::widget_of(this.widget(app)).builder);
4135                let built = builder(app, this, layout_info);
4136                let child = app.get(self).child;
4137                let child = this.update_child(app, child, Some(built), None);
4138                debug_assert!(child.is_some());
4139                let state = app.get_mut(self);
4140                state.child = child;
4141                state.needs_build = false;
4142                state.previous_layout_info = Some(layout_info);
4143            }) as BuildScopeCallback
4144        });
4145        let owner = this.owner(app).expect("a laying-out element has an owner");
4146        owner.build_scope(app, this, callback);
4147    }
4148}
4149
4150impl RenderObjectElementWidget for OverlayChildLayoutBuilderElement {
4151    type Widget = OverlayChildLayoutBuilderWidget;
4152
4153    fn widget_of(widget: &WidgetRef) -> &OverlayChildLayoutBuilderWidget {
4154        downcast_widget::<OverlayChildLayoutBuilderWidget>(&**widget)
4155            .expect("an OverlayChildLayoutBuilderElement holds its widget")
4156    }
4157}
4158
4159impl RenderObjectElement for OverlayChildLayoutBuilderElement {
4160    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
4161        &app.get(self).render_object_element
4162    }
4163
4164    fn render_object_element_data_mut(
4165        self: Handle<Self>,
4166        app: &mut App,
4167    ) -> &mut RenderObjectElementData {
4168        &mut app.get_mut(self).render_object_element
4169    }
4170}
4171
4172impl Element for OverlayChildLayoutBuilderElement {
4173    crate::element_accessors!();
4174
4175    const IS_RENDER_OBJECT_ELEMENT: bool = true;
4176
4177    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
4178        self.render_object_element_data(app).render_object()
4179    }
4180
4181    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
4182        None
4183    }
4184
4185    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
4186        false
4187    }
4188
4189    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
4190        app.get(self)
4191            .build_scope
4192            .handle()
4193            .expect("created with the element")
4194    }
4195
4196    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
4197        if let Some(child) = app.get(self).child {
4198            visitor(child);
4199        }
4200    }
4201
4202    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
4203        debug_assert!(app.get(self).child == Some(child));
4204        app.get_mut(self).child = None;
4205    }
4206
4207    fn mount(
4208        self: Handle<Self>,
4209        app: &mut App,
4210        parent: Option<AnyElement>,
4211        new_slot: Option<Slot>,
4212    ) {
4213        RenderObjectElement::mount(self, app, parent, new_slot); // Creates the renderObject.
4214        let render_object = self.render_layout_builder(app);
4215        render_object.update_callback(
4216            app,
4217            Listener::handle_method(self, Self::rebuild_with_constraints),
4218        );
4219    }
4220
4221    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
4222        let old_widget = self.as_element().widget(app).clone();
4223        debug_assert!(!Rc::ptr_eq(&old_widget, &new_widget));
4224        RenderObjectElement::update(self, app, new_widget.clone());
4225        let render_object = self.render_layout_builder(app);
4226        render_object.update_callback(
4227            app,
4228            Listener::handle_method(self, Self::rebuild_with_constraints),
4229        );
4230        if Self::widget_of(&new_widget).update_should_rebuild(Self::widget_of(&old_widget)) {
4231            app.get_mut(self).needs_build = true;
4232            render_object.schedule_layout_callback(app);
4233        }
4234    }
4235
4236    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
4237        self.render_layout_builder(app)
4238            .schedule_layout_callback(app);
4239        app.get_mut(self).needs_build = true;
4240    }
4241
4242    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
4243        self.render_layout_builder(app)
4244            .schedule_layout_callback(app);
4245        app.get_mut(self).needs_build = true;
4246        RenderObjectElement::perform_rebuild(self, app);
4247    }
4248
4249    fn deactivate(self: Handle<Self>, app: &mut App) {
4250        RenderObjectElement::deactivate(self, app);
4251    }
4252
4253    fn unmount(self: Handle<Self>, app: &mut App) {
4254        let render_object = self.render_layout_builder(app);
4255        render_object.get_mut(app).callback = None;
4256        RenderObjectElement::unmount(self, app);
4257    }
4258
4259    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
4260        RenderObjectElement::update_parent_data(self, app, parent_data_element);
4261    }
4262
4263    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
4264        RenderObjectElement::update_slot(self, app, new_slot);
4265    }
4266
4267    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
4268        RenderObjectElement::attach_render_object(self, app, new_slot);
4269    }
4270
4271    fn detach_render_object(self: Handle<Self>, app: &mut App) {
4272        RenderObjectElement::detach_render_object(self, app);
4273    }
4274
4275    fn insert_render_object_child(
4276        self: Handle<Self>,
4277        app: &mut App,
4278        child: AnyRenderObject,
4279        slot: Option<Slot>,
4280    ) {
4281        debug_assert!(slot.is_none());
4282        let render_object = self.render_layout_builder(app);
4283        render_object.set_child(app, Some(child.as_box().expect("a box child")));
4284    }
4285
4286    fn move_render_object_child(
4287        self: Handle<Self>,
4288        _app: &mut App,
4289        _child: AnyRenderObject,
4290        _old_slot: Option<Slot>,
4291        _new_slot: Option<Slot>,
4292    ) {
4293        debug_assert!(false, "a layout builder has one child");
4294    }
4295
4296    fn remove_render_object_child(
4297        self: Handle<Self>,
4298        app: &mut App,
4299        child: AnyRenderObject,
4300        _slot: Option<Slot>,
4301    ) {
4302        let render_object = self.render_layout_builder(app);
4303        debug_assert!(render_object.child(app).map(|current| current.as_object()) == Some(child));
4304        render_object.set_child(app, None);
4305    }
4306}
4307
4308// Dart's `_RenderLayoutBuilder`: a render box that
4309//  - has the same size and paint transform as its parent and its theater; in other words the
4310//    three boxes describe the same rect on screen.
4311//  - is a relayout boundary, and gets marked dirty for relayout every frame (but only when a
4312//    frame is already scheduled, and mark_needs_layout does not schedule a new frame since it
4313//    is called in a transient callback).
4314//  - runs a layout callback in perform_layout.
4315//
4316// Additionally, like RenderDeferredLayoutBox, this box also uses the stack layout algorithm so
4317// developers can use the Positioned widget.
4318struct RenderOverlayChildLayoutBuilder {
4319    render_object: RenderObjectData,
4320    render_box: RenderBoxData,
4321    child: RenderObjectWithChildData<AnyRenderBox>,
4322    layout_callback: RenderObjectWithLayoutCallbackData,
4323    callback: Option<Listener>,
4324    // The size here is the child size of the regular child in its own parent's coordinates.
4325    layout_info: Option<OverlayChildLayoutInfo>,
4326    callback_id: Option<i64>,
4327}
4328
4329impl RenderOverlayChildLayoutBuilder {
4330    fn new(app: &mut App) -> RenderHandle<RenderOverlayChildLayoutBuilder> {
4331        RenderHandle::new_box(
4332            app,
4333            RenderOverlayChildLayoutBuilder {
4334                render_object: RenderObjectData::new(),
4335                render_box: RenderBoxData::new(),
4336                child: RenderObjectWithChildData::new(),
4337                layout_callback: RenderObjectWithLayoutCallbackData::default(),
4338                callback: None,
4339                layout_info: None,
4340                callback_id: None,
4341            },
4342        )
4343    }
4344
4345    /// The information the builder is given.
4346    fn layout_info(self: RenderHandle<Self>, app: &App) -> OverlayChildLayoutInfo {
4347        self.get(app)
4348            .layout_info
4349            .expect("the layout callback computes the layout information first")
4350    }
4351
4352    /// Change the layout callback and schedule it (Dart's
4353    /// `RenderAbstractLayoutBuilderMixin.updateCallback`).
4354    fn update_callback(self: RenderHandle<Self>, app: &mut App, value: Listener) {
4355        if self.get(app).callback.as_ref() == Some(&value) {
4356            return;
4357        }
4358        self.get_mut(app).callback = Some(value);
4359        self.schedule_layout_callback(app);
4360    }
4361
4362    fn compute_new_layout_info(self: RenderHandle<Self>, app: &App) -> OverlayChildLayoutInfo {
4363        let theater = self.theater(app);
4364        let parent = self
4365            .parent(app)
4366            .and_then(|parent| parent.downcast::<RenderDeferredLayoutBox>(app))
4367            .expect("the parent of an overlay child layout builder is a deferred layout box");
4368        let layout_surrogate = parent.get(app).layout_surrogate;
4369        debug_assert!(layout_surrogate.has_size(app));
4370        debug_assert!(
4371            layout_surrogate
4372                .child(app)
4373                .is_none_or(|child| child.size(app) == layout_surrogate.size(app))
4374        );
4375        debug_assert!(self.size(app) == theater.size(app));
4376        let overlay_portal_size = layout_surrogate.size(app);
4377        let paint_transform = layout_surrogate
4378            .as_object()
4379            .get_transform_to(app, Some(theater.as_object()));
4380        OverlayChildLayoutInfo {
4381            child_size: overlay_portal_size,
4382            child_paint_transform: paint_transform,
4383            overlay_size: self.size(app),
4384        }
4385    }
4386
4387    fn frame_callback(self: RenderHandle<Self>, app: &mut App) {
4388        self.get_mut(app).callback_id = None;
4389        RenderBox::mark_needs_layout(self, app);
4390    }
4391
4392    fn cancel_frame_callback(self: RenderHandle<Self>, app: &mut App) {
4393        if let Some(callback_id) = self.get_mut(app).callback_id.take() {
4394            SchedulerBinding::cancel_frame_callback_with_id(app, callback_id);
4395        }
4396    }
4397}
4398
4399impl RenderObjectWithChildMixin for RenderOverlayChildLayoutBuilder {
4400    type ChildType = AnyRenderBox;
4401
4402    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
4403        &self.get(app).child
4404    }
4405
4406    fn child_data_mut(
4407        self: RenderHandle<Self>,
4408        app: &mut App,
4409    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
4410        &mut self.get_mut(app).child
4411    }
4412}
4413
4414impl RenderProxyBoxMixin for RenderOverlayChildLayoutBuilder {}
4415
4416impl RenderObjectWithLayoutCallbackMixin for RenderOverlayChildLayoutBuilder {
4417    fn layout_callback_data(
4418        self: RenderHandle<Self>,
4419        app: &App,
4420    ) -> &RenderObjectWithLayoutCallbackData {
4421        &self.get(app).layout_callback
4422    }
4423
4424    fn layout_callback_data_mut(
4425        self: RenderHandle<Self>,
4426        app: &mut App,
4427    ) -> &mut RenderObjectWithLayoutCallbackData {
4428        &mut self.get_mut(app).layout_callback
4429    }
4430
4431    fn layout_callback(self: RenderHandle<Self>, app: &mut App) {
4432        let layout_info = self.compute_new_layout_info(app);
4433        self.get_mut(app).layout_info = Some(layout_info);
4434        let callback = self
4435            .get(app)
4436            .callback
4437            .clone()
4438            .expect("a callback is set before layout");
4439        callback.call(app);
4440    }
4441}
4442
4443impl RenderTheaterMixin for RenderOverlayChildLayoutBuilder {
4444    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater> {
4445        self.parent(app)
4446            .and_then(|parent| parent.downcast::<RenderDeferredLayoutBox>(app))
4447            .expect("the parent of an overlay child layout builder is a deferred layout box")
4448            .theater(app)
4449    }
4450
4451    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
4452        TheaterChildren::single(self.child(app))
4453    }
4454
4455    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
4456        RenderTheaterMixin::children_in_paint_order(self, app)
4457    }
4458}
4459
4460impl RenderObject for RenderOverlayChildLayoutBuilder {
4461    waft_rendering::render_object_accessors!();
4462
4463    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
4464        true
4465    }
4466
4467    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4468        self.run_layout_callback(app);
4469        if let Some(child) = self.child(app) {
4470            let constraints = self.constraints(app);
4471            self.layout_child(app, child, constraints);
4472        }
4473        debug_assert!(self.get(app).callback_id.is_none());
4474        if self.get(app).callback_id.is_none() {
4475            let callback_id = SchedulerBinding::schedule_frame_callback(
4476                app,
4477                FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
4478                None,
4479                false,
4480                false,
4481            );
4482            self.get_mut(app).callback_id = Some(callback_id);
4483        }
4484    }
4485
4486    fn visit_children(
4487        self: RenderHandle<Self>,
4488        app: &App,
4489        visitor: &mut dyn FnMut(AnyRenderObject),
4490    ) {
4491        if let Some(child) = self.child(app) {
4492            visitor(child.as_object());
4493        }
4494    }
4495
4496    fn paint(
4497        self: RenderHandle<Self>,
4498        app: &mut App,
4499        context: &mut PaintingContext,
4500        offset: Offset,
4501    ) {
4502        RenderTheaterMixin::paint(self, app, context, offset);
4503    }
4504}
4505
4506impl RenderBox for RenderOverlayChildLayoutBuilder {
4507    waft_rendering::render_box_accessors!();
4508
4509    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
4510        let size = self.constraints(app).biggest();
4511        self.set_size(app, size);
4512    }
4513
4514    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
4515        RenderTheaterMixin::setup_parent_data(self, app, child);
4516    }
4517
4518    fn hit_test_children(
4519        self: RenderHandle<Self>,
4520        app: &mut App,
4521        result: &mut BoxHitTestResult<'_>,
4522        position: Offset,
4523    ) -> bool {
4524        RenderTheaterMixin::hit_test_children(self, app, result, position)
4525    }
4526}
4527
4528#[cfg(test)]
4529mod tests {
4530    use super::*;
4531    use crate::test_harness::Harness;
4532    use crate::widgets::basic::SizedBox;
4533    use crate::widgets::media_query::MediaQueryData;
4534    use waft_foundation::{AppCell, DiagnosticLevel};
4535
4536    fn test_entry(app: &mut App) -> Ref<OverlayEntry> {
4537        OverlayEntry::new(
4538            app,
4539            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
4540            false,
4541            false,
4542            false,
4543        )
4544    }
4545
4546    fn mount_overlay(app: &mut App, entries: Vec<Ref<OverlayEntry>>) -> Harness {
4547        let tree = MediaQuery::new(
4548            MediaQueryData::new(),
4549            Directionality::new(TextDirection::Ltr, Overlay::new().initial_entries(entries)),
4550        )
4551        .into_widget();
4552        let harness = Harness::mount(app, tree);
4553        harness.pump(app);
4554        harness
4555    }
4556
4557    fn theater_of(harness: &Harness, app: &App) -> RenderHandle<RenderTheater> {
4558        harness
4559            .render_root(app)
4560            .child(app)
4561            .expect("the overlay's render object")
4562            .as_object()
4563            .downcast::<RenderTheater>(app)
4564            .expect("a RenderTheater")
4565    }
4566
4567    fn entry_of(app: &App, child: AnyRenderBox) -> Handle<OverlayEntry> {
4568        child
4569            .as_object()
4570            .parent_data_of::<TheaterParentData>(app)
4571            .overlay_entry
4572            .handle()
4573            .expect("a child built by an entry")
4574    }
4575
4576    fn entries_in_render_order(
4577        app: &App,
4578        theater: RenderHandle<RenderTheater>,
4579    ) -> Vec<Handle<OverlayEntry>> {
4580        let mut order = Vec::new();
4581        let mut child = theater.first_child(app);
4582        while let Some(current) = child {
4583            order.push(entry_of(app, current));
4584            child = theater.child_after(app, current);
4585        }
4586        order
4587    }
4588
4589    #[test]
4590    fn overlay_entries_are_inserted_rearranged_and_removed_in_order() {
4591        let cell = AppCell::new();
4592        let mut app = cell.borrow_mut();
4593        let (first, second) = (test_entry(&mut app), test_entry(&mut app));
4594        let harness = mount_overlay(&mut app, vec![first.clone(), second.clone()]);
4595        let theater = theater_of(&harness, &app);
4596        assert_eq!(
4597            entries_in_render_order(&app, theater),
4598            vec![first.handle(), second.handle()]
4599        );
4600
4601        let overlay = app
4602            .get(&first)
4603            .overlay
4604            .expect("inserted by initial_entries");
4605        let third = test_entry(&mut app);
4606        overlay.insert(&mut app, third.clone(), Some(first.handle()), None);
4607        harness.pump(&mut app);
4608        assert_eq!(
4609            entries_in_render_order(&app, theater),
4610            vec![third.handle(), first.handle(), second.handle()]
4611        );
4612
4613        let fourth = test_entry(&mut app);
4614        overlay.insert_all(&mut app, vec![fourth.clone()], None, None);
4615        harness.pump(&mut app);
4616        assert_eq!(
4617            entries_in_render_order(&app, theater),
4618            vec![
4619                third.handle(),
4620                first.handle(),
4621                second.handle(),
4622                fourth.handle()
4623            ]
4624        );
4625
4626        // `first` and `second` move to the bottom; the entries not mentioned stay on top.
4627        overlay.rearrange(&mut app, vec![second.clone(), first.clone()], None, None);
4628        harness.pump(&mut app);
4629        assert_eq!(
4630            entries_in_render_order(&app, theater),
4631            vec![
4632                second.handle(),
4633                first.handle(),
4634                third.handle(),
4635                fourth.handle()
4636            ]
4637        );
4638
4639        second.remove(&mut app);
4640        second.dispose(&mut app);
4641        harness.pump(&mut app);
4642        assert_eq!(
4643            entries_in_render_order(&app, theater),
4644            vec![first.handle(), third.handle(), fourth.handle()]
4645        );
4646    }
4647
4648    #[test]
4649    fn an_opaque_entry_takes_the_entries_below_it_offstage() {
4650        let cell = AppCell::new();
4651        let mut app = cell.borrow_mut();
4652        let bottom = OverlayEntry::new(
4653            &mut app,
4654            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
4655            false,
4656            true,
4657            false,
4658        );
4659        let top = OverlayEntry::new(
4660            &mut app,
4661            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
4662            true,
4663            false,
4664            false,
4665        );
4666        let harness = mount_overlay(&mut app, vec![bottom.clone(), top.clone()]);
4667        let theater = theater_of(&harness, &app);
4668
4669        // `bottom` is kept in the tree by maintain_state, but skipped when painting.
4670        assert_eq!(theater.child_count(&app), 2);
4671        assert_eq!(theater.skip_count(&app), 1);
4672        let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
4673        assert_eq!(painted.len(), 1);
4674        assert_eq!(entry_of(&app, painted[0]), top);
4675
4676        // Without maintain_state an offstage entry is not built at all.
4677        bottom.set_maintain_state(&mut app, false);
4678        harness.pump(&mut app);
4679        assert_eq!(theater.child_count(&app), 1);
4680        assert_eq!(theater.skip_count(&app), 0);
4681        assert_eq!(entries_in_render_order(&app, theater), vec![top.handle()]);
4682
4683        // Dropping the opacity brings it back onstage.
4684        top.set_opaque(&mut app, false);
4685        harness.pump(&mut app);
4686        assert_eq!(theater.skip_count(&app), 0);
4687        assert_eq!(
4688            RenderTheaterMixin::children_in_paint_order(theater, &app)
4689                .collect(&app)
4690                .len(),
4691            2
4692        );
4693    }
4694
4695    #[test]
4696    fn an_overlay_portal_shows_and_hides_its_overlay_child_in_the_overlay() {
4697        let cell = AppCell::new();
4698        let mut app = cell.borrow_mut();
4699        let controller = OverlayPortalController::new(&mut app, None);
4700        let portal_controller = controller.clone();
4701        let entry = OverlayEntry::new(
4702            &mut app,
4703            Rc::new(move |_app: &mut App, _context| {
4704                OverlayPortal::new(portal_controller.clone(), |_app: &mut App, _context| {
4705                    SizedBox::square(Some(40.0)).into_widget()
4706                })
4707                .child(SizedBox::square(Some(10.0)))
4708                .into_widget()
4709            }),
4710            false,
4711            false,
4712            false,
4713        );
4714        let harness = mount_overlay(&mut app, vec![entry.clone()]);
4715        let theater = theater_of(&harness, &app);
4716        assert!(!controller.is_showing(&app));
4717        assert_eq!(
4718            RenderTheaterMixin::children_in_paint_order(theater, &app)
4719                .collect(&app)
4720                .len(),
4721            1
4722        );
4723
4724        controller.show(&mut app);
4725        assert!(controller.is_showing(&app));
4726        harness.pump(&mut app);
4727        let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
4728        assert_eq!(painted.len(), 2);
4729        // The overlay child is a render child of the theater, painted above the entry.
4730        let deferred = painted[1]
4731            .as_object()
4732            .downcast::<RenderDeferredLayoutBox>(&app)
4733            .expect("the overlay child");
4734        assert_eq!(deferred.parent(&app), Some(theater.as_object()));
4735        assert_eq!(deferred.size(&app), theater.size(&app));
4736        assert_eq!(
4737            deferred.child(&app).expect("built").size(&app),
4738            theater.size(&app)
4739        );
4740        // The theater's child model still holds one entry child.
4741        assert_eq!(theater.child_count(&app), 1);
4742
4743        // The overlay child is named after its entry and its position in that entry's paint
4744        // order, as Dart's `_RenderTheater.debugDescribeChildren` names it.
4745        let dump = theater
4746            .as_object()
4747            .to_string_deep_with(&app, DiagnosticLevel::Info);
4748        assert!(dump.contains("onstage 1 - 1:"), "{dump}");
4749
4750        // Resume the lazy generator after entry layout removes its portal.
4751        let mut children = theater.children_in_paint_order(&app);
4752        assert_eq!(children.next(&app), Some(painted[0]));
4753        controller.toggle(&mut app);
4754        assert!(!controller.is_showing(&app));
4755        harness.pump(&mut app);
4756        assert_eq!(children.next(&app), None);
4757        assert_eq!(
4758            RenderTheaterMixin::children_in_paint_order(theater, &app)
4759                .collect(&app)
4760                .len(),
4761            1
4762        );
4763
4764        controller.toggle(&mut app);
4765        assert!(controller.is_showing(&app));
4766        harness.pump(&mut app);
4767        assert_eq!(
4768            RenderTheaterMixin::children_in_paint_order(theater, &app)
4769                .collect(&app)
4770                .len(),
4771            2
4772        );
4773
4774        controller.hide(&mut app);
4775        harness.pump(&mut app);
4776        assert_eq!(
4777            RenderTheaterMixin::children_in_paint_order(theater, &app)
4778                .collect(&app)
4779                .len(),
4780            1
4781        );
4782    }
4783
4784    #[test]
4785    fn overlay_layout_builder_resizes_without_requesting_child_dry_layout() {
4786        use crate::widgets::basic::Positioned;
4787        use std::cell::Cell;
4788
4789        let cell = AppCell::new();
4790        let mut app = cell.borrow_mut();
4791        let controller = OverlayPortalController::new(&mut app, None);
4792        let observed = Rc::new(Cell::new(None::<OverlayChildLayoutInfo>));
4793        let output = observed.clone();
4794        let portal_controller = controller.clone();
4795        let entry = OverlayEntry::new(
4796            &mut app,
4797            Rc::new(move |_, _| {
4798                let output = output.clone();
4799                Positioned::new(
4800                    OverlayPortal::overlay_child_layout_builder(
4801                        portal_controller.clone(),
4802                        move |_, _, info| {
4803                            output.set(Some(info));
4804                            Positioned::new(SizedBox::expand())
4805                                .left(0.0)
4806                                .top(0.0)
4807                                .width(40.0)
4808                                .height(20.0)
4809                                .into_widget()
4810                        },
4811                    )
4812                    .child(SizedBox::expand()),
4813                )
4814                .left(30.0)
4815                .top(40.0)
4816                .width(80.0)
4817                .height(60.0)
4818                .into_widget()
4819            }),
4820            false,
4821            false,
4822            false,
4823        );
4824        let harness = mount_overlay(&mut app, vec![entry.clone()]);
4825        let theater = theater_of(&harness, &app);
4826        for _ in 0..2 {
4827            controller.show(&mut app);
4828            harness.pump(&mut app);
4829            let info = observed.get().expect("the overlay built after layout");
4830            assert_eq!(info.child_size(), Size::new(80.0, 60.0));
4831            assert_eq!(info.overlay_size(), theater.size(&app));
4832            assert_eq!(
4833                waft_painting::transform_point(&info.child_paint_transform(), Offset::ZERO),
4834                Offset::new(30.0, 40.0),
4835            );
4836            let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
4837            let deferred = painted[1]
4838                .as_object()
4839                .downcast::<RenderDeferredLayoutBox>(&app)
4840                .unwrap();
4841            let builder = deferred.child(&app).unwrap();
4842            assert_eq!(deferred.size(&app), theater.size(&app));
4843            assert_eq!(builder.size(&app), theater.size(&app));
4844            let builder = builder
4845                .as_object()
4846                .downcast::<RenderOverlayChildLayoutBuilder>(&app)
4847                .unwrap();
4848            assert_eq!(
4849                builder.child(&app).unwrap().size(&app),
4850                Size::new(40.0, 20.0)
4851            );
4852            controller.hide(&mut app);
4853            harness.pump(&mut app);
4854        }
4855    }
4856
4857    /// `overlay_test.dart`'s "OverflowEntries context contains Overlay": the theater names its
4858    /// onstage children and says when no child is offstage.
4859    #[test]
4860    fn a_theater_dump_names_onstage_children_and_says_when_none_are_offstage() {
4861        let cell = AppCell::new();
4862        let mut app = cell.borrow_mut();
4863        let first = test_entry(&mut app);
4864        let second = test_entry(&mut app);
4865        let harness = mount_overlay(&mut app, vec![first, second]);
4866        let theater = theater_of(&harness, &app);
4867
4868        let dump = theater
4869            .as_object()
4870            .to_string_deep_with(&app, DiagnosticLevel::Info);
4871        assert!(dump.contains("skipCount: 0"), "{dump}");
4872        assert!(dump.contains("textDirection: ltr"), "{dump}");
4873        assert!(
4874            dump.lines()
4875                .any(|line| line.contains("onstage 1: RenderConstrainedBox#")),
4876            "{dump}"
4877        );
4878        assert!(
4879            dump.lines()
4880                .any(|line| line.contains("onstage 2: RenderConstrainedBox#")),
4881            "{dump}"
4882        );
4883        assert!(dump.contains("╌no offstage children"), "{dump}");
4884    }
4885
4886    /// `overlay_test.dart`'s "Offstage overlay": children below the first onstage child are
4887    /// named offstage and marked with the offstage style.
4888    #[test]
4889    fn a_theater_dump_names_offstage_children_and_marks_them_offstage() {
4890        let cell = AppCell::new();
4891        let mut app = cell.borrow_mut();
4892        let entry = |app: &mut App| {
4893            OverlayEntry::new(
4894                app,
4895                Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
4896                true,
4897                true,
4898                false,
4899            )
4900        };
4901        let first = entry(&mut app);
4902        let second = entry(&mut app);
4903        let third = entry(&mut app);
4904        let harness = mount_overlay(&mut app, vec![first, second, third]);
4905        let theater = theater_of(&harness, &app);
4906
4907        let dump = theater
4908            .as_object()
4909            .to_string_deep_with(&app, DiagnosticLevel::Info);
4910        assert!(dump.contains("skipCount: 2"), "{dump}");
4911        assert!(
4912            dump.lines()
4913                .any(|line| line.contains("onstage 1: RenderConstrainedBox#")),
4914            "{dump}"
4915        );
4916        assert!(
4917            dump.lines()
4918                .any(|line| line.contains("offstage 1: RenderConstrainedBox#")),
4919            "{dump}"
4920        );
4921        assert!(
4922            dump.lines()
4923                .any(|line| line.contains("offstage 2: RenderConstrainedBox#")),
4924            "{dump}"
4925        );
4926        assert!(
4927            dump.lines()
4928                .any(|line| line.contains("╌offstage 1: RenderConstrainedBox#")),
4929            "{dump}"
4930        );
4931        assert!(!dump.contains("no offstage children"), "{dump}");
4932    }
4933
4934    /// `overlay_test.dart`'s "Overlay can set and update clipBehavior": each clip behavior
4935    /// decides what the theater says it clips its entries to.
4936    #[test]
4937    fn the_theater_describes_its_clip_for_each_clip_behavior() {
4938        for clip_behavior in [
4939            Clip::None,
4940            Clip::HardEdge,
4941            Clip::AntiAlias,
4942            Clip::AntiAliasWithSaveLayer,
4943        ] {
4944            let cell = AppCell::new();
4945            let mut app = cell.borrow_mut();
4946            let entry = test_entry(&mut app);
4947            let tree = MediaQuery::new(
4948                MediaQueryData::new(),
4949                Directionality::new(
4950                    TextDirection::Ltr,
4951                    Overlay::new()
4952                        .clip_behavior(clip_behavior)
4953                        .initial_entries(vec![entry]),
4954                ),
4955            )
4956            .into_widget();
4957            let harness = Harness::mount(&mut app, tree);
4958            harness.pump(&mut app);
4959
4960            let theater = theater_of(&harness, &app);
4961            assert_eq!(theater.clip_behavior(&app), clip_behavior);
4962            let child = theater.first_child(&app).expect("an entry's render object");
4963            let expected = match clip_behavior {
4964                Clip::None => None,
4965                Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
4966                    Some(Offset::ZERO & theater.size(&app))
4967                }
4968            };
4969            assert_eq!(
4970                theater
4971                    .as_object()
4972                    .describe_approximate_paint_clip(&app, child.as_object()),
4973                expected,
4974                "{clip_behavior:?}"
4975            );
4976        }
4977    }
4978}