1use 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
46pub type OverlayChildLayoutBuilder =
49 Rc<dyn Fn(&mut App, BuildContext, OverlayChildLayoutInfo) -> WidgetRef>;
50
51#[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 pub fn child_size(&self) -> Size {
63 self.child_size
64 }
65
66 pub fn child_paint_transform(&self) -> Matrix4 {
69 self.child_paint_transform
70 }
71
72 pub fn overlay_size(&self) -> Size {
74 self.overlay_size
75 }
76}
77
78pub struct OverlayEntry {
111 pub builder: WidgetBuilder,
119 opaque: bool,
120 maintain_state: bool,
121 can_size_overlay: bool,
122 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 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 pub fn opaque(self: Handle<Self>, app: &App) -> bool {
163 app.get(self).opaque
164 }
165
166 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 pub fn maintain_state(self: Handle<Self>, app: &App) -> bool {
190 app.get(self).maintain_state
191 }
192
193 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 pub fn can_size_overlay(self: Handle<Self>, app: &App) -> bool {
216 app.get(self).can_size_overlay
217 }
218
219 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 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 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 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 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#[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
364struct OverlayEntryWidgetState {
366 state: StateData<OverlayEntryWidget>,
367 theater: Option<RenderHandle<RenderTheater>>,
368 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 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 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 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 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 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#[derive(Debug)]
540pub struct Overlay {
541 pub key: Option<KeyRef>,
543 pub initial_entries: Vec<Ref<OverlayEntry>>,
555 pub clip_behavior: Clip,
559 pub always_size_to_content: bool,
569}
570
571impl Overlay {
572 pub fn new() -> Overlay {
577 Overlay::default()
578 }
579
580 pub fn key(mut self, key: KeyRef) -> Overlay {
582 self.key = Some(key);
583 self
584 }
585
586 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 pub fn clip_behavior(mut self, clip_behavior: Clip) -> Overlay {
597 self.clip_behavior = clip_behavior;
598 self
599 }
600
601 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 #[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 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 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
688pub 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 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 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 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 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 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 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#[derive(Debug)]
1047pub struct WrappingOverlay {
1048 pub key: Option<KeyRef>,
1050 pub clip_behavior: Clip,
1052 pub always_size_to_content: bool,
1054 pub child: WidgetRef,
1056}
1057
1058impl WrappingOverlay {
1059 pub fn key(mut self, key: KeyRef) -> WrappingOverlay {
1061 self.key = Some(key);
1062 self
1063 }
1064
1065 pub fn clip_behavior(mut self, clip_behavior: Clip) -> WrappingOverlay {
1067 self.clip_behavior = clip_behavior;
1068 self
1069 }
1070
1071 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
1093pub struct WrappingOverlayState {
1095 state: StateData<WrappingOverlay>,
1096 entry: Option<Ref<OverlayEntry>>,
1097}
1098
1099impl WrappingOverlayState {
1100 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#[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
1208struct 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 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 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#[derive(Debug, Default)]
1405pub struct TheaterParentData {
1406 stack: StackParentData,
1407 overlay_entry: Option<Ref<OverlayEntry>>,
1409}
1410
1411impl TheaterParentData {
1412 pub fn new() -> TheaterParentData {
1414 TheaterParentData {
1415 stack: StackParentData::new(),
1416 overlay_entry: None,
1417 }
1418 }
1419
1420 pub fn stack(&self) -> &StackParentData {
1422 &self.stack
1423 }
1424
1425 pub fn stack_mut(&mut self) -> &mut StackParentData {
1427 &mut self.stack
1428 }
1429
1430 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 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
1518fn 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
1551pub struct TheaterChildren {
1556 theater: Option<RenderHandle<RenderTheater>>,
1558
1559 entry: Option<AnyRenderBox>,
1561
1562 reversed: bool,
1564
1565 remaining: usize,
1567
1568 phase: TheaterChildrenPhase,
1570
1571 candidate: Option<Handle<OverlayEntryLocation>>,
1573}
1574
1575enum TheaterChildrenPhase {
1577 Entry,
1579
1580 OpenPortals,
1582
1583 Portals,
1585
1586 NextEntry,
1588}
1589
1590impl TheaterChildren {
1591 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 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 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 #[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
1700pub trait RenderTheaterMixin: RenderBox {
1705 fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater>;
1707
1708 fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;
1710
1711 fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;
1713
1714 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 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 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 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 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
1806pub 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 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 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 pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
1868 self.get(app).text_direction
1869 }
1870
1871 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 pub fn skip_count(self: RenderHandle<Self>, app: &App) -> usize {
1882 self.get(app).skip_count
1883 }
1884
1885 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 pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
1897 self.get(app).clip_behavior
1898 }
1899
1900 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 pub fn always_size_to_content(self: RenderHandle<Self>, app: &App) -> bool {
1910 self.get(app).always_size_to_content
1911 }
1912
1913 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 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 self.mark_needs_paint(app);
1933
1934 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 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 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 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#[derive(Debug)]
2271struct RenderTheaterMarker {
2272 theater: RenderHandle<RenderTheater>,
2273 overlay_entry_widget_state: Handle<OverlayEntryWidgetState>,
2274 child: WidgetRef,
2275}
2276
2277#[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
2365thread_local! {
2389 static WALL_TIME: Cell<i64> = const { Cell::new(i64::MIN) };
2391}
2392
2393pub struct OverlayPortalController {
2404 attach_target: Option<Handle<OverlayPortalState>>,
2405 z_order_index: Option<i64>,
2409 debug_label: Option<String>,
2410}
2411
2412impl OverlayPortalController {
2413 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 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 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2512pub enum OverlayChildLocation {
2513 NearestOverlay,
2516
2517 RootOverlay,
2523}
2524
2525pub struct OverlayPortal {
2575 pub key: Option<KeyRef>,
2577 pub controller: Ref<OverlayPortalController>,
2579 pub overlay_child_builder: WidgetBuilder,
2596 pub child: Option<WidgetRef>,
2598 pub overlay_location: OverlayChildLocation,
2601}
2602
2603impl OverlayPortal {
2604 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 #[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 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 pub fn key(mut self, key: KeyRef) -> OverlayPortal {
2680 self.key = Some(key);
2681 self
2682 }
2683
2684 #[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 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
2723pub struct OverlayPortalState {
2725 state: StateData<OverlayPortal>,
2726 z_order_index: Option<i64>,
2727 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 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 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
2924struct OverlayEntryLocation {
2955 z_order_index: i64,
2956 child_model: Handle<OverlayEntryWidgetState>,
2957 theater: RenderHandle<RenderTheater>,
2958 overlay_child_render_box: Option<RenderHandle<RenderDeferredLayoutBox>>,
2959 slot_token: Option<Rc<dyn Any>>,
2961 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 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 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 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 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 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 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#[derive(Debug)]
3154struct RawOverlayPortal {
3155 overlay_child: Option<WidgetRef>,
3156 child: Option<WidgetRef>,
3158 overlay_location: Option<Ref<OverlayEntryLocation>>,
3159 created: Option<CreationLocation>,
3161}
3162
3163impl RawOverlayPortal {
3164 #[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
3221struct 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 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 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 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#[derive(Debug)]
3466struct DeferredLayout {
3467 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
3517struct RenderDeferredLayoutBox {
3534 render_object: RenderObjectData,
3535 render_box: RenderBoxData,
3536 child: RenderObjectWithChildData<AnyRenderBox>,
3537 layout_surrogate: RenderHandle<RenderLayoutSurrogateProxyBox>,
3538 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 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 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 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 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
3745struct RenderLayoutSurrogateProxyBox {
3752 render_object: RenderObjectData,
3753 render_box: RenderBoxData,
3754 child: RenderObjectWithChildData<AnyRenderBox>,
3755 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 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 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 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 let theater = deferred_child.theater(app);
3870 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
3956struct OverlayChildLayoutBuilderWidget {
3963 builder: OverlayChildLayoutBuilder,
3964 created: Option<CreationLocation>,
3966}
3967
3968impl OverlayChildLayoutBuilderWidget {
3969 #[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 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 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 render_object.cancel_frame_callback(app);
4046 }
4047}
4048
4049struct OverlayChildLayoutBuilderElement {
4052 element: ElementData,
4053 render_object_element: RenderObjectElementData,
4054 child: Option<AnyElement>,
4055 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); 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
4308struct RenderOverlayChildLayoutBuilder {
4319 render_object: RenderObjectData,
4320 render_box: RenderBoxData,
4321 child: RenderObjectWithChildData<AnyRenderBox>,
4322 layout_callback: RenderObjectWithLayoutCallbackData,
4323 callback: Option<Listener>,
4324 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 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 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 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 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 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 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 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 assert_eq!(theater.child_count(&app), 1);
4742
4743 let dump = theater
4746 .as_object()
4747 .to_string_deep_with(&app, DiagnosticLevel::Info);
4748 assert!(dump.contains("onstage 1 - 1:"), "{dump}");
4749
4750 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 #[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 #[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 #[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}