Skip to main content

waft_widgets/widgets/
basic.rs

1//! Flutter counterpart: `widgets/basic.dart`.
2//!
3//! `Spacer` is Flutter's `widgets/spacer.dart` and `IndexedStack` is
4//! `widgets/indexed_stack.dart`. They live here until those files are ported.
5//! `WidgetBuilder` is Flutter's `framework.dart` typedef; the framework module does not export
6//! one, so it is defined here next to `Builder`.
7
8use std::any::Any;
9use std::collections::HashSet;
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12
13use indexmap::{IndexMap, IndexSet};
14use waft_embedder::{
15    BlendMode, Clip, Color, FilterQuality, ImageFilter, Locale, Matrix4, Offset, Path, RRect,
16    RSuperellipse, Rect, SemanticsHitTestBehavior, SemanticsInputType, SemanticsRole,
17    SemanticsValidationResult, Size, TextBaseline, TextDirection,
18};
19use waft_foundation::{
20    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty,
21    EnumProperty, FlagProperty, Handle, IntProperty, IterableProperty, Ref, ValueKey, VoidCallback,
22};
23use waft_gestures::{
24    PointerCancelEventListener, PointerDownEventListener, PointerEnterEventListener,
25    PointerExitEventListener, PointerHoverEventListener, PointerMoveEventListener,
26    PointerPanZoomEndEventListener, PointerPanZoomStartEventListener,
27    PointerPanZoomUpdateEventListener, PointerSignalEventListener, PointerUpEventListener,
28};
29use waft_painting::{
30    Alignment, AlignmentGeometry, AnyColor, Axis, AxisDirection, BorderRadius,
31    BorderRadiusGeometry, BoxFit, BoxShape, ColorProperty, EdgeInsetsGeometry, ShapeBorderRef,
32    VerticalDirection, flip_axis_direction, text_direction_to_axis_direction,
33};
34use waft_rendering::{
35    AccessibilityFocusBlockType, AnyRenderObject, AttributedString, BackdropKey, BoxConstraints,
36    BoxConstraintsTransform, ChildLayoutId, CrossAxisAlignment, CustomClipper, CustomPainter,
37    CustomSemanticsAction, FlexFit, FlexParentData, HitTestBehavior, ImageFilterConfig, LayerLink,
38    MainAxisAlignment, MainAxisSize, MoveCursorHandler, MultiChildLayoutDelegate,
39    MultiChildLayoutParentData, OverflowBoxFit, RelativeRect, RenderAbsorbPointer,
40    RenderAligningShiftedBox, RenderAspectRatio, RenderBackdropFilter, RenderBaseline,
41    RenderBlockSemantics, RenderBox, RenderClipOval, RenderClipPath, RenderClipRRect,
42    RenderClipRSuperellipse, RenderClipRect, RenderColoredBox, RenderConstrainedBox,
43    RenderConstrainedBoxBase, RenderConstrainedOverflowBox, RenderConstraintsTransformBox,
44    RenderCustomClip, RenderCustomMultiChildLayoutBox, RenderCustomPaint,
45    RenderCustomSingleChildLayoutBox, RenderExcludeSemantics, RenderFittedBox, RenderFlex,
46    RenderFollowerLayer, RenderFractionalTranslation, RenderFractionallySizedOverflowBox,
47    RenderHandle, RenderIgnorePointer, RenderIndexedSemantics, RenderIndexedStack,
48    RenderIntrinsicHeight, RenderIntrinsicWidth, RenderLeaderLayer, RenderLimitedBox,
49    RenderListBody, RenderMergeSemantics, RenderMetaData, RenderMouseRegion, RenderMouseRegionBase,
50    RenderOffstage, RenderOpacity, RenderPadding, RenderPhysicalModel, RenderPhysicalModelBase,
51    RenderPhysicalShape, RenderPointerListener, RenderPositionedBox, RenderRepaintBoundary,
52    RenderSemanticsAnnotations, RenderSizedOverflowBox, RenderSliver, RenderSliverPadding,
53    RenderSliverToBoxAdapter, RenderStack, RenderStackBase, RenderTransform, RenderWrap,
54    SemanticsAnnotationsMixin, SemanticsProperties, SemanticsSortKeyRef, SemanticsTag,
55    SetSelectionHandler, SetTextHandler, ShapeBorderClipper, SingleChildLayoutDelegate, StackFit,
56    StackParentData, WrapAlignment, WrapCrossAlignment,
57};
58use waft_services::{MouseCursor, MouseCursorRef};
59
60use crate::framework::{
61    BuildContext, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectWidget,
62    ParentDataWidget, RenderObjectWidget, SingleChildRenderObjectWidget, State, StateData,
63    StatefulWidget, StatelessWidget, WidgetRef,
64};
65use crate::widgets::focus_scope::ExcludeFocus;
66use crate::widgets::overlay::TheaterParentData;
67
68// BIDIRECTIONAL TEXT SUPPORT
69
70/// A widget that determines the ambient directionality of text and
71/// text-direction-sensitive render objects.
72///
73/// For example, [`Padding`] depends on the [`Directionality`] to resolve
74/// `EdgeInsetsDirectional` objects into absolute `EdgeInsets` objects.
75///
76/// This example uses a right-to-left [`TextDirection`] and draws a blue box with
77/// a right margin of 8 pixels.
78///
79/// ```text
80/// Directionality {
81///   text_direction: TextDirection::Rtl,
82///   child: Container(margin: EdgeInsetsGeometry::directional(8.0, 0.0, 0.0, 0.0), color: blue),
83/// }
84/// ```
85///
86/// Flutter's `_UbiquitousInheritedWidget` / `_UbiquitousInheritedElement` is an
87/// optimisation that skips per-dependent bookkeeping and notifies by walking the subtree;
88/// this is a plain [`InheritedWidget`] with the same observable behaviour.
89#[derive(Debug)]
90pub struct Directionality {
91    pub key: Option<KeyRef>,
92    /// The text direction for this subtree.
93    pub text_direction: TextDirection,
94    pub child: WidgetRef,
95}
96
97impl Directionality {
98    /// Creates a `Directionality`; Dart's optional named arguments are the setters.
99    #[cfg_attr(debug_assertions, track_caller)]
100    pub fn new<K>(text_direction: TextDirection, child: impl IntoWidget<K>) -> Directionality {
101        Directionality {
102            key: None,
103            text_direction,
104            child: child.into_widget(),
105        }
106    }
107
108    /// Dart `Directionality(key:)`.
109    pub fn key(mut self, key: KeyRef) -> Directionality {
110        self.key = Some(key);
111        self
112    }
113
114    /// The text direction from the closest instance of this class that encloses
115    /// the given context.
116    ///
117    /// If there is no [`Directionality`] ancestor widget in the tree at the given
118    /// context, then this will panic with a descriptive message.
119    ///
120    /// Typical usage is as follows:
121    ///
122    /// ```text
123    /// let text_direction = Directionality::of(app, context);
124    /// ```
125    ///
126    /// See also:
127    ///
128    ///  * [`maybe_of`](Self::maybe_of), which will return `None` if no [`Directionality`]
129    ///    ancestor widget is in the tree.
130    pub fn of(app: &mut App, context: BuildContext) -> TextDirection {
131        let widget = context
132            .depend_on_inherited_widget_of_exact_type::<Directionality>(app)
133            .expect(
134                "No Directionality widget found. This widget requires a Directionality widget \
135                 ancestor. Typically, the Directionality widget is introduced by the WidgetsApp \
136                 widget at the top of your application widget tree. It determines the ambient \
137                 reading direction and is used, for example, to determine how to lay out text, \
138                 how to interpret \"start\" and \"end\" values, and to resolve \
139                 EdgeInsetsDirectional, AlignmentDirectional, and other *Directional objects.",
140            );
141        widget.text_direction
142    }
143
144    /// The text direction from the closest instance of this class that encloses
145    /// the given context.
146    ///
147    /// If there is no [`Directionality`] ancestor widget in the tree at the given
148    /// context, then this will return `None`.
149    ///
150    /// Typical usage is as follows:
151    ///
152    /// ```text
153    /// let text_direction: Option<TextDirection> = Directionality::maybe_of(app, context);
154    /// ```
155    ///
156    /// See also:
157    ///
158    ///  * [`of`](Self::of), which will panic if no [`Directionality`] ancestor widget is in
159    ///    the tree.
160    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<TextDirection> {
161        let widget = context.depend_on_inherited_widget_of_exact_type::<Directionality>(app);
162        widget.map(|widget| widget.text_direction)
163    }
164}
165
166impl InheritedWidget for Directionality {
167    fn key(&self) -> Option<&KeyRef> {
168        self.key.as_ref()
169    }
170
171    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
172        properties.add(EnumProperty::new("textDirection", self.text_direction));
173    }
174
175    fn child(&self) -> &WidgetRef {
176        &self.child
177    }
178
179    fn update_should_notify(&self, old_widget: &Directionality) -> bool {
180        self.text_direction != old_widget.text_direction
181    }
182}
183
184// PAINTING NODES
185
186/// A widget that can be targeted by a [`CompositedTransformFollower`].
187///
188/// When this widget is composited during the compositing phase (which comes after the paint
189/// phase, as described in `WidgetsBinding.drawFrame`), it updates the [`link`](Self::link)
190/// object so that any [`CompositedTransformFollower`] widgets that are subsequently composited
191/// in the same frame and were given the same [`LayerLink`] can position themselves at the same
192/// screen location.
193///
194/// A single [`CompositedTransformTarget`] can be followed by multiple
195/// [`CompositedTransformFollower`] widgets.
196///
197/// The [`CompositedTransformTarget`] must come earlier in the paint order than any linked
198/// [`CompositedTransformFollower`]s.
199#[derive(Debug)]
200pub struct CompositedTransformTarget {
201    pub key: Option<KeyRef>,
202    /// The link object that connects this [`CompositedTransformTarget`] with one or more
203    /// [`CompositedTransformFollower`]s.
204    pub link: Ref<LayerLink>,
205    pub child: Option<WidgetRef>,
206}
207
208impl CompositedTransformTarget {
209    /// Dart's `CompositedTransformTarget({required link, child})`.
210    pub fn new(link: Ref<LayerLink>) -> CompositedTransformTarget {
211        CompositedTransformTarget {
212            key: None,
213            link,
214            child: None,
215        }
216    }
217
218    /// Dart `CompositedTransformTarget(key:)`.
219    pub fn key(mut self, key: KeyRef) -> CompositedTransformTarget {
220        self.key = Some(key);
221        self
222    }
223
224    /// Dart `CompositedTransformTarget(child:)`.
225    #[cfg_attr(debug_assertions, track_caller)]
226    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CompositedTransformTarget {
227        self.child = Some(child.into_widget());
228        self
229    }
230}
231
232impl RenderObjectWidget for CompositedTransformTarget {
233    type RenderObject = RenderLeaderLayer;
234
235    fn key(&self) -> Option<&KeyRef> {
236        self.key.as_ref()
237    }
238
239    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
240        RenderLeaderLayer::new(app, self.link.clone(), None).as_object()
241    }
242
243    fn update_render_object(
244        &self,
245        app: &mut App,
246        _context: BuildContext,
247        render_object: RenderHandle<RenderLeaderLayer>,
248    ) {
249        render_object.set_link(app, self.link.clone());
250    }
251}
252
253impl SingleChildRenderObjectWidget for CompositedTransformTarget {
254    fn child(&self) -> Option<&WidgetRef> {
255        self.child.as_ref()
256    }
257}
258
259/// A widget that follows a [`CompositedTransformTarget`].
260///
261/// When this widget is composited during the compositing phase (which comes after the paint
262/// phase, as described in `WidgetsBinding.drawFrame`), it applies a transformation that brings
263/// [`target_anchor`](Self::target_anchor) of the linked [`CompositedTransformTarget`] and
264/// [`follower_anchor`](Self::follower_anchor) of this widget together. The two anchor points
265/// will have the same global coordinates, unless [`offset`](Self::offset) is not zero, in
266/// which case [`follower_anchor`](Self::follower_anchor) will be offset by
267/// [`offset`](Self::offset) in the linked [`CompositedTransformTarget`]'s coordinate space.
268///
269/// The [`LayerLink`] object used as the [`link`](Self::link) must be the same object as that
270/// provided to the matching [`CompositedTransformTarget`].
271///
272/// The [`CompositedTransformTarget`] must come earlier in the paint order than this
273/// [`CompositedTransformFollower`].
274///
275/// Hit testing on descendants of this widget will only work if the target position is within
276/// the box that this widget's parent considers to be hittable. If the parent covers the screen,
277/// this is trivially achievable, so this widget is usually used as the root of an
278/// `OverlayEntry` in an app-wide `Overlay` (e.g. as created by `WidgetsApp`).
279#[derive(Debug)]
280pub struct CompositedTransformFollower {
281    pub key: Option<KeyRef>,
282    /// The link object that connects this [`CompositedTransformFollower`] with a
283    /// [`CompositedTransformTarget`].
284    pub link: Ref<LayerLink>,
285    /// Whether to show the widget's contents when there is no corresponding
286    /// [`CompositedTransformTarget`] with the same [`link`](Self::link).
287    ///
288    /// When the widget is linked, the child is positioned such that it has the same global
289    /// position as the linked [`CompositedTransformTarget`].
290    ///
291    /// When the widget is not linked, then: if [`show_when_unlinked`](Self::show_when_unlinked)
292    /// is true, the child is visible and not repositioned; if it is false, then the child is
293    /// hidden.
294    pub show_when_unlinked: bool,
295    /// The anchor point on the linked [`CompositedTransformTarget`] that
296    /// [`follower_anchor`](Self::follower_anchor) will line up with.
297    ///
298    /// Defaults to [`Alignment::TOP_LEFT`].
299    pub target_anchor: Alignment,
300    /// The anchor point on this widget that will line up with
301    /// [`target_anchor`](Self::target_anchor) on the linked [`CompositedTransformTarget`].
302    ///
303    /// Defaults to [`Alignment::TOP_LEFT`].
304    pub follower_anchor: Alignment,
305    /// The additional offset to apply to the [`target_anchor`](Self::target_anchor) of the
306    /// linked [`CompositedTransformTarget`] to obtain this widget's
307    /// [`follower_anchor`](Self::follower_anchor) position.
308    pub offset: Offset,
309    pub child: Option<WidgetRef>,
310}
311
312impl CompositedTransformFollower {
313    /// Dart's `CompositedTransformFollower({required link, ..})`.
314    pub fn new(link: Ref<LayerLink>) -> CompositedTransformFollower {
315        CompositedTransformFollower {
316            key: None,
317            link,
318            show_when_unlinked: true,
319            target_anchor: Alignment::TOP_LEFT,
320            follower_anchor: Alignment::TOP_LEFT,
321            offset: Offset::ZERO,
322            child: None,
323        }
324    }
325
326    /// Dart `CompositedTransformFollower(key:)`.
327    pub fn key(mut self, key: KeyRef) -> CompositedTransformFollower {
328        self.key = Some(key);
329        self
330    }
331
332    /// Dart `CompositedTransformFollower(showWhenUnlinked:)`.
333    pub fn show_when_unlinked(mut self, show_when_unlinked: bool) -> CompositedTransformFollower {
334        self.show_when_unlinked = show_when_unlinked;
335        self
336    }
337
338    /// Dart `CompositedTransformFollower(targetAnchor:)`.
339    pub fn target_anchor(mut self, target_anchor: Alignment) -> CompositedTransformFollower {
340        self.target_anchor = target_anchor;
341        self
342    }
343
344    /// Dart `CompositedTransformFollower(followerAnchor:)`.
345    pub fn follower_anchor(mut self, follower_anchor: Alignment) -> CompositedTransformFollower {
346        self.follower_anchor = follower_anchor;
347        self
348    }
349
350    /// Dart `CompositedTransformFollower(offset:)`.
351    pub fn offset(mut self, offset: Offset) -> CompositedTransformFollower {
352        self.offset = offset;
353        self
354    }
355
356    /// Dart `CompositedTransformFollower(child:)`.
357    #[cfg_attr(debug_assertions, track_caller)]
358    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CompositedTransformFollower {
359        self.child = Some(child.into_widget());
360        self
361    }
362}
363
364impl RenderObjectWidget for CompositedTransformFollower {
365    type RenderObject = RenderFollowerLayer;
366
367    fn key(&self) -> Option<&KeyRef> {
368        self.key.as_ref()
369    }
370
371    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
372        RenderFollowerLayer::new(
373            app,
374            self.link.clone(),
375            self.show_when_unlinked,
376            self.offset,
377            self.target_anchor,
378            self.follower_anchor,
379            None,
380        )
381        .as_object()
382    }
383
384    fn update_render_object(
385        &self,
386        app: &mut App,
387        _context: BuildContext,
388        render_object: RenderHandle<RenderFollowerLayer>,
389    ) {
390        render_object.set_link(app, self.link.clone());
391        render_object.set_show_when_unlinked(app, self.show_when_unlinked);
392        render_object.set_offset(app, self.offset);
393        render_object.set_leader_anchor(app, self.target_anchor);
394        render_object.set_follower_anchor(app, self.follower_anchor);
395    }
396}
397
398impl SingleChildRenderObjectWidget for CompositedTransformFollower {
399    fn child(&self) -> Option<&WidgetRef> {
400        self.child.as_ref()
401    }
402}
403
404/// A widget that makes its child partially transparent.
405///
406/// This class paints its child into an intermediate buffer and then blends the
407/// child back into the scene partially transparent.
408///
409/// For values of opacity other than 0.0 and 1.0, this class is relatively
410/// expensive because it requires painting the child into an intermediate
411/// buffer. For the value 0.0, the child is not painted at all. For the
412/// value 1.0, the child is painted immediately without an intermediate buffer.
413///
414/// The presence of the intermediate buffer which has a transparent background
415/// by default may cause some child widgets to behave differently. For example
416/// a `BackdropFilter` child will only be able to apply its filter to the content
417/// between this widget and the backdrop child and may require adjusting the
418/// `BackdropFilter.blendMode` property to produce the desired results.
419///
420/// This example shows some `Text` when the `visible` member field is true, and
421/// hides it when it is false:
422///
423/// ```text
424/// Opacity {
425///   opacity: if visible { 1.0 } else { 0.0 },
426///   child: Some(Text("Now you see me, now you don't!")),
427///   ..Default::default()
428/// }
429/// ```
430///
431/// This is more efficient than adding and removing the child widget from the
432/// tree on demand.
433///
434/// ## Performance considerations for opacity animation
435///
436/// Animating an [`Opacity`] widget directly causes the widget (and possibly its
437/// subtree) to rebuild each frame, which is not very efficient. Consider using
438/// one of these alternative widgets instead:
439///
440///  * `AnimatedOpacity`, which uses an animation internally to efficiently
441///    animate opacity.
442///  * `FadeTransition`, which uses a provided animation to efficiently animate
443///    opacity.
444///
445/// ## Transparent image
446///
447/// If only a single `Image` or `Color` needs to be composited with an opacity
448/// between 0.0 and 1.0, it's much faster to directly use them without [`Opacity`]
449/// widgets.
450///
451/// For example, `Container(color: Color.fromRGBO(255, 0, 0, 0.5))` is much
452/// faster than `Opacity(opacity: 0.5, child: Container(color: Colors.red))`.
453///
454/// Directly drawing an `Image` or `Color` with opacity is faster than using
455/// [`Opacity`] on top of them because [`Opacity`] could apply the opacity to a
456/// group of widgets and therefore a costly offscreen buffer will be used.
457/// Drawing content into the offscreen buffer may also trigger render target
458/// switches and such switching is particularly slow in older GPUs.
459///
460/// ## Hit testing
461///
462/// Setting the [`opacity`](Self::opacity) to zero does not prevent hit testing from being
463/// applied to the descendants of the [`Opacity`] widget. This can be confusing for the
464/// user, who may not see anything, and may believe the area of the interface
465/// where the [`Opacity`] is hiding a widget to be non-interactive.
466///
467/// With certain widgets, such as `Flow`, that compute their positions only when
468/// they are painted, this can actually lead to bugs (from unexpected geometry
469/// to exceptions), because those widgets are not painted by the [`Opacity`]
470/// widget at all when the [`opacity`](Self::opacity) is zero.
471///
472/// To avoid such problems, it is generally a good idea to use an
473/// `IgnorePointer` widget when setting the [`opacity`](Self::opacity) to zero. This
474/// prevents interactions with any children in the subtree.
475///
476/// See also:
477///
478///  * `Visibility`, which can hide a child more efficiently (albeit less
479///    subtly, because it is either visible or hidden, rather than allowing
480///    fractional opacity values). Specifically, the `Visibility.maintain`
481///    constructor is equivalent to using an opacity widget with values of
482///    `0.0` or `1.0`.
483///  * `ShaderMask`, which can apply more elaborate effects to its child.
484///  * `Transform`, which applies an arbitrary transform to its child widget at
485///    paint time.
486///  * `SliverOpacity`, the sliver version of this widget.
487///
488/// Flutter's `alwaysIncludeSemantics` waits on accessibility.
489#[derive(Debug)]
490pub struct Opacity {
491    pub key: Option<KeyRef>,
492    /// The fraction to scale the child's alpha value.
493    ///
494    /// An opacity of one is fully opaque. An opacity of zero is fully transparent
495    /// (i.e., invisible).
496    ///
497    /// Values one and zero are painted with a fast path. Other values require
498    /// painting the child into an intermediate buffer, which is expensive.
499    ///
500    /// Must be between zero and one, inclusive.
501    pub opacity: f64,
502    pub child: Option<WidgetRef>,
503}
504
505impl Opacity {
506    /// Creates a `Opacity`; Dart's optional named arguments are the setters.
507    pub fn new(opacity: f64) -> Opacity {
508        Opacity {
509            key: None,
510            opacity,
511            child: None,
512        }
513    }
514
515    /// Dart `Opacity(key:)`.
516    pub fn key(mut self, key: KeyRef) -> Opacity {
517        self.key = Some(key);
518        self
519    }
520
521    /// Dart `Opacity(child:)`.
522    #[cfg_attr(debug_assertions, track_caller)]
523    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Opacity {
524        self.child = Some(child.into_widget());
525        self
526    }
527}
528
529impl RenderObjectWidget for Opacity {
530    type RenderObject = RenderOpacity;
531
532    fn key(&self) -> Option<&KeyRef> {
533        self.key.as_ref()
534    }
535
536    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
537        properties.add(DoubleProperty::new("opacity", self.opacity));
538    }
539
540    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
541        RenderOpacity::new(app, self.opacity, None).as_object()
542    }
543
544    fn update_render_object(
545        &self,
546        app: &mut App,
547        _context: BuildContext,
548        render_object: RenderHandle<RenderOpacity>,
549    ) {
550        render_object.set_opacity(app, self.opacity);
551    }
552}
553
554impl SingleChildRenderObjectWidget for Opacity {
555    fn child(&self) -> Option<&WidgetRef> {
556        self.child.as_ref()
557    }
558}
559
560/// A widget that provides a canvas on which to draw during the paint phase.
561///
562/// When asked to paint, [`CustomPaint`] first asks its [`painter`](Self::painter) to paint on
563/// the current canvas, then it paints its child, and then, after painting its child, it asks
564/// its [`foreground_painter`](Self::foreground_painter) to paint. The coordinate system of the
565/// canvas matches the coordinate system of the [`CustomPaint`] object. The painters are
566/// expected to paint within a rectangle starting at the origin and encompassing a region of
567/// the given size. (If the painters paint outside those bounds, there might be insufficient
568/// memory allocated to rasterize the painting commands and the resulting behavior is
569/// undefined.) To enforce painting within those bounds, consider wrapping this
570/// [`CustomPaint`] with a [`ClipRect`] widget.
571///
572/// Painters are implemented by implementing [`CustomPainter`].
573///
574/// Because custom paint calls its painters during paint, you cannot call
575/// `set_state` or `mark_needs_layout` during the callback (the layout for this
576/// frame has already happened).
577///
578/// Custom painters normally size themselves to their [`child`](Self::child). If they do not
579/// have a child, they attempt to size themselves to the specified [`size`](Self::size), which
580/// defaults to `Size::ZERO`. The parent may enforce constraints on this size.
581///
582/// The [`is_complex`](Self::is_complex) and [`will_change`](Self::will_change) properties are
583/// hints to the compositor's raster cache.
584///
585/// See also:
586///
587///  * [`CustomPainter`], the trait to implement when creating custom painters.
588///  * `Canvas`, the class that a custom painter uses to paint.
589pub struct CustomPaint {
590    pub key: Option<KeyRef>,
591    /// The painter that paints before the children.
592    pub painter: Option<Rc<dyn CustomPainter>>,
593    /// The painter that paints after the children.
594    pub foreground_painter: Option<Rc<dyn CustomPainter>>,
595    /// The size that this [`CustomPaint`] should aim for, given the layout
596    /// constraints, if there is no child.
597    ///
598    /// Defaults to `Size::ZERO`.
599    ///
600    /// If there's a child, this is ignored, and the size of the child is used
601    /// instead.
602    pub size: Size,
603    /// Whether the painting is complex enough to benefit from caching.
604    ///
605    /// The compositor contains a raster cache that holds bitmaps of layers in
606    /// order to avoid the cost of repeatedly rendering those layers on each
607    /// frame. If this flag is not set, then the compositor will apply its own
608    /// heuristics to decide whether the layer containing this widget is complex
609    /// enough to benefit from caching.
610    ///
611    /// This flag can't be set to true if both [`painter`](Self::painter) and
612    /// [`foreground_painter`](Self::foreground_painter) are `None` because this flag will be
613    /// ignored in such case.
614    pub is_complex: bool,
615    /// Whether the raster cache should be told that this painting is likely
616    /// to change in the next frame.
617    ///
618    /// This hint tells the compositor not to cache the layer containing this
619    /// widget because the cache will not be used in the future. If this hint is
620    /// not set, the compositor will apply its own heuristics to decide whether
621    /// the layer is likely to be reused in the future.
622    ///
623    /// This flag can't be set to true if both [`painter`](Self::painter) and
624    /// [`foreground_painter`](Self::foreground_painter) are `None` because this flag will be
625    /// ignored in such case.
626    pub will_change: bool,
627    pub child: Option<WidgetRef>,
628}
629
630impl CustomPaint {
631    /// Creates a `CustomPaint`; Dart's named arguments are the setters.
632    pub fn new() -> CustomPaint {
633        CustomPaint::default()
634    }
635
636    /// Dart `CustomPaint(key:)`.
637    pub fn key(mut self, key: KeyRef) -> CustomPaint {
638        self.key = Some(key);
639        self
640    }
641
642    /// Dart `CustomPaint(painter:)`.
643    pub fn painter(mut self, painter: impl CustomPainter) -> CustomPaint {
644        self.painter = Some(Rc::new(painter));
645        self
646    }
647
648    /// Dart `CustomPaint(foregroundPainter:)`.
649    pub fn foreground_painter(mut self, foreground_painter: impl CustomPainter) -> CustomPaint {
650        self.foreground_painter = Some(Rc::new(foreground_painter));
651        self
652    }
653
654    /// Dart `CustomPaint(size:)`.
655    pub fn size(mut self, size: Size) -> CustomPaint {
656        self.size = size;
657        self
658    }
659
660    /// Dart `CustomPaint(isComplex:)`.
661    pub fn is_complex(mut self, is_complex: bool) -> CustomPaint {
662        self.is_complex = is_complex;
663        self
664    }
665
666    /// Dart `CustomPaint(willChange:)`.
667    pub fn will_change(mut self, will_change: bool) -> CustomPaint {
668        self.will_change = will_change;
669        self
670    }
671
672    /// Dart `CustomPaint(child:)`.
673    #[cfg_attr(debug_assertions, track_caller)]
674    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CustomPaint {
675        self.child = Some(child.into_widget());
676        self
677    }
678
679    /// Dart's constructor assert: a raster cache hint needs a painter to hint about.
680    fn debug_check_hints(&self) {
681        debug_assert!(
682            self.painter.is_some()
683                || self.foreground_painter.is_some()
684                || (!self.is_complex && !self.will_change)
685        );
686    }
687}
688
689impl Default for CustomPaint {
690    fn default() -> CustomPaint {
691        CustomPaint {
692            key: None,
693            painter: None,
694            foreground_painter: None,
695            size: Size::ZERO,
696            is_complex: false,
697            will_change: false,
698            child: None,
699        }
700    }
701}
702
703impl RenderObjectWidget for CustomPaint {
704    type RenderObject = RenderCustomPaint;
705
706    fn key(&self) -> Option<&KeyRef> {
707        self.key.as_ref()
708    }
709
710    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
711        self.debug_check_hints();
712        RenderCustomPaint::new(
713            app,
714            self.painter.clone(),
715            self.foreground_painter.clone(),
716            self.size,
717            self.is_complex,
718            self.will_change,
719            None,
720        )
721        .as_object()
722    }
723
724    fn update_render_object(
725        &self,
726        app: &mut App,
727        _context: BuildContext,
728        render_object: RenderHandle<RenderCustomPaint>,
729    ) {
730        self.debug_check_hints();
731        render_object.set_painter(app, self.painter.clone());
732        render_object.set_foreground_painter(app, self.foreground_painter.clone());
733        render_object.set_preferred_size(app, self.size);
734        render_object.set_is_complex(app, self.is_complex);
735        render_object.set_will_change(app, self.will_change);
736    }
737
738    fn did_unmount_render_object(
739        &self,
740        app: &mut App,
741        render_object: RenderHandle<RenderCustomPaint>,
742    ) {
743        render_object.set_painter(app, None);
744        render_object.set_foreground_painter(app, None);
745    }
746}
747
748impl SingleChildRenderObjectWidget for CustomPaint {
749    fn child(&self) -> Option<&WidgetRef> {
750        self.child.as_ref()
751    }
752}
753
754impl Debug for CustomPaint {
755    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756        f.debug_struct("CustomPaint")
757            .field("key", &self.key)
758            .field("has_painter", &self.painter.is_some())
759            .field("has_foreground_painter", &self.foreground_painter.is_some())
760            .field("size", &self.size)
761            .field("is_complex", &self.is_complex)
762            .field("will_change", &self.will_change)
763            .field("child", &self.child)
764            .finish()
765    }
766}
767
768/// A widget that clips its child using a rectangle.
769///
770/// By default, [`ClipRect`] prevents its child from painting outside its
771/// bounds, but the size and location of the clip rect can be customized using a
772/// custom [`clipper`](Self::clipper).
773///
774/// [`ClipRect`] is commonly used with these widgets, which commonly paint outside
775/// their bounds:
776///
777///  * [`CustomPaint`]
778///  * `CustomSingleChildLayout`
779///  * `CustomMultiChildLayout`
780///  * [`Align`] and [`Center`] (e.g., if [`Align::width_factor`] or
781///    [`Align::height_factor`] is less than 1.0).
782///  * `OverflowBox`
783///  * `SizedOverflowBox`
784///
785/// For example, by combining a [`ClipRect`] with an [`Align`], one can show just
786/// the top half of an image:
787///
788/// ```text
789/// ClipRect::new().child(
790///     Align::new()
791///         .alignment(AlignmentGeometry::TOP_CENTER)
792///         .height_factor(0.5)
793///         .child(avatar),
794/// )
795/// ```
796///
797/// See also:
798///
799///  * [`CustomClipper`], for information about creating custom clips.
800///  * [`ClipRRect`], for a clip with rounded corners.
801///  * `ClipOval`, for an elliptical clip.
802///  * `ClipPath`, for an arbitrarily shaped clip.
803pub struct ClipRect {
804    pub key: Option<KeyRef>,
805    /// If non-`None`, determines which clip to use.
806    pub clipper: Option<Rc<dyn CustomClipper<Rect>>>,
807    /// Whether and how to clip the child.
808    ///
809    /// Defaults to [`Clip::HardEdge`].
810    pub clip_behavior: Clip,
811    pub child: Option<WidgetRef>,
812}
813
814impl ClipRect {
815    /// Creates a rectangular clip; Dart's named arguments are the setters.
816    ///
817    /// If [`clipper`](Self::clipper) is `None`, the clip will match the layout size and
818    /// position of the child.
819    ///
820    /// If [`clip_behavior`](Self::clip_behavior) is [`Clip::None`], no clipping will be
821    /// applied.
822    pub fn new() -> ClipRect {
823        ClipRect::default()
824    }
825
826    /// Dart `ClipRect(key:)`.
827    pub fn key(mut self, key: KeyRef) -> ClipRect {
828        self.key = Some(key);
829        self
830    }
831
832    /// Dart `ClipRect(clipper:)`.
833    pub fn clipper(mut self, clipper: impl CustomClipper<Rect>) -> ClipRect {
834        self.clipper = Some(Rc::new(clipper));
835        self
836    }
837
838    /// Dart `ClipRect(clipBehavior:)`.
839    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipRect {
840        self.clip_behavior = clip_behavior;
841        self
842    }
843
844    /// Dart `ClipRect(child:)`.
845    #[cfg_attr(debug_assertions, track_caller)]
846    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipRect {
847        self.child = Some(child.into_widget());
848        self
849    }
850}
851
852impl Default for ClipRect {
853    fn default() -> ClipRect {
854        ClipRect {
855            key: None,
856            clipper: None,
857            clip_behavior: Clip::HardEdge,
858            child: None,
859        }
860    }
861}
862
863impl RenderObjectWidget for ClipRect {
864    type RenderObject = RenderClipRect;
865
866    fn key(&self) -> Option<&KeyRef> {
867        self.key.as_ref()
868    }
869
870    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
871        properties.add(
872            DiagnosticsProperty::<String>::new(
873                "clipper",
874                self.clipper
875                    .as_ref()
876                    .map(|_| "Instance of 'CustomClipper<Rect>'".to_string()),
877            )
878            .default_value(None),
879        );
880    }
881
882    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
883        RenderClipRect::new(app, self.clipper.clone(), self.clip_behavior, None).as_object()
884    }
885
886    fn update_render_object(
887        &self,
888        app: &mut App,
889        _context: BuildContext,
890        render_object: RenderHandle<RenderClipRect>,
891    ) {
892        render_object.set_clipper(app, self.clipper.clone());
893        render_object.set_clip_behavior(app, self.clip_behavior);
894    }
895
896    fn did_unmount_render_object(
897        &self,
898        app: &mut App,
899        render_object: RenderHandle<RenderClipRect>,
900    ) {
901        render_object.set_clipper(app, None);
902    }
903}
904
905impl SingleChildRenderObjectWidget for ClipRect {
906    fn child(&self) -> Option<&WidgetRef> {
907        self.child.as_ref()
908    }
909}
910
911impl Debug for ClipRect {
912    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
913        f.debug_struct("ClipRect")
914            .field("key", &self.key)
915            .field("has_clipper", &self.clipper.is_some())
916            .field("clip_behavior", &self.clip_behavior)
917            .field("child", &self.child)
918            .finish()
919    }
920}
921
922/// A widget that clips its child using a rounded rectangle.
923///
924/// By default, [`ClipRRect`] uses its own bounds as the base rectangle for the
925/// clip, but the size and location of the clip can be customized using a custom
926/// [`clipper`](Self::clipper).
927///
928/// ## Troubleshooting
929///
930/// ### Why doesn't my [`ClipRRect`] child have rounded corners?
931///
932/// When a [`ClipRRect`] is bigger than the child it contains, its rounded corners
933/// could be drawn in unexpected positions. Make sure that [`ClipRRect`] and its child
934/// have the same bounds (by shrinking the [`ClipRRect`] with a `FittedBox` or by
935/// growing the child).
936///
937/// See also:
938///
939///  * [`CustomClipper`], for information about creating custom clips.
940///  * [`ClipRect`], for more efficient clips without rounded corners.
941///  * `ClipRSuperellipse`, for a similar clipping shape with smoother
942///    transitions between the straight sides and the rounded corners.
943///  * `ClipOval`, for an elliptical clip.
944///  * `ClipPath`, for an arbitrarily shaped clip.
945pub struct ClipRRect {
946    pub key: Option<KeyRef>,
947    /// The border radius of the rounded corners.
948    ///
949    /// Values are clamped so that horizontal and vertical radii sums do not
950    /// exceed width/height.
951    ///
952    /// This value is ignored if [`clipper`](Self::clipper) is non-`None`.
953    pub border_radius: BorderRadiusGeometry,
954    /// If non-`None`, determines which clip to use.
955    pub clipper: Option<Rc<dyn CustomClipper<RRect>>>,
956    /// Whether and how to clip the child.
957    ///
958    /// Defaults to [`Clip::AntiAlias`].
959    pub clip_behavior: Clip,
960    pub child: Option<WidgetRef>,
961}
962
963impl ClipRRect {
964    /// Creates a rounded-rectangular clip; Dart's named arguments are the setters.
965    ///
966    /// The [`border_radius`](Self::border_radius) defaults to
967    /// [`BorderRadiusGeometry::ZERO`], i.e. a rectangle with right-angled corners.
968    ///
969    /// If [`clipper`](Self::clipper) is non-`None`, then
970    /// [`border_radius`](Self::border_radius) is ignored.
971    ///
972    /// If [`clip_behavior`](Self::clip_behavior) is [`Clip::None`], no clipping will be
973    /// applied.
974    pub fn new() -> ClipRRect {
975        ClipRRect::default()
976    }
977
978    /// Dart `ClipRRect(key:)`.
979    pub fn key(mut self, key: KeyRef) -> ClipRRect {
980        self.key = Some(key);
981        self
982    }
983
984    /// Dart `ClipRRect(borderRadius:)`.
985    pub fn border_radius(mut self, border_radius: BorderRadiusGeometry) -> ClipRRect {
986        self.border_radius = border_radius;
987        self
988    }
989
990    /// Dart `ClipRRect(clipper:)`.
991    pub fn clipper(mut self, clipper: impl CustomClipper<RRect>) -> ClipRRect {
992        self.clipper = Some(Rc::new(clipper));
993        self
994    }
995
996    /// Dart `ClipRRect(clipBehavior:)`.
997    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipRRect {
998        self.clip_behavior = clip_behavior;
999        self
1000    }
1001
1002    /// Dart `ClipRRect(child:)`.
1003    #[cfg_attr(debug_assertions, track_caller)]
1004    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipRRect {
1005        self.child = Some(child.into_widget());
1006        self
1007    }
1008}
1009
1010impl Default for ClipRRect {
1011    fn default() -> ClipRRect {
1012        ClipRRect {
1013            key: None,
1014            border_radius: BorderRadiusGeometry::ZERO,
1015            clipper: None,
1016            clip_behavior: Clip::AntiAlias,
1017            child: None,
1018        }
1019    }
1020}
1021
1022impl RenderObjectWidget for ClipRRect {
1023    type RenderObject = RenderClipRRect;
1024
1025    fn key(&self) -> Option<&KeyRef> {
1026        self.key.as_ref()
1027    }
1028
1029    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1030        properties.add(
1031            DiagnosticsProperty::<BorderRadiusGeometry>::new("borderRadius", self.border_radius)
1032                .with_show_name(false),
1033        );
1034        properties.add(
1035            DiagnosticsProperty::<String>::new(
1036                "clipper",
1037                self.clipper
1038                    .as_ref()
1039                    .map(|_| "Instance of 'CustomClipper<RRect>'".to_string()),
1040            )
1041            .default_value(None),
1042        );
1043    }
1044
1045    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1046        let text_direction = Directionality::maybe_of(app, context);
1047        RenderClipRRect::new(
1048            app,
1049            self.border_radius,
1050            self.clipper.clone(),
1051            self.clip_behavior,
1052            text_direction,
1053            None,
1054        )
1055        .as_object()
1056    }
1057
1058    fn update_render_object(
1059        &self,
1060        app: &mut App,
1061        context: BuildContext,
1062        render_object: RenderHandle<RenderClipRRect>,
1063    ) {
1064        render_object.set_border_radius(app, self.border_radius);
1065        render_object.set_clip_behavior(app, self.clip_behavior);
1066        render_object.set_clipper(app, self.clipper.clone());
1067        let text_direction = Directionality::maybe_of(app, context);
1068        render_object.set_text_direction(app, text_direction);
1069    }
1070}
1071
1072impl SingleChildRenderObjectWidget for ClipRRect {
1073    fn child(&self) -> Option<&WidgetRef> {
1074        self.child.as_ref()
1075    }
1076}
1077
1078impl Debug for ClipRRect {
1079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080        f.debug_struct("ClipRRect")
1081            .field("key", &self.key)
1082            .field("border_radius", &self.border_radius)
1083            .field("has_clipper", &self.clipper.is_some())
1084            .field("clip_behavior", &self.clip_behavior)
1085            .field("child", &self.child)
1086            .finish()
1087    }
1088}
1089
1090/// A widget that clips its child using a rounded superellipse.
1091///
1092/// By default, [`ClipRSuperellipse`] uses its own bounds as the base rectangle for the
1093/// clip, but the size and location of the clip can be customized using a custom
1094/// [`clipper`](Self::clipper).
1095///
1096/// ## Troubleshooting
1097///
1098/// ### Why doesn't my [`ClipRSuperellipse`] child have rounded corners?
1099///
1100/// When a [`ClipRSuperellipse`] is bigger than the child it contains, its rounded corners
1101/// could be drawn in unexpected positions. Make sure that [`ClipRSuperellipse`] and its child
1102/// have the same bounds (by shrinking the [`ClipRSuperellipse`] with a `FittedBox` or by
1103/// growing the child).
1104///
1105/// See also:
1106///
1107///  * [`CustomClipper`], for information about creating custom clips.
1108///  * [`ClipRect`], for more efficient clips without rounded corners.
1109///  * `ClipRSuperellipse`, for a similar clipping shape with smoother
1110///    transitions between the straight sides and the rounded corners.
1111///  * `ClipOval`, for an elliptical clip.
1112///  * `ClipPath`, for an arbitrarily shaped clip.
1113pub struct ClipRSuperellipse {
1114    pub key: Option<KeyRef>,
1115    /// The border radius of the rounded corners.
1116    ///
1117    /// Values are clamped so that horizontal and vertical radii sums do not
1118    /// exceed width/height.
1119    ///
1120    /// This value is ignored if [`clipper`](Self::clipper) is non-`None`.
1121    pub border_radius: BorderRadiusGeometry,
1122    /// If non-`None`, determines which clip to use.
1123    pub clipper: Option<Rc<dyn CustomClipper<RSuperellipse>>>,
1124    /// Whether and how to clip the child.
1125    ///
1126    /// Defaults to [`Clip::AntiAlias`].
1127    pub clip_behavior: Clip,
1128    pub child: Option<WidgetRef>,
1129}
1130
1131impl ClipRSuperellipse {
1132    /// Creates a rounded-rectangular clip; Dart's named arguments are the setters.
1133    ///
1134    /// The [`border_radius`](Self::border_radius) defaults to
1135    /// [`BorderRadiusGeometry::ZERO`], i.e. a rectangle with right-angled corners.
1136    ///
1137    /// If [`clipper`](Self::clipper) is non-`None`, then
1138    /// [`border_radius`](Self::border_radius) is ignored.
1139    ///
1140    /// If [`clip_behavior`](Self::clip_behavior) is [`Clip::None`], no clipping will be
1141    /// applied.
1142    pub fn new() -> ClipRSuperellipse {
1143        ClipRSuperellipse::default()
1144    }
1145
1146    /// Dart `ClipRSuperellipse(key:)`.
1147    pub fn key(mut self, key: KeyRef) -> ClipRSuperellipse {
1148        self.key = Some(key);
1149        self
1150    }
1151
1152    /// Dart `ClipRSuperellipse(borderRadius:)`.
1153    pub fn border_radius(mut self, border_radius: BorderRadiusGeometry) -> ClipRSuperellipse {
1154        self.border_radius = border_radius;
1155        self
1156    }
1157
1158    /// Dart `ClipRSuperellipse(clipper:)`.
1159    pub fn clipper(mut self, clipper: impl CustomClipper<RSuperellipse>) -> ClipRSuperellipse {
1160        self.clipper = Some(Rc::new(clipper));
1161        self
1162    }
1163
1164    /// Dart `ClipRSuperellipse(clipBehavior:)`.
1165    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipRSuperellipse {
1166        self.clip_behavior = clip_behavior;
1167        self
1168    }
1169
1170    /// Dart `ClipRSuperellipse(child:)`.
1171    #[cfg_attr(debug_assertions, track_caller)]
1172    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipRSuperellipse {
1173        self.child = Some(child.into_widget());
1174        self
1175    }
1176}
1177
1178impl Default for ClipRSuperellipse {
1179    fn default() -> ClipRSuperellipse {
1180        ClipRSuperellipse {
1181            key: None,
1182            border_radius: BorderRadiusGeometry::ZERO,
1183            clipper: None,
1184            clip_behavior: Clip::AntiAlias,
1185            child: None,
1186        }
1187    }
1188}
1189
1190impl RenderObjectWidget for ClipRSuperellipse {
1191    type RenderObject = RenderClipRSuperellipse;
1192
1193    fn key(&self) -> Option<&KeyRef> {
1194        self.key.as_ref()
1195    }
1196
1197    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1198        properties.add(
1199            DiagnosticsProperty::<BorderRadiusGeometry>::new("borderRadius", self.border_radius)
1200                .with_show_name(false),
1201        );
1202        properties.add(
1203            DiagnosticsProperty::<String>::new(
1204                "clipper",
1205                self.clipper
1206                    .as_ref()
1207                    .map(|_| "Instance of 'CustomClipper<RSuperellipse>'".to_string()),
1208            )
1209            .default_value(None),
1210        );
1211    }
1212
1213    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1214        let text_direction = Directionality::maybe_of(app, context);
1215        RenderClipRSuperellipse::new(
1216            app,
1217            self.border_radius,
1218            self.clipper.clone(),
1219            self.clip_behavior,
1220            text_direction,
1221            None,
1222        )
1223        .as_object()
1224    }
1225
1226    fn update_render_object(
1227        &self,
1228        app: &mut App,
1229        context: BuildContext,
1230        render_object: RenderHandle<RenderClipRSuperellipse>,
1231    ) {
1232        render_object.set_border_radius(app, self.border_radius);
1233        render_object.set_clip_behavior(app, self.clip_behavior);
1234        render_object.set_clipper(app, self.clipper.clone());
1235        let text_direction = Directionality::maybe_of(app, context);
1236        render_object.set_text_direction(app, text_direction);
1237    }
1238}
1239
1240impl SingleChildRenderObjectWidget for ClipRSuperellipse {
1241    fn child(&self) -> Option<&WidgetRef> {
1242        self.child.as_ref()
1243    }
1244}
1245
1246impl Debug for ClipRSuperellipse {
1247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248        f.debug_struct("ClipRSuperellipse")
1249            .field("key", &self.key)
1250            .field("border_radius", &self.border_radius)
1251            .field("has_clipper", &self.clipper.is_some())
1252            .field("clip_behavior", &self.clip_behavior)
1253            .field("child", &self.child)
1254            .finish()
1255    }
1256}
1257
1258/// A widget that clips its child using an oval.
1259///
1260/// By default, inscribes an axis-aligned oval into its layout dimensions and
1261/// prevents its child from painting outside that oval, but the size and
1262/// location of the clip oval can be customized using a custom `clipper`.
1263///
1264/// See also:
1265///
1266///  * `CustomClipper`, for information about creating custom clips.
1267///  * [`ClipRect`], for more efficient clips without rounded corners.
1268///  * [`ClipRRect`], for a clip with rounded corners.
1269///  * [`ClipPath`], for an arbitrarily shaped clip.
1270pub struct ClipOval {
1271    pub key: Option<KeyRef>,
1272    /// If non-`None`, determines which clip to use.
1273    ///
1274    /// The delegate returns a rectangle that describes the axis-aligned
1275    /// bounding box of the oval. The oval's axes will themselves also
1276    /// be axis-aligned.
1277    ///
1278    /// If the `clipper` delegate is `None`, then the oval uses the
1279    /// widget's bounding box (the layout dimensions of the render
1280    /// object) instead.
1281    pub clipper: Option<Rc<dyn CustomClipper<Rect>>>,
1282    /// Whether and how to clip the child.
1283    ///
1284    /// Defaults to [`Clip::AntiAlias`].
1285    pub clip_behavior: Clip,
1286    /// The widget below this widget in the tree.
1287    pub child: Option<WidgetRef>,
1288}
1289
1290impl ClipOval {
1291    /// Creates an oval-shaped clip; Dart's named arguments are the setters.
1292    pub fn new() -> ClipOval {
1293        ClipOval::default()
1294    }
1295
1296    /// Dart `ClipOval(key:)`.
1297    pub fn key(mut self, key: KeyRef) -> ClipOval {
1298        self.key = Some(key);
1299        self
1300    }
1301
1302    /// Dart `ClipOval(clipper:)`.
1303    pub fn clipper(mut self, clipper: Rc<dyn CustomClipper<Rect>>) -> ClipOval {
1304        self.clipper = Some(clipper);
1305        self
1306    }
1307
1308    /// Dart `ClipOval(clipBehavior:)`.
1309    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipOval {
1310        self.clip_behavior = clip_behavior;
1311        self
1312    }
1313
1314    /// Dart `ClipOval(child:)`.
1315    #[cfg_attr(debug_assertions, track_caller)]
1316    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipOval {
1317        self.child = Some(child.into_widget());
1318        self
1319    }
1320}
1321
1322impl Default for ClipOval {
1323    fn default() -> ClipOval {
1324        ClipOval {
1325            key: None,
1326            clipper: None,
1327            clip_behavior: Clip::AntiAlias,
1328            child: None,
1329        }
1330    }
1331}
1332
1333impl RenderObjectWidget for ClipOval {
1334    type RenderObject = RenderClipOval;
1335
1336    fn key(&self) -> Option<&KeyRef> {
1337        self.key.as_ref()
1338    }
1339
1340    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1341        properties.add(
1342            DiagnosticsProperty::<String>::new(
1343                "clipper",
1344                self.clipper
1345                    .as_ref()
1346                    .map(|_| "Instance of 'CustomClipper<Rect>'".to_string()),
1347            )
1348            .default_value(None),
1349        );
1350    }
1351
1352    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1353        RenderClipOval::new(app, self.clipper.clone(), self.clip_behavior, None).as_object()
1354    }
1355
1356    fn update_render_object(
1357        &self,
1358        app: &mut App,
1359        _context: BuildContext,
1360        render_object: RenderHandle<RenderClipOval>,
1361    ) {
1362        render_object.set_clipper(app, self.clipper.clone());
1363        render_object.set_clip_behavior(app, self.clip_behavior);
1364    }
1365
1366    fn did_unmount_render_object(
1367        &self,
1368        app: &mut App,
1369        render_object: RenderHandle<RenderClipOval>,
1370    ) {
1371        render_object.set_clipper(app, None);
1372    }
1373}
1374
1375impl SingleChildRenderObjectWidget for ClipOval {
1376    fn child(&self) -> Option<&WidgetRef> {
1377        self.child.as_ref()
1378    }
1379}
1380
1381impl Debug for ClipOval {
1382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1383        f.debug_struct("ClipOval")
1384            .field("key", &self.key)
1385            .field("clipper", &self.clipper.as_ref().map(|_| "..."))
1386            .field("clip_behavior", &self.clip_behavior)
1387            .field("child", &self.child)
1388            .finish()
1389    }
1390}
1391
1392/// A widget that clips its child using a path.
1393///
1394/// Calls a callback on a delegate whenever the widget is to be
1395/// painted. The callback returns a path and the widget prevents the
1396/// child from painting outside the path.
1397///
1398/// Clipping to a path is expensive. Certain shapes have more
1399/// optimized widgets:
1400///
1401///  * To clip to a rectangle, consider [`ClipRect`].
1402///  * To clip to an oval or circle, consider [`ClipOval`].
1403///  * To clip to a rounded rectangle, consider [`ClipRRect`].
1404///
1405/// To clip to a particular `ShapeBorder`, consider using either the
1406/// [`ClipPath::shape`] static method or the `ShapeBorderClipper` custom clipper
1407/// class.
1408pub struct ClipPath {
1409    pub key: Option<KeyRef>,
1410    /// If non-`None`, determines which clip to use.
1411    ///
1412    /// The default clip, which is used if this property is `None`, is the
1413    /// bounding box rectangle of the widget. [`ClipRect`] is a more
1414    /// efficient way of obtaining that effect.
1415    pub clipper: Option<Rc<dyn CustomClipper<Path>>>,
1416    /// Whether and how to clip the child.
1417    ///
1418    /// Defaults to [`Clip::AntiAlias`].
1419    pub clip_behavior: Clip,
1420    /// The widget below this widget in the tree.
1421    pub child: Option<WidgetRef>,
1422}
1423
1424impl ClipPath {
1425    /// Creates a path clip; Dart's named arguments are the setters.
1426    pub fn new() -> ClipPath {
1427        ClipPath::default()
1428    }
1429
1430    /// Creates a shape clip.
1431    ///
1432    /// Uses a `ShapeBorderClipper` to configure the [`ClipPath`] to clip to the
1433    /// given `ShapeBorder`. Dart's optional arguments are the setters of the
1434    /// [`ClipPathShape`] this returns.
1435    pub fn shape(shape: impl Into<ShapeBorderRef>) -> ClipPathShape {
1436        ClipPathShape {
1437            key: None,
1438            shape: shape.into(),
1439            clip_behavior: Clip::AntiAlias,
1440            child: None,
1441        }
1442    }
1443
1444    /// Dart `ClipPath(key:)`.
1445    pub fn key(mut self, key: KeyRef) -> ClipPath {
1446        self.key = Some(key);
1447        self
1448    }
1449
1450    /// Dart `ClipPath(clipper:)`.
1451    pub fn clipper(mut self, clipper: Rc<dyn CustomClipper<Path>>) -> ClipPath {
1452        self.clipper = Some(clipper);
1453        self
1454    }
1455
1456    /// Dart `ClipPath(clipBehavior:)`.
1457    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipPath {
1458        self.clip_behavior = clip_behavior;
1459        self
1460    }
1461
1462    /// Dart `ClipPath(child:)`.
1463    #[cfg_attr(debug_assertions, track_caller)]
1464    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipPath {
1465        self.child = Some(child.into_widget());
1466        self
1467    }
1468}
1469
1470impl Default for ClipPath {
1471    fn default() -> ClipPath {
1472        ClipPath {
1473            key: None,
1474            clipper: None,
1475            clip_behavior: Clip::AntiAlias,
1476            child: None,
1477        }
1478    }
1479}
1480
1481impl RenderObjectWidget for ClipPath {
1482    type RenderObject = RenderClipPath;
1483
1484    fn key(&self) -> Option<&KeyRef> {
1485        self.key.as_ref()
1486    }
1487
1488    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1489        properties.add(
1490            DiagnosticsProperty::<String>::new(
1491                "clipper",
1492                self.clipper
1493                    .as_ref()
1494                    .map(|_| "Instance of 'CustomClipper<Path>'".to_string()),
1495            )
1496            .default_value(None),
1497        );
1498    }
1499
1500    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1501        RenderClipPath::new(app, self.clipper.clone(), self.clip_behavior, None).as_object()
1502    }
1503
1504    fn update_render_object(
1505        &self,
1506        app: &mut App,
1507        _context: BuildContext,
1508        render_object: RenderHandle<RenderClipPath>,
1509    ) {
1510        render_object.set_clipper(app, self.clipper.clone());
1511        render_object.set_clip_behavior(app, self.clip_behavior);
1512    }
1513
1514    fn did_unmount_render_object(
1515        &self,
1516        app: &mut App,
1517        render_object: RenderHandle<RenderClipPath>,
1518    ) {
1519        render_object.set_clipper(app, None);
1520    }
1521}
1522
1523impl SingleChildRenderObjectWidget for ClipPath {
1524    fn child(&self) -> Option<&WidgetRef> {
1525        self.child.as_ref()
1526    }
1527}
1528
1529impl Debug for ClipPath {
1530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531        f.debug_struct("ClipPath")
1532            .field("key", &self.key)
1533            .field("clipper", &self.clipper.as_ref().map(|_| "..."))
1534            .field("clip_behavior", &self.clip_behavior)
1535            .field("child", &self.child)
1536            .finish()
1537    }
1538}
1539
1540/// Dart's `ClipPath.shape(..)` before its optional arguments are known: a [`Builder`] that
1541/// clips to a `ShapeBorder` resolved against the ambient [`Directionality`].
1542pub struct ClipPathShape {
1543    key: Option<KeyRef>,
1544    shape: ShapeBorderRef,
1545    clip_behavior: Clip,
1546    child: Option<WidgetRef>,
1547}
1548
1549impl ClipPathShape {
1550    /// Dart `ClipPath.shape(key:)`.
1551    pub fn key(mut self, key: KeyRef) -> ClipPathShape {
1552        self.key = Some(key);
1553        self
1554    }
1555
1556    /// Dart `ClipPath.shape(clipBehavior:)`.
1557    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ClipPathShape {
1558        self.clip_behavior = clip_behavior;
1559        self
1560    }
1561
1562    /// Dart `ClipPath.shape(child:)`.
1563    #[cfg_attr(debug_assertions, track_caller)]
1564    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ClipPathShape {
1565        self.child = Some(child.into_widget());
1566        self
1567    }
1568}
1569
1570/// The kind tag of [`IntoWidget`] for a [`ClipPathShape`].
1571pub struct ClipPathShapeKind;
1572
1573impl IntoWidget<ClipPathShapeKind> for ClipPathShape {
1574    #[cfg_attr(debug_assertions, track_caller)]
1575    fn into_widget(self) -> WidgetRef {
1576        let ClipPathShape {
1577            key,
1578            shape,
1579            clip_behavior,
1580            child,
1581        } = self;
1582        let builder = Builder::new(move |app, context| {
1583            let text_direction = Directionality::maybe_of(app, context);
1584            ClipPath {
1585                key: None,
1586                clipper: Some(Rc::new(ShapeBorderClipper::new(
1587                    shape.clone(),
1588                    text_direction,
1589                ))),
1590                clip_behavior,
1591                child: child.clone(),
1592            }
1593            .into_widget()
1594        });
1595        match key {
1596            Some(key) => builder.key(key).into_widget(),
1597            None => builder.into_widget(),
1598        }
1599    }
1600}
1601
1602/// A widget representing a physical layer that clips its children to a shape.
1603///
1604/// Physical layers cast shadows based on an [`elevation`](Self::elevation) which is nominally
1605/// in logical pixels, coming vertically out of the rendering surface.
1606///
1607/// For shapes that cannot be expressed as a rectangle with rounded corners use
1608/// [`PhysicalShape`].
1609///
1610/// See also:
1611///
1612///  * `DecoratedBox`, which can apply more arbitrary shadow effects.
1613///  * [`ClipRect`], which applies a clip to its child.
1614pub struct PhysicalModel {
1615    pub key: Option<KeyRef>,
1616    /// The type of shape.
1617    pub shape: BoxShape,
1618    /// The content will be clipped (or not) according to this option.
1619    ///
1620    /// Defaults to [`Clip::None`].
1621    pub clip_behavior: Clip,
1622    /// The border radius of the rounded corners.
1623    ///
1624    /// Values are clamped so that horizontal and vertical radii sums do not
1625    /// exceed width/height.
1626    ///
1627    /// This is ignored if the [`shape`](Self::shape) is not [`BoxShape::Rectangle`].
1628    pub border_radius: Option<BorderRadius>,
1629    /// The z-coordinate relative to the parent at which to place this physical
1630    /// object.
1631    ///
1632    /// The value is non-negative.
1633    pub elevation: f64,
1634    /// The background color.
1635    pub color: AnyColor,
1636    /// The shadow color.
1637    pub shadow_color: AnyColor,
1638    /// The widget below this widget in the tree.
1639    pub child: Option<WidgetRef>,
1640}
1641
1642impl PhysicalModel {
1643    /// Creates a physical model with a rounded-rectangular clip; Dart's optional named arguments
1644    /// are the setters.
1645    ///
1646    /// Dart's defaults: `shape` [`BoxShape::Rectangle`], `clip_behavior` [`Clip::None`],
1647    /// `elevation` 0, `shadow_color` opaque black.
1648    pub fn new(color: impl Into<AnyColor>) -> PhysicalModel {
1649        PhysicalModel {
1650            key: None,
1651            shape: BoxShape::Rectangle,
1652            clip_behavior: Clip::None,
1653            border_radius: None,
1654            elevation: 0.0,
1655            color: color.into(),
1656            shadow_color: AnyColor::new(Color::new(0xFF000000)),
1657            child: None,
1658        }
1659    }
1660
1661    /// Dart `PhysicalModel(key:)`.
1662    pub fn key(mut self, key: KeyRef) -> PhysicalModel {
1663        self.key = Some(key);
1664        self
1665    }
1666
1667    /// Dart `PhysicalModel(shape:)`.
1668    pub fn shape(mut self, shape: BoxShape) -> PhysicalModel {
1669        self.shape = shape;
1670        self
1671    }
1672
1673    /// Dart `PhysicalModel(clipBehavior:)`.
1674    pub fn clip_behavior(mut self, clip_behavior: Clip) -> PhysicalModel {
1675        self.clip_behavior = clip_behavior;
1676        self
1677    }
1678
1679    /// Dart `PhysicalModel(borderRadius:)`.
1680    pub fn border_radius(mut self, border_radius: BorderRadius) -> PhysicalModel {
1681        self.border_radius = Some(border_radius);
1682        self
1683    }
1684
1685    /// Dart `PhysicalModel(elevation:)`.
1686    pub fn elevation(mut self, elevation: f64) -> PhysicalModel {
1687        debug_assert!(elevation >= 0.0);
1688        self.elevation = elevation;
1689        self
1690    }
1691
1692    /// Dart `PhysicalModel(shadowColor:)`.
1693    pub fn shadow_color(mut self, shadow_color: impl Into<AnyColor>) -> PhysicalModel {
1694        self.shadow_color = shadow_color.into();
1695        self
1696    }
1697
1698    /// Dart `PhysicalModel(child:)`.
1699    #[cfg_attr(debug_assertions, track_caller)]
1700    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> PhysicalModel {
1701        self.child = Some(child.into_widget());
1702        self
1703    }
1704}
1705
1706impl RenderObjectWidget for PhysicalModel {
1707    type RenderObject = RenderPhysicalModel;
1708
1709    fn key(&self) -> Option<&KeyRef> {
1710        self.key.as_ref()
1711    }
1712
1713    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1714        properties.add(EnumProperty::new("shape", self.shape));
1715        properties.add(DiagnosticsProperty::<BorderRadius>::new(
1716            "borderRadius",
1717            self.border_radius,
1718        ));
1719        properties.add(DoubleProperty::new("elevation", self.elevation));
1720        properties.add(ColorProperty::new("color", self.color.color()));
1721        properties.add(ColorProperty::new("shadowColor", self.shadow_color.color()));
1722    }
1723
1724    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1725        RenderPhysicalModel::new(
1726            app,
1727            None,
1728            self.shape,
1729            self.clip_behavior,
1730            self.border_radius,
1731            self.elevation,
1732            self.color.color(),
1733            self.shadow_color.color(),
1734        )
1735        .as_object()
1736    }
1737
1738    fn update_render_object(
1739        &self,
1740        app: &mut App,
1741        _context: BuildContext,
1742        render_object: RenderHandle<RenderPhysicalModel>,
1743    ) {
1744        render_object.set_shape(app, self.shape);
1745        render_object.set_clip_behavior(app, self.clip_behavior);
1746        render_object.set_border_radius(app, self.border_radius);
1747        render_object.set_elevation(app, self.elevation);
1748        render_object.set_color(app, self.color.color());
1749        render_object.set_shadow_color(app, self.shadow_color.color());
1750    }
1751}
1752
1753impl SingleChildRenderObjectWidget for PhysicalModel {
1754    fn child(&self) -> Option<&WidgetRef> {
1755        self.child.as_ref()
1756    }
1757}
1758
1759impl Debug for PhysicalModel {
1760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1761        f.debug_struct("PhysicalModel")
1762            .field("key", &self.key)
1763            .field("shape", &self.shape)
1764            .field("border_radius", &self.border_radius)
1765            .field("elevation", &self.elevation)
1766            .field("color", &self.color)
1767            .field("shadow_color", &self.shadow_color)
1768            .field("child", &self.child)
1769            .finish()
1770    }
1771}
1772
1773/// A widget representing a physical layer that clips its children to a path.
1774///
1775/// Physical layers cast shadows based on an [`elevation`](Self::elevation) which is nominally
1776/// in logical pixels, coming vertically out of the rendering surface.
1777///
1778/// [`PhysicalModel`] does the same but only supports shapes that can be expressed
1779/// as rectangles with rounded corners.
1780///
1781/// See also:
1782///
1783///  * `ShapeBorderClipper`, which converts a `ShapeBorder` to a [`CustomClipper`], as
1784///    needed by this widget.
1785pub struct PhysicalShape {
1786    pub key: Option<KeyRef>,
1787    /// Determines which clip to use.
1788    ///
1789    /// If the path in question is expressed as a `ShapeBorder` subclass,
1790    /// consider using the `ShapeBorderClipper` delegate class to adapt the
1791    /// shape for use with this widget.
1792    pub clipper: Rc<dyn CustomClipper<Path>>,
1793    /// The content will be clipped (or not) according to this option.
1794    ///
1795    /// Defaults to [`Clip::None`].
1796    pub clip_behavior: Clip,
1797    /// The z-coordinate relative to the parent at which to place this physical
1798    /// object.
1799    ///
1800    /// The value is non-negative.
1801    pub elevation: f64,
1802    /// The background color.
1803    pub color: AnyColor,
1804    /// When elevation is non zero the color to use for the shadow color.
1805    pub shadow_color: AnyColor,
1806    /// The widget below this widget in the tree.
1807    pub child: Option<WidgetRef>,
1808}
1809
1810impl PhysicalShape {
1811    /// Creates a physical model with an arbitrary shape clip; Dart's optional named arguments
1812    /// are the setters.
1813    ///
1814    /// Dart's defaults: `clip_behavior` [`Clip::None`], `elevation` 0, `shadow_color` opaque
1815    /// black.
1816    pub fn new(clipper: Rc<dyn CustomClipper<Path>>, color: impl Into<AnyColor>) -> PhysicalShape {
1817        PhysicalShape {
1818            key: None,
1819            clipper,
1820            clip_behavior: Clip::None,
1821            elevation: 0.0,
1822            color: color.into(),
1823            shadow_color: AnyColor::new(Color::new(0xFF000000)),
1824            child: None,
1825        }
1826    }
1827
1828    /// Dart `PhysicalShape(key:)`.
1829    pub fn key(mut self, key: KeyRef) -> PhysicalShape {
1830        self.key = Some(key);
1831        self
1832    }
1833
1834    /// Dart `PhysicalShape(clipBehavior:)`.
1835    pub fn clip_behavior(mut self, clip_behavior: Clip) -> PhysicalShape {
1836        self.clip_behavior = clip_behavior;
1837        self
1838    }
1839
1840    /// Dart `PhysicalShape(elevation:)`.
1841    pub fn elevation(mut self, elevation: f64) -> PhysicalShape {
1842        debug_assert!(elevation >= 0.0);
1843        self.elevation = elevation;
1844        self
1845    }
1846
1847    /// Dart `PhysicalShape(shadowColor:)`.
1848    pub fn shadow_color(mut self, shadow_color: impl Into<AnyColor>) -> PhysicalShape {
1849        self.shadow_color = shadow_color.into();
1850        self
1851    }
1852
1853    /// Dart `PhysicalShape(child:)`.
1854    #[cfg_attr(debug_assertions, track_caller)]
1855    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> PhysicalShape {
1856        self.child = Some(child.into_widget());
1857        self
1858    }
1859}
1860
1861impl RenderObjectWidget for PhysicalShape {
1862    type RenderObject = RenderPhysicalShape;
1863
1864    fn key(&self) -> Option<&KeyRef> {
1865        self.key.as_ref()
1866    }
1867
1868    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1869        properties.add(DiagnosticsProperty::<String>::new(
1870            "clipper",
1871            Some("Instance of 'CustomClipper<Path>'".to_string()),
1872        ));
1873        properties.add(DoubleProperty::new("elevation", self.elevation));
1874        properties.add(ColorProperty::new("color", self.color.color()));
1875        properties.add(ColorProperty::new("shadowColor", self.shadow_color.color()));
1876    }
1877
1878    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1879        RenderPhysicalShape::new(
1880            app,
1881            None,
1882            Rc::clone(&self.clipper),
1883            self.clip_behavior,
1884            self.elevation,
1885            self.color.color(),
1886            self.shadow_color.color(),
1887        )
1888        .as_object()
1889    }
1890
1891    fn update_render_object(
1892        &self,
1893        app: &mut App,
1894        _context: BuildContext,
1895        render_object: RenderHandle<RenderPhysicalShape>,
1896    ) {
1897        render_object.set_clipper(app, Some(Rc::clone(&self.clipper)));
1898        render_object.set_clip_behavior(app, self.clip_behavior);
1899        render_object.set_elevation(app, self.elevation);
1900        render_object.set_color(app, self.color.color());
1901        render_object.set_shadow_color(app, self.shadow_color.color());
1902    }
1903}
1904
1905impl SingleChildRenderObjectWidget for PhysicalShape {
1906    fn child(&self) -> Option<&WidgetRef> {
1907        self.child.as_ref()
1908    }
1909}
1910
1911impl Debug for PhysicalShape {
1912    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1913        f.debug_struct("PhysicalShape")
1914            .field("key", &self.key)
1915            .field("clipper", &"...")
1916            .field("elevation", &self.elevation)
1917            .field("color", &self.color)
1918            .field("shadow_color", &self.shadow_color)
1919            .field("child", &self.child)
1920            .finish()
1921    }
1922}
1923
1924// POSITIONING AND SIZING NODES
1925
1926/// A widget that applies a transformation before painting its child.
1927///
1928/// Unlike `RotatedBox`, which applies a rotation prior to layout, this object
1929/// applies its transformation just prior to painting, which means the
1930/// transformation is not taken into account when calculating how much space
1931/// this widget's child (and thus this widget) consumes.
1932///
1933/// This example rotates and skews an orange box containing text, keeping the
1934/// top right corner pinned to its original position.
1935///
1936/// ```text
1937/// ColoredBox::new(Color::BLACK).child(
1938///     Transform::new(skew_y)
1939///         .alignment(AlignmentGeometry::TOP_RIGHT)
1940///         .child(Text::new("Apartment for rent!")),
1941/// )
1942/// ```
1943///
1944/// See also:
1945///
1946///  * `RotatedBox`, which rotates the child widget during layout, not just
1947///    during painting.
1948///  * [`FractionalTranslation`], which applies a translation to the child
1949///    that is relative to the child's size.
1950///  * `FittedBox`, which sizes and positions its child widget to fit the parent
1951///    according to a given `BoxFit` discipline.
1952///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
1953///
1954/// Dart's named constructors are the associated functions [`rotate`](Self::rotate),
1955/// [`translate`](Self::translate), [`scale`](Self::scale), and [`flip`](Self::flip).
1956#[derive(Debug)]
1957pub struct Transform {
1958    pub key: Option<KeyRef>,
1959    /// The matrix to transform the child by during painting.
1960    pub transform: Matrix4,
1961    /// The origin of the coordinate system in which to apply the matrix,
1962    /// described relative to the point given by [`alignment`](Self::alignment).
1963    ///
1964    /// Setting an origin is equivalent to conjugating the transform matrix by a
1965    /// translation. This property is provided just for convenience.
1966    ///
1967    /// This offset is applied in addition to any [`alignment`](Self::alignment)
1968    /// transformation, so a [`rotate`](Self::rotate) with no origin turns the child about its
1969    /// center, while `Transform::rotate(PI).origin(Offset::new(75.0, 75.0))` on a 150x150
1970    /// child turns it about its bottom-right corner.
1971    pub origin: Option<Offset>,
1972    /// The alignment of the origin, relative to the size of the box.
1973    ///
1974    /// When this and [`origin`](Self::origin) are both `None`, the origin is the upper-left
1975    /// corner of this render object. The default for this field is `None` for some
1976    /// constructors, and `AlignmentGeometry::CENTER` for others.
1977    ///
1978    /// This is equivalent to setting an origin based on the size of the box.
1979    /// If it is specified at the same time as the [`origin`](Self::origin), both are applied.
1980    ///
1981    /// An `AlignmentDirectional::CENTER_START` value is the same as an `Alignment`
1982    /// whose `x` value is `-1.0` if [`Directionality::of`] returns
1983    /// [`TextDirection::Ltr`], and `1.0` if it returns [`TextDirection::Rtl`]. Similarly
1984    /// `AlignmentDirectional::CENTER_END` is the same as an `Alignment` whose `x` value is
1985    /// `1.0` if [`Directionality::of`] returns [`TextDirection::Ltr`], and `-1.0` if it
1986    /// returns [`TextDirection::Rtl`].
1987    pub alignment: Option<AlignmentGeometry>,
1988    /// Whether to transform registered hits into the child's resulting coordinate system.
1989    ///
1990    /// When `true`, hit coordinates within the parent's bounds are transformed to match
1991    /// where the child appears visually after any transformation such as translation,
1992    /// rotation, scaling, or skewing.
1993    ///
1994    /// When `false`, hit coordinates are not transformed, potentially causing taps to
1995    /// register in a different location relative to the child's visual position.
1996    ///
1997    /// **Important:** Even when [`transform_hit_tests`](Self::transform_hit_tests) is true,
1998    /// children cannot receive events outside the parent's bounds. Hit testing always starts
1999    /// with the parent's own bounds check in `RenderBox::hit_test`. If the pointer is outside
2000    /// the parent's bounds, `RenderBox::hit_test_children` is not invoked and the children are
2001    /// not considered for hit testing.
2002    ///
2003    /// Defaults to true.
2004    pub transform_hit_tests: bool,
2005    /// The filter quality with which to apply the transform as a bitmap operation.
2006    ///
2007    /// The transform will be applied by re-rendering the child if
2008    /// [`filter_quality`](Self::filter_quality) is `None`, otherwise it controls the quality
2009    /// of an `ImageFilter.matrix` applied to a bitmap rendering of the child.
2010    pub filter_quality: Option<FilterQuality>,
2011    pub child: Option<WidgetRef>,
2012}
2013
2014impl Transform {
2015    /// Creates a widget that transforms its child; Dart's optional named arguments are the
2016    /// setters.
2017    pub fn new(transform: Matrix4) -> Transform {
2018        Transform {
2019            key: None,
2020            transform,
2021            origin: None,
2022            alignment: None,
2023            transform_hit_tests: true,
2024            filter_quality: None,
2025            child: None,
2026        }
2027    }
2028
2029    /// Creates a widget that transforms its child using a rotation around the
2030    /// center.
2031    ///
2032    /// The `angle` argument gives the rotation in clockwise radians.
2033    ///
2034    /// See also:
2035    ///
2036    ///  * `RotationTransition`, which animates changes in rotation smoothly
2037    ///    over a given duration.
2038    pub fn rotate(angle: f64) -> Transform {
2039        Transform::new(Transform::compute_rotation(angle)).alignment(AlignmentGeometry::CENTER)
2040    }
2041
2042    /// Creates a widget that transforms its child using a translation.
2043    ///
2044    /// The `offset` argument specifies the translation.
2045    pub fn translate(offset: Offset) -> Transform {
2046        Transform::new(Matrix4::translation(offset.dx() as f32, offset.dy() as f32))
2047    }
2048
2049    /// Creates a widget that scales its child along the 2D plane.
2050    ///
2051    /// The `scale_x` argument provides the scalar by which to multiply the `x`
2052    /// axis, and the `scale_y` argument provides the scalar by which to multiply
2053    /// the `y` axis. Either may be `None`, in which case the scaling factor for
2054    /// that axis defaults to 1.0.
2055    ///
2056    /// For convenience, to scale the child uniformly, instead of providing
2057    /// `scale_x` and `scale_y`, the `scale` parameter may be used.
2058    ///
2059    /// At least one of `scale`, `scale_x`, and `scale_y` must be non-`None`. If
2060    /// `scale` is provided, the other two must be `None`.
2061    ///
2062    /// The [`alignment`](Self::alignment) controls the origin of the scale; by default, this
2063    /// is the center of the box.
2064    ///
2065    /// See also:
2066    ///
2067    ///  * `ScaleTransition`, which animates changes in scale smoothly over a given
2068    ///    duration.
2069    pub fn scale(scale: Option<f64>, scale_x: Option<f64>, scale_y: Option<f64>) -> Transform {
2070        debug_assert!(
2071            !(scale.is_none() && scale_x.is_none() && scale_y.is_none()),
2072            "At least one of 'scale', 'scale_x' and 'scale_y' is required to be non-None"
2073        );
2074        debug_assert!(
2075            scale.is_none() || (scale_x.is_none() && scale_y.is_none()),
2076            "If 'scale' is non-None then 'scale_x' and 'scale_y' must be left None"
2077        );
2078        let transform = Matrix4::scale(
2079            scale.or(scale_x).unwrap_or(1.0) as f32,
2080            scale.or(scale_y).unwrap_or(1.0) as f32,
2081        );
2082        Transform::new(transform).alignment(AlignmentGeometry::CENTER)
2083    }
2084
2085    /// Creates a widget that mirrors its child about the widget's center point.
2086    ///
2087    /// If `flip_x` is true, the child widget will be flipped horizontally.
2088    ///
2089    /// If `flip_y` is true, the child widget will be flipped vertically.
2090    ///
2091    /// If both are true, the child widget will be flipped both vertically and
2092    /// horizontally, equivalent to a 180 degree rotation.
2093    pub fn flip(flip_x: bool, flip_y: bool) -> Transform {
2094        let transform = Matrix4::scale(
2095            if flip_x { -1.0 } else { 1.0 },
2096            if flip_y { -1.0 } else { 1.0 },
2097        );
2098        Transform::new(transform).alignment(AlignmentGeometry::CENTER)
2099    }
2100
2101    /// Dart `Transform(key:)`.
2102    pub fn key(mut self, key: KeyRef) -> Transform {
2103        self.key = Some(key);
2104        self
2105    }
2106
2107    /// Dart `Transform(origin:)`.
2108    pub fn origin(mut self, origin: Offset) -> Transform {
2109        self.origin = Some(origin);
2110        self
2111    }
2112
2113    /// Dart `Transform(alignment:)`.
2114    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Transform {
2115        self.alignment = Some(alignment);
2116        self
2117    }
2118
2119    /// Dart `Transform(transformHitTests:)`.
2120    pub fn transform_hit_tests(mut self, transform_hit_tests: bool) -> Transform {
2121        self.transform_hit_tests = transform_hit_tests;
2122        self
2123    }
2124
2125    /// Dart `Transform(filterQuality:)`.
2126    pub fn filter_quality(mut self, filter_quality: FilterQuality) -> Transform {
2127        self.filter_quality = Some(filter_quality);
2128        self
2129    }
2130
2131    /// Dart `Transform(child:)`.
2132    #[cfg_attr(debug_assertions, track_caller)]
2133    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Transform {
2134        self.child = Some(child.into_widget());
2135        self
2136    }
2137
2138    /// Computes a rotation matrix for an angle in radians, attempting to keep rotations
2139    /// at integral values for angles of 0, π/2, π, 3π/2.
2140    fn compute_rotation(radians: f64) -> Matrix4 {
2141        debug_assert!(
2142            radians.is_finite(),
2143            "Cannot compute the rotation matrix for a non-finite angle: {radians}"
2144        );
2145        if radians == 0.0 {
2146            return Matrix4::IDENTITY;
2147        }
2148        let sin = radians.sin();
2149        if sin == 1.0 {
2150            return Transform::create_z_rotation(1.0, 0.0);
2151        }
2152        if sin == -1.0 {
2153            return Transform::create_z_rotation(-1.0, 0.0);
2154        }
2155        let cos = radians.cos();
2156        if cos == -1.0 {
2157            return Transform::create_z_rotation(0.0, -1.0);
2158        }
2159        Transform::create_z_rotation(sin, cos)
2160    }
2161
2162    fn create_z_rotation(sin: f64, cos: f64) -> Matrix4 {
2163        let (sin, cos) = (sin as f32, cos as f32);
2164        #[rustfmt::skip]
2165        let rotation = Matrix4::from_flutter_array(&[
2166            cos, sin, 0.0, 0.0,
2167            -sin, cos, 0.0, 0.0,
2168            0.0, 0.0, 1.0, 0.0,
2169            0.0, 0.0, 0.0, 1.0,
2170        ]);
2171        rotation
2172    }
2173}
2174
2175impl RenderObjectWidget for Transform {
2176    type RenderObject = RenderTransform;
2177
2178    fn key(&self) -> Option<&KeyRef> {
2179        self.key.as_ref()
2180    }
2181
2182    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2183        let text_direction = Directionality::maybe_of(app, context);
2184        RenderTransform::new(
2185            app,
2186            self.transform,
2187            self.origin,
2188            self.alignment,
2189            text_direction,
2190            self.transform_hit_tests,
2191            self.filter_quality,
2192            None,
2193        )
2194        .as_object()
2195    }
2196
2197    fn update_render_object(
2198        &self,
2199        app: &mut App,
2200        context: BuildContext,
2201        render_object: RenderHandle<RenderTransform>,
2202    ) {
2203        render_object.set_transform(app, self.transform);
2204        render_object.set_origin(app, self.origin);
2205        render_object.set_alignment(app, self.alignment);
2206        let text_direction = Directionality::maybe_of(app, context);
2207        render_object.set_text_direction(app, text_direction);
2208        render_object.set_transform_hit_tests(app, self.transform_hit_tests);
2209        render_object.set_filter_quality(app, self.filter_quality);
2210    }
2211}
2212
2213impl SingleChildRenderObjectWidget for Transform {
2214    fn child(&self) -> Option<&WidgetRef> {
2215        self.child.as_ref()
2216    }
2217}
2218
2219/// Scales and positions its child within itself according to [`fit`](Self::fit).
2220///
2221/// See also:
2222///
2223/// * [`Transform`], which applies an arbitrary transform to its child widget at
2224///   paint time.
2225/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2226#[derive(Debug)]
2227pub struct FittedBox {
2228    pub key: Option<KeyRef>,
2229    /// How to inscribe the child into the space allocated during layout.
2230    pub fit: BoxFit,
2231    /// How to align the child within its parent's bounds.
2232    ///
2233    /// An alignment of (-1.0, -1.0) aligns the child to the top-left corner of its
2234    /// parent's bounds. An alignment of (1.0, 0.0) aligns the child to the middle
2235    /// of the right edge of its parent's bounds.
2236    ///
2237    /// Defaults to `AlignmentGeometry::CENTER`.
2238    ///
2239    /// See also:
2240    ///
2241    ///  * `Alignment`, a class with convenient constants typically used to
2242    ///    specify an `AlignmentGeometry`.
2243    ///  * `AlignmentDirectional`, like `Alignment` for specifying alignments
2244    ///    relative to text direction.
2245    pub alignment: AlignmentGeometry,
2246    /// How to clip a child that overflows this box.
2247    ///
2248    /// Defaults to [`Clip::None`].
2249    pub clip_behavior: Clip,
2250    pub child: Option<WidgetRef>,
2251}
2252
2253impl FittedBox {
2254    /// Creates a widget that scales and positions its child within itself according to
2255    /// [`fit`](Self::fit); Dart's named arguments are the setters.
2256    pub fn new() -> FittedBox {
2257        FittedBox::default()
2258    }
2259
2260    /// Dart `FittedBox(key:)`.
2261    pub fn key(mut self, key: KeyRef) -> FittedBox {
2262        self.key = Some(key);
2263        self
2264    }
2265
2266    /// Dart `FittedBox(fit:)`.
2267    pub fn fit(mut self, fit: BoxFit) -> FittedBox {
2268        self.fit = fit;
2269        self
2270    }
2271
2272    /// Dart `FittedBox(alignment:)`.
2273    pub fn alignment(mut self, alignment: AlignmentGeometry) -> FittedBox {
2274        self.alignment = alignment;
2275        self
2276    }
2277
2278    /// Dart `FittedBox(clipBehavior:)`.
2279    pub fn clip_behavior(mut self, clip_behavior: Clip) -> FittedBox {
2280        self.clip_behavior = clip_behavior;
2281        self
2282    }
2283
2284    /// Dart `FittedBox(child:)`.
2285    #[cfg_attr(debug_assertions, track_caller)]
2286    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FittedBox {
2287        self.child = Some(child.into_widget());
2288        self
2289    }
2290}
2291
2292impl Default for FittedBox {
2293    fn default() -> FittedBox {
2294        FittedBox {
2295            key: None,
2296            fit: BoxFit::Contain,
2297            alignment: AlignmentGeometry::CENTER,
2298            clip_behavior: Clip::None,
2299            child: None,
2300        }
2301    }
2302}
2303
2304impl RenderObjectWidget for FittedBox {
2305    type RenderObject = RenderFittedBox;
2306
2307    fn key(&self) -> Option<&KeyRef> {
2308        self.key.as_ref()
2309    }
2310
2311    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2312        properties.add(EnumProperty::new("fit", self.fit));
2313        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
2314    }
2315
2316    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2317        let text_direction = Directionality::maybe_of(app, context);
2318        let render_object =
2319            RenderFittedBox::new(app, self.fit, self.alignment, text_direction, None);
2320        render_object.set_clip_behavior(app, self.clip_behavior);
2321        render_object.as_object()
2322    }
2323
2324    fn update_render_object(
2325        &self,
2326        app: &mut App,
2327        context: BuildContext,
2328        render_object: RenderHandle<RenderFittedBox>,
2329    ) {
2330        render_object.set_fit(app, self.fit);
2331        render_object.set_alignment(app, self.alignment);
2332        let text_direction = Directionality::maybe_of(app, context);
2333        render_object.set_text_direction(app, text_direction);
2334        render_object.set_clip_behavior(app, self.clip_behavior);
2335    }
2336}
2337
2338impl SingleChildRenderObjectWidget for FittedBox {
2339    fn child(&self) -> Option<&WidgetRef> {
2340        self.child.as_ref()
2341    }
2342}
2343
2344/// Applies a translation transformation before painting its child.
2345///
2346/// The translation is expressed as an [`Offset`] scaled to the child's size. For
2347/// example, an [`Offset`] with a `dx` of 0.25 will result in a horizontal
2348/// translation of one quarter the width of the child.
2349///
2350/// Hit tests will only be detected inside the bounds of the
2351/// [`FractionalTranslation`], even if the contents are offset such that
2352/// they overflow.
2353///
2354/// See also:
2355///
2356///  * [`Transform`], which applies an arbitrary transform to its child widget at
2357///    paint time.
2358///  * [`Transform::translate`], which applies an absolute offset translation
2359///    transformation instead of an offset scaled to the child.
2360///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2361#[derive(Debug)]
2362pub struct FractionalTranslation {
2363    pub key: Option<KeyRef>,
2364    /// The translation to apply to the child, scaled to the child's size.
2365    ///
2366    /// For example, an [`Offset`] with a `dx` of 0.25 will result in a horizontal
2367    /// translation of one quarter the width of the child.
2368    pub translation: Offset,
2369    /// Whether to apply the translation when performing hit tests.
2370    pub transform_hit_tests: bool,
2371    pub child: Option<WidgetRef>,
2372}
2373
2374impl FractionalTranslation {
2375    /// Creates a widget that translates its child's painting; Dart's optional named
2376    /// arguments are the setters.
2377    pub fn new(translation: Offset) -> FractionalTranslation {
2378        FractionalTranslation {
2379            key: None,
2380            translation,
2381            transform_hit_tests: true,
2382            child: None,
2383        }
2384    }
2385
2386    /// Dart `FractionalTranslation(key:)`.
2387    pub fn key(mut self, key: KeyRef) -> FractionalTranslation {
2388        self.key = Some(key);
2389        self
2390    }
2391
2392    /// Dart `FractionalTranslation(transformHitTests:)`.
2393    pub fn transform_hit_tests(mut self, transform_hit_tests: bool) -> FractionalTranslation {
2394        self.transform_hit_tests = transform_hit_tests;
2395        self
2396    }
2397
2398    /// Dart `FractionalTranslation(child:)`.
2399    #[cfg_attr(debug_assertions, track_caller)]
2400    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FractionalTranslation {
2401        self.child = Some(child.into_widget());
2402        self
2403    }
2404}
2405
2406impl RenderObjectWidget for FractionalTranslation {
2407    type RenderObject = RenderFractionalTranslation;
2408
2409    fn key(&self) -> Option<&KeyRef> {
2410        self.key.as_ref()
2411    }
2412
2413    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2414        RenderFractionalTranslation::new(app, self.translation, self.transform_hit_tests, None)
2415            .as_object()
2416    }
2417
2418    fn update_render_object(
2419        &self,
2420        app: &mut App,
2421        _context: BuildContext,
2422        render_object: RenderHandle<RenderFractionalTranslation>,
2423    ) {
2424        render_object.set_translation(app, self.translation);
2425        render_object.set_transform_hit_tests(app, self.transform_hit_tests);
2426    }
2427}
2428
2429impl SingleChildRenderObjectWidget for FractionalTranslation {
2430    fn child(&self) -> Option<&WidgetRef> {
2431        self.child.as_ref()
2432    }
2433}
2434
2435/// A widget that insets its child by the given padding.
2436///
2437/// When passing layout constraints to its child, padding shrinks the
2438/// constraints by the given padding, causing the child to layout at a smaller
2439/// size. Padding then sizes itself to its child's size, inflated by the
2440/// padding, effectively creating empty space around the child.
2441///
2442/// This snippet creates "Hello World!" `Text` inside a `Card` that is indented
2443/// by sixteen pixels in each direction.
2444///
2445/// ```text
2446/// Card {
2447///   child: Padding {
2448///     padding: EdgeInsetsGeometry::all(16.0),
2449///     child: Some(Text("Hello World!")),
2450///     ..Default::default()
2451///   },
2452/// }
2453/// ```
2454///
2455/// ## Design discussion
2456///
2457/// ### Why use a [`Padding`] widget rather than a `Container` with `Container.padding`?
2458///
2459/// There isn't really any difference between the two. If you supply a
2460/// `Container.padding` argument, `Container` builds a [`Padding`] widget
2461/// for you.
2462///
2463/// `Container` doesn't implement its properties directly. Instead, `Container`
2464/// combines a number of simpler widgets together into a convenient package. For
2465/// example, the `Container.padding` property causes the container to build a
2466/// [`Padding`] widget and the `Container.decoration` property causes the
2467/// container to build a [`DecoratedBox`](crate::DecoratedBox) widget. If you find `Container`
2468/// convenient, feel free to use it. If not, feel free to build these simpler
2469/// widgets in whatever combination meets your needs.
2470///
2471/// In fact, the majority of widgets in Flutter are combinations of other
2472/// simpler widgets. Composition, rather than inheritance, is the primary
2473/// mechanism for building up widgets.
2474///
2475/// See also:
2476///
2477///  * `EdgeInsets`, the class that is used to describe the padding dimensions.
2478///  * `AnimatedPadding`, which animates changes in [`padding`](Self::padding) over a given
2479///    duration.
2480///  * `SliverPadding`, the sliver equivalent of this widget.
2481///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2482#[derive(Debug)]
2483pub struct Padding {
2484    pub key: Option<KeyRef>,
2485    /// The amount of space by which to inset the child.
2486    pub padding: EdgeInsetsGeometry,
2487    pub child: Option<WidgetRef>,
2488}
2489
2490impl Padding {
2491    /// Creates a `Padding`; Dart's optional named arguments are the setters.
2492    pub fn new(padding: impl Into<EdgeInsetsGeometry>) -> Padding {
2493        let padding = padding.into();
2494        Padding {
2495            key: None,
2496            padding,
2497            child: None,
2498        }
2499    }
2500
2501    /// Dart `Padding(key:)`.
2502    pub fn key(mut self, key: KeyRef) -> Padding {
2503        self.key = Some(key);
2504        self
2505    }
2506
2507    /// Dart `Padding(child:)`.
2508    #[cfg_attr(debug_assertions, track_caller)]
2509    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Padding {
2510        self.child = Some(child.into_widget());
2511        self
2512    }
2513}
2514
2515impl RenderObjectWidget for Padding {
2516    type RenderObject = RenderPadding;
2517
2518    fn key(&self) -> Option<&KeyRef> {
2519        self.key.as_ref()
2520    }
2521
2522    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2523        properties.add(DiagnosticsProperty::new("padding", self.padding));
2524    }
2525
2526    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2527        let text_direction = Directionality::maybe_of(app, context);
2528        RenderPadding::new(app, self.padding, text_direction, None).as_object()
2529    }
2530
2531    fn update_render_object(
2532        &self,
2533        app: &mut App,
2534        context: BuildContext,
2535        render_object: RenderHandle<RenderPadding>,
2536    ) {
2537        render_object.set_padding(app, self.padding);
2538        let text_direction = Directionality::maybe_of(app, context);
2539        render_object.set_text_direction(app, text_direction);
2540    }
2541}
2542
2543impl SingleChildRenderObjectWidget for Padding {
2544    fn child(&self) -> Option<&WidgetRef> {
2545        self.child.as_ref()
2546    }
2547}
2548
2549/// A widget that aligns its child within itself and optionally sizes itself
2550/// based on the child's size.
2551///
2552/// For example, to align a box at the bottom right, you would pass this box a
2553/// tight constraint that is bigger than the child's natural size,
2554/// with an alignment of `Alignment::BOTTOM_RIGHT`.
2555///
2556/// This widget will be as big as possible if its dimensions are constrained and
2557/// [`width_factor`](Self::width_factor) and [`height_factor`](Self::height_factor) are
2558/// `None`. If a dimension is unconstrained and the corresponding size factor is `None` then
2559/// the widget will match its child's size in that dimension. If a size factor is non-`None`
2560/// then the corresponding dimension of this widget will be the product of the child's
2561/// dimension and the size factor. For example if `width_factor` is 2.0 then
2562/// the width of this widget will always be twice its child's width.
2563///
2564/// ## How it works
2565///
2566/// The [`alignment`](Self::alignment) property describes a point in the `child`'s coordinate
2567/// system and a different point in the coordinate system of this widget. The [`Align`]
2568/// widget positions the `child` such that both points are lined up on top of
2569/// each other.
2570///
2571/// See also:
2572///
2573///  * `AnimatedAlign`, which animates changes in [`alignment`](Self::alignment) smoothly
2574///    over a given duration.
2575///  * `CustomSingleChildLayout`, which uses a delegate to control the layout of
2576///    a single child.
2577///  * [`Center`], which is the same as [`Align`] but with the
2578///    [`alignment`](Self::alignment) always set to `Alignment::CENTER`.
2579///  * `FractionallySizedBox`, which sizes its child based on a fraction of its
2580///    own size and positions the child according to an `Alignment` value.
2581///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2582#[derive(Debug)]
2583pub struct Align {
2584    pub key: Option<KeyRef>,
2585    /// How to align the child.
2586    ///
2587    /// The x and y values of the `Alignment` control the horizontal and vertical
2588    /// alignment, respectively. An x value of -1.0 means that the left edge of
2589    /// the child is aligned with the left edge of the parent whereas an x value
2590    /// of 1.0 means that the right edge of the child is aligned with the right
2591    /// edge of the parent. Other values interpolate (and extrapolate) linearly.
2592    /// For example, a value of 0.0 means that the center of the child is aligned
2593    /// with the center of the parent.
2594    ///
2595    /// Defaults to `AlignmentGeometry::CENTER`.
2596    ///
2597    /// See also:
2598    ///
2599    ///  * `Alignment`, which has more details and some convenience constants for
2600    ///    common positions.
2601    ///  * `AlignmentDirectional`, which has a horizontal coordinate orientation
2602    ///    that depends on the [`TextDirection`].
2603    pub alignment: AlignmentGeometry,
2604    /// If non-`None`, sets its width to the child's width multiplied by this factor.
2605    ///
2606    /// Can be both greater and less than 1.0 but must be non-negative.
2607    pub width_factor: Option<f64>,
2608    /// If non-`None`, sets its height to the child's height multiplied by this factor.
2609    ///
2610    /// Can be both greater and less than 1.0 but must be non-negative.
2611    pub height_factor: Option<f64>,
2612    pub child: Option<WidgetRef>,
2613}
2614
2615impl Align {
2616    /// Creates a `Align`; Dart's named arguments are the setters.
2617    pub fn new() -> Align {
2618        Align::default()
2619    }
2620
2621    /// Dart `Align(key:)`.
2622    pub fn key(mut self, key: KeyRef) -> Align {
2623        self.key = Some(key);
2624        self
2625    }
2626
2627    /// Dart `Align(alignment:)`.
2628    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Align {
2629        self.alignment = alignment;
2630        self
2631    }
2632
2633    /// Dart `Align(width_factor:)`.
2634    pub fn width_factor(mut self, width_factor: f64) -> Align {
2635        self.width_factor = Some(width_factor);
2636        self
2637    }
2638
2639    /// Dart `Align(height_factor:)`.
2640    pub fn height_factor(mut self, height_factor: f64) -> Align {
2641        self.height_factor = Some(height_factor);
2642        self
2643    }
2644
2645    /// Dart `Align(child:)`.
2646    #[cfg_attr(debug_assertions, track_caller)]
2647    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Align {
2648        self.child = Some(child.into_widget());
2649        self
2650    }
2651
2652    /// Dart's `Align.debugFillProperties`, which [`Center`] inherits.
2653    fn fill_properties(
2654        alignment: AlignmentGeometry,
2655        width_factor: Option<f64>,
2656        height_factor: Option<f64>,
2657        properties: &mut DiagnosticPropertiesBuilder,
2658    ) {
2659        properties.add(DiagnosticsProperty::new("alignment", alignment));
2660        properties.add(DoubleProperty::new("widthFactor", width_factor).default_value(None));
2661        properties.add(DoubleProperty::new("heightFactor", height_factor).default_value(None));
2662    }
2663
2664    /// `Align.createRenderObject`'s body, shared with [`Center`].
2665    fn create_positioned_box(
2666        app: &mut App,
2667        context: BuildContext,
2668        alignment: AlignmentGeometry,
2669        width_factor: Option<f64>,
2670        height_factor: Option<f64>,
2671    ) -> AnyRenderObject {
2672        let text_direction = Directionality::maybe_of(app, context);
2673        RenderPositionedBox::new(
2674            app,
2675            alignment,
2676            text_direction,
2677            width_factor,
2678            height_factor,
2679            None,
2680        )
2681        .as_object()
2682    }
2683
2684    /// `Align.updateRenderObject`'s body, shared with [`Center`].
2685    fn update_positioned_box(
2686        app: &mut App,
2687        context: BuildContext,
2688        render_object: RenderHandle<RenderPositionedBox>,
2689        alignment: AlignmentGeometry,
2690        width_factor: Option<f64>,
2691        height_factor: Option<f64>,
2692    ) {
2693        render_object.set_alignment(app, alignment);
2694        render_object.set_width_factor(app, width_factor);
2695        render_object.set_height_factor(app, height_factor);
2696        let text_direction = Directionality::maybe_of(app, context);
2697        render_object.set_text_direction(app, text_direction);
2698    }
2699}
2700
2701impl Default for Align {
2702    fn default() -> Align {
2703        Align {
2704            key: None,
2705            alignment: AlignmentGeometry::CENTER,
2706            width_factor: None,
2707            height_factor: None,
2708            child: None,
2709        }
2710    }
2711}
2712
2713impl RenderObjectWidget for Align {
2714    type RenderObject = RenderPositionedBox;
2715
2716    fn key(&self) -> Option<&KeyRef> {
2717        self.key.as_ref()
2718    }
2719
2720    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2721        Align::fill_properties(
2722            self.alignment,
2723            self.width_factor,
2724            self.height_factor,
2725            properties,
2726        );
2727    }
2728
2729    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2730        Align::create_positioned_box(
2731            app,
2732            context,
2733            self.alignment,
2734            self.width_factor,
2735            self.height_factor,
2736        )
2737    }
2738
2739    fn update_render_object(
2740        &self,
2741        app: &mut App,
2742        context: BuildContext,
2743        render_object: RenderHandle<RenderPositionedBox>,
2744    ) {
2745        Align::update_positioned_box(
2746            app,
2747            context,
2748            render_object,
2749            self.alignment,
2750            self.width_factor,
2751            self.height_factor,
2752        );
2753    }
2754}
2755
2756impl SingleChildRenderObjectWidget for Align {
2757    fn child(&self) -> Option<&WidgetRef> {
2758        self.child.as_ref()
2759    }
2760}
2761
2762/// A widget that centers its child within itself.
2763///
2764/// This widget will be as big as possible if its dimensions are constrained and
2765/// [`width_factor`](Self::width_factor) and [`height_factor`](Self::height_factor) are
2766/// `None`. If a dimension is unconstrained and the corresponding size factor is `None` then
2767/// the widget will match its child's size in that dimension. If a size factor is non-`None`
2768/// then the corresponding dimension of this widget will be the product of the child's
2769/// dimension and the size factor. For example if `width_factor` is 2.0 then
2770/// the width of this widget will always be twice its child's width.
2771///
2772/// See also:
2773///
2774///  * [`Align`], which lets you arbitrarily position a child within itself,
2775///    rather than just centering it.
2776///  * `Row`, a widget that displays its children in a horizontal array.
2777///  * `Column`, a widget that displays its children in a vertical array.
2778///  * `Container`, a convenience widget that combines common painting,
2779///    positioning, and sizing widgets.
2780///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2781///
2782/// Dart's `class Center extends Align`: a distinct widget type whose behaviour is
2783/// [`Align`]'s with the alignment fixed at `AlignmentGeometry::CENTER`.
2784#[derive(Debug, Default)]
2785pub struct Center {
2786    pub key: Option<KeyRef>,
2787    /// See [`Align::width_factor`].
2788    pub width_factor: Option<f64>,
2789    /// See [`Align::height_factor`].
2790    pub height_factor: Option<f64>,
2791    pub child: Option<WidgetRef>,
2792}
2793
2794impl Center {
2795    /// Creates a `Center`; Dart's named arguments are the setters.
2796    pub fn new() -> Center {
2797        Center::default()
2798    }
2799
2800    /// Dart `Center(key:)`.
2801    pub fn key(mut self, key: KeyRef) -> Center {
2802        self.key = Some(key);
2803        self
2804    }
2805
2806    /// Dart `Center(width_factor:)`.
2807    pub fn width_factor(mut self, width_factor: f64) -> Center {
2808        self.width_factor = Some(width_factor);
2809        self
2810    }
2811
2812    /// Dart `Center(height_factor:)`.
2813    pub fn height_factor(mut self, height_factor: f64) -> Center {
2814        self.height_factor = Some(height_factor);
2815        self
2816    }
2817
2818    /// Dart `Center(child:)`.
2819    #[cfg_attr(debug_assertions, track_caller)]
2820    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Center {
2821        self.child = Some(child.into_widget());
2822        self
2823    }
2824
2825    /// How to align the child: always `AlignmentGeometry::CENTER` (the inherited
2826    /// [`Align::alignment`]).
2827    pub fn alignment(&self) -> AlignmentGeometry {
2828        AlignmentGeometry::CENTER
2829    }
2830}
2831
2832impl RenderObjectWidget for Center {
2833    type RenderObject = RenderPositionedBox;
2834
2835    fn key(&self) -> Option<&KeyRef> {
2836        self.key.as_ref()
2837    }
2838
2839    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2840        Align::fill_properties(
2841            self.alignment(),
2842            self.width_factor,
2843            self.height_factor,
2844            properties,
2845        );
2846    }
2847
2848    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2849        Align::create_positioned_box(
2850            app,
2851            context,
2852            self.alignment(),
2853            self.width_factor,
2854            self.height_factor,
2855        )
2856    }
2857
2858    fn update_render_object(
2859        &self,
2860        app: &mut App,
2861        context: BuildContext,
2862        render_object: RenderHandle<RenderPositionedBox>,
2863    ) {
2864        Align::update_positioned_box(
2865            app,
2866            context,
2867            render_object,
2868            self.alignment(),
2869            self.width_factor,
2870            self.height_factor,
2871        );
2872    }
2873}
2874
2875impl SingleChildRenderObjectWidget for Center {
2876    fn child(&self) -> Option<&WidgetRef> {
2877        self.child.as_ref()
2878    }
2879}
2880
2881/// A widget that defers the layout of its single child to a delegate.
2882///
2883/// The delegate can determine the layout constraints for the child and can decide where to
2884/// position the child. The delegate can also determine the size of the parent, but the size of
2885/// the parent cannot depend on the size of the child.
2886///
2887/// See also:
2888///
2889///  * [`SingleChildLayoutDelegate`], which controls the layout of the child.
2890///  * [`Align`], which sizes itself based on its child's size and positions the child according
2891///    to an [`Alignment`] value.
2892///  * `FractionallySizedBox`, which sizes its child based on a fraction of its own size and
2893///    positions the child according to an [`Alignment`] value.
2894///  * [`CustomMultiChildLayout`], which uses a delegate to position multiple children.
2895///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
2896#[derive(Debug)]
2897pub struct CustomSingleChildLayout {
2898    pub key: Option<KeyRef>,
2899    /// The delegate that controls the layout of the child.
2900    pub delegate: Rc<dyn SingleChildLayoutDelegate>,
2901    pub child: Option<WidgetRef>,
2902}
2903
2904impl CustomSingleChildLayout {
2905    /// Creates a custom single child layout; Dart's optional named arguments are the setters.
2906    pub fn new(delegate: Rc<dyn SingleChildLayoutDelegate>) -> CustomSingleChildLayout {
2907        CustomSingleChildLayout {
2908            key: None,
2909            delegate,
2910            child: None,
2911        }
2912    }
2913
2914    /// Dart `CustomSingleChildLayout(key:)`.
2915    pub fn key(mut self, key: KeyRef) -> CustomSingleChildLayout {
2916        self.key = Some(key);
2917        self
2918    }
2919
2920    /// Dart `CustomSingleChildLayout(child:)`.
2921    #[cfg_attr(debug_assertions, track_caller)]
2922    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CustomSingleChildLayout {
2923        self.child = Some(child.into_widget());
2924        self
2925    }
2926}
2927
2928impl RenderObjectWidget for CustomSingleChildLayout {
2929    type RenderObject = RenderCustomSingleChildLayoutBox;
2930
2931    fn key(&self) -> Option<&KeyRef> {
2932        self.key.as_ref()
2933    }
2934
2935    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2936        RenderCustomSingleChildLayoutBox::new(app, Rc::clone(&self.delegate), None).as_object()
2937    }
2938
2939    fn update_render_object(
2940        &self,
2941        app: &mut App,
2942        _context: BuildContext,
2943        render_object: RenderHandle<RenderCustomSingleChildLayoutBox>,
2944    ) {
2945        render_object.set_delegate(app, Rc::clone(&self.delegate));
2946    }
2947}
2948
2949impl SingleChildRenderObjectWidget for CustomSingleChildLayout {
2950    fn child(&self) -> Option<&WidgetRef> {
2951        self.child.as_ref()
2952    }
2953}
2954
2955/// Metadata for identifying children in a [`CustomMultiChildLayout`].
2956///
2957/// [`MultiChildLayoutChildren::has_child`](waft_rendering::MultiChildLayoutChildren::has_child),
2958/// [`layout_child`](waft_rendering::MultiChildLayoutChildren::layout_child) and
2959/// [`position_child`](waft_rendering::MultiChildLayoutChildren::position_child) use these
2960/// identifiers.
2961#[derive(Debug)]
2962pub struct LayoutId {
2963    /// Dart's `key ?? ValueKey<Object>(id)`; the id is already a key here.
2964    pub key: KeyRef,
2965    /// An object representing the identity of this child.
2966    ///
2967    /// The [`id`](Self::id) needs to be unique among the children that the
2968    /// [`CustomMultiChildLayout`] manages.
2969    pub id: ChildLayoutId,
2970    pub child: WidgetRef,
2971}
2972
2973impl LayoutId {
2974    /// Marks a child with a layout identifier.
2975    #[cfg_attr(debug_assertions, track_caller)]
2976    pub fn new<K>(id: ChildLayoutId, child: impl IntoWidget<K>) -> LayoutId {
2977        LayoutId {
2978            key: KeyRef::Local(Rc::clone(&id)),
2979            id,
2980            child: child.into_widget(),
2981        }
2982    }
2983
2984    /// Dart `LayoutId(key:)`.
2985    pub fn key(mut self, key: KeyRef) -> LayoutId {
2986        self.key = key;
2987        self
2988    }
2989}
2990
2991impl ParentDataWidget for LayoutId {
2992    type ParentData = MultiChildLayoutParentData;
2993
2994    fn key(&self) -> Option<&KeyRef> {
2995        Some(&self.key)
2996    }
2997
2998    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2999        properties.add(DiagnosticsProperty::<String>::new(
3000            "id",
3001            Some(format!("{:?}", self.id)),
3002        ));
3003    }
3004
3005    fn child(&self) -> &WidgetRef {
3006        &self.child
3007    }
3008
3009    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
3010        debug_assert!(render_object.parent_data_is::<MultiChildLayoutParentData>(app));
3011        let parent_data = render_object.parent_data_of_mut::<MultiChildLayoutParentData>(app);
3012        if parent_data.id.as_ref() != Some(&self.id) {
3013            parent_data.id = Some(Rc::clone(&self.id));
3014            if let Some(parent) = render_object.parent(app) {
3015                parent.mark_needs_layout(app);
3016            }
3017        }
3018    }
3019}
3020
3021/// A widget that uses a delegate to size and position multiple children.
3022///
3023/// The delegate can determine the layout constraints for each child and can decide where to
3024/// position each child. The delegate can also determine the size of the parent, but the size of
3025/// the parent cannot depend on the sizes of the children.
3026///
3027/// [`CustomMultiChildLayout`] is appropriate when there are complex relationships between the
3028/// size and positioning of multiple widgets. For simple cases, such as aligning a widget to one
3029/// or another edge, the [`Stack`] widget is more appropriate.
3030///
3031/// Each child must be wrapped in a [`LayoutId`] widget to identify the widget for the delegate.
3032///
3033/// See also:
3034///
3035///  * [`MultiChildLayoutDelegate`], for details about how to control the layout of the
3036///    children.
3037///  * [`Stack`], which arranges children relative to the edges of the container.
3038///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
3039#[derive(Debug)]
3040pub struct CustomMultiChildLayout {
3041    pub key: Option<KeyRef>,
3042    /// The delegate that controls the layout of the children.
3043    pub delegate: Rc<dyn MultiChildLayoutDelegate>,
3044    pub children: Vec<WidgetRef>,
3045}
3046
3047impl CustomMultiChildLayout {
3048    /// Creates a custom multi-child layout; Dart's optional named arguments are the setters.
3049    pub fn new(delegate: Rc<dyn MultiChildLayoutDelegate>) -> CustomMultiChildLayout {
3050        CustomMultiChildLayout {
3051            key: None,
3052            delegate,
3053            children: Vec::new(),
3054        }
3055    }
3056
3057    /// Dart `CustomMultiChildLayout(key:)`.
3058    pub fn key(mut self, key: KeyRef) -> CustomMultiChildLayout {
3059        self.key = Some(key);
3060        self
3061    }
3062
3063    /// Dart `CustomMultiChildLayout(children:)`.
3064    pub fn children(
3065        mut self,
3066        children: impl IntoIterator<Item = WidgetRef>,
3067    ) -> CustomMultiChildLayout {
3068        self.children = children.into_iter().collect();
3069        self
3070    }
3071}
3072
3073impl RenderObjectWidget for CustomMultiChildLayout {
3074    type RenderObject = RenderCustomMultiChildLayoutBox;
3075
3076    fn key(&self) -> Option<&KeyRef> {
3077        self.key.as_ref()
3078    }
3079
3080    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
3081        RenderCustomMultiChildLayoutBox::new(app, Rc::clone(&self.delegate)).as_object()
3082    }
3083
3084    fn update_render_object(
3085        &self,
3086        app: &mut App,
3087        _context: BuildContext,
3088        render_object: RenderHandle<RenderCustomMultiChildLayoutBox>,
3089    ) {
3090        render_object.set_delegate(app, Rc::clone(&self.delegate));
3091    }
3092}
3093
3094impl MultiChildRenderObjectWidget for CustomMultiChildLayout {
3095    fn children(&self) -> &[WidgetRef] {
3096        &self.children
3097    }
3098}
3099
3100/// A box with a specified size.
3101///
3102/// If given a child, this widget forces it to have a specific width and/or height.
3103/// These values will be ignored if this widget's parent does not permit them.
3104/// For example, this happens if the parent is the screen (forces the child to
3105/// be the same size as the parent), or another [`SizedBox`] (forces its child to
3106/// have a specific width and/or height). This can be remedied by wrapping the
3107/// child [`SizedBox`] in a widget that does permit it to be any size up to the
3108/// size of the parent, such as [`Center`] or [`Align`].
3109///
3110/// If either the width or height is `None`, this widget will try to size itself to
3111/// match the child's size in that dimension. If the child's size depends on the
3112/// size of its parent, the height and width must be provided.
3113///
3114/// If not given a child, [`SizedBox`] will try to size itself as close to the
3115/// specified height and width as possible given the parent's constraints. If
3116/// `height` or `width` is `None` or unspecified, it will be treated as zero.
3117///
3118/// The [`expand`](Self::expand) constructor can be used to make a [`SizedBox`] that sizes
3119/// itself to fit the parent. It is equivalent to setting `width` and `height` to
3120/// `f64::INFINITY`.
3121///
3122/// This snippet makes the child widget (a `Card` with some `Text`) have the
3123/// exact size 200x300, parental constraints permitting:
3124///
3125/// ```text
3126/// SizedBox {
3127///   width: Some(200.0),
3128///   height: Some(300.0),
3129///   child: Some(Card(child: Text("Hello World!"))),
3130///   ..Default::default()
3131/// }
3132/// ```
3133///
3134/// See also:
3135///
3136///  * [`ConstrainedBox`], a more generic version of this class that takes
3137///    arbitrary [`BoxConstraints`] instead of an explicit width and height.
3138///  * `UnconstrainedBox`, a container that tries to let its child draw without
3139///    constraints.
3140///  * `FractionallySizedBox`, a widget that sizes its child to a fraction of
3141///    the total available space.
3142///  * `AspectRatio`, a widget that attempts to fit within the parent's
3143///    constraints while also sizing its child to match a given aspect ratio.
3144///  * `FittedBox`, which sizes and positions its child widget to fit the parent
3145///    according to a given `BoxFit` discipline.
3146///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
3147///
3148/// Dart's named constructors are the associated functions [`expand`](Self::expand),
3149/// [`shrink`](Self::shrink), [`from_size`](Self::from_size), and [`square`](Self::square);
3150/// set a key through struct update syntax: `SizedBox { key: Some(key), ..SizedBox::expand(child) }`.
3151#[derive(Default)]
3152pub struct SizedBox {
3153    pub key: Option<KeyRef>,
3154    /// If non-`None`, requires the child to have exactly this width.
3155    pub width: Option<f64>,
3156    /// If non-`None`, requires the child to have exactly this height.
3157    pub height: Option<f64>,
3158    pub child: Option<WidgetRef>,
3159}
3160
3161impl SizedBox {
3162    /// Creates a `SizedBox`; Dart's named arguments are the setters.
3163    pub fn new() -> SizedBox {
3164        SizedBox::default()
3165    }
3166
3167    /// Dart `SizedBox(key:)`.
3168    pub fn key(mut self, key: KeyRef) -> SizedBox {
3169        self.key = Some(key);
3170        self
3171    }
3172
3173    /// Dart `SizedBox(width:)`.
3174    pub fn width(mut self, width: f64) -> SizedBox {
3175        self.width = Some(width);
3176        self
3177    }
3178
3179    /// Dart `SizedBox(height:)`.
3180    pub fn height(mut self, height: f64) -> SizedBox {
3181        self.height = Some(height);
3182        self
3183    }
3184
3185    /// Dart `SizedBox(child:)`.
3186    #[cfg_attr(debug_assertions, track_caller)]
3187    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SizedBox {
3188        self.child = Some(child.into_widget());
3189        self
3190    }
3191
3192    /// Creates a box that will become as large as its parent allows.
3193    pub fn expand() -> SizedBox {
3194        SizedBox {
3195            key: None,
3196            width: Some(f64::INFINITY),
3197            height: Some(f64::INFINITY),
3198            child: None,
3199        }
3200    }
3201
3202    /// Creates a box that will become as small as its parent allows.
3203    pub fn shrink() -> SizedBox {
3204        SizedBox {
3205            key: None,
3206            width: Some(0.0),
3207            height: Some(0.0),
3208            child: None,
3209        }
3210    }
3211
3212    /// Creates a box with the specified size.
3213    pub fn from_size(size: Option<Size>) -> SizedBox {
3214        SizedBox {
3215            key: None,
3216            width: size.map(|size| size.width()),
3217            height: size.map(|size| size.height()),
3218            child: None,
3219        }
3220    }
3221
3222    /// Creates a box whose [`width`](Self::width) and [`height`](Self::height) are equal.
3223    pub fn square(dimension: Option<f64>) -> SizedBox {
3224        SizedBox {
3225            key: None,
3226            width: dimension,
3227            height: dimension,
3228            child: None,
3229        }
3230    }
3231
3232    fn additional_constraints(&self) -> BoxConstraints {
3233        BoxConstraints::tight_for(self.width, self.height)
3234    }
3235
3236    /// Dart's `toStringShort`: the named constructor this box is equivalent to.
3237    fn short_name(&self) -> &'static str {
3238        match (self.width, self.height) {
3239            (Some(f64::INFINITY), Some(f64::INFINITY)) => "SizedBox.expand",
3240            (Some(0.0), Some(0.0)) => "SizedBox.shrink",
3241            _ => "SizedBox",
3242        }
3243    }
3244}
3245
3246impl RenderObjectWidget for SizedBox {
3247    type RenderObject = RenderConstrainedBox;
3248
3249    fn key(&self) -> Option<&KeyRef> {
3250        self.key.as_ref()
3251    }
3252
3253    /// Dart's `SizedBox.toStringShort`: `SizedBox.expand` and `SizedBox.shrink` by the sizes
3254    /// those constructors give.
3255    fn to_string_short(&self) -> String {
3256        let type_name = match (self.width, self.height) {
3257            (Some(f64::INFINITY), Some(f64::INFINITY)) => "SizedBox.expand",
3258            (Some(0.0), Some(0.0)) => "SizedBox.shrink",
3259            _ => "SizedBox",
3260        };
3261        crate::describe_widget(type_name, self.key())
3262    }
3263
3264    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3265        let expanded_or_shrunk = matches!(
3266            (self.width, self.height),
3267            (Some(f64::INFINITY), Some(f64::INFINITY)) | (Some(0.0), Some(0.0))
3268        );
3269        let level = if expanded_or_shrunk {
3270            DiagnosticLevel::Hidden
3271        } else {
3272            DiagnosticLevel::Info
3273        };
3274        properties.add(
3275            DoubleProperty::new("width", self.width)
3276                .default_value(None)
3277                .with_level(level),
3278        );
3279        properties.add(
3280            DoubleProperty::new("height", self.height)
3281                .default_value(None)
3282                .with_level(level),
3283        );
3284    }
3285
3286    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
3287        RenderConstrainedBox::new(app, self.additional_constraints(), None).as_object()
3288    }
3289
3290    fn update_render_object(
3291        &self,
3292        app: &mut App,
3293        _context: BuildContext,
3294        render_object: RenderHandle<RenderConstrainedBox>,
3295    ) {
3296        render_object.set_additional_constraints(app, self.additional_constraints());
3297    }
3298}
3299
3300impl SingleChildRenderObjectWidget for SizedBox {
3301    fn child(&self) -> Option<&WidgetRef> {
3302        self.child.as_ref()
3303    }
3304}
3305
3306impl Debug for SizedBox {
3307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3308        let mut debug = f.debug_struct(self.short_name());
3309        debug.field("key", &self.key);
3310        if self.short_name() == "SizedBox" {
3311            debug.field("width", &self.width);
3312            debug.field("height", &self.height);
3313        }
3314        debug.field("child", &self.child).finish()
3315    }
3316}
3317
3318/// A widget that imposes additional constraints on its child.
3319///
3320/// For example, if you wanted [`child`](Self::child) to have a minimum height of 50.0 logical
3321/// pixels, you could use `BoxConstraints::new().min_height(50.0)` as the
3322/// [`constraints`](Self::constraints).
3323///
3324/// This snippet makes the child widget (a `Card` with some `Text`) fill the
3325/// parent, by applying `BoxConstraints.expand` constraints:
3326///
3327/// ```text
3328/// ConstrainedBox {
3329///   constraints: BoxConstraints::expand(),
3330///   child: Some(Card(child: Text("Hello World!"))),
3331///   key: None,
3332/// }
3333/// ```
3334///
3335/// The same behavior can be obtained using the [`SizedBox::expand`] widget.
3336///
3337/// See also:
3338///
3339///  * [`BoxConstraints`], the class that describes constraints.
3340///  * `UnconstrainedBox`, a container that tries to let its child draw without
3341///    constraints.
3342///  * [`SizedBox`], which lets you specify tight constraints by explicitly
3343///    specifying the height or width.
3344///  * `FractionallySizedBox`, which sizes its child based on a fraction of its
3345///    own size and positions the child according to an `Alignment` value.
3346///  * `AspectRatio`, a widget that attempts to fit within the parent's
3347///    constraints while also sizing its child to match a given aspect ratio.
3348///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
3349#[derive(Debug)]
3350pub struct ConstrainedBox {
3351    pub key: Option<KeyRef>,
3352    /// The additional constraints to impose on the child.
3353    ///
3354    /// Must be valid (`BoxConstraints::debug_assert_is_valid`).
3355    pub constraints: BoxConstraints,
3356    pub child: Option<WidgetRef>,
3357}
3358
3359impl ConstrainedBox {
3360    /// Creates a `ConstrainedBox`; Dart's optional named arguments are the setters.
3361    pub fn new(constraints: BoxConstraints) -> ConstrainedBox {
3362        ConstrainedBox {
3363            key: None,
3364            constraints,
3365            child: None,
3366        }
3367    }
3368
3369    /// Dart `ConstrainedBox(key:)`.
3370    pub fn key(mut self, key: KeyRef) -> ConstrainedBox {
3371        self.key = Some(key);
3372        self
3373    }
3374
3375    /// Dart `ConstrainedBox(child:)`.
3376    #[cfg_attr(debug_assertions, track_caller)]
3377    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ConstrainedBox {
3378        self.child = Some(child.into_widget());
3379        self
3380    }
3381}
3382
3383impl RenderObjectWidget for ConstrainedBox {
3384    type RenderObject = RenderConstrainedBox;
3385
3386    fn key(&self) -> Option<&KeyRef> {
3387        self.key.as_ref()
3388    }
3389
3390    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3391        properties
3392            .add(DiagnosticsProperty::new("constraints", self.constraints).with_show_name(false));
3393    }
3394
3395    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
3396        RenderConstrainedBox::new(app, self.constraints, None).as_object()
3397    }
3398
3399    fn update_render_object(
3400        &self,
3401        app: &mut App,
3402        _context: BuildContext,
3403        render_object: RenderHandle<RenderConstrainedBox>,
3404    ) {
3405        render_object.set_additional_constraints(app, self.constraints);
3406    }
3407}
3408
3409impl SingleChildRenderObjectWidget for ConstrainedBox {
3410    fn child(&self) -> Option<&WidgetRef> {
3411        self.child.as_ref()
3412    }
3413}
3414
3415/// A container widget that applies an arbitrary transform to its constraints,
3416/// and sizes its child using the resulting [`BoxConstraints`], optionally
3417/// clipping, or treating the overflow as an error.
3418///
3419/// This container sizes its child using a [`BoxConstraints`] created by applying
3420/// [`constraints_transform`](Self::constraints_transform) to its own constraints. This
3421/// container will then attempt to adopt the same size, within the limits of its own
3422/// constraints. If it ends up with a different size, it will align the child based on
3423/// [`alignment`](Self::alignment). If the container cannot expand enough to accommodate the
3424/// entire child, the child will be clipped if [`clip_behavior`](Self::clip_behavior) is not
3425/// [`Clip::None`].
3426///
3427/// When [`child`](Self::child) is `None`, this widget becomes as small as possible and never
3428/// overflows.
3429///
3430/// This widget can be used to ensure some of the child's natural dimensions are
3431/// honored. For instance, if the child requires a minimum height to fully display its
3432/// content, [`constraints_transform`](Self::constraints_transform) can be set to
3433/// [`max_height_unconstrained`](Self::max_height_unconstrained), so that the child may still
3434/// grow vertically when the parent fails to provide enough vertical space:
3435///
3436/// ```text
3437/// ConstrainedBox::new(BoxConstraints::new().min_height(40.0).max_height(100.0)).child(
3438///     ConstraintsTransformBox::new(ConstraintsTransformBox::max_height_unconstrained)
3439///         .child(Text::new("Hello World!")),
3440/// )
3441/// ```
3442///
3443/// See also:
3444///
3445///  * [`ConstrainedBox`], which renders a box which imposes constraints
3446///    on its child.
3447///  * [`OverflowBox`], a widget that imposes additional constraints on its child,
3448///    and allows the child to overflow itself.
3449///  * [`UnconstrainedBox`] which allows its children to render themselves
3450///    unconstrained and expands to fit them.
3451#[derive(Debug)]
3452pub struct ConstraintsTransformBox {
3453    pub key: Option<KeyRef>,
3454    /// The text direction to use when interpreting the [`alignment`](Self::alignment) if it is
3455    /// an `AlignmentDirectional`.
3456    ///
3457    /// Defaults to `None`, in which case `Directionality::maybe_of` is used to determine the
3458    /// text direction.
3459    pub text_direction: Option<TextDirection>,
3460    /// The alignment to use when laying out the child, if it has a different size
3461    /// than this widget.
3462    ///
3463    /// If this is an `AlignmentDirectional`, then
3464    /// [`text_direction`](Self::text_direction) must not be `None`.
3465    ///
3466    /// See also:
3467    ///
3468    ///  * `Alignment` for non-`Directionality`-aware alignments.
3469    ///  * `AlignmentDirectional` for `Directionality`-aware alignments.
3470    pub alignment: AlignmentGeometry,
3471    /// The function used to transform the incoming [`BoxConstraints`], to size
3472    /// [`child`](Self::child).
3473    ///
3474    /// The function must return a [`BoxConstraints`] that is normalized.
3475    ///
3476    /// See [`ConstraintsTransformBox`] for predefined common
3477    /// [`BoxConstraintsTransform`]s.
3478    pub constraints_transform: BoxConstraintsTransform,
3479    /// How to clip a child that overflows this box.
3480    ///
3481    /// Defaults to [`Clip::None`].
3482    pub clip_behavior: Clip,
3483    /// A description of the transform to show in a dump, when it is not one of the predefined
3484    /// transforms this widget knows.
3485    pub debug_transform_type: String,
3486    pub child: Option<WidgetRef>,
3487}
3488
3489impl ConstraintsTransformBox {
3490    /// Creates a widget that uses a function to transform the constraints it
3491    /// passes to its child; Dart's optional named arguments are the setters.
3492    pub fn new(constraints_transform: BoxConstraintsTransform) -> ConstraintsTransformBox {
3493        ConstraintsTransformBox {
3494            key: None,
3495            text_direction: None,
3496            alignment: AlignmentGeometry::CENTER,
3497            constraints_transform,
3498            clip_behavior: Clip::None,
3499            debug_transform_type: String::new(),
3500            child: None,
3501        }
3502    }
3503
3504    /// Dart `ConstraintsTransformBox(debugTransformType:)`.
3505    pub fn debug_transform_type(
3506        mut self,
3507        debug_transform_type: impl Into<String>,
3508    ) -> ConstraintsTransformBox {
3509        self.debug_transform_type = debug_transform_type.into();
3510        self
3511    }
3512
3513    /// Dart `ConstraintsTransformBox(key:)`.
3514    pub fn key(mut self, key: KeyRef) -> ConstraintsTransformBox {
3515        self.key = Some(key);
3516        self
3517    }
3518
3519    /// Dart `ConstraintsTransformBox(textDirection:)`.
3520    pub fn text_direction(mut self, text_direction: TextDirection) -> ConstraintsTransformBox {
3521        self.text_direction = Some(text_direction);
3522        self
3523    }
3524
3525    /// Dart `ConstraintsTransformBox(alignment:)`.
3526    pub fn alignment(mut self, alignment: AlignmentGeometry) -> ConstraintsTransformBox {
3527        self.alignment = alignment;
3528        self
3529    }
3530
3531    /// Dart `ConstraintsTransformBox(clipBehavior:)`.
3532    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ConstraintsTransformBox {
3533        self.clip_behavior = clip_behavior;
3534        self
3535    }
3536
3537    /// Dart `ConstraintsTransformBox(child:)`.
3538    #[cfg_attr(debug_assertions, track_caller)]
3539    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ConstraintsTransformBox {
3540        self.child = Some(child.into_widget());
3541        self
3542    }
3543
3544    /// The label `debugFillProperties` gives a transform, Dart's `_debugKnownTransforms`.
3545    fn debug_transform_label(transform: BoxConstraintsTransform) -> Option<&'static str> {
3546        let known: [(BoxConstraintsTransform, &'static str); 7] = [
3547            (Self::unmodified, "unmodified"),
3548            (Self::unconstrained, "unconstrained"),
3549            (Self::width_unconstrained, "width constraints removed"),
3550            (Self::height_unconstrained, "height constraints removed"),
3551            (Self::max_width_unconstrained, "maxWidth constraint removed"),
3552            (
3553                Self::max_height_unconstrained,
3554                "maxHeight constraint removed",
3555            ),
3556            (
3557                Self::max_unconstrained,
3558                "maxWidth & maxHeight constraints removed",
3559            ),
3560        ];
3561        known
3562            .into_iter()
3563            .find(|(known, _)| std::ptr::fn_addr_eq(*known, transform))
3564            .map(|(_, label)| label)
3565    }
3566
3567    /// A [`BoxConstraintsTransform`] that always returns its argument as-is (i.e.,
3568    /// it is an identity function).
3569    ///
3570    /// The [`ConstraintsTransformBox`] becomes a proxy widget that has no effect on
3571    /// layout if [`constraints_transform`](Self::constraints_transform) is set to this.
3572    pub fn unmodified(constraints: BoxConstraints) -> BoxConstraints {
3573        constraints
3574    }
3575
3576    /// A [`BoxConstraintsTransform`] that always returns a [`BoxConstraints`] that
3577    /// imposes no constraints on either dimension.
3578    ///
3579    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3580    /// [`child`](Self::child) to render at its "natural" size (equivalent to an
3581    /// [`UnconstrainedBox`] with `constrained_axis` set to `None`).
3582    pub fn unconstrained(_constraints: BoxConstraints) -> BoxConstraints {
3583        BoxConstraints::new()
3584    }
3585
3586    /// A [`BoxConstraintsTransform`] that removes the width constraints from the
3587    /// input.
3588    ///
3589    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3590    /// [`child`](Self::child) to render at its "natural" width (equivalent to an
3591    /// [`UnconstrainedBox`] with `constrained_axis` set to `Axis::Horizontal`).
3592    pub fn width_unconstrained(constraints: BoxConstraints) -> BoxConstraints {
3593        constraints.height_constraints()
3594    }
3595
3596    /// A [`BoxConstraintsTransform`] that removes the height constraints from the
3597    /// input.
3598    ///
3599    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3600    /// [`child`](Self::child) to render at its "natural" height (equivalent to an
3601    /// [`UnconstrainedBox`] with `constrained_axis` set to `Axis::Vertical`).
3602    pub fn height_unconstrained(constraints: BoxConstraints) -> BoxConstraints {
3603        constraints.width_constraints()
3604    }
3605
3606    /// A [`BoxConstraintsTransform`] that removes the `max_height` constraint from
3607    /// the input.
3608    ///
3609    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3610    /// [`child`](Self::child) to render at its "natural" height or the `min_height` of the
3611    /// incoming [`BoxConstraints`], whichever is larger.
3612    pub fn max_height_unconstrained(constraints: BoxConstraints) -> BoxConstraints {
3613        constraints.copy_with().max_height(f64::INFINITY)
3614    }
3615
3616    /// A [`BoxConstraintsTransform`] that removes the `max_width` constraint from
3617    /// the input.
3618    ///
3619    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3620    /// [`child`](Self::child) to render at its "natural" width or the `min_width` of the
3621    /// incoming [`BoxConstraints`], whichever is larger.
3622    pub fn max_width_unconstrained(constraints: BoxConstraints) -> BoxConstraints {
3623        constraints.copy_with().max_width(f64::INFINITY)
3624    }
3625
3626    /// A [`BoxConstraintsTransform`] that removes both the `max_width` and the
3627    /// `max_height` constraints from the input.
3628    ///
3629    /// Setting [`constraints_transform`](Self::constraints_transform) to this allows
3630    /// [`child`](Self::child) to render at least its "natural" size, and grow along an axis if
3631    /// the incoming [`BoxConstraints`] has a larger minimum constraint on that axis.
3632    pub fn max_unconstrained(constraints: BoxConstraints) -> BoxConstraints {
3633        constraints
3634            .copy_with()
3635            .max_width(f64::INFINITY)
3636            .max_height(f64::INFINITY)
3637    }
3638}
3639
3640impl RenderObjectWidget for ConstraintsTransformBox {
3641    type RenderObject = RenderConstraintsTransformBox;
3642
3643    fn key(&self) -> Option<&KeyRef> {
3644        self.key.as_ref()
3645    }
3646
3647    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3648        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
3649        properties.add(
3650            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
3651                .default_value(None),
3652        );
3653        let debug_transform_label = if !self.debug_transform_type.is_empty() {
3654            Some(self.debug_transform_type.as_str())
3655        } else {
3656            ConstraintsTransformBox::debug_transform_label(self.constraints_transform)
3657        };
3658        if let Some(debug_transform_label) = debug_transform_label {
3659            properties.add(DiagnosticsProperty::<String>::new(
3660                "constraints transform",
3661                debug_transform_label.to_string(),
3662            ));
3663        }
3664    }
3665
3666    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
3667        let text_direction = self
3668            .text_direction
3669            .or_else(|| Directionality::maybe_of(app, context));
3670        let render_object = RenderConstraintsTransformBox::new(
3671            app,
3672            self.alignment,
3673            text_direction,
3674            self.constraints_transform,
3675            None,
3676        );
3677        render_object.set_clip_behavior(app, self.clip_behavior);
3678        render_object.as_object()
3679    }
3680
3681    fn update_render_object(
3682        &self,
3683        app: &mut App,
3684        context: BuildContext,
3685        render_object: RenderHandle<RenderConstraintsTransformBox>,
3686    ) {
3687        let text_direction = self
3688            .text_direction
3689            .or_else(|| Directionality::maybe_of(app, context));
3690        render_object.set_text_direction(app, text_direction);
3691        render_object.set_constraints_transform(app, self.constraints_transform);
3692        render_object.set_alignment(app, self.alignment);
3693        render_object.set_clip_behavior(app, self.clip_behavior);
3694    }
3695}
3696
3697impl SingleChildRenderObjectWidget for ConstraintsTransformBox {
3698    fn child(&self) -> Option<&WidgetRef> {
3699        self.child.as_ref()
3700    }
3701}
3702
3703/// A widget that imposes no constraints on its child, allowing it to render
3704/// at its "natural" size.
3705///
3706/// This allows a child to render at the size it would render if it were alone
3707/// on an infinite canvas with no constraints. This container will then attempt
3708/// to adopt the same size, within the limits of its own constraints. If it ends
3709/// up with a different size, it will align the child based on
3710/// [`alignment`](Self::alignment). If the box cannot expand enough to accommodate the entire
3711/// child, the child will be clipped.
3712///
3713/// See also:
3714///
3715///  * [`ConstrainedBox`], for a box which imposes constraints on its child.
3716///  * [`Align`], which loosens the constraints given to the child rather than
3717///    removing them entirely.
3718///  * `Container`, a convenience widget that combines common painting,
3719///    positioning, and sizing widgets.
3720///  * [`OverflowBox`], a widget that imposes different constraints on its child
3721///    than it gets from its parent, possibly allowing the child to overflow
3722///    the parent.
3723///  * [`ConstraintsTransformBox`], a widget that sizes its child using a
3724///    transformed [`BoxConstraints`].
3725#[derive(Debug)]
3726pub struct UnconstrainedBox {
3727    pub key: Option<KeyRef>,
3728    /// The text direction to use when interpreting the [`alignment`](Self::alignment) if it is
3729    /// an `AlignmentDirectional`.
3730    pub text_direction: Option<TextDirection>,
3731    /// The alignment to use when laying out the child.
3732    ///
3733    /// If this is an `AlignmentDirectional`, then
3734    /// [`text_direction`](Self::text_direction) must not be `None`.
3735    ///
3736    /// See also:
3737    ///
3738    ///  * `Alignment` for non-`Directionality`-aware alignments.
3739    ///  * `AlignmentDirectional` for `Directionality`-aware alignments.
3740    pub alignment: AlignmentGeometry,
3741    /// The axis to retain constraints on, if any.
3742    ///
3743    /// If not set, or set to `None` (the default), neither axis will retain its
3744    /// constraints. If set to `Axis::Vertical`, then vertical constraints will
3745    /// be retained, and if set to `Axis::Horizontal`, then horizontal constraints
3746    /// will be retained.
3747    pub constrained_axis: Option<Axis>,
3748    /// How to clip a child that overflows this box.
3749    ///
3750    /// Defaults to [`Clip::None`].
3751    pub clip_behavior: Clip,
3752    pub child: Option<WidgetRef>,
3753}
3754
3755impl UnconstrainedBox {
3756    /// Creates a widget that imposes no constraints on its child, allowing it to
3757    /// render at its "natural" size; Dart's named arguments are the setters.
3758    pub fn new() -> UnconstrainedBox {
3759        UnconstrainedBox::default()
3760    }
3761
3762    /// Dart `UnconstrainedBox(key:)`.
3763    pub fn key(mut self, key: KeyRef) -> UnconstrainedBox {
3764        self.key = Some(key);
3765        self
3766    }
3767
3768    /// Dart `UnconstrainedBox(textDirection:)`.
3769    pub fn text_direction(mut self, text_direction: TextDirection) -> UnconstrainedBox {
3770        self.text_direction = Some(text_direction);
3771        self
3772    }
3773
3774    /// Dart `UnconstrainedBox(alignment:)`.
3775    pub fn alignment(mut self, alignment: AlignmentGeometry) -> UnconstrainedBox {
3776        self.alignment = alignment;
3777        self
3778    }
3779
3780    /// Dart `UnconstrainedBox(constrainedAxis:)`.
3781    pub fn constrained_axis(mut self, constrained_axis: Axis) -> UnconstrainedBox {
3782        self.constrained_axis = Some(constrained_axis);
3783        self
3784    }
3785
3786    /// Dart `UnconstrainedBox(clipBehavior:)`.
3787    pub fn clip_behavior(mut self, clip_behavior: Clip) -> UnconstrainedBox {
3788        self.clip_behavior = clip_behavior;
3789        self
3790    }
3791
3792    /// Dart `UnconstrainedBox(child:)`.
3793    #[cfg_attr(debug_assertions, track_caller)]
3794    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> UnconstrainedBox {
3795        self.child = Some(child.into_widget());
3796        self
3797    }
3798
3799    fn axis_to_transform(constrained_axis: Option<Axis>) -> BoxConstraintsTransform {
3800        match constrained_axis {
3801            Some(Axis::Horizontal) => ConstraintsTransformBox::height_unconstrained,
3802            Some(Axis::Vertical) => ConstraintsTransformBox::width_unconstrained,
3803            None => ConstraintsTransformBox::unconstrained,
3804        }
3805    }
3806}
3807
3808impl Default for UnconstrainedBox {
3809    fn default() -> UnconstrainedBox {
3810        UnconstrainedBox {
3811            key: None,
3812            text_direction: None,
3813            alignment: AlignmentGeometry::CENTER,
3814            constrained_axis: None,
3815            clip_behavior: Clip::None,
3816            child: None,
3817        }
3818    }
3819}
3820
3821impl StatelessWidget for UnconstrainedBox {
3822    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3823        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
3824        properties.add(
3825            EnumProperty::<Axis>::new("constrainedAxis", self.constrained_axis).default_value(None),
3826        );
3827        properties.add(
3828            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
3829                .default_value(None),
3830        );
3831    }
3832
3833    fn key(&self) -> Option<&KeyRef> {
3834        self.key.as_ref()
3835    }
3836
3837    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
3838        let mut transform_box = ConstraintsTransformBox::new(UnconstrainedBox::axis_to_transform(
3839            self.constrained_axis,
3840        ))
3841        .alignment(self.alignment)
3842        .clip_behavior(self.clip_behavior);
3843        if let Some(text_direction) = self.text_direction {
3844            transform_box = transform_box.text_direction(text_direction);
3845        }
3846        if let Some(child) = &self.child {
3847            transform_box = transform_box.child(child.clone());
3848        }
3849        transform_box.into_widget()
3850    }
3851}
3852
3853/// A widget that sizes its child to a fraction of the total available space.
3854/// For more details about the layout algorithm, see
3855/// [`RenderFractionallySizedOverflowBox`].
3856///
3857/// See also:
3858///
3859///  * [`Align`], which sizes itself based on its child's size and positions
3860///    the child according to an `Alignment` value.
3861///  * [`OverflowBox`], a widget that imposes different constraints on its child
3862///    than it gets from its parent, possibly allowing the child to overflow the
3863///    parent.
3864///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
3865#[derive(Debug)]
3866pub struct FractionallySizedBox {
3867    pub key: Option<KeyRef>,
3868    /// How to align the child.
3869    ///
3870    /// The x and y values of the alignment control the horizontal and vertical
3871    /// alignment, respectively. An x value of -1.0 means that the left edge of
3872    /// the child is aligned with the left edge of the parent whereas an x value
3873    /// of 1.0 means that the right edge of the child is aligned with the right
3874    /// edge of the parent. Other values interpolate (and extrapolate) linearly.
3875    /// For example, a value of 0.0 means that the center of the child is aligned
3876    /// with the center of the parent.
3877    ///
3878    /// Defaults to `AlignmentGeometry::CENTER`.
3879    pub alignment: AlignmentGeometry,
3880    /// If non-`None`, the fraction of the incoming width given to the child.
3881    ///
3882    /// If non-`None`, the child is given a tight width constraint that is the max
3883    /// incoming width constraint multiplied by this factor.
3884    ///
3885    /// If `None`, the incoming width constraints are passed to the child
3886    /// unmodified.
3887    pub width_factor: Option<f64>,
3888    /// If non-`None`, the fraction of the incoming height given to the child.
3889    ///
3890    /// If non-`None`, the child is given a tight height constraint that is the max
3891    /// incoming height constraint multiplied by this factor.
3892    ///
3893    /// If `None`, the incoming height constraints are passed to the child
3894    /// unmodified.
3895    pub height_factor: Option<f64>,
3896    pub child: Option<WidgetRef>,
3897}
3898
3899impl FractionallySizedBox {
3900    /// Creates a widget that sizes its child to a fraction of the total available space;
3901    /// Dart's named arguments are the setters.
3902    pub fn new() -> FractionallySizedBox {
3903        FractionallySizedBox::default()
3904    }
3905
3906    /// Dart `FractionallySizedBox(key:)`.
3907    pub fn key(mut self, key: KeyRef) -> FractionallySizedBox {
3908        self.key = Some(key);
3909        self
3910    }
3911
3912    /// Dart `FractionallySizedBox(alignment:)`.
3913    pub fn alignment(mut self, alignment: AlignmentGeometry) -> FractionallySizedBox {
3914        self.alignment = alignment;
3915        self
3916    }
3917
3918    /// Dart `FractionallySizedBox(widthFactor:)`.
3919    pub fn width_factor(mut self, width_factor: f64) -> FractionallySizedBox {
3920        debug_assert!(width_factor >= 0.0);
3921        self.width_factor = Some(width_factor);
3922        self
3923    }
3924
3925    /// Dart `FractionallySizedBox(heightFactor:)`.
3926    pub fn height_factor(mut self, height_factor: f64) -> FractionallySizedBox {
3927        debug_assert!(height_factor >= 0.0);
3928        self.height_factor = Some(height_factor);
3929        self
3930    }
3931
3932    /// Dart `FractionallySizedBox(child:)`.
3933    #[cfg_attr(debug_assertions, track_caller)]
3934    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FractionallySizedBox {
3935        self.child = Some(child.into_widget());
3936        self
3937    }
3938}
3939
3940impl Default for FractionallySizedBox {
3941    fn default() -> FractionallySizedBox {
3942        FractionallySizedBox {
3943            key: None,
3944            alignment: AlignmentGeometry::CENTER,
3945            width_factor: None,
3946            height_factor: None,
3947            child: None,
3948        }
3949    }
3950}
3951
3952impl RenderObjectWidget for FractionallySizedBox {
3953    type RenderObject = RenderFractionallySizedOverflowBox;
3954
3955    fn key(&self) -> Option<&KeyRef> {
3956        self.key.as_ref()
3957    }
3958
3959    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3960        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
3961        properties.add(DoubleProperty::new("widthFactor", self.width_factor).default_value(None));
3962        properties.add(DoubleProperty::new("heightFactor", self.height_factor).default_value(None));
3963    }
3964
3965    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
3966        let text_direction = Directionality::maybe_of(app, context);
3967        let render_object =
3968            RenderFractionallySizedOverflowBox::new(app, self.alignment, text_direction, None);
3969        render_object.set_width_factor(app, self.width_factor);
3970        render_object.set_height_factor(app, self.height_factor);
3971        render_object.as_object()
3972    }
3973
3974    fn update_render_object(
3975        &self,
3976        app: &mut App,
3977        context: BuildContext,
3978        render_object: RenderHandle<RenderFractionallySizedOverflowBox>,
3979    ) {
3980        render_object.set_alignment(app, self.alignment);
3981        render_object.set_width_factor(app, self.width_factor);
3982        render_object.set_height_factor(app, self.height_factor);
3983        let text_direction = Directionality::maybe_of(app, context);
3984        render_object.set_text_direction(app, text_direction);
3985    }
3986}
3987
3988impl SingleChildRenderObjectWidget for FractionallySizedBox {
3989    fn child(&self) -> Option<&WidgetRef> {
3990        self.child.as_ref()
3991    }
3992}
3993
3994/// A box that limits its size only when it's unconstrained.
3995///
3996/// If this widget's maximum width is unconstrained then its child's width is
3997/// limited to [`max_width`](Self::max_width). Similarly, if this widget's maximum height is
3998/// unconstrained then its child's height is limited to [`max_height`](Self::max_height).
3999///
4000/// This has the effect of giving the child a natural dimension in unbounded
4001/// environments. For example, by providing a [`max_height`](Self::max_height) to a widget
4002/// that normally tries to be as big as possible, the widget will normally size
4003/// itself to fit its parent, but when placed in a vertical list, it will take
4004/// on the given height.
4005///
4006/// This is useful when composing widgets that normally try to match their
4007/// parents' size, so that they behave reasonably in lists (which are
4008/// unbounded).
4009///
4010/// See also:
4011///
4012///  * [`ConstrainedBox`], which applies its constraints in all cases, not just
4013///    when the incoming constraints are unbounded.
4014///  * [`SizedBox`], which lets you specify tight constraints by explicitly
4015///    specifying the height or width.
4016///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4017#[derive(Debug)]
4018pub struct LimitedBox {
4019    pub key: Option<KeyRef>,
4020    /// The maximum width limit to apply in the absence of a
4021    /// [`BoxConstraints::max_width`] constraint.
4022    pub max_width: f64,
4023    /// The maximum height limit to apply in the absence of a
4024    /// [`BoxConstraints::max_height`] constraint.
4025    pub max_height: f64,
4026    pub child: Option<WidgetRef>,
4027}
4028
4029impl LimitedBox {
4030    /// Creates a box that limits its size only when it's unconstrained; Dart's named
4031    /// arguments are the setters.
4032    pub fn new() -> LimitedBox {
4033        LimitedBox::default()
4034    }
4035
4036    /// Dart `LimitedBox(key:)`.
4037    pub fn key(mut self, key: KeyRef) -> LimitedBox {
4038        self.key = Some(key);
4039        self
4040    }
4041
4042    /// Dart `LimitedBox(maxWidth:)`; must not be negative.
4043    pub fn max_width(mut self, max_width: f64) -> LimitedBox {
4044        debug_assert!(max_width >= 0.0);
4045        self.max_width = max_width;
4046        self
4047    }
4048
4049    /// Dart `LimitedBox(maxHeight:)`; must not be negative.
4050    pub fn max_height(mut self, max_height: f64) -> LimitedBox {
4051        debug_assert!(max_height >= 0.0);
4052        self.max_height = max_height;
4053        self
4054    }
4055
4056    /// Dart `LimitedBox(child:)`.
4057    #[cfg_attr(debug_assertions, track_caller)]
4058    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> LimitedBox {
4059        self.child = Some(child.into_widget());
4060        self
4061    }
4062}
4063
4064impl Default for LimitedBox {
4065    fn default() -> LimitedBox {
4066        LimitedBox {
4067            key: None,
4068            max_width: f64::INFINITY,
4069            max_height: f64::INFINITY,
4070            child: None,
4071        }
4072    }
4073}
4074
4075impl RenderObjectWidget for LimitedBox {
4076    type RenderObject = RenderLimitedBox;
4077
4078    fn key(&self) -> Option<&KeyRef> {
4079        self.key.as_ref()
4080    }
4081
4082    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4083        properties.add(
4084            DoubleProperty::new("maxWidth", self.max_width).default_value(Some(f64::INFINITY)),
4085        );
4086        properties.add(
4087            DoubleProperty::new("maxHeight", self.max_height).default_value(Some(f64::INFINITY)),
4088        );
4089    }
4090
4091    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4092        RenderLimitedBox::new(app, self.max_width, self.max_height, None).as_object()
4093    }
4094
4095    fn update_render_object(
4096        &self,
4097        app: &mut App,
4098        _context: BuildContext,
4099        render_object: RenderHandle<RenderLimitedBox>,
4100    ) {
4101        render_object.set_max_width(app, self.max_width);
4102        render_object.set_max_height(app, self.max_height);
4103    }
4104}
4105
4106impl SingleChildRenderObjectWidget for LimitedBox {
4107    fn child(&self) -> Option<&WidgetRef> {
4108        self.child.as_ref()
4109    }
4110}
4111
4112/// A widget that imposes different constraints on its child than it gets
4113/// from its parent, possibly allowing the child to overflow the parent.
4114///
4115/// See also:
4116///
4117///  * [`RenderConstrainedOverflowBox`] for details about how [`OverflowBox`] is
4118///    rendered.
4119///  * [`SizedOverflowBox`], a widget that is a specific size but passes its
4120///    original constraints through to its child, which may then overflow.
4121///  * [`ConstrainedBox`], a widget that imposes additional constraints on its
4122///    child.
4123///  * [`UnconstrainedBox`], a container that tries to let its child draw without
4124///    constraints.
4125///  * [`SizedBox`], a box with a specified size.
4126///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4127#[derive(Debug)]
4128pub struct OverflowBox {
4129    pub key: Option<KeyRef>,
4130    /// How to align the child.
4131    ///
4132    /// The x and y values of the alignment control the horizontal and vertical
4133    /// alignment, respectively. An x value of -1.0 means that the left edge of
4134    /// the child is aligned with the left edge of the parent whereas an x value
4135    /// of 1.0 means that the right edge of the child is aligned with the right
4136    /// edge of the parent. Other values interpolate (and extrapolate) linearly.
4137    /// For example, a value of 0.0 means that the center of the child is aligned
4138    /// with the center of the parent.
4139    ///
4140    /// Defaults to `AlignmentGeometry::CENTER`.
4141    pub alignment: AlignmentGeometry,
4142    /// The minimum width constraint to give the child. Set this to `None` (the
4143    /// default) to use the constraint from the parent instead.
4144    pub min_width: Option<f64>,
4145    /// The maximum width constraint to give the child. Set this to `None` (the
4146    /// default) to use the constraint from the parent instead.
4147    pub max_width: Option<f64>,
4148    /// The minimum height constraint to give the child. Set this to `None` (the
4149    /// default) to use the constraint from the parent instead.
4150    pub min_height: Option<f64>,
4151    /// The maximum height constraint to give the child. Set this to `None` (the
4152    /// default) to use the constraint from the parent instead.
4153    pub max_height: Option<f64>,
4154    /// The way to size the render object.
4155    ///
4156    /// This only affects the scenario where the child does not indeed overflow.
4157    /// If set to [`OverflowBoxFit::DeferToChild`], the render object will size itself to
4158    /// match the size of its child within the constraints of its parent or be
4159    /// as small as the parent allows if no child is set. If set to
4160    /// [`OverflowBoxFit::Max`] (the default), the render object will size itself
4161    /// to be as large as the parent allows.
4162    pub fit: OverflowBoxFit,
4163    pub child: Option<WidgetRef>,
4164}
4165
4166impl OverflowBox {
4167    /// Creates a widget that lets its child overflow itself; Dart's named arguments are the
4168    /// setters.
4169    pub fn new() -> OverflowBox {
4170        OverflowBox::default()
4171    }
4172
4173    /// Dart `OverflowBox(key:)`.
4174    pub fn key(mut self, key: KeyRef) -> OverflowBox {
4175        self.key = Some(key);
4176        self
4177    }
4178
4179    /// Dart `OverflowBox(alignment:)`.
4180    pub fn alignment(mut self, alignment: AlignmentGeometry) -> OverflowBox {
4181        self.alignment = alignment;
4182        self
4183    }
4184
4185    /// Dart `OverflowBox(minWidth:)`.
4186    pub fn min_width(mut self, min_width: f64) -> OverflowBox {
4187        self.min_width = Some(min_width);
4188        self
4189    }
4190
4191    /// Dart `OverflowBox(maxWidth:)`.
4192    pub fn max_width(mut self, max_width: f64) -> OverflowBox {
4193        self.max_width = Some(max_width);
4194        self
4195    }
4196
4197    /// Dart `OverflowBox(minHeight:)`.
4198    pub fn min_height(mut self, min_height: f64) -> OverflowBox {
4199        self.min_height = Some(min_height);
4200        self
4201    }
4202
4203    /// Dart `OverflowBox(maxHeight:)`.
4204    pub fn max_height(mut self, max_height: f64) -> OverflowBox {
4205        self.max_height = Some(max_height);
4206        self
4207    }
4208
4209    /// Dart `OverflowBox(fit:)`.
4210    pub fn fit(mut self, fit: OverflowBoxFit) -> OverflowBox {
4211        self.fit = fit;
4212        self
4213    }
4214
4215    /// Dart `OverflowBox(child:)`.
4216    #[cfg_attr(debug_assertions, track_caller)]
4217    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> OverflowBox {
4218        self.child = Some(child.into_widget());
4219        self
4220    }
4221}
4222
4223impl Default for OverflowBox {
4224    fn default() -> OverflowBox {
4225        OverflowBox {
4226            key: None,
4227            alignment: AlignmentGeometry::CENTER,
4228            min_width: None,
4229            max_width: None,
4230            min_height: None,
4231            max_height: None,
4232            fit: OverflowBoxFit::Max,
4233            child: None,
4234        }
4235    }
4236}
4237
4238impl RenderObjectWidget for OverflowBox {
4239    type RenderObject = RenderConstrainedOverflowBox;
4240
4241    fn key(&self) -> Option<&KeyRef> {
4242        self.key.as_ref()
4243    }
4244
4245    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4246        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
4247        properties.add(DoubleProperty::new("minWidth", self.min_width).default_value(None));
4248        properties.add(DoubleProperty::new("maxWidth", self.max_width).default_value(None));
4249        properties.add(DoubleProperty::new("minHeight", self.min_height).default_value(None));
4250        properties.add(DoubleProperty::new("maxHeight", self.max_height).default_value(None));
4251        properties.add(EnumProperty::new("fit", self.fit));
4252    }
4253
4254    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
4255        let text_direction = Directionality::maybe_of(app, context);
4256        RenderConstrainedOverflowBox::new(
4257            app,
4258            self.min_width,
4259            self.max_width,
4260            self.min_height,
4261            self.max_height,
4262            self.fit,
4263            self.alignment,
4264            text_direction,
4265            None,
4266        )
4267        .as_object()
4268    }
4269
4270    fn update_render_object(
4271        &self,
4272        app: &mut App,
4273        context: BuildContext,
4274        render_object: RenderHandle<RenderConstrainedOverflowBox>,
4275    ) {
4276        render_object.set_alignment(app, self.alignment);
4277        render_object.set_min_width(app, self.min_width);
4278        render_object.set_max_width(app, self.max_width);
4279        render_object.set_min_height(app, self.min_height);
4280        render_object.set_max_height(app, self.max_height);
4281        render_object.set_fit(app, self.fit);
4282        let text_direction = Directionality::maybe_of(app, context);
4283        render_object.set_text_direction(app, text_direction);
4284    }
4285}
4286
4287impl SingleChildRenderObjectWidget for OverflowBox {
4288    fn child(&self) -> Option<&WidgetRef> {
4289        self.child.as_ref()
4290    }
4291}
4292
4293/// A widget that is a specific size but passes its original constraints
4294/// through to its child, which may then overflow.
4295///
4296/// See also:
4297///
4298///  * [`OverflowBox`], a widget that imposes different constraints on its child
4299///    than it gets from its parent, possibly allowing the child to overflow the
4300///    parent.
4301///  * [`ConstrainedBox`], a widget that imposes additional constraints on its
4302///    child.
4303///  * [`UnconstrainedBox`], a container that tries to let its child draw without
4304///    constraints.
4305///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4306#[derive(Debug)]
4307pub struct SizedOverflowBox {
4308    pub key: Option<KeyRef>,
4309    /// How to align the child.
4310    ///
4311    /// The x and y values of the alignment control the horizontal and vertical
4312    /// alignment, respectively. An x value of -1.0 means that the left edge of
4313    /// the child is aligned with the left edge of the parent whereas an x value
4314    /// of 1.0 means that the right edge of the child is aligned with the right
4315    /// edge of the parent. Other values interpolate (and extrapolate) linearly.
4316    /// For example, a value of 0.0 means that the center of the child is aligned
4317    /// with the center of the parent.
4318    ///
4319    /// Defaults to `AlignmentGeometry::CENTER`.
4320    pub alignment: AlignmentGeometry,
4321    /// The size this widget should attempt to be.
4322    pub size: Size,
4323    pub child: Option<WidgetRef>,
4324}
4325
4326impl SizedOverflowBox {
4327    /// Creates a widget of a given size that lets its child overflow; Dart's optional named
4328    /// arguments are the setters.
4329    pub fn new(size: Size) -> SizedOverflowBox {
4330        SizedOverflowBox {
4331            key: None,
4332            alignment: AlignmentGeometry::CENTER,
4333            size,
4334            child: None,
4335        }
4336    }
4337
4338    /// Dart `SizedOverflowBox(key:)`.
4339    pub fn key(mut self, key: KeyRef) -> SizedOverflowBox {
4340        self.key = Some(key);
4341        self
4342    }
4343
4344    /// Dart `SizedOverflowBox(alignment:)`.
4345    pub fn alignment(mut self, alignment: AlignmentGeometry) -> SizedOverflowBox {
4346        self.alignment = alignment;
4347        self
4348    }
4349
4350    /// Dart `SizedOverflowBox(child:)`.
4351    #[cfg_attr(debug_assertions, track_caller)]
4352    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SizedOverflowBox {
4353        self.child = Some(child.into_widget());
4354        self
4355    }
4356}
4357
4358impl RenderObjectWidget for SizedOverflowBox {
4359    type RenderObject = RenderSizedOverflowBox;
4360
4361    fn key(&self) -> Option<&KeyRef> {
4362        self.key.as_ref()
4363    }
4364
4365    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4366        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
4367        properties.add(DiagnosticsProperty::<Size>::new("size", self.size).default_value(None));
4368    }
4369
4370    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
4371        let text_direction = Directionality::of(app, context);
4372        RenderSizedOverflowBox::new(app, self.size, self.alignment, Some(text_direction), None)
4373            .as_object()
4374    }
4375
4376    fn update_render_object(
4377        &self,
4378        app: &mut App,
4379        context: BuildContext,
4380        render_object: RenderHandle<RenderSizedOverflowBox>,
4381    ) {
4382        render_object.set_alignment(app, self.alignment);
4383        render_object.set_requested_size(app, self.size);
4384        let text_direction = Directionality::of(app, context);
4385        render_object.set_text_direction(app, Some(text_direction));
4386    }
4387}
4388
4389impl SingleChildRenderObjectWidget for SizedOverflowBox {
4390    fn child(&self) -> Option<&WidgetRef> {
4391        self.child.as_ref()
4392    }
4393}
4394
4395/// A widget that lays the child out as if it was in the tree, but without
4396/// painting anything, without making the child available for hit testing, and
4397/// without taking any room in the parent.
4398///
4399/// Offstage children are still active: they can receive focus and have keyboard
4400/// input directed to them.
4401///
4402/// Animations continue to run in offstage children, and therefore use battery
4403/// and CPU time, regardless of whether the animations end up being visible.
4404///
4405/// [`Offstage`] can be used to measure the dimensions of a widget without
4406/// bringing it on screen (yet). To hide a widget from view while it is not
4407/// needed, prefer removing the widget from the tree entirely rather than
4408/// keeping it alive in an [`Offstage`] subtree.
4409///
4410/// See also:
4411///
4412///  * `Visibility`, which can hide a child more efficiently (albeit less
4413///    subtly).
4414///  * [`TickerMode`](crate::TickerMode), which can be used to disable animations in a subtree.
4415///  * `SliverOffstage`, the sliver version of this widget.
4416///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4417///
4418/// Flutter's `_OffstageElement` only overrides `debugVisitOnstageChildren`; this uses the
4419/// plain single-child element.
4420#[derive(Debug)]
4421pub struct Offstage {
4422    pub key: Option<KeyRef>,
4423    /// Whether the child is hidden from the rest of the tree.
4424    ///
4425    /// If true, the child is laid out as if it was in the tree, but without
4426    /// painting anything, without making the child available for hit testing, and
4427    /// without taking any room in the parent.
4428    ///
4429    /// Offstage children are still active: they can receive focus and have keyboard
4430    /// input directed to them.
4431    ///
4432    /// Animations continue to run in offstage children, and therefore use battery
4433    /// and CPU time, regardless of whether the animations end up being visible.
4434    ///
4435    /// If false, the child is included in the tree as normal.
4436    pub offstage: bool,
4437    pub child: Option<WidgetRef>,
4438}
4439
4440impl Offstage {
4441    /// Creates a widget that visually hides its child; Dart's named arguments are the
4442    /// setters.
4443    pub fn new() -> Offstage {
4444        Offstage::default()
4445    }
4446
4447    /// Dart `Offstage(key:)`.
4448    pub fn key(mut self, key: KeyRef) -> Offstage {
4449        self.key = Some(key);
4450        self
4451    }
4452
4453    /// Dart `Offstage(offstage:)`.
4454    pub fn offstage(mut self, offstage: bool) -> Offstage {
4455        self.offstage = offstage;
4456        self
4457    }
4458
4459    /// Dart `Offstage(child:)`.
4460    #[cfg_attr(debug_assertions, track_caller)]
4461    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Offstage {
4462        self.child = Some(child.into_widget());
4463        self
4464    }
4465}
4466
4467impl Default for Offstage {
4468    fn default() -> Offstage {
4469        Offstage {
4470            key: None,
4471            offstage: true,
4472            child: None,
4473        }
4474    }
4475}
4476
4477impl RenderObjectWidget for Offstage {
4478    type RenderObject = RenderOffstage;
4479
4480    fn key(&self) -> Option<&KeyRef> {
4481        self.key.as_ref()
4482    }
4483
4484    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4485        properties.add(DiagnosticsProperty::new("offstage", self.offstage));
4486    }
4487
4488    /// Dart's `_OffstageElement.debugVisitOnstageChildren`: no child while offstage.
4489    fn debug_visit_onstage_children(
4490        &self,
4491        _app: &App,
4492        children: &[crate::AnyElement],
4493        visitor: &mut dyn FnMut(crate::AnyElement),
4494    ) {
4495        if !self.offstage {
4496            children.iter().for_each(|child| visitor(*child));
4497        }
4498    }
4499
4500    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4501        RenderOffstage::new(app, self.offstage, None).as_object()
4502    }
4503
4504    fn update_render_object(
4505        &self,
4506        app: &mut App,
4507        _context: BuildContext,
4508        render_object: RenderHandle<RenderOffstage>,
4509    ) {
4510        render_object.set_offstage(app, self.offstage);
4511    }
4512}
4513
4514impl SingleChildRenderObjectWidget for Offstage {
4515    fn child(&self) -> Option<&WidgetRef> {
4516        self.child.as_ref()
4517    }
4518}
4519
4520/// A widget that attempts to size the child to a specific aspect ratio.
4521///
4522/// The widget first tries the largest width permitted by the layout
4523/// constraints. The height of the widget is determined by applying the
4524/// given aspect ratio to the width, expressed as a ratio of width to height.
4525///
4526/// For example, a 16:9 width:height aspect ratio would have a value of
4527/// 16.0/9.0. If the maximum width is infinite, the initial width is determined
4528/// by applying the aspect ratio to the maximum height.
4529///
4530/// Now consider a second example, this time with an aspect ratio of 2.0 and
4531/// layout constraints that require the width to be between 0.0 and 100.0 and
4532/// the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the
4533/// biggest allowed) and a height of 50.0 (to match the aspect ratio).
4534///
4535/// ## Setting the aspect ratio in unconstrained situations
4536///
4537/// When using a widget such as [`FittedBox`], the constraints are unbounded. This
4538/// results in [`AspectRatio`] being unable to find a suitable set of constraints
4539/// to apply. In that situation, consider explicitly setting a size using
4540/// [`SizedBox`] instead of setting the aspect ratio using [`AspectRatio`]. The size
4541/// is then scaled appropriately by the [`FittedBox`].
4542///
4543/// See also:
4544///
4545///  * [`Align`], a widget that aligns its child within itself and optionally
4546///    sizes itself based on the child's size.
4547///  * [`ConstrainedBox`], a widget that imposes additional constraints on its
4548///    child.
4549///  * [`UnconstrainedBox`], a container that tries to let its child draw without
4550///    constraints.
4551///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4552#[derive(Debug)]
4553pub struct AspectRatio {
4554    pub key: Option<KeyRef>,
4555    /// The aspect ratio to attempt to use.
4556    ///
4557    /// The aspect ratio is expressed as a ratio of width to height. For example,
4558    /// a 16:9 width:height aspect ratio would have a value of 16.0/9.0.
4559    pub aspect_ratio: f64,
4560    pub child: Option<WidgetRef>,
4561}
4562
4563impl AspectRatio {
4564    /// Creates a widget with a specific aspect ratio; Dart's optional named arguments are the
4565    /// setters.
4566    ///
4567    /// The `aspect_ratio` argument must be a finite number greater than zero.
4568    pub fn new(aspect_ratio: f64) -> AspectRatio {
4569        debug_assert!(aspect_ratio > 0.0);
4570        AspectRatio {
4571            key: None,
4572            aspect_ratio,
4573            child: None,
4574        }
4575    }
4576
4577    /// Dart `AspectRatio(key:)`.
4578    pub fn key(mut self, key: KeyRef) -> AspectRatio {
4579        self.key = Some(key);
4580        self
4581    }
4582
4583    /// Dart `AspectRatio(child:)`.
4584    #[cfg_attr(debug_assertions, track_caller)]
4585    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AspectRatio {
4586        self.child = Some(child.into_widget());
4587        self
4588    }
4589}
4590
4591impl RenderObjectWidget for AspectRatio {
4592    type RenderObject = RenderAspectRatio;
4593
4594    fn key(&self) -> Option<&KeyRef> {
4595        self.key.as_ref()
4596    }
4597
4598    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4599        properties.add(DoubleProperty::new("aspectRatio", self.aspect_ratio));
4600    }
4601
4602    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4603        RenderAspectRatio::new(app, self.aspect_ratio, None).as_object()
4604    }
4605
4606    fn update_render_object(
4607        &self,
4608        app: &mut App,
4609        _context: BuildContext,
4610        render_object: RenderHandle<RenderAspectRatio>,
4611    ) {
4612        render_object.set_aspect_ratio(app, self.aspect_ratio);
4613    }
4614}
4615
4616impl SingleChildRenderObjectWidget for AspectRatio {
4617    fn child(&self) -> Option<&WidgetRef> {
4618        self.child.as_ref()
4619    }
4620}
4621
4622/// A widget that sizes its child to the child's maximum intrinsic width.
4623///
4624/// This class is useful, for example, when unlimited width is available and
4625/// you would like a child that would otherwise attempt to expand infinitely to
4626/// instead size itself to a more reasonable width. Additionally, putting a
4627/// [`Column`] inside an [`IntrinsicWidth`] will allow all [`Column`] children to be
4628/// as wide as the widest child.
4629///
4630/// The constraints that this widget passes to its child will adhere to the
4631/// parent's constraints, so if the constraints are not large enough to satisfy
4632/// the child's maximum intrinsic width, then the child will get less width
4633/// than it otherwise would. Likewise, if the minimum width constraint is
4634/// larger than the child's maximum intrinsic width, the child will be given
4635/// more width than it otherwise would.
4636///
4637/// If [`step_width`](Self::step_width) is non-`None`, the child's width will be snapped to a
4638/// multiple of the [`step_width`](Self::step_width). Similarly, if
4639/// [`step_height`](Self::step_height) is non-`None`, the child's height will be snapped to a
4640/// multiple of the [`step_height`](Self::step_height).
4641///
4642/// This class is relatively expensive, because it adds a speculative layout
4643/// pass before the final layout phase. Avoid using it where possible. In the
4644/// worst case, this widget can result in a layout that is O(N²) in the depth of
4645/// the tree.
4646///
4647/// See also:
4648///
4649///  * [`Align`], a widget that aligns its child within itself. This can be used
4650///    to loosen the constraints passed to the [`RenderIntrinsicWidth`],
4651///    allowing the [`RenderIntrinsicWidth`]'s child to be smaller than that of
4652///    its parent.
4653///  * [`Row`], which when used with `CrossAxisAlignment::Stretch` can be used
4654///    to loosen just the width constraints that are passed to the
4655///    [`RenderIntrinsicWidth`], allowing the [`RenderIntrinsicWidth`]'s child's
4656///    width to be smaller than that of its parent.
4657///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4658#[derive(Debug, Default)]
4659pub struct IntrinsicWidth {
4660    pub key: Option<KeyRef>,
4661    /// If non-`None`, force the child's width to be a multiple of this value.
4662    ///
4663    /// If `None` or 0.0 the child's width will be the same as its maximum
4664    /// intrinsic width.
4665    ///
4666    /// This value must not be negative.
4667    ///
4668    /// See also:
4669    ///
4670    ///  * `AnyRenderBox::get_max_intrinsic_width`, which defines a widget's max
4671    ///    intrinsic width in general.
4672    pub step_width: Option<f64>,
4673    /// If non-`None`, force the child's height to be a multiple of this value.
4674    ///
4675    /// If `None` or 0.0 the child's height will not be constrained.
4676    ///
4677    /// This value must not be negative.
4678    pub step_height: Option<f64>,
4679    pub child: Option<WidgetRef>,
4680}
4681
4682impl IntrinsicWidth {
4683    /// Creates a widget that sizes its child to the child's intrinsic width; Dart's named
4684    /// arguments are the setters.
4685    ///
4686    /// This class is relatively expensive. Avoid using it where possible.
4687    pub fn new() -> IntrinsicWidth {
4688        IntrinsicWidth::default()
4689    }
4690
4691    /// Dart `IntrinsicWidth(key:)`.
4692    pub fn key(mut self, key: KeyRef) -> IntrinsicWidth {
4693        self.key = Some(key);
4694        self
4695    }
4696
4697    /// Dart `IntrinsicWidth(stepWidth:)`.
4698    pub fn step_width(mut self, step_width: f64) -> IntrinsicWidth {
4699        debug_assert!(step_width >= 0.0);
4700        self.step_width = Some(step_width);
4701        self
4702    }
4703
4704    /// Dart `IntrinsicWidth(stepHeight:)`.
4705    pub fn step_height(mut self, step_height: f64) -> IntrinsicWidth {
4706        debug_assert!(step_height >= 0.0);
4707        self.step_height = Some(step_height);
4708        self
4709    }
4710
4711    /// Dart `IntrinsicWidth(child:)`.
4712    #[cfg_attr(debug_assertions, track_caller)]
4713    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> IntrinsicWidth {
4714        self.child = Some(child.into_widget());
4715        self
4716    }
4717
4718    /// Dart's private `_stepWidth`: a step of 0.0 is no step at all.
4719    fn effective_step_width(&self) -> Option<f64> {
4720        self.step_width.filter(|step| *step != 0.0)
4721    }
4722
4723    /// Dart's private `_stepHeight`.
4724    fn effective_step_height(&self) -> Option<f64> {
4725        self.step_height.filter(|step| *step != 0.0)
4726    }
4727}
4728
4729impl RenderObjectWidget for IntrinsicWidth {
4730    type RenderObject = RenderIntrinsicWidth;
4731
4732    fn key(&self) -> Option<&KeyRef> {
4733        self.key.as_ref()
4734    }
4735
4736    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4737        RenderIntrinsicWidth::new(
4738            app,
4739            self.effective_step_width(),
4740            self.effective_step_height(),
4741            None,
4742        )
4743        .as_object()
4744    }
4745
4746    fn update_render_object(
4747        &self,
4748        app: &mut App,
4749        _context: BuildContext,
4750        render_object: RenderHandle<RenderIntrinsicWidth>,
4751    ) {
4752        render_object.set_step_width(app, self.effective_step_width());
4753        render_object.set_step_height(app, self.effective_step_height());
4754    }
4755}
4756
4757impl SingleChildRenderObjectWidget for IntrinsicWidth {
4758    fn child(&self) -> Option<&WidgetRef> {
4759        self.child.as_ref()
4760    }
4761}
4762
4763/// A widget that sizes its child to the child's intrinsic height.
4764///
4765/// This class is useful, for example, when unlimited height is available and
4766/// you would like a child that would otherwise attempt to expand infinitely to
4767/// instead size itself to a more reasonable height. Additionally, putting a
4768/// [`Row`] inside an [`IntrinsicHeight`] will allow all [`Row`] children to be as tall
4769/// as the tallest child.
4770///
4771/// The constraints that this widget passes to its child will adhere to the
4772/// parent's constraints, so if the constraints are not large enough to satisfy
4773/// the child's maximum intrinsic height, then the child will get less height
4774/// than it otherwise would. Likewise, if the minimum height constraint is
4775/// larger than the child's maximum intrinsic height, the child will be given
4776/// more height than it otherwise would.
4777///
4778/// This class is relatively expensive, because it adds a speculative layout
4779/// pass before the final layout phase. Avoid using it where possible. In the
4780/// worst case, this widget can result in a layout that is O(N²) in the depth of
4781/// the tree.
4782///
4783/// See also:
4784///
4785///  * [`Align`], a widget that aligns its child within itself. This can be used
4786///    to loosen the constraints passed to the [`RenderIntrinsicHeight`],
4787///    allowing the [`RenderIntrinsicHeight`]'s child to be smaller than that of
4788///    its parent.
4789///  * [`Column`], which when used with `CrossAxisAlignment::Stretch` can be used
4790///    to loosen just the height constraints that are passed to the
4791///    [`RenderIntrinsicHeight`], allowing the [`RenderIntrinsicHeight`]'s child's
4792///    height to be smaller than that of its parent.
4793///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4794#[derive(Debug, Default)]
4795pub struct IntrinsicHeight {
4796    pub key: Option<KeyRef>,
4797    pub child: Option<WidgetRef>,
4798}
4799
4800impl IntrinsicHeight {
4801    /// Creates a widget that sizes its child to the child's intrinsic height; Dart's named
4802    /// arguments are the setters.
4803    ///
4804    /// This class is relatively expensive. Avoid using it where possible.
4805    pub fn new() -> IntrinsicHeight {
4806        IntrinsicHeight::default()
4807    }
4808
4809    /// Dart `IntrinsicHeight(key:)`.
4810    pub fn key(mut self, key: KeyRef) -> IntrinsicHeight {
4811        self.key = Some(key);
4812        self
4813    }
4814
4815    /// Dart `IntrinsicHeight(child:)`.
4816    #[cfg_attr(debug_assertions, track_caller)]
4817    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> IntrinsicHeight {
4818        self.child = Some(child.into_widget());
4819        self
4820    }
4821}
4822
4823impl RenderObjectWidget for IntrinsicHeight {
4824    type RenderObject = RenderIntrinsicHeight;
4825
4826    fn key(&self) -> Option<&KeyRef> {
4827        self.key.as_ref()
4828    }
4829
4830    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4831        RenderIntrinsicHeight::new(app, None).as_object()
4832    }
4833}
4834
4835impl SingleChildRenderObjectWidget for IntrinsicHeight {
4836    fn child(&self) -> Option<&WidgetRef> {
4837        self.child.as_ref()
4838    }
4839}
4840
4841/// A widget that positions its child according to the child's baseline.
4842///
4843/// This widget shifts the child down such that the child's baseline (or the
4844/// bottom of the child, if the child has no baseline) is
4845/// [`baseline`](Self::baseline) logical pixels below the top of this box, then sizes this box
4846/// to contain the child. If [`baseline`](Self::baseline) is less than the distance from the
4847/// top of the child to the baseline of the child, then the child is top-aligned instead.
4848///
4849/// See also:
4850///
4851///  * [`Align`], a widget that aligns its child within itself and optionally
4852///    sizes itself based on the child's size.
4853///  * [`Center`], a widget that centers its child within itself.
4854///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
4855#[derive(Debug)]
4856pub struct Baseline {
4857    pub key: Option<KeyRef>,
4858    /// The number of logical pixels from the top of this box at which to position
4859    /// the child's baseline.
4860    pub baseline: f64,
4861    /// The type of baseline to use for positioning the child.
4862    pub baseline_type: TextBaseline,
4863    pub child: Option<WidgetRef>,
4864}
4865
4866impl Baseline {
4867    /// Creates a widget that positions its child according to the child's baseline; Dart's
4868    /// optional named arguments are the setters.
4869    pub fn new(baseline: f64, baseline_type: TextBaseline) -> Baseline {
4870        Baseline {
4871            key: None,
4872            baseline,
4873            baseline_type,
4874            child: None,
4875        }
4876    }
4877
4878    /// Dart `Baseline(key:)`.
4879    pub fn key(mut self, key: KeyRef) -> Baseline {
4880        self.key = Some(key);
4881        self
4882    }
4883
4884    /// Dart `Baseline(child:)`.
4885    #[cfg_attr(debug_assertions, track_caller)]
4886    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Baseline {
4887        self.child = Some(child.into_widget());
4888        self
4889    }
4890}
4891
4892impl RenderObjectWidget for Baseline {
4893    type RenderObject = RenderBaseline;
4894
4895    fn key(&self) -> Option<&KeyRef> {
4896        self.key.as_ref()
4897    }
4898
4899    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4900        RenderBaseline::new(app, self.baseline, self.baseline_type, None).as_object()
4901    }
4902
4903    fn update_render_object(
4904        &self,
4905        app: &mut App,
4906        _context: BuildContext,
4907        render_object: RenderHandle<RenderBaseline>,
4908    ) {
4909        render_object.set_baseline(app, self.baseline);
4910        render_object.set_baseline_type(app, self.baseline_type);
4911    }
4912}
4913
4914impl SingleChildRenderObjectWidget for Baseline {
4915    fn child(&self) -> Option<&WidgetRef> {
4916        self.child.as_ref()
4917    }
4918}
4919
4920// SLIVERS
4921
4922/// A sliver that contains a single box widget.
4923///
4924/// Slivers are special-purpose widgets that can be combined using a `CustomScrollView` to
4925/// create custom scroll effects. A [`SliverToBoxAdapter`] is a basic sliver that creates a
4926/// bridge back to one of the usual box-based widgets.
4927///
4928/// _To learn more about slivers, see `CustomScrollView::slivers`._
4929///
4930/// Rather than using multiple [`SliverToBoxAdapter`] widgets to display multiple box widgets
4931/// in a `CustomScrollView`, consider using `SliverList`, `SliverFixedExtentList`,
4932/// `SliverPrototypeExtentList`, or `SliverGrid`, which are more efficient because they
4933/// instantiate only those children that are actually visible through the scroll view's
4934/// viewport.
4935///
4936/// See also:
4937///
4938///  * `CustomScrollView`, which displays a scrollable list of slivers.
4939///  * `SliverList`, which displays multiple box widgets in a linear array.
4940///  * `SliverFixedExtentList`, which displays multiple box widgets with the same main-axis
4941///    extent in a linear array.
4942///  * `SliverGrid`, which displays multiple box widgets in arbitrary positions.
4943#[derive(Debug, Default)]
4944pub struct SliverToBoxAdapter {
4945    pub key: Option<KeyRef>,
4946    pub child: Option<WidgetRef>,
4947}
4948
4949impl SliverToBoxAdapter {
4950    /// Creates a sliver that contains a single box widget.
4951    pub fn new() -> SliverToBoxAdapter {
4952        SliverToBoxAdapter::default()
4953    }
4954
4955    /// Dart `SliverToBoxAdapter(key:)`.
4956    pub fn key(mut self, key: KeyRef) -> SliverToBoxAdapter {
4957        self.key = Some(key);
4958        self
4959    }
4960
4961    /// Dart `SliverToBoxAdapter(child:)`.
4962    #[cfg_attr(debug_assertions, track_caller)]
4963    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SliverToBoxAdapter {
4964        self.child = Some(child.into_widget());
4965        self
4966    }
4967}
4968
4969impl RenderObjectWidget for SliverToBoxAdapter {
4970    type RenderObject = RenderSliverToBoxAdapter;
4971
4972    fn key(&self) -> Option<&KeyRef> {
4973        self.key.as_ref()
4974    }
4975
4976    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
4977        RenderSliverToBoxAdapter::new(app, None).as_object()
4978    }
4979}
4980
4981impl SingleChildRenderObjectWidget for SliverToBoxAdapter {
4982    fn child(&self) -> Option<&WidgetRef> {
4983        self.child.as_ref()
4984    }
4985}
4986
4987/// A sliver that applies padding on each side of another sliver.
4988///
4989/// Slivers are special-purpose widgets that can be combined using a `CustomScrollView` to
4990/// create custom scroll effects. A [`SliverPadding`] is a basic sliver that insets another
4991/// sliver by applying padding on each side.
4992///
4993/// Applying padding in the main axis of the viewport to a sliver whose
4994/// `SliverGeometry::scroll_extent` is longer than the viewport is generally undesirable, as
4995/// the padding is applied to the whole sliver rather than to the visible part of it.
4996///
4997/// See also:
4998///
4999///  * `CustomScrollView`, which displays a scrollable list of slivers.
5000///  * [`Padding`], the box version of this widget.
5001#[derive(Debug)]
5002pub struct SliverPadding {
5003    pub key: Option<KeyRef>,
5004    /// The amount of space by which to inset the child sliver.
5005    pub padding: EdgeInsetsGeometry,
5006    pub sliver: Option<WidgetRef>,
5007}
5008
5009impl SliverPadding {
5010    /// Creates a sliver that applies padding on each side of another sliver.
5011    pub fn new(padding: impl Into<EdgeInsetsGeometry>) -> SliverPadding {
5012        let padding = padding.into();
5013        SliverPadding {
5014            key: None,
5015            padding,
5016            sliver: None,
5017        }
5018    }
5019
5020    /// Dart `SliverPadding(key:)`.
5021    pub fn key(mut self, key: KeyRef) -> SliverPadding {
5022        self.key = Some(key);
5023        self
5024    }
5025
5026    /// Dart `SliverPadding(sliver:)`.
5027    #[cfg_attr(debug_assertions, track_caller)]
5028    pub fn sliver<K>(mut self, sliver: impl IntoWidget<K>) -> SliverPadding {
5029        self.sliver = Some(sliver.into_widget());
5030        self
5031    }
5032}
5033
5034impl RenderObjectWidget for SliverPadding {
5035    type RenderObject = RenderSliverPadding;
5036
5037    fn key(&self) -> Option<&KeyRef> {
5038        self.key.as_ref()
5039    }
5040
5041    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5042        properties.add(DiagnosticsProperty::new("padding", self.padding));
5043    }
5044
5045    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
5046        let text_direction = Directionality::of(app, context);
5047        RenderSliverPadding::new(app, self.padding, Some(text_direction), None).as_object()
5048    }
5049
5050    fn update_render_object(
5051        &self,
5052        app: &mut App,
5053        context: BuildContext,
5054        render_object: RenderHandle<RenderSliverPadding>,
5055    ) {
5056        render_object.set_padding(app, self.padding);
5057        let text_direction = Directionality::of(app, context);
5058        render_object.set_text_direction(app, Some(text_direction));
5059    }
5060}
5061
5062impl SingleChildRenderObjectWidget for SliverPadding {
5063    fn child(&self) -> Option<&WidgetRef> {
5064        self.sliver.as_ref()
5065    }
5066}
5067
5068// EVENT HANDLING
5069
5070/// A widget that calls callbacks in response to common pointer events.
5071///
5072/// It listens to events that can construct gestures, such as when the
5073/// pointer is pressed, moved, then released or canceled.
5074///
5075/// It does not listen to events that are exclusive to mouse, such as when the
5076/// mouse enters, exits or hovers a region without pressing any buttons. For
5077/// these events, use [`MouseRegion`].
5078///
5079/// Rather than listening for raw pointer events, consider listening for
5080/// higher-level gestures using `GestureDetector`.
5081///
5082/// ## Layout behavior
5083///
5084/// _See [`BoxConstraints`] for an introduction to box layout models._
5085///
5086/// If it has a child, this widget defers to the child for sizing behavior. If
5087/// it does not have a child, it grows to fit the parent instead.
5088///
5089/// The [`behavior`](Self::behavior) argument defaults to [`HitTestBehavior::DeferToChild`].
5090pub struct Listener {
5091    pub key: Option<KeyRef>,
5092    /// Called when a pointer comes into contact with the screen (for touch
5093    /// pointers), or has its button pressed (for mouse pointers) at this widget's
5094    /// location.
5095    pub on_pointer_down: Option<PointerDownEventListener>,
5096    /// Called when a pointer that triggered an [`on_pointer_down`](Self::on_pointer_down)
5097    /// changes position.
5098    pub on_pointer_move: Option<PointerMoveEventListener>,
5099    /// Called when a pointer that triggered an [`on_pointer_down`](Self::on_pointer_down) is
5100    /// no longer in contact with the screen.
5101    pub on_pointer_up: Option<PointerUpEventListener>,
5102    /// Called when a pointer that has not triggered an
5103    /// [`on_pointer_down`](Self::on_pointer_down) changes position.
5104    ///
5105    /// This is only fired for pointers which report their location when not down
5106    /// (e.g. mouse pointers, but not most touch pointers).
5107    pub on_pointer_hover: Option<PointerHoverEventListener>,
5108    /// Called when the input from a pointer that triggered an
5109    /// [`on_pointer_down`](Self::on_pointer_down) is no longer directed towards this receiver.
5110    pub on_pointer_cancel: Option<PointerCancelEventListener>,
5111    /// Called when a pan/zoom begins such as from a trackpad gesture.
5112    pub on_pointer_pan_zoom_start: Option<PointerPanZoomStartEventListener>,
5113    /// Called when a pan/zoom is updated.
5114    pub on_pointer_pan_zoom_update: Option<PointerPanZoomUpdateEventListener>,
5115    /// Called when a pan/zoom finishes.
5116    pub on_pointer_pan_zoom_end: Option<PointerPanZoomEndEventListener>,
5117    /// Called when a pointer signal occurs over this object.
5118    ///
5119    /// See also:
5120    ///
5121    ///  * `PointerSignalEvent`, which goes into more detail on pointer signal
5122    ///    events.
5123    pub on_pointer_signal: Option<PointerSignalEventListener>,
5124    /// How to behave during hit testing.
5125    pub behavior: HitTestBehavior,
5126    pub child: Option<WidgetRef>,
5127}
5128
5129impl Listener {
5130    /// Creates a `Listener`; Dart's named arguments are the setters.
5131    pub fn new() -> Listener {
5132        Listener::default()
5133    }
5134
5135    /// Dart `Listener(key:)`.
5136    pub fn key(mut self, key: KeyRef) -> Listener {
5137        self.key = Some(key);
5138        self
5139    }
5140
5141    /// Dart `Listener(on_pointer_down:)`.
5142    pub fn on_pointer_down(mut self, on_pointer_down: PointerDownEventListener) -> Listener {
5143        self.on_pointer_down = Some(on_pointer_down);
5144        self
5145    }
5146
5147    /// Dart `Listener(on_pointer_move:)`.
5148    pub fn on_pointer_move(mut self, on_pointer_move: PointerMoveEventListener) -> Listener {
5149        self.on_pointer_move = Some(on_pointer_move);
5150        self
5151    }
5152
5153    /// Dart `Listener(on_pointer_up:)`.
5154    pub fn on_pointer_up(mut self, on_pointer_up: PointerUpEventListener) -> Listener {
5155        self.on_pointer_up = Some(on_pointer_up);
5156        self
5157    }
5158
5159    /// Dart `Listener(on_pointer_hover:)`.
5160    pub fn on_pointer_hover(mut self, on_pointer_hover: PointerHoverEventListener) -> Listener {
5161        self.on_pointer_hover = Some(on_pointer_hover);
5162        self
5163    }
5164
5165    /// Dart `Listener(on_pointer_cancel:)`.
5166    pub fn on_pointer_cancel(mut self, on_pointer_cancel: PointerCancelEventListener) -> Listener {
5167        self.on_pointer_cancel = Some(on_pointer_cancel);
5168        self
5169    }
5170
5171    /// Dart `Listener(on_pointer_pan_zoom_start:)`.
5172    pub fn on_pointer_pan_zoom_start(
5173        mut self,
5174        on_pointer_pan_zoom_start: PointerPanZoomStartEventListener,
5175    ) -> Listener {
5176        self.on_pointer_pan_zoom_start = Some(on_pointer_pan_zoom_start);
5177        self
5178    }
5179
5180    /// Dart `Listener(on_pointer_pan_zoom_update:)`.
5181    pub fn on_pointer_pan_zoom_update(
5182        mut self,
5183        on_pointer_pan_zoom_update: PointerPanZoomUpdateEventListener,
5184    ) -> Listener {
5185        self.on_pointer_pan_zoom_update = Some(on_pointer_pan_zoom_update);
5186        self
5187    }
5188
5189    /// Dart `Listener(on_pointer_pan_zoom_end:)`.
5190    pub fn on_pointer_pan_zoom_end(
5191        mut self,
5192        on_pointer_pan_zoom_end: PointerPanZoomEndEventListener,
5193    ) -> Listener {
5194        self.on_pointer_pan_zoom_end = Some(on_pointer_pan_zoom_end);
5195        self
5196    }
5197
5198    /// Dart `Listener(on_pointer_signal:)`.
5199    pub fn on_pointer_signal(mut self, on_pointer_signal: PointerSignalEventListener) -> Listener {
5200        self.on_pointer_signal = Some(on_pointer_signal);
5201        self
5202    }
5203
5204    /// Dart `Listener(behavior:)`.
5205    pub fn behavior(mut self, behavior: HitTestBehavior) -> Listener {
5206        self.behavior = behavior;
5207        self
5208    }
5209
5210    /// Dart `Listener(child:)`.
5211    #[cfg_attr(debug_assertions, track_caller)]
5212    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Listener {
5213        self.child = Some(child.into_widget());
5214        self
5215    }
5216
5217    /// Copies the callbacks onto the render object; Dart's constructor and the setters
5218    /// share this list.
5219    fn apply_listeners(&self, app: &mut App, render_object: RenderHandle<RenderPointerListener>) {
5220        render_object.set_on_pointer_down(app, self.on_pointer_down.clone());
5221        render_object.set_on_pointer_move(app, self.on_pointer_move.clone());
5222        render_object.set_on_pointer_up(app, self.on_pointer_up.clone());
5223        render_object.set_on_pointer_hover(app, self.on_pointer_hover.clone());
5224        render_object.set_on_pointer_cancel(app, self.on_pointer_cancel.clone());
5225        render_object.set_on_pointer_pan_zoom_start(app, self.on_pointer_pan_zoom_start.clone());
5226        render_object.set_on_pointer_pan_zoom_update(app, self.on_pointer_pan_zoom_update.clone());
5227        render_object.set_on_pointer_pan_zoom_end(app, self.on_pointer_pan_zoom_end.clone());
5228        render_object.set_on_pointer_signal(app, self.on_pointer_signal.clone());
5229    }
5230
5231    /// Dart's `debugFillProperties` `listeners` list: the callbacks that are set.
5232    fn listener_names(&self) -> Vec<&'static str> {
5233        let listeners = [
5234            (self.on_pointer_down.is_some(), "down"),
5235            (self.on_pointer_move.is_some(), "move"),
5236            (self.on_pointer_up.is_some(), "up"),
5237            (self.on_pointer_hover.is_some(), "hover"),
5238            (self.on_pointer_cancel.is_some(), "cancel"),
5239            (self.on_pointer_pan_zoom_start.is_some(), "panZoomStart"),
5240            (self.on_pointer_pan_zoom_update.is_some(), "panZoomUpdate"),
5241            (self.on_pointer_pan_zoom_end.is_some(), "panZoomEnd"),
5242            (self.on_pointer_signal.is_some(), "signal"),
5243        ];
5244        listeners
5245            .into_iter()
5246            .filter_map(|(is_set, name)| is_set.then_some(name))
5247            .collect()
5248    }
5249}
5250
5251impl Default for Listener {
5252    fn default() -> Listener {
5253        Listener {
5254            key: None,
5255            on_pointer_down: None,
5256            on_pointer_move: None,
5257            on_pointer_up: None,
5258            on_pointer_hover: None,
5259            on_pointer_cancel: None,
5260            on_pointer_pan_zoom_start: None,
5261            on_pointer_pan_zoom_update: None,
5262            on_pointer_pan_zoom_end: None,
5263            on_pointer_signal: None,
5264            behavior: HitTestBehavior::DeferToChild,
5265            child: None,
5266        }
5267    }
5268}
5269
5270impl RenderObjectWidget for Listener {
5271    type RenderObject = RenderPointerListener;
5272
5273    fn key(&self) -> Option<&KeyRef> {
5274        self.key.as_ref()
5275    }
5276
5277    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5278        let mut listeners: Vec<String> = Vec::new();
5279        if self.on_pointer_down.is_some() {
5280            listeners.push("down".to_string());
5281        }
5282        if self.on_pointer_move.is_some() {
5283            listeners.push("move".to_string());
5284        }
5285        if self.on_pointer_up.is_some() {
5286            listeners.push("up".to_string());
5287        }
5288        if self.on_pointer_hover.is_some() {
5289            listeners.push("hover".to_string());
5290        }
5291        if self.on_pointer_cancel.is_some() {
5292            listeners.push("cancel".to_string());
5293        }
5294        if self.on_pointer_pan_zoom_start.is_some() {
5295            listeners.push("panZoomStart".to_string());
5296        }
5297        if self.on_pointer_pan_zoom_update.is_some() {
5298            listeners.push("panZoomUpdate".to_string());
5299        }
5300        if self.on_pointer_pan_zoom_end.is_some() {
5301            listeners.push("panZoomEnd".to_string());
5302        }
5303        if self.on_pointer_signal.is_some() {
5304            listeners.push("signal".to_string());
5305        }
5306        properties.add(IterableProperty::<String>::new("listeners", listeners).if_empty("<none>"));
5307        properties.add(EnumProperty::new("behavior", self.behavior));
5308    }
5309
5310    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
5311        let render_object = RenderPointerListener::new(app, self.behavior, None);
5312        self.apply_listeners(app, render_object);
5313        render_object.as_object()
5314    }
5315
5316    fn update_render_object(
5317        &self,
5318        app: &mut App,
5319        _context: BuildContext,
5320        render_object: RenderHandle<RenderPointerListener>,
5321    ) {
5322        self.apply_listeners(app, render_object);
5323        render_object.set_behavior(app, self.behavior);
5324    }
5325}
5326
5327impl SingleChildRenderObjectWidget for Listener {
5328    fn child(&self) -> Option<&WidgetRef> {
5329        self.child.as_ref()
5330    }
5331}
5332
5333impl Debug for Listener {
5334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5335        f.debug_struct("Listener")
5336            .field("key", &self.key)
5337            .field("listeners", &self.listener_names())
5338            .field("behavior", &self.behavior)
5339            .field("child", &self.child)
5340            .finish()
5341    }
5342}
5343
5344/// A widget that tracks the movement of mice.
5345///
5346/// [`MouseRegion`] is used
5347/// when it is needed to compare the list of objects that a mouse pointer is
5348/// hovering over between this frame and the last frame. This means entering
5349/// events, exiting events, and mouse cursors.
5350///
5351/// To listen to general pointer events, use [`Listener`], or more preferably,
5352/// `GestureDetector`.
5353///
5354/// ## Layout behavior
5355///
5356/// _See [`BoxConstraints`] for an introduction to box layout models._
5357///
5358/// If it has a child, this widget defers to the child for sizing behavior. If
5359/// it does not have a child, it grows to fit the parent instead.
5360///
5361/// See also:
5362///
5363///  * [`Listener`], a similar widget that tracks pointer events when the pointer
5364///    has buttons pressed.
5365///
5366/// By default, all callbacks are empty, [`cursor`](Self::cursor) is `MouseCursor.defer`, and
5367/// [`opaque`](Self::opaque) is true.
5368pub struct MouseRegion {
5369    pub key: Option<KeyRef>,
5370    /// Triggered when a mouse pointer has entered this widget.
5371    ///
5372    /// This callback is triggered when the pointer, with or without buttons
5373    /// pressed, has started to be contained by the region of this widget. More
5374    /// specifically, the callback is triggered by the following cases:
5375    ///
5376    ///  * This widget has appeared under a pointer.
5377    ///  * This widget has moved to under a pointer.
5378    ///  * A new pointer has been added to somewhere within this widget.
5379    ///  * An existing pointer has moved into this widget.
5380    ///
5381    /// This callback is not always matched by an [`on_exit`](Self::on_exit). If the
5382    /// [`MouseRegion`] is unmounted while being hovered by a pointer, the
5383    /// [`on_exit`](Self::on_exit) of the widget callback will never called. For more details,
5384    /// see [`on_exit`](Self::on_exit).
5385    ///
5386    /// The time that this callback is triggered is always between frames: either
5387    /// during the post-frame callbacks, or during the callback of a pointer
5388    /// event.
5389    ///
5390    /// See also:
5391    ///
5392    ///  * [`on_exit`](Self::on_exit), which is triggered when a mouse pointer exits the region.
5393    ///  * `MouseTrackerAnnotation.onEnter`, which is how this callback is
5394    ///    internally implemented.
5395    pub on_enter: Option<PointerEnterEventListener>,
5396    /// Triggered when a pointer moves into a position within this widget without
5397    /// buttons pressed.
5398    ///
5399    /// Usually this is only fired for pointers which report their location when
5400    /// not down (e.g. mouse pointers). Certain devices also fire this event on
5401    /// single taps in accessibility mode.
5402    ///
5403    /// This callback is not triggered by the movement of the widget.
5404    ///
5405    /// The time that this callback is triggered is during the callback of a
5406    /// pointer event, which is always between frames.
5407    ///
5408    /// See also:
5409    ///
5410    ///  * [`Listener::on_pointer_hover`], which does the same job. Prefer using
5411    ///    [`Listener::on_pointer_hover`], since hover events are similar to other regular
5412    ///    events.
5413    pub on_hover: Option<PointerHoverEventListener>,
5414    /// Triggered when a mouse pointer has exited this widget when the widget is
5415    /// still mounted.
5416    ///
5417    /// This callback is triggered when the pointer, with or without buttons
5418    /// pressed, has stopped being contained by the region of this widget, except
5419    /// when the exit is caused by the disappearance of this widget. More
5420    /// specifically, this callback is triggered by the following cases:
5421    ///
5422    ///  * A pointer that is hovering this widget has moved away.
5423    ///  * A pointer that is hovering this widget has been removed.
5424    ///  * This widget, which is being hovered by a pointer, has moved away.
5425    ///
5426    /// And is __not__ triggered by the following case:
5427    ///
5428    ///  * This widget, which is being hovered by a pointer, has disappeared.
5429    ///
5430    /// This means that a [`MouseRegion::on_exit`] might not be matched by a
5431    /// [`MouseRegion::on_enter`].
5432    ///
5433    /// This restriction aims to prevent a common misuse: if `State::set_state` is
5434    /// called during [`MouseRegion::on_exit`] without checking whether the widget is
5435    /// still mounted, an exception will occur. This is because the callback is
5436    /// triggered during the post-frame phase, at which point the widget has been
5437    /// unmounted. Since `State::set_state` is exclusive to widgets, the restriction
5438    /// is specific to [`MouseRegion`], and does not apply to its lower-level
5439    /// counterparts, [`RenderMouseRegion`] and `MouseTrackerAnnotation`.
5440    ///
5441    /// There are a few ways to mitigate this restriction:
5442    ///
5443    ///  * If the hover state is completely contained within a widget that
5444    ///    unconditionally creates this [`MouseRegion`], then this will not be a
5445    ///    concern, since after the [`MouseRegion`] is unmounted the state is no
5446    ///    longer used.
5447    ///  * Otherwise, the outer widget very likely has access to the variable that
5448    ///    controls whether this [`MouseRegion`] is present. If so, call
5449    ///    [`on_exit`](Self::on_exit) at the event that turns the condition from true to false.
5450    ///  * In cases where the solutions above won't work, you can always
5451    ///    override `State::dispose` and call [`on_exit`](Self::on_exit), or create your own
5452    ///    widget using [`RenderMouseRegion`].
5453    ///
5454    /// See also:
5455    ///
5456    ///  * [`on_enter`](Self::on_enter), which is triggered when a mouse pointer enters the
5457    ///    region.
5458    ///  * [`RenderMouseRegion`] and `MouseTrackerAnnotation.onExit`, which are how
5459    ///    this callback is internally implemented, but without the restriction.
5460    pub on_exit: Option<PointerExitEventListener>,
5461    /// The mouse cursor for mouse pointers that are hovering over the region.
5462    ///
5463    /// When a mouse enters the region, its cursor will be changed to the
5464    /// [`cursor`](Self::cursor). When the mouse leaves the region, the cursor will be decided
5465    /// by the region found at the new location.
5466    ///
5467    /// The [`cursor`](Self::cursor) defaults to `MouseCursor.defer`, deferring the choice of
5468    /// cursor to the next region behind it in hit-test order.
5469    pub cursor: MouseCursorRef,
5470    /// Whether this widget should prevent other [`MouseRegion`]s visually behind it
5471    /// from detecting the pointer.
5472    ///
5473    /// This changes the list of regions that a pointer hovers, thus affecting how
5474    /// their [`on_hover`](Self::on_hover), [`on_enter`](Self::on_enter),
5475    /// [`on_exit`](Self::on_exit), and [`cursor`](Self::cursor) behave.
5476    ///
5477    /// If [`opaque`](Self::opaque) is true, this widget will absorb the mouse pointer and
5478    /// prevent this widget's siblings (or any other widgets that are not
5479    /// ancestors or descendants of this widget) from detecting the mouse
5480    /// pointer even when the pointer is within their areas.
5481    ///
5482    /// If [`opaque`](Self::opaque) is false, this object will not affect how [`MouseRegion`]s
5483    /// behind it behave, which will detect the mouse pointer as long as the
5484    /// pointer is within their areas.
5485    ///
5486    /// This defaults to true.
5487    pub opaque: bool,
5488    /// How to behave during hit testing.
5489    ///
5490    /// This defaults to [`HitTestBehavior::Opaque`] if `None`.
5491    pub hit_test_behavior: Option<HitTestBehavior>,
5492    pub child: Option<WidgetRef>,
5493}
5494
5495impl MouseRegion {
5496    /// Creates a `MouseRegion`; Dart's named arguments are the setters.
5497    pub fn new() -> MouseRegion {
5498        MouseRegion::default()
5499    }
5500
5501    /// Dart `MouseRegion(key:)`.
5502    pub fn key(mut self, key: KeyRef) -> MouseRegion {
5503        self.key = Some(key);
5504        self
5505    }
5506
5507    /// Dart `MouseRegion(on_enter:)`.
5508    pub fn on_enter(mut self, on_enter: PointerEnterEventListener) -> MouseRegion {
5509        self.on_enter = Some(on_enter);
5510        self
5511    }
5512
5513    /// Dart `MouseRegion(on_hover:)`.
5514    pub fn on_hover(mut self, on_hover: PointerHoverEventListener) -> MouseRegion {
5515        self.on_hover = Some(on_hover);
5516        self
5517    }
5518
5519    /// Dart `MouseRegion(on_exit:)`.
5520    pub fn on_exit(mut self, on_exit: PointerExitEventListener) -> MouseRegion {
5521        self.on_exit = Some(on_exit);
5522        self
5523    }
5524
5525    /// Dart `MouseRegion(cursor:)`.
5526    pub fn cursor(mut self, cursor: MouseCursorRef) -> MouseRegion {
5527        self.cursor = cursor;
5528        self
5529    }
5530
5531    /// Dart `MouseRegion(opaque:)`.
5532    pub fn opaque(mut self, opaque: bool) -> MouseRegion {
5533        self.opaque = opaque;
5534        self
5535    }
5536
5537    /// Dart `MouseRegion(hit_test_behavior:)`.
5538    pub fn hit_test_behavior(mut self, hit_test_behavior: HitTestBehavior) -> MouseRegion {
5539        self.hit_test_behavior = Some(hit_test_behavior);
5540        self
5541    }
5542
5543    /// Dart `MouseRegion(child:)`.
5544    #[cfg_attr(debug_assertions, track_caller)]
5545    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MouseRegion {
5546        self.child = Some(child.into_widget());
5547        self
5548    }
5549
5550    /// Copies the configuration onto the render object; Dart's constructor and the setters
5551    /// share this list. Generic so a subclass's render object takes it as Dart's inherited
5552    /// `updateRenderObject` does (`raw_tooltip.rs`'s `ExclusiveMouseRegion`).
5553    pub(crate) fn apply_configuration<R: RenderMouseRegionBase>(
5554        &self,
5555        app: &mut App,
5556        render_object: RenderHandle<R>,
5557    ) {
5558        render_object.set_on_enter(app, self.on_enter.clone());
5559        render_object.set_on_hover(app, self.on_hover.clone());
5560        render_object.set_on_exit(app, self.on_exit.clone());
5561        render_object.set_cursor(app, Rc::clone(&self.cursor));
5562        render_object.set_opaque(app, self.opaque);
5563        render_object.set_hit_test_behavior(app, self.hit_test_behavior);
5564    }
5565
5566    /// Dart's `debugFillProperties` `listeners` list: the callbacks that are set.
5567    fn listener_names(&self) -> Vec<&'static str> {
5568        let listeners = [
5569            (self.on_enter.is_some(), "enter"),
5570            (self.on_exit.is_some(), "exit"),
5571            (self.on_hover.is_some(), "hover"),
5572        ];
5573        listeners
5574            .into_iter()
5575            .filter_map(|(is_set, name)| is_set.then_some(name))
5576            .collect()
5577    }
5578}
5579
5580impl Default for MouseRegion {
5581    fn default() -> MouseRegion {
5582        MouseRegion {
5583            key: None,
5584            on_enter: None,
5585            on_hover: None,
5586            on_exit: None,
5587            cursor: <dyn MouseCursor>::defer(),
5588            opaque: true,
5589            hit_test_behavior: None,
5590            child: None,
5591        }
5592    }
5593}
5594
5595impl RenderObjectWidget for MouseRegion {
5596    type RenderObject = RenderMouseRegion;
5597
5598    fn key(&self) -> Option<&KeyRef> {
5599        self.key.as_ref()
5600    }
5601
5602    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5603        let mut listeners: Vec<String> = Vec::new();
5604        if self.on_enter.is_some() {
5605            listeners.push("enter".to_string());
5606        }
5607        if self.on_exit.is_some() {
5608            listeners.push("exit".to_string());
5609        }
5610        if self.on_hover.is_some() {
5611            listeners.push("hover".to_string());
5612        }
5613        properties.add(IterableProperty::<String>::new("listeners", listeners).if_empty("<none>"));
5614        properties.add(DiagnosticsProperty::<String>::new(
5615            "cursor",
5616            Some(self.cursor.debug_description()),
5617        ));
5618        properties.add(
5619            DiagnosticsProperty::<bool>::new("opaque", Some(self.opaque)).default_value(Some(true)),
5620        );
5621    }
5622
5623    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
5624        let render_object = RenderMouseRegion::new(app, true, None);
5625        self.apply_configuration(app, render_object);
5626        render_object.as_object()
5627    }
5628
5629    fn update_render_object(
5630        &self,
5631        app: &mut App,
5632        _context: BuildContext,
5633        render_object: RenderHandle<RenderMouseRegion>,
5634    ) {
5635        self.apply_configuration(app, render_object);
5636    }
5637}
5638
5639impl SingleChildRenderObjectWidget for MouseRegion {
5640    fn child(&self) -> Option<&WidgetRef> {
5641        self.child.as_ref()
5642    }
5643}
5644
5645impl Debug for MouseRegion {
5646    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5647        f.debug_struct("MouseRegion")
5648            .field("key", &self.key)
5649            .field("listeners", &self.listener_names())
5650            .field("cursor", &self.cursor)
5651            .field("opaque", &self.opaque)
5652            .field("child", &self.child)
5653            .finish()
5654    }
5655}
5656
5657/// A widget that creates a separate display list for its child.
5658///
5659/// This widget creates a separate display list for its child, which
5660/// can improve performance if the subtree repaints at different times than
5661/// the surrounding parts of the tree.
5662///
5663/// This is useful since `RenderObject::paint` may be triggered even if its
5664/// associated `Widget` instances did not change or rebuild. A `RenderObject`
5665/// will repaint whenever any `RenderObject` that shares the same `Layer` is
5666/// marked as being dirty and needing paint (see `RenderObject::mark_needs_paint`),
5667/// such as when an ancestor scrolls or when an ancestor or descendant animates.
5668///
5669/// Containing `RenderObject::paint` to parts of the render subtree that are
5670/// actually visually changing using [`RepaintBoundary`] explicitly or implicitly
5671/// is therefore critical to minimizing redundant work and improving the app's
5672/// performance.
5673///
5674/// When a `RenderObject` is flagged as needing to paint via
5675/// `RenderObject::mark_needs_paint`, the nearest ancestor `RenderObject` with
5676/// `RenderObject::is_repaint_boundary`, up to possibly the root of the application,
5677/// is requested to repaint. That nearest ancestor's `RenderObject::paint` method
5678/// will cause _all_ of its descendant `RenderObject`s to repaint in the same
5679/// layer.
5680///
5681/// [`RepaintBoundary`] is therefore used, both while propagating the
5682/// `mark_needs_paint` flag up the render tree and while traversing down the
5683/// render tree via `PaintingContext::paint_child`, to strategically contain
5684/// repaints to the render subtree that visually changed for performance. This
5685/// is done because the [`RepaintBoundary`] widget creates a `RenderObject` that
5686/// always has a `Layer`, decoupling ancestor render objects from the descendant
5687/// render objects.
5688///
5689/// [`RepaintBoundary`] has the further side-effect of possibly hinting to the
5690/// engine that it should further optimize animation performance if the render
5691/// subtree behind the [`RepaintBoundary`] is sufficiently complex and is static
5692/// while the surrounding tree changes frequently. In those cases, the engine
5693/// may choose to pay a one time cost of rasterizing and caching the pixel
5694/// values of the subtree for faster future GPU re-rendering speed.
5695///
5696/// Several framework widgets insert [`RepaintBoundary`] widgets to mark natural
5697/// separation points in applications. For instance, contents in Material Design
5698/// drawers typically don't change while the drawer opens and closes, so
5699/// repaints are automatically contained to regions inside or outside the drawer
5700/// when using the `Drawer` widget during transitions.
5701///
5702/// See also:
5703///
5704///  * `debugRepaintRainbowEnabled`, a debugging flag to help visually monitor
5705///    render tree repaints in a running app.
5706///  * `debugProfilePaintsEnabled`, a debugging flag to show render tree
5707///    repaints in Flutter DevTools' timeline view.
5708///
5709/// Dart's `RepaintBoundary.wrap` and `wrapAll` wait on their callers, the sliver child
5710/// delegates; their key is formed as [`KeyedSubtree::wrap`]'s is.
5711#[derive(Debug, Default)]
5712pub struct RepaintBoundary {
5713    pub key: Option<KeyRef>,
5714    pub child: Option<WidgetRef>,
5715}
5716
5717impl RepaintBoundary {
5718    /// Creates a `RepaintBoundary`; Dart's named arguments are the setters.
5719    pub fn new() -> RepaintBoundary {
5720        RepaintBoundary::default()
5721    }
5722
5723    /// Dart `RepaintBoundary(key:)`.
5724    pub fn key(mut self, key: KeyRef) -> RepaintBoundary {
5725        self.key = Some(key);
5726        self
5727    }
5728
5729    /// Dart `RepaintBoundary(child:)`.
5730    #[cfg_attr(debug_assertions, track_caller)]
5731    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RepaintBoundary {
5732        self.child = Some(child.into_widget());
5733        self
5734    }
5735}
5736
5737impl RenderObjectWidget for RepaintBoundary {
5738    type RenderObject = RenderRepaintBoundary;
5739
5740    fn key(&self) -> Option<&KeyRef> {
5741        self.key.as_ref()
5742    }
5743
5744    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
5745        RenderRepaintBoundary::new(app, None).as_object()
5746    }
5747}
5748
5749impl SingleChildRenderObjectWidget for RepaintBoundary {
5750    fn child(&self) -> Option<&WidgetRef> {
5751        self.child.as_ref()
5752    }
5753}
5754
5755/// A widget that is invisible during hit testing.
5756///
5757/// When [`ignoring`](Self::ignoring) is true, this widget (and its subtree) is invisible
5758/// to hit testing. It still consumes space during layout and paints its child
5759/// as usual. It just cannot be the target of located events, because it returns
5760/// false from `RenderBox::hit_test`.
5761///
5762/// See also:
5763///
5764///  * [`AbsorbPointer`], which also prevents its children from receiving pointer
5765///    events but is itself visible to hit testing.
5766///  * `SliverIgnorePointer`, the sliver version of this widget.
5767///
5768/// Flutter's deprecated `ignoringSemantics` waits on accessibility.
5769#[derive(Debug)]
5770pub struct IgnorePointer {
5771    pub key: Option<KeyRef>,
5772    /// Whether this widget is ignored during hit testing.
5773    ///
5774    /// Regardless of whether this widget is ignored during hit testing, it will
5775    /// still consume space during layout and be visible during painting.
5776    ///
5777    /// Defaults to true.
5778    pub ignoring: bool,
5779    pub child: Option<WidgetRef>,
5780}
5781
5782impl IgnorePointer {
5783    /// Creates a widget that is invisible to hit testing; Dart's named arguments are the
5784    /// setters.
5785    pub fn new() -> IgnorePointer {
5786        IgnorePointer::default()
5787    }
5788
5789    /// Dart `IgnorePointer(key:)`.
5790    pub fn key(mut self, key: KeyRef) -> IgnorePointer {
5791        self.key = Some(key);
5792        self
5793    }
5794
5795    /// Dart `IgnorePointer(ignoring:)`.
5796    pub fn ignoring(mut self, ignoring: bool) -> IgnorePointer {
5797        self.ignoring = ignoring;
5798        self
5799    }
5800
5801    /// Dart `IgnorePointer(child:)`.
5802    #[cfg_attr(debug_assertions, track_caller)]
5803    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> IgnorePointer {
5804        self.child = Some(child.into_widget());
5805        self
5806    }
5807}
5808
5809impl Default for IgnorePointer {
5810    fn default() -> IgnorePointer {
5811        IgnorePointer {
5812            key: None,
5813            ignoring: true,
5814            child: None,
5815        }
5816    }
5817}
5818
5819impl RenderObjectWidget for IgnorePointer {
5820    type RenderObject = RenderIgnorePointer;
5821
5822    fn key(&self) -> Option<&KeyRef> {
5823        self.key.as_ref()
5824    }
5825
5826    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5827        properties.add(DiagnosticsProperty::new("ignoring", self.ignoring));
5828    }
5829
5830    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
5831        RenderIgnorePointer::new(app, self.ignoring, None).as_object()
5832    }
5833
5834    fn update_render_object(
5835        &self,
5836        app: &mut App,
5837        _context: BuildContext,
5838        render_object: RenderHandle<RenderIgnorePointer>,
5839    ) {
5840        render_object.set_ignoring(app, self.ignoring);
5841    }
5842}
5843
5844impl SingleChildRenderObjectWidget for IgnorePointer {
5845    fn child(&self) -> Option<&WidgetRef> {
5846        self.child.as_ref()
5847    }
5848}
5849
5850/// A widget that absorbs pointers during hit testing.
5851///
5852/// When [`absorbing`](Self::absorbing) is true, this widget prevents its subtree from
5853/// receiving pointer events by terminating hit testing at itself. It still consumes space
5854/// during layout and paints its child as usual. It just prevents its children
5855/// from being the target of located events, because it returns true from
5856/// `RenderBox::hit_test`.
5857///
5858/// See also:
5859///
5860///  * [`IgnorePointer`], which also prevents its children from receiving pointer
5861///    events but is itself invisible to hit testing.
5862///
5863/// Flutter's deprecated `ignoringSemantics` waits on accessibility.
5864#[derive(Debug)]
5865pub struct AbsorbPointer {
5866    pub key: Option<KeyRef>,
5867    /// Whether this widget absorbs pointers during hit testing.
5868    ///
5869    /// Regardless of whether this render object absorbs pointers during hit
5870    /// testing, it will still consume space during layout and be visible during
5871    /// painting.
5872    ///
5873    /// Defaults to true.
5874    pub absorbing: bool,
5875    pub child: Option<WidgetRef>,
5876}
5877
5878impl AbsorbPointer {
5879    /// Creates a widget that absorbs pointers during hit testing; Dart's named arguments are
5880    /// the setters.
5881    pub fn new() -> AbsorbPointer {
5882        AbsorbPointer::default()
5883    }
5884
5885    /// Dart `AbsorbPointer(key:)`.
5886    pub fn key(mut self, key: KeyRef) -> AbsorbPointer {
5887        self.key = Some(key);
5888        self
5889    }
5890
5891    /// Dart `AbsorbPointer(absorbing:)`.
5892    pub fn absorbing(mut self, absorbing: bool) -> AbsorbPointer {
5893        self.absorbing = absorbing;
5894        self
5895    }
5896
5897    /// Dart `AbsorbPointer(child:)`.
5898    #[cfg_attr(debug_assertions, track_caller)]
5899    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AbsorbPointer {
5900        self.child = Some(child.into_widget());
5901        self
5902    }
5903}
5904
5905impl Default for AbsorbPointer {
5906    fn default() -> AbsorbPointer {
5907        AbsorbPointer {
5908            key: None,
5909            absorbing: true,
5910            child: None,
5911        }
5912    }
5913}
5914
5915impl RenderObjectWidget for AbsorbPointer {
5916    type RenderObject = RenderAbsorbPointer;
5917
5918    fn key(&self) -> Option<&KeyRef> {
5919        self.key.as_ref()
5920    }
5921
5922    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5923        properties.add(DiagnosticsProperty::new("absorbing", self.absorbing));
5924    }
5925
5926    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
5927        RenderAbsorbPointer::new(app, self.absorbing, None).as_object()
5928    }
5929
5930    fn update_render_object(
5931        &self,
5932        app: &mut App,
5933        _context: BuildContext,
5934        render_object: RenderHandle<RenderAbsorbPointer>,
5935    ) {
5936        render_object.set_absorbing(app, self.absorbing);
5937    }
5938}
5939
5940impl SingleChildRenderObjectWidget for AbsorbPointer {
5941    fn child(&self) -> Option<&WidgetRef> {
5942        self.child.as_ref()
5943    }
5944}
5945
5946/// Holds opaque meta data in the render tree.
5947///
5948/// Useful for decorating the render tree with information that will be consumed
5949/// later. For example, you could store information in the render tree that will
5950/// be used when the user interacts with the render tree but has no visual impact
5951/// prior to the interaction.
5952pub struct MetaData {
5953    pub key: Option<KeyRef>,
5954    /// Opaque meta data ignored by the render tree.
5955    pub meta_data: Option<Rc<dyn Any>>,
5956    /// How to behave during hit testing.
5957    pub behavior: HitTestBehavior,
5958    /// The widget below this widget in the tree.
5959    pub child: Option<WidgetRef>,
5960}
5961
5962impl MetaData {
5963    /// Creates a widget that hold opaque meta data; Dart's named arguments are the setters.
5964    ///
5965    /// The [`behavior`](Self::behavior) defaults to [`HitTestBehavior::DeferToChild`].
5966    pub fn new() -> MetaData {
5967        MetaData::default()
5968    }
5969
5970    /// Dart `MetaData(key:)`.
5971    pub fn key(mut self, key: KeyRef) -> MetaData {
5972        self.key = Some(key);
5973        self
5974    }
5975
5976    /// Dart `MetaData(metaData:)`.
5977    pub fn meta_data(mut self, meta_data: Rc<dyn Any>) -> MetaData {
5978        self.meta_data = Some(meta_data);
5979        self
5980    }
5981
5982    /// Dart `MetaData(behavior:)`.
5983    pub fn behavior(mut self, behavior: HitTestBehavior) -> MetaData {
5984        self.behavior = behavior;
5985        self
5986    }
5987
5988    /// Dart `MetaData(child:)`.
5989    #[cfg_attr(debug_assertions, track_caller)]
5990    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MetaData {
5991        self.child = Some(child.into_widget());
5992        self
5993    }
5994}
5995
5996impl Default for MetaData {
5997    fn default() -> MetaData {
5998        MetaData {
5999            key: None,
6000            meta_data: None,
6001            behavior: HitTestBehavior::DeferToChild,
6002            child: None,
6003        }
6004    }
6005}
6006
6007impl RenderObjectWidget for MetaData {
6008    type RenderObject = RenderMetaData;
6009
6010    fn key(&self) -> Option<&KeyRef> {
6011        self.key.as_ref()
6012    }
6013
6014    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
6015        properties.add(EnumProperty::new("behavior", self.behavior));
6016        properties.add(DiagnosticsProperty::<String>::new(
6017            "metaData",
6018            self.meta_data
6019                .as_ref()
6020                .map(|_| "Instance of 'Object'".to_string()),
6021        ));
6022    }
6023
6024    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
6025        RenderMetaData::new(app, self.meta_data.clone(), self.behavior, None).as_object()
6026    }
6027
6028    fn update_render_object(
6029        &self,
6030        app: &mut App,
6031        _context: BuildContext,
6032        render_object: RenderHandle<RenderMetaData>,
6033    ) {
6034        render_object.set_meta_data(app, self.meta_data.clone());
6035        render_object.set_behavior(app, self.behavior);
6036    }
6037}
6038
6039impl SingleChildRenderObjectWidget for MetaData {
6040    fn child(&self) -> Option<&WidgetRef> {
6041        self.child.as_ref()
6042    }
6043}
6044
6045/// A widget that groups multiple [`BackdropFilter`] widgets so that they share one backdrop.
6046///
6047/// Every [`BackdropFilter::grouped`] descendant of this widget applies its filter to the
6048/// same snapshot of the scene, at the cost of one filter pass for the whole group. The
6049/// grouped filters must lie over the same background for the result to look right.
6050#[derive(Debug)]
6051pub struct BackdropGroup {
6052    pub key: Option<KeyRef>,
6053    /// The key the grouped filters share; a fresh one unless the caller supplies it.
6054    pub backdrop_key: BackdropKey,
6055    /// The widget below this widget in the tree.
6056    pub child: WidgetRef,
6057}
6058
6059impl BackdropGroup {
6060    /// Creates a group with a fresh [`BackdropKey`]; Dart's named arguments are the setters.
6061    #[cfg_attr(debug_assertions, track_caller)]
6062    pub fn new<K>(child: impl IntoWidget<K>) -> BackdropGroup {
6063        BackdropGroup {
6064            key: None,
6065            backdrop_key: BackdropKey::new(),
6066            child: child.into_widget(),
6067        }
6068    }
6069
6070    /// Dart `BackdropGroup(key:)`.
6071    pub fn key(mut self, key: KeyRef) -> BackdropGroup {
6072        self.key = Some(key);
6073        self
6074    }
6075
6076    /// Dart `BackdropGroup(backdropKey:)`.
6077    pub fn backdrop_key(mut self, backdrop_key: BackdropKey) -> BackdropGroup {
6078        self.backdrop_key = backdrop_key;
6079        self
6080    }
6081
6082    /// Returns the [`BackdropGroup`] enclosing `context`, if any, creating a dependency on it.
6083    pub fn of(app: &mut App, context: BuildContext) -> Option<&BackdropGroup> {
6084        context.depend_on_inherited_widget_of_exact_type::<BackdropGroup>(app)
6085    }
6086}
6087
6088impl InheritedWidget for BackdropGroup {
6089    fn key(&self) -> Option<&KeyRef> {
6090        self.key.as_ref()
6091    }
6092
6093    fn child(&self) -> &WidgetRef {
6094        &self.child
6095    }
6096
6097    fn update_should_notify(&self, old_widget: &BackdropGroup) -> bool {
6098        old_widget.backdrop_key != self.backdrop_key
6099    }
6100}
6101
6102/// A widget that applies a filter to the existing painted content and then paints `child`.
6103///
6104/// The filter will be applied to all the areas of the underlying background that the
6105/// widget's paint bounds cover, so the filter is bounded to the widget and clipped by the
6106/// enclosing clips.
6107///
6108/// Wrap it in a `ClipRect` to limit the effect; place it under a [`BackdropGroup`] and use
6109/// [`BackdropFilter::grouped`] to share one blur among several filters.
6110///
6111/// This effect is relatively expensive, especially if the filter is non-local, such as a
6112/// blur.
6113pub struct BackdropFilter {
6114    pub key: Option<KeyRef>,
6115    /// The configuration that resolves the filter against the widget's bounds at paint time.
6116    pub filter_config: ImageFilterConfig,
6117    /// The blend mode to use to apply the filtered background content onto the background
6118    /// surface.
6119    ///
6120    /// The default value of this property is [`BlendMode::SrcOver`].
6121    pub blend_mode: BlendMode,
6122    /// Whether or not the backdrop filter operation will be applied to the child.
6123    pub enabled: bool,
6124    /// A backdrop key that identifies a shared backdrop, when given explicitly.
6125    pub backdrop_group_key: Option<BackdropKey>,
6126    /// The widget below this widget in the tree.
6127    pub child: Option<WidgetRef>,
6128    /// Whether to look up the backdrop key from a parent [`BackdropGroup`].
6129    use_shared_key: bool,
6130}
6131
6132impl BackdropFilter {
6133    /// Creates a backdrop filter from its configuration; Dart's named arguments are the
6134    /// setters.
6135    pub fn new(filter_config: ImageFilterConfig) -> BackdropFilter {
6136        BackdropFilter {
6137            key: None,
6138            filter_config,
6139            blend_mode: BlendMode::SrcOver,
6140            enabled: true,
6141            backdrop_group_key: None,
6142            child: None,
6143            use_shared_key: false,
6144        }
6145    }
6146
6147    /// Dart `BackdropFilter(filter:)`: a filter applied as it is.
6148    pub fn filter(filter: ImageFilter) -> BackdropFilter {
6149        BackdropFilter::new(ImageFilterConfig::new(filter))
6150    }
6151
6152    /// Creates a backdrop filter that shares the backdrop of the enclosing [`BackdropGroup`].
6153    pub fn grouped(filter_config: ImageFilterConfig) -> BackdropFilter {
6154        BackdropFilter {
6155            use_shared_key: true,
6156            ..BackdropFilter::new(filter_config)
6157        }
6158    }
6159
6160    /// Dart `BackdropFilter(key:)`.
6161    pub fn key(mut self, key: KeyRef) -> BackdropFilter {
6162        self.key = Some(key);
6163        self
6164    }
6165
6166    /// Dart `BackdropFilter(blendMode:)`.
6167    pub fn blend_mode(mut self, blend_mode: BlendMode) -> BackdropFilter {
6168        self.blend_mode = blend_mode;
6169        self
6170    }
6171
6172    /// Dart `BackdropFilter(enabled:)`.
6173    pub fn enabled(mut self, enabled: bool) -> BackdropFilter {
6174        self.enabled = enabled;
6175        self
6176    }
6177
6178    /// Dart `BackdropFilter(backdropGroupKey:)`; not for a [`grouped`](Self::grouped) filter.
6179    pub fn backdrop_group_key(mut self, backdrop_group_key: BackdropKey) -> BackdropFilter {
6180        debug_assert!(!self.use_shared_key);
6181        self.backdrop_group_key = Some(backdrop_group_key);
6182        self
6183    }
6184
6185    /// Dart `BackdropFilter(child:)`.
6186    #[cfg_attr(debug_assertions, track_caller)]
6187    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> BackdropFilter {
6188        self.child = Some(child.into_widget());
6189        self
6190    }
6191
6192    fn get_backdrop_group_key(&self, app: &mut App, context: BuildContext) -> Option<BackdropKey> {
6193        if self.use_shared_key {
6194            return BackdropGroup::of(app, context).map(|group| group.backdrop_key);
6195        }
6196        self.backdrop_group_key
6197    }
6198}
6199
6200impl RenderObjectWidget for BackdropFilter {
6201    type RenderObject = RenderBackdropFilter;
6202
6203    fn key(&self) -> Option<&KeyRef> {
6204        self.key.as_ref()
6205    }
6206
6207    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
6208        properties.add(
6209            DiagnosticsProperty::<ImageFilterConfig>::new(
6210                "filterConfig",
6211                Some(self.filter_config.clone()),
6212            )
6213            .default_value(None),
6214        );
6215        properties.add(EnumProperty::new("blendMode", self.blend_mode));
6216        properties.add(FlagProperty::new("enabled", Some(self.enabled)).if_true("enabled"));
6217    }
6218
6219    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
6220        let backdrop_key = self.get_backdrop_group_key(app, context);
6221        RenderBackdropFilter::new(
6222            app,
6223            self.filter_config.clone(),
6224            self.blend_mode,
6225            self.enabled,
6226            backdrop_key,
6227            None,
6228        )
6229        .as_object()
6230    }
6231
6232    fn update_render_object(
6233        &self,
6234        app: &mut App,
6235        context: BuildContext,
6236        render_object: RenderHandle<RenderBackdropFilter>,
6237    ) {
6238        render_object.set_filter_config(app, self.filter_config.clone());
6239        render_object.set_enabled(app, self.enabled);
6240        render_object.set_blend_mode(app, self.blend_mode);
6241        let backdrop_key = self.get_backdrop_group_key(app, context);
6242        render_object.set_backdrop_key(app, backdrop_key);
6243    }
6244}
6245
6246impl SingleChildRenderObjectWidget for BackdropFilter {
6247    fn child(&self) -> Option<&WidgetRef> {
6248        self.child.as_ref()
6249    }
6250}
6251
6252impl Debug for BackdropFilter {
6253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6254        f.debug_struct("BackdropFilter")
6255            .field("key", &self.key)
6256            .field("filter_config", &self.filter_config)
6257            .field("blend_mode", &self.blend_mode)
6258            .field("enabled", &self.enabled)
6259            .field("child", &self.child)
6260            .finish_non_exhaustive()
6261    }
6262}
6263
6264impl Debug for MetaData {
6265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6266        f.debug_struct("MetaData")
6267            .field("key", &self.key)
6268            .field("meta_data", &self.meta_data.as_ref().map(|_| "..."))
6269            .field("behavior", &self.behavior)
6270            .field("child", &self.child)
6271            .finish()
6272    }
6273}
6274
6275// UTILITY NODES
6276
6277/// A widget that annotates the widget tree with a description of the meaning of
6278/// the widgets.
6279///
6280/// Used by assistive technologies, search engines, and other semantic analysis
6281/// software to determine the meaning of the application.
6282///
6283/// Its render object, a [`RenderSemanticsAnnotations`], is a proxy box: like any box it takes
6284/// a hit only inside its size, so it bounds a child that takes hits outside itself.
6285///
6286/// Dart's sealed `_SemanticsBase` is these fields and `get_text_direction`; its other leaf,
6287/// `SliverSemantics`, waits on `RenderSliverSemanticsAnnotations`.
6288///
6289/// See also:
6290///
6291///  * [`MergeSemantics`], which marks a subtree as being a single node for
6292///    accessibility purposes.
6293///  * [`ExcludeSemantics`], which excludes a subtree from the accessibility tree.
6294///  * [`RenderSemanticsAnnotations`], the render object that implements this
6295///    behavior.
6296pub struct Semantics {
6297    pub key: Option<KeyRef>,
6298    pub child: Option<WidgetRef>,
6299
6300    /// Contains properties used by assistive technologies to make the application
6301    /// more accessible.
6302    pub properties: Rc<SemanticsProperties>,
6303
6304    /// If [`container`](Self::container) is true, this widget will introduce a new
6305    /// node in the semantics tree. Otherwise, the semantics will be
6306    /// merged with the semantics of any ancestors (if the ancestor allows that).
6307    ///
6308    /// Whether descendants of this widget can add their semantic information to the
6309    /// `SemanticsNode` introduced by this configuration is controlled by
6310    /// [`explicit_child_nodes`](Self::explicit_child_nodes).
6311    pub container: bool,
6312
6313    /// Whether descendants of this widget are allowed to add semantic information
6314    /// to the `SemanticsNode` annotated by this widget.
6315    ///
6316    /// When set to false descendants are allowed to annotate `SemanticsNode`s of
6317    /// their parent with the semantic information they want to contribute to the
6318    /// semantic tree.
6319    /// When set to true the only way for descendants to contribute semantic
6320    /// information to the semantic tree is to introduce new explicit
6321    /// `SemanticsNode`s to the tree.
6322    ///
6323    /// If the semantics properties of this node include
6324    /// [`SemanticsProperties::scopes_route`] set to true, then
6325    /// [`explicit_child_nodes`](Self::explicit_child_nodes) must be true also.
6326    ///
6327    /// This setting is often used in combination with
6328    /// `SemanticsConfiguration.isSemanticBoundary` to create semantic boundaries
6329    /// that are either writable or not for children.
6330    pub explicit_child_nodes: bool,
6331
6332    /// The [`Locale`] for the semantics subtree.
6333    ///
6334    /// If null, it inherits the locale from the ancestor semantics node.
6335    pub locale_for_subtree: Option<Locale>,
6336
6337    /// Whether to replace all child semantics with this node.
6338    ///
6339    /// Defaults to false.
6340    ///
6341    /// When this flag is set to true, all child semantics nodes are ignored.
6342    /// This can be used as a convenience for cases where a child is wrapped in
6343    /// an [`ExcludeSemantics`] widget and then another [`Semantics`] widget.
6344    pub exclude_semantics: bool,
6345
6346    /// Whether to block user interactions for the rendering subtree.
6347    ///
6348    /// Setting this to true will prevent users from interacting with the
6349    /// rendering object configured by this widget and its subtree through
6350    /// pointer-related `SemanticsAction`s in assistive technologies.
6351    ///
6352    /// The `SemanticsNode` created from this widget is still focusable by
6353    /// assistive technologies. Only pointer-related `SemanticsAction`s, such as
6354    /// `SemanticsAction::TAP` or its friends, are blocked.
6355    ///
6356    /// If this widget is merged into a parent semantics node, only the
6357    /// `SemanticsAction`s from this widget and the widgets in the subtree are
6358    /// blocked.
6359    pub block_user_actions: bool,
6360}
6361
6362impl Semantics {
6363    /// Creates a semantic annotation.
6364    ///
6365    /// To create a [`Semantics`] widget with a whole [`SemanticsProperties`], use
6366    /// [`from_properties`](Self::from_properties). Dart's named arguments are the setters; the
6367    /// properties' own write into [`properties`](Self::properties).
6368    pub fn new() -> Semantics {
6369        Semantics::from_properties(Rc::new(SemanticsProperties::new()))
6370    }
6371
6372    /// Creates a semantic annotation using [`SemanticsProperties`].
6373    pub fn from_properties(properties: Rc<SemanticsProperties>) -> Semantics {
6374        Semantics {
6375            key: None,
6376            child: None,
6377            properties,
6378            container: false,
6379            explicit_child_nodes: false,
6380            locale_for_subtree: None,
6381            exclude_semantics: false,
6382            block_user_actions: false,
6383        }
6384    }
6385
6386    /// Dart `Semantics(key:)`.
6387    pub fn key(mut self, key: KeyRef) -> Semantics {
6388        self.key = Some(key);
6389        self
6390    }
6391
6392    /// Dart `Semantics(child:)`.
6393    #[cfg_attr(debug_assertions, track_caller)]
6394    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Semantics {
6395        self.child = Some(child.into_widget());
6396        self
6397    }
6398
6399    /// Dart `Semantics(container:)`.
6400    pub fn container(mut self, container: bool) -> Semantics {
6401        self.container = container;
6402        self
6403    }
6404
6405    /// Dart `Semantics(explicitChildNodes:)`.
6406    pub fn explicit_child_nodes(mut self, explicit_child_nodes: bool) -> Semantics {
6407        self.explicit_child_nodes = explicit_child_nodes;
6408        self
6409    }
6410
6411    /// Dart `Semantics(excludeSemantics:)`.
6412    pub fn exclude_semantics(mut self, exclude_semantics: bool) -> Semantics {
6413        self.exclude_semantics = exclude_semantics;
6414        self
6415    }
6416
6417    /// Dart `Semantics(blockUserActions:)`.
6418    pub fn block_user_actions(mut self, block_user_actions: bool) -> Semantics {
6419        self.block_user_actions = block_user_actions;
6420        self
6421    }
6422
6423    /// Writes one of Dart's `SemanticsProperties` arguments into [`properties`](Self::properties).
6424    fn with_properties(
6425        mut self,
6426        update: impl FnOnce(SemanticsProperties) -> SemanticsProperties,
6427    ) -> Semantics {
6428        self.properties = Rc::new(update(Rc::unwrap_or_clone(self.properties)));
6429        self
6430    }
6431
6432    /// Dart `Semantics(enabled:)`.
6433    pub fn enabled(self, enabled: bool) -> Semantics {
6434        self.with_properties(|properties| properties.enabled(enabled))
6435    }
6436
6437    /// Dart `Semantics(checked:)`.
6438    pub fn checked(self, checked: bool) -> Semantics {
6439        self.with_properties(|properties| properties.checked(checked))
6440    }
6441
6442    /// Dart `Semantics(mixed:)`.
6443    pub fn mixed(self, mixed: bool) -> Semantics {
6444        self.with_properties(|properties| properties.mixed(mixed))
6445    }
6446
6447    /// Dart `Semantics(selected:)`.
6448    pub fn selected(self, selected: bool) -> Semantics {
6449        self.with_properties(|properties| properties.selected(selected))
6450    }
6451
6452    /// Dart `Semantics(toggled:)`.
6453    pub fn toggled(self, toggled: bool) -> Semantics {
6454        self.with_properties(|properties| properties.toggled(toggled))
6455    }
6456
6457    /// Dart `Semantics(button:)`.
6458    pub fn button(self, button: bool) -> Semantics {
6459        self.with_properties(|properties| properties.button(button))
6460    }
6461
6462    /// Dart `Semantics(slider:)`.
6463    pub fn slider(self, slider: bool) -> Semantics {
6464        self.with_properties(|properties| properties.slider(slider))
6465    }
6466
6467    /// Dart `Semantics(keyboardKey:)`.
6468    pub fn keyboard_key(self, keyboard_key: bool) -> Semantics {
6469        self.with_properties(|properties| properties.keyboard_key(keyboard_key))
6470    }
6471
6472    /// Dart `Semantics(link:)`.
6473    pub fn link(self, link: bool) -> Semantics {
6474        self.with_properties(|properties| properties.link(link))
6475    }
6476
6477    /// Dart `Semantics(linkUrl:)`.
6478    pub fn link_url(self, link_url: impl Into<String>) -> Semantics {
6479        self.with_properties(|properties| properties.link_url(link_url))
6480    }
6481
6482    /// Dart `Semantics(header:)`.
6483    pub fn header(self, header: bool) -> Semantics {
6484        self.with_properties(|properties| properties.header(header))
6485    }
6486
6487    /// Dart `Semantics(headingLevel:)`.
6488    pub fn heading_level(self, heading_level: i32) -> Semantics {
6489        self.with_properties(|properties| properties.heading_level(heading_level))
6490    }
6491
6492    /// Dart `Semantics(textField:)`.
6493    pub fn text_field(self, text_field: bool) -> Semantics {
6494        self.with_properties(|properties| properties.text_field(text_field))
6495    }
6496
6497    /// Dart `Semantics(readOnly:)`.
6498    pub fn read_only(self, read_only: bool) -> Semantics {
6499        self.with_properties(|properties| properties.read_only(read_only))
6500    }
6501
6502    /// Dart `Semantics(focusable:)`.
6503    pub fn focusable(self, focusable: bool) -> Semantics {
6504        self.with_properties(|properties| properties.focusable(focusable))
6505    }
6506
6507    /// Dart `Semantics(focused:)`.
6508    pub fn focused(self, focused: bool) -> Semantics {
6509        self.with_properties(|properties| properties.focused(focused))
6510    }
6511
6512    /// Dart `Semantics(accessibilityFocusBlockType:)`.
6513    pub fn accessibility_focus_block_type(
6514        self,
6515        accessibility_focus_block_type: AccessibilityFocusBlockType,
6516    ) -> Semantics {
6517        self.with_properties(|properties| {
6518            properties.accessibility_focus_block_type(accessibility_focus_block_type)
6519        })
6520    }
6521
6522    /// Dart `Semantics(inMutuallyExclusiveGroup:)`.
6523    pub fn in_mutually_exclusive_group(self, in_mutually_exclusive_group: bool) -> Semantics {
6524        self.with_properties(|properties| {
6525            properties.in_mutually_exclusive_group(in_mutually_exclusive_group)
6526        })
6527    }
6528
6529    /// Dart `Semantics(obscured:)`.
6530    pub fn obscured(self, obscured: bool) -> Semantics {
6531        self.with_properties(|properties| properties.obscured(obscured))
6532    }
6533
6534    /// Dart `Semantics(multiline:)`.
6535    pub fn multiline(self, multiline: bool) -> Semantics {
6536        self.with_properties(|properties| properties.multiline(multiline))
6537    }
6538
6539    /// Dart `Semantics(scopesRoute:)`.
6540    pub fn scopes_route(self, scopes_route: bool) -> Semantics {
6541        self.with_properties(|properties| properties.scopes_route(scopes_route))
6542    }
6543
6544    /// Dart `Semantics(namesRoute:)`.
6545    pub fn names_route(self, names_route: bool) -> Semantics {
6546        self.with_properties(|properties| properties.names_route(names_route))
6547    }
6548
6549    /// Dart `Semantics(hidden:)`.
6550    pub fn hidden(self, hidden: bool) -> Semantics {
6551        self.with_properties(|properties| properties.hidden(hidden))
6552    }
6553
6554    /// Dart `Semantics(image:)`.
6555    pub fn image(self, image: bool) -> Semantics {
6556        self.with_properties(|properties| properties.image(image))
6557    }
6558
6559    /// Dart `Semantics(liveRegion:)`.
6560    pub fn live_region(self, live_region: bool) -> Semantics {
6561        self.with_properties(|properties| properties.live_region(live_region))
6562    }
6563
6564    /// Dart `Semantics(expanded:)`.
6565    pub fn expanded(self, expanded: bool) -> Semantics {
6566        self.with_properties(|properties| properties.expanded(expanded))
6567    }
6568
6569    /// Dart `Semantics(isRequired:)`.
6570    pub fn is_required(self, is_required: bool) -> Semantics {
6571        self.with_properties(|properties| properties.is_required(is_required))
6572    }
6573
6574    /// Dart `Semantics(maxValueLength:)`.
6575    pub fn max_value_length(self, max_value_length: i32) -> Semantics {
6576        self.with_properties(|properties| properties.max_value_length(max_value_length))
6577    }
6578
6579    /// Dart `Semantics(currentValueLength:)`.
6580    pub fn current_value_length(self, current_value_length: i32) -> Semantics {
6581        self.with_properties(|properties| properties.current_value_length(current_value_length))
6582    }
6583
6584    /// Dart `Semantics(identifier:)`.
6585    pub fn identifier(self, identifier: impl Into<String>) -> Semantics {
6586        self.with_properties(|properties| properties.identifier(identifier))
6587    }
6588
6589    /// Dart `Semantics(traversalParentIdentifier:)`.
6590    pub fn traversal_parent_identifier(
6591        self,
6592        traversal_parent_identifier: Rc<dyn Any>,
6593    ) -> Semantics {
6594        self.with_properties(|properties| {
6595            properties.traversal_parent_identifier(traversal_parent_identifier)
6596        })
6597    }
6598
6599    /// Dart `Semantics(traversalChildIdentifier:)`.
6600    pub fn traversal_child_identifier(self, traversal_child_identifier: Rc<dyn Any>) -> Semantics {
6601        self.with_properties(|properties| {
6602            properties.traversal_child_identifier(traversal_child_identifier)
6603        })
6604    }
6605
6606    /// Dart `Semantics(label:)`.
6607    pub fn label(self, label: impl Into<String>) -> Semantics {
6608        self.with_properties(|properties| properties.label(label))
6609    }
6610
6611    /// Dart `Semantics(attributedLabel:)`.
6612    pub fn attributed_label(self, attributed_label: AttributedString) -> Semantics {
6613        self.with_properties(|properties| properties.attributed_label(attributed_label))
6614    }
6615
6616    /// Dart `Semantics(value:)`.
6617    pub fn value(self, value: impl Into<String>) -> Semantics {
6618        self.with_properties(|properties| properties.value(value))
6619    }
6620
6621    /// Dart `Semantics(attributedValue:)`.
6622    pub fn attributed_value(self, attributed_value: AttributedString) -> Semantics {
6623        self.with_properties(|properties| properties.attributed_value(attributed_value))
6624    }
6625
6626    /// Dart `Semantics(increasedValue:)`.
6627    pub fn increased_value(self, increased_value: impl Into<String>) -> Semantics {
6628        self.with_properties(|properties| properties.increased_value(increased_value))
6629    }
6630
6631    /// Dart `Semantics(attributedIncreasedValue:)`.
6632    pub fn attributed_increased_value(
6633        self,
6634        attributed_increased_value: AttributedString,
6635    ) -> Semantics {
6636        self.with_properties(|properties| {
6637            properties.attributed_increased_value(attributed_increased_value)
6638        })
6639    }
6640
6641    /// Dart `Semantics(decreasedValue:)`.
6642    pub fn decreased_value(self, decreased_value: impl Into<String>) -> Semantics {
6643        self.with_properties(|properties| properties.decreased_value(decreased_value))
6644    }
6645
6646    /// Dart `Semantics(attributedDecreasedValue:)`.
6647    pub fn attributed_decreased_value(
6648        self,
6649        attributed_decreased_value: AttributedString,
6650    ) -> Semantics {
6651        self.with_properties(|properties| {
6652            properties.attributed_decreased_value(attributed_decreased_value)
6653        })
6654    }
6655
6656    /// Dart `Semantics(hint:)`.
6657    pub fn hint(self, hint: impl Into<String>) -> Semantics {
6658        self.with_properties(|properties| properties.hint(hint))
6659    }
6660
6661    /// Dart `Semantics(attributedHint:)`.
6662    pub fn attributed_hint(self, attributed_hint: AttributedString) -> Semantics {
6663        self.with_properties(|properties| properties.attributed_hint(attributed_hint))
6664    }
6665
6666    /// Dart `Semantics(tooltip:)`.
6667    pub fn tooltip(self, tooltip: impl Into<String>) -> Semantics {
6668        self.with_properties(|properties| properties.tooltip(tooltip))
6669    }
6670
6671    /// Dart `Semantics(onTapHint:)`: with the other hint, the properties' `hintOverrides`.
6672    pub fn on_tap_hint(self, on_tap_hint: impl Into<String>) -> Semantics {
6673        self.with_properties(|properties| {
6674            let hint_overrides = properties.hint_overrides.clone().unwrap_or_default();
6675            properties.hint_overrides(hint_overrides.on_tap_hint(on_tap_hint))
6676        })
6677    }
6678
6679    /// Dart `Semantics(onLongPressHint:)`: with the other hint, the properties' `hintOverrides`.
6680    pub fn on_long_press_hint(self, on_long_press_hint: impl Into<String>) -> Semantics {
6681        self.with_properties(|properties| {
6682            let hint_overrides = properties.hint_overrides.clone().unwrap_or_default();
6683            properties.hint_overrides(hint_overrides.on_long_press_hint(on_long_press_hint))
6684        })
6685    }
6686
6687    /// Dart `Semantics(textDirection:)`.
6688    pub fn text_direction(self, text_direction: TextDirection) -> Semantics {
6689        self.with_properties(|properties| properties.text_direction(text_direction))
6690    }
6691
6692    /// Dart `Semantics(sortKey:)`.
6693    pub fn sort_key(self, sort_key: SemanticsSortKeyRef) -> Semantics {
6694        self.with_properties(|properties| properties.sort_key(sort_key))
6695    }
6696
6697    /// Dart `Semantics(tagForChildren:)`.
6698    pub fn tag_for_children(self, tag_for_children: Rc<SemanticsTag>) -> Semantics {
6699        self.with_properties(|properties| properties.tag_for_children(tag_for_children))
6700    }
6701
6702    /// Dart `Semantics(onTap:)`.
6703    pub fn on_tap(self, on_tap: VoidCallback) -> Semantics {
6704        self.with_properties(|properties| properties.on_tap(on_tap))
6705    }
6706
6707    /// Dart `Semantics(onLongPress:)`.
6708    pub fn on_long_press(self, on_long_press: VoidCallback) -> Semantics {
6709        self.with_properties(|properties| properties.on_long_press(on_long_press))
6710    }
6711
6712    /// Dart `Semantics(onScrollLeft:)`.
6713    pub fn on_scroll_left(self, on_scroll_left: VoidCallback) -> Semantics {
6714        self.with_properties(|properties| properties.on_scroll_left(on_scroll_left))
6715    }
6716
6717    /// Dart `Semantics(onScrollRight:)`.
6718    pub fn on_scroll_right(self, on_scroll_right: VoidCallback) -> Semantics {
6719        self.with_properties(|properties| properties.on_scroll_right(on_scroll_right))
6720    }
6721
6722    /// Dart `Semantics(onScrollUp:)`.
6723    pub fn on_scroll_up(self, on_scroll_up: VoidCallback) -> Semantics {
6724        self.with_properties(|properties| properties.on_scroll_up(on_scroll_up))
6725    }
6726
6727    /// Dart `Semantics(onScrollDown:)`.
6728    pub fn on_scroll_down(self, on_scroll_down: VoidCallback) -> Semantics {
6729        self.with_properties(|properties| properties.on_scroll_down(on_scroll_down))
6730    }
6731
6732    /// Dart `Semantics(onIncrease:)`.
6733    pub fn on_increase(self, on_increase: VoidCallback) -> Semantics {
6734        self.with_properties(|properties| properties.on_increase(on_increase))
6735    }
6736
6737    /// Dart `Semantics(onDecrease:)`.
6738    pub fn on_decrease(self, on_decrease: VoidCallback) -> Semantics {
6739        self.with_properties(|properties| properties.on_decrease(on_decrease))
6740    }
6741
6742    /// Dart `Semantics(onCopy:)`.
6743    pub fn on_copy(self, on_copy: VoidCallback) -> Semantics {
6744        self.with_properties(|properties| properties.on_copy(on_copy))
6745    }
6746
6747    /// Dart `Semantics(onCut:)`.
6748    pub fn on_cut(self, on_cut: VoidCallback) -> Semantics {
6749        self.with_properties(|properties| properties.on_cut(on_cut))
6750    }
6751
6752    /// Dart `Semantics(onPaste:)`.
6753    pub fn on_paste(self, on_paste: VoidCallback) -> Semantics {
6754        self.with_properties(|properties| properties.on_paste(on_paste))
6755    }
6756
6757    /// Dart `Semantics(onDismiss:)`.
6758    pub fn on_dismiss(self, on_dismiss: VoidCallback) -> Semantics {
6759        self.with_properties(|properties| properties.on_dismiss(on_dismiss))
6760    }
6761
6762    /// Dart `Semantics(onMoveCursorForwardByCharacter:)`.
6763    pub fn on_move_cursor_forward_by_character(
6764        self,
6765        on_move_cursor_forward_by_character: MoveCursorHandler,
6766    ) -> Semantics {
6767        self.with_properties(|properties| {
6768            properties.on_move_cursor_forward_by_character(on_move_cursor_forward_by_character)
6769        })
6770    }
6771
6772    /// Dart `Semantics(onMoveCursorBackwardByCharacter:)`.
6773    pub fn on_move_cursor_backward_by_character(
6774        self,
6775        on_move_cursor_backward_by_character: MoveCursorHandler,
6776    ) -> Semantics {
6777        self.with_properties(|properties| {
6778            properties.on_move_cursor_backward_by_character(on_move_cursor_backward_by_character)
6779        })
6780    }
6781
6782    /// Dart `Semantics(onSetSelection:)`.
6783    pub fn on_set_selection(self, on_set_selection: SetSelectionHandler) -> Semantics {
6784        self.with_properties(|properties| properties.on_set_selection(on_set_selection))
6785    }
6786
6787    /// Dart `Semantics(onSetText:)`.
6788    pub fn on_set_text(self, on_set_text: SetTextHandler) -> Semantics {
6789        self.with_properties(|properties| properties.on_set_text(on_set_text))
6790    }
6791
6792    /// Dart `Semantics(onDidGainAccessibilityFocus:)`.
6793    pub fn on_did_gain_accessibility_focus(
6794        self,
6795        on_did_gain_accessibility_focus: VoidCallback,
6796    ) -> Semantics {
6797        self.with_properties(|properties| {
6798            properties.on_did_gain_accessibility_focus(on_did_gain_accessibility_focus)
6799        })
6800    }
6801
6802    /// Dart `Semantics(onDidLoseAccessibilityFocus:)`.
6803    pub fn on_did_lose_accessibility_focus(
6804        self,
6805        on_did_lose_accessibility_focus: VoidCallback,
6806    ) -> Semantics {
6807        self.with_properties(|properties| {
6808            properties.on_did_lose_accessibility_focus(on_did_lose_accessibility_focus)
6809        })
6810    }
6811
6812    /// Dart `Semantics(onFocus:)`.
6813    pub fn on_focus(self, on_focus: VoidCallback) -> Semantics {
6814        self.with_properties(|properties| properties.on_focus(on_focus))
6815    }
6816
6817    /// Dart `Semantics(onExpand:)`.
6818    pub fn on_expand(self, on_expand: VoidCallback) -> Semantics {
6819        self.with_properties(|properties| properties.on_expand(on_expand))
6820    }
6821
6822    /// Dart `Semantics(onCollapse:)`.
6823    pub fn on_collapse(self, on_collapse: VoidCallback) -> Semantics {
6824        self.with_properties(|properties| properties.on_collapse(on_collapse))
6825    }
6826
6827    /// Dart `Semantics(customSemanticsActions:)`.
6828    pub fn custom_semantics_actions(
6829        self,
6830        custom_semantics_actions: IndexMap<CustomSemanticsAction, VoidCallback>,
6831    ) -> Semantics {
6832        self.with_properties(|properties| {
6833            properties.custom_semantics_actions(custom_semantics_actions)
6834        })
6835    }
6836
6837    /// Dart `Semantics(role:)`.
6838    pub fn role(self, role: SemanticsRole) -> Semantics {
6839        self.with_properties(|properties| properties.role(role))
6840    }
6841
6842    /// Dart `Semantics(controlsNodes:)`.
6843    pub fn controls_nodes(self, controls_nodes: IndexSet<String>) -> Semantics {
6844        self.with_properties(|properties| properties.controls_nodes(controls_nodes))
6845    }
6846
6847    /// Dart `Semantics(validationResult:)`.
6848    pub fn validation_result(self, validation_result: SemanticsValidationResult) -> Semantics {
6849        self.with_properties(|properties| properties.validation_result(validation_result))
6850    }
6851
6852    /// Dart `Semantics(hitTestBehavior:)`.
6853    pub fn hit_test_behavior(self, hit_test_behavior: SemanticsHitTestBehavior) -> Semantics {
6854        self.with_properties(|properties| properties.hit_test_behavior(hit_test_behavior))
6855    }
6856
6857    /// Dart `Semantics(inputType:)`.
6858    pub fn input_type(self, input_type: SemanticsInputType) -> Semantics {
6859        self.with_properties(|properties| properties.input_type(input_type))
6860    }
6861
6862    /// Dart `Semantics(localeForSubtree:)`.
6863    pub fn locale_for_subtree(mut self, locale_for_subtree: Locale) -> Semantics {
6864        self.locale_for_subtree = Some(locale_for_subtree);
6865        self
6866    }
6867
6868    /// Dart `Semantics(minValue:)`.
6869    pub fn min_value(self, min_value: impl Into<String>) -> Semantics {
6870        self.with_properties(|properties| properties.min_value(min_value))
6871    }
6872
6873    /// Dart `Semantics(maxValue:)`.
6874    pub fn max_value(self, max_value: impl Into<String>) -> Semantics {
6875        self.with_properties(|properties| properties.max_value(max_value))
6876    }
6877
6878    /// Dart's `_SemanticsBase._getTextDirection`.
6879    fn get_text_direction(&self, app: &mut App, context: BuildContext) -> Option<TextDirection> {
6880        if self.properties.text_direction.is_some() {
6881            return self.properties.text_direction;
6882        }
6883
6884        let properties = &self.properties;
6885        let contains_text = properties.label.is_some()
6886            || properties.attributed_label.is_some()
6887            || properties.value.is_some()
6888            || properties.attributed_value.is_some()
6889            || properties.increased_value.is_some()
6890            || properties.attributed_increased_value.is_some()
6891            || properties.decreased_value.is_some()
6892            || properties.attributed_decreased_value.is_some()
6893            || properties.hint.is_some()
6894            || properties.attributed_hint.is_some()
6895            || properties.tooltip.is_some();
6896
6897        if !contains_text {
6898            return None;
6899        }
6900
6901        Directionality::maybe_of(app, context)
6902    }
6903}
6904
6905impl Default for Semantics {
6906    fn default() -> Semantics {
6907        Semantics::new()
6908    }
6909}
6910
6911impl RenderObjectWidget for Semantics {
6912    type RenderObject = RenderSemanticsAnnotations;
6913
6914    fn key(&self) -> Option<&KeyRef> {
6915        self.key.as_ref()
6916    }
6917
6918    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
6919        let text_direction = self.get_text_direction(app, context);
6920        RenderSemanticsAnnotations::new(
6921            app,
6922            self.properties.clone(),
6923            self.container,
6924            self.explicit_child_nodes,
6925            self.exclude_semantics,
6926            self.block_user_actions,
6927            self.locale_for_subtree.clone(),
6928            text_direction,
6929            None,
6930        )
6931        .as_object()
6932    }
6933
6934    fn update_render_object(
6935        &self,
6936        app: &mut App,
6937        context: BuildContext,
6938        render_object: RenderHandle<RenderSemanticsAnnotations>,
6939    ) {
6940        render_object.set_container(app, self.container);
6941        render_object.set_explicit_child_nodes(app, self.explicit_child_nodes);
6942        render_object.set_exclude_semantics(app, self.exclude_semantics);
6943        render_object.set_block_user_actions(app, self.block_user_actions);
6944        render_object.set_properties(app, self.properties.clone());
6945        let text_direction = self.get_text_direction(app, context);
6946        render_object.set_text_direction(app, text_direction);
6947        render_object.set_locale_for_subtree(app, self.locale_for_subtree.clone());
6948    }
6949
6950    fn debug_check_constructor(&self) {
6951        self.properties.debug_check_constructor();
6952    }
6953}
6954
6955impl SingleChildRenderObjectWidget for Semantics {
6956    fn child(&self) -> Option<&WidgetRef> {
6957        self.child.as_ref()
6958    }
6959}
6960
6961impl Debug for Semantics {
6962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6963        f.debug_struct("Semantics")
6964            .field("container", &self.container)
6965            .field("properties", &self.properties)
6966            .finish_non_exhaustive()
6967    }
6968}
6969
6970/// A widget that merges the semantics of its descendants.
6971///
6972/// Causes all the semantics of the subtree rooted at this node to be
6973/// merged into one node in the semantics tree. For example, if you
6974/// have a widget with a Text node next to a checkbox widget, this
6975/// could be used to merge the label from the Text node with the
6976/// "checked" semantic state of the checkbox into a single node that
6977/// had both the label and the checked state. Otherwise, the label
6978/// would be presented as a separate feature than the checkbox, and
6979/// the user would not be able to be sure that they were related.
6980///
6981/// Be aware that if two nodes in the subtree have conflicting
6982/// semantics, the result may be nonsensical. For example, a subtree
6983/// with a checked checkbox and an unchecked checkbox will be
6984/// presented as checked. All the labels will be merged into a single
6985/// string (with newlines separating each label from the other). If
6986/// multiple nodes in the merged subtree can handle semantic gestures,
6987/// the first one in tree order will be the one to receive the
6988/// callbacks.
6989#[derive(Debug, Default)]
6990pub struct MergeSemantics {
6991    pub key: Option<KeyRef>,
6992    pub child: Option<WidgetRef>,
6993}
6994
6995impl MergeSemantics {
6996    /// Creates a widget that merges the semantics of its descendants; Dart's named arguments
6997    /// are the setters.
6998    pub fn new() -> MergeSemantics {
6999        MergeSemantics::default()
7000    }
7001
7002    /// Dart `MergeSemantics(key:)`.
7003    pub fn key(mut self, key: KeyRef) -> MergeSemantics {
7004        self.key = Some(key);
7005        self
7006    }
7007
7008    /// Dart `MergeSemantics(child:)`.
7009    #[cfg_attr(debug_assertions, track_caller)]
7010    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MergeSemantics {
7011        self.child = Some(child.into_widget());
7012        self
7013    }
7014}
7015
7016impl RenderObjectWidget for MergeSemantics {
7017    type RenderObject = RenderMergeSemantics;
7018
7019    fn key(&self) -> Option<&KeyRef> {
7020        self.key.as_ref()
7021    }
7022
7023    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7024        RenderMergeSemantics::new(app, None).as_object()
7025    }
7026}
7027
7028impl SingleChildRenderObjectWidget for MergeSemantics {
7029    fn child(&self) -> Option<&WidgetRef> {
7030        self.child.as_ref()
7031    }
7032}
7033
7034/// A widget that drops the semantics of all widget that were painted before it
7035/// in the same semantic container.
7036///
7037/// This is useful to hide widgets from accessibility tools that are painted
7038/// behind a certain widget, e.g. an alert should usually disallow interaction
7039/// with any widget located "behind" the alert (even when they are still
7040/// partially visible). Similarly, an open `Drawer` blocks interactions with
7041/// any widget outside the drawer.
7042///
7043/// See also:
7044///
7045///  * [`ExcludeSemantics`] which drops all semantics of its descendants.
7046#[derive(Debug)]
7047pub struct BlockSemantics {
7048    pub key: Option<KeyRef>,
7049
7050    /// Whether this widget is blocking semantics of all widget that were painted
7051    /// before it in the same semantic container.
7052    pub blocking: bool,
7053    pub child: Option<WidgetRef>,
7054}
7055
7056impl BlockSemantics {
7057    /// Creates a widget that excludes the semantics of all widgets painted before
7058    /// it in the same semantic container; Dart's named arguments are the setters.
7059    pub fn new() -> BlockSemantics {
7060        BlockSemantics::default()
7061    }
7062
7063    /// Dart `BlockSemantics(key:)`.
7064    pub fn key(mut self, key: KeyRef) -> BlockSemantics {
7065        self.key = Some(key);
7066        self
7067    }
7068
7069    /// Dart `BlockSemantics(blocking:)`.
7070    pub fn blocking(mut self, blocking: bool) -> BlockSemantics {
7071        self.blocking = blocking;
7072        self
7073    }
7074
7075    /// Dart `BlockSemantics(child:)`.
7076    #[cfg_attr(debug_assertions, track_caller)]
7077    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> BlockSemantics {
7078        self.child = Some(child.into_widget());
7079        self
7080    }
7081}
7082
7083impl Default for BlockSemantics {
7084    fn default() -> BlockSemantics {
7085        BlockSemantics {
7086            key: None,
7087            blocking: true,
7088            child: None,
7089        }
7090    }
7091}
7092
7093impl RenderObjectWidget for BlockSemantics {
7094    type RenderObject = RenderBlockSemantics;
7095
7096    fn key(&self) -> Option<&KeyRef> {
7097        self.key.as_ref()
7098    }
7099
7100    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7101        RenderBlockSemantics::new(app, self.blocking, None).as_object()
7102    }
7103
7104    fn update_render_object(
7105        &self,
7106        app: &mut App,
7107        _context: BuildContext,
7108        render_object: RenderHandle<RenderBlockSemantics>,
7109    ) {
7110        render_object.set_blocking(app, self.blocking);
7111    }
7112}
7113
7114impl SingleChildRenderObjectWidget for BlockSemantics {
7115    fn child(&self) -> Option<&WidgetRef> {
7116        self.child.as_ref()
7117    }
7118}
7119
7120/// A widget that drops all the semantics of its descendants.
7121///
7122/// When [`excluding`](Self::excluding) is true, this widget (and its subtree) is excluded from
7123/// the semantics tree.
7124///
7125/// This can be used to hide descendant widgets that would otherwise be
7126/// reported but that would only be confusing. For example, the
7127/// material library's `Chip` widget hides the avatar since it is
7128/// redundant with the chip label.
7129///
7130/// See also:
7131///
7132///  * [`BlockSemantics`] which drops semantics of widgets earlier in the tree.
7133#[derive(Debug)]
7134pub struct ExcludeSemantics {
7135    pub key: Option<KeyRef>,
7136
7137    /// Whether this widget is excluded in the semantics tree.
7138    pub excluding: bool,
7139    pub child: Option<WidgetRef>,
7140}
7141
7142impl ExcludeSemantics {
7143    /// Creates a widget that drops all the semantics of its descendants; Dart's named arguments
7144    /// are the setters.
7145    pub fn new() -> ExcludeSemantics {
7146        ExcludeSemantics::default()
7147    }
7148
7149    /// Dart `ExcludeSemantics(key:)`.
7150    pub fn key(mut self, key: KeyRef) -> ExcludeSemantics {
7151        self.key = Some(key);
7152        self
7153    }
7154
7155    /// Dart `ExcludeSemantics(excluding:)`.
7156    pub fn excluding(mut self, excluding: bool) -> ExcludeSemantics {
7157        self.excluding = excluding;
7158        self
7159    }
7160
7161    /// Dart `ExcludeSemantics(child:)`.
7162    #[cfg_attr(debug_assertions, track_caller)]
7163    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ExcludeSemantics {
7164        self.child = Some(child.into_widget());
7165        self
7166    }
7167}
7168
7169impl Default for ExcludeSemantics {
7170    fn default() -> ExcludeSemantics {
7171        ExcludeSemantics {
7172            key: None,
7173            excluding: true,
7174            child: None,
7175        }
7176    }
7177}
7178
7179impl RenderObjectWidget for ExcludeSemantics {
7180    type RenderObject = RenderExcludeSemantics;
7181
7182    fn key(&self) -> Option<&KeyRef> {
7183        self.key.as_ref()
7184    }
7185
7186    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7187        RenderExcludeSemantics::new(app, self.excluding, None).as_object()
7188    }
7189
7190    fn update_render_object(
7191        &self,
7192        app: &mut App,
7193        _context: BuildContext,
7194        render_object: RenderHandle<RenderExcludeSemantics>,
7195    ) {
7196        render_object.set_excluding(app, self.excluding);
7197    }
7198}
7199
7200impl SingleChildRenderObjectWidget for ExcludeSemantics {
7201    fn child(&self) -> Option<&WidgetRef> {
7202        self.child.as_ref()
7203    }
7204}
7205
7206/// A widget that annotates the child semantics with an index.
7207///
7208/// Semantic indexes are used by TalkBack/Voiceover to make announcements about
7209/// the current scroll state. Certain widgets like the `ListView` will
7210/// automatically provide a child index for building semantics. A user may wish
7211/// to manually provide semantic indexes if not all child of the scrollable
7212/// contribute semantics.
7213///
7214/// See also:
7215///
7216///  * `CustomScrollView`, for an explanation of index semantics.
7217#[derive(Debug)]
7218pub struct IndexedSemantics {
7219    pub key: Option<KeyRef>,
7220
7221    /// The index used to annotate the first child semantics node.
7222    pub index: i32,
7223    pub child: Option<WidgetRef>,
7224}
7225
7226impl IndexedSemantics {
7227    /// Creates a widget that annotated the first child semantics node with an index; Dart's
7228    /// named arguments are the setters.
7229    pub fn new(index: i32) -> IndexedSemantics {
7230        IndexedSemantics {
7231            key: None,
7232            index,
7233            child: None,
7234        }
7235    }
7236
7237    /// Dart `IndexedSemantics(key:)`.
7238    pub fn key(mut self, key: KeyRef) -> IndexedSemantics {
7239        self.key = Some(key);
7240        self
7241    }
7242
7243    /// Dart `IndexedSemantics(child:)`.
7244    #[cfg_attr(debug_assertions, track_caller)]
7245    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> IndexedSemantics {
7246        self.child = Some(child.into_widget());
7247        self
7248    }
7249}
7250
7251impl RenderObjectWidget for IndexedSemantics {
7252    type RenderObject = RenderIndexedSemantics;
7253
7254    fn key(&self) -> Option<&KeyRef> {
7255        self.key.as_ref()
7256    }
7257
7258    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7259        RenderIndexedSemantics::new(app, self.index, None).as_object()
7260    }
7261
7262    fn update_render_object(
7263        &self,
7264        app: &mut App,
7265        _context: BuildContext,
7266        render_object: RenderHandle<RenderIndexedSemantics>,
7267    ) {
7268        render_object.set_index(app, self.index);
7269    }
7270}
7271
7272impl SingleChildRenderObjectWidget for IndexedSemantics {
7273    fn child(&self) -> Option<&WidgetRef> {
7274        self.child.as_ref()
7275    }
7276}
7277
7278/// A widget that builds its child.
7279///
7280/// Useful for attaching a key to an existing widget.
7281#[derive(Debug)]
7282pub struct KeyedSubtree {
7283    pub key: Option<KeyRef>,
7284    /// The widget below this widget in the tree.
7285    pub child: WidgetRef,
7286}
7287
7288impl KeyedSubtree {
7289    /// Creates a widget that builds its child while assigning it a key.
7290    ///
7291    /// This is useful when you want to preserve the state of a widget when it moves around in
7292    /// the widget tree by associating it with a consistent key.
7293    #[cfg_attr(debug_assertions, track_caller)]
7294    pub fn new<K>(child: impl IntoWidget<K>) -> KeyedSubtree {
7295        KeyedSubtree {
7296            key: None,
7297            child: child.into_widget(),
7298        }
7299    }
7300
7301    /// Creates a [`KeyedSubtree`] for child with a key that's based on the child's existing
7302    /// key or `child_index`.
7303    ///
7304    /// Dart's `ValueKey<Object>(child.key ?? childIndex)` is one key type for both: it never
7305    /// equals a `ValueKey` of another type, such as a caller's own `ValueKey<int>`.
7306    pub fn wrap(child: WidgetRef, child_index: i64) -> KeyedSubtree {
7307        let value = match child.key() {
7308            Some(key) => WrapKeyValue::Key(key.clone()),
7309            None => WrapKeyValue::Index(child_index),
7310        };
7311        KeyedSubtree {
7312            key: Some(ValueKey::new(value).into()),
7313            child,
7314        }
7315    }
7316
7317    /// Dart `KeyedSubtree(key:)`.
7318    pub fn key(mut self, key: KeyRef) -> KeyedSubtree {
7319        self.key = Some(key);
7320        self
7321    }
7322
7323    /// Wrap each item in a KeyedSubtree whose key is based on the item's existing key or
7324    /// the sum of its list index and `base_index`.
7325    ///
7326    /// Dart's `baseIndex` defaults to 0.
7327    pub fn ensure_unique_keys_for_list(items: Vec<WidgetRef>, base_index: i64) -> Vec<WidgetRef> {
7328        if items.is_empty() {
7329            return items;
7330        }
7331
7332        let items_with_unique_keys: Vec<WidgetRef> = items
7333            .into_iter()
7334            .zip(0..)
7335            .map(|(item, i)| KeyedSubtree::wrap(item, base_index + i).into_widget())
7336            .collect();
7337
7338        debug_assert!(!debug_items_have_duplicate_keys(&items_with_unique_keys));
7339        items_with_unique_keys
7340    }
7341}
7342
7343impl StatelessWidget for KeyedSubtree {
7344    fn key(&self) -> Option<&KeyRef> {
7345        self.key.as_ref()
7346    }
7347
7348    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
7349        self.child.clone()
7350    }
7351}
7352
7353/// The value of [`KeyedSubtree::wrap`]'s key: Dart's `Object` holding `child.key ?? childIndex`.
7354#[derive(Clone, PartialEq, Eq, Hash)]
7355enum WrapKeyValue {
7356    Key(KeyRef),
7357    Index(i64),
7358}
7359
7360impl Debug for WrapKeyValue {
7361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7362        match self {
7363            WrapKeyValue::Key(key) => key.fmt(f),
7364            WrapKeyValue::Index(index) => index.fmt(f),
7365        }
7366    }
7367}
7368
7369/// Dart's `_firstNonUniqueKey` from `widgets/debug.dart`.
7370fn first_non_unique_key(widgets: &[WidgetRef]) -> Option<&KeyRef> {
7371    let mut key_set = HashSet::new();
7372    widgets
7373        .iter()
7374        .filter_map(|widget| widget.key())
7375        .find(|&key| !key_set.insert(key))
7376}
7377
7378/// Asserts if the given list of items contains any duplicate non-null keys.
7379///
7380/// Call it as `debug_assert!(!debug_items_have_duplicate_keys(&items))`. Always returns
7381/// false. Dart's from `widgets/debug.dart`.
7382fn debug_items_have_duplicate_keys(items: &[WidgetRef]) -> bool {
7383    if let Some(non_unique_key) = first_non_unique_key(items) {
7384        panic!("Duplicate key found: {non_unique_key:?}.");
7385    }
7386    false
7387}
7388
7389/// Signature for a function that creates a widget, e.g. [`StatelessWidget::build`]
7390/// or `State::build`.
7391///
7392/// Used by [`Builder::builder`], `OverlayEntry.builder`, etc.
7393///
7394/// See also:
7395///
7396///  * `IndexedWidgetBuilder`, which is similar but also takes an index.
7397///  * `TransitionBuilder`, which is similar but also takes a child.
7398///  * `ValueWidgetBuilder`, which is similar but takes a value and a child.
7399///
7400/// Flutter's `Widget Function(BuildContext context)` from `framework.dart`; receives
7401/// [`App`] because a Rust callback cannot capture what it mutates.
7402pub type WidgetBuilder = Rc<dyn Fn(&mut App, BuildContext) -> WidgetRef>;
7403
7404/// Signature for a function that creates a widget for a given index, e.g., in a list.
7405///
7406/// Used by `ReorderableList.itemBuilder`.
7407///
7408/// See also:
7409///
7410///  * [`WidgetBuilder`], which is similar but only takes a [`BuildContext`].
7411///  * `NullableIndexedWidgetBuilder`, which is similar but may return `None`.
7412///
7413/// Flutter's `Widget Function(BuildContext context, int index)` from `framework.dart`;
7414/// receives [`App`] because a Rust callback cannot capture what it mutates.
7415pub type IndexedWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, i32) -> WidgetRef>;
7416
7417/// A stateless utility widget whose [`build`](StatelessWidget::build) method uses its
7418/// [`builder`](Self::builder) callback to create the widget's child.
7419///
7420/// The [`Builder`] widget is essentially a fancy way of calling a closure that returns a
7421/// widget, but with two key differences:
7422///
7423/// 1. It creates a new [`BuildContext`]. This means that any [`BuildContext`]-dependent
7424///    calls inside it, such as `Theme.of` or `Directionality.of`, will use the
7425///    context of the [`Builder`] rather than the enclosing widget's.
7426/// 2. It lets you avoid creating a separate widget class for what may be a very
7427///    simple nested build.
7428///
7429/// ## Why is the [`Builder`] widget necessary?
7430///
7431/// The [`Builder`] widget is useful when you need to access a [`BuildContext`]
7432/// that is a descendant of a particular widget, for example an inherited widget
7433/// introduced by the same `build` method.
7434///
7435/// See also:
7436///
7437///  * `StatefulBuilder`, A stateful utility widget whose build method uses its
7438///    builder callback to create the widget's child.
7439pub struct Builder {
7440    pub key: Option<KeyRef>,
7441    /// Called to obtain the child widget.
7442    ///
7443    /// This function is called whenever this widget is included in its parent's
7444    /// build and the old widget (if any) that it synchronizes with has a distinct
7445    /// object identity. Typically the parent's build method will construct
7446    /// a new tree of widgets and so a new Builder child will not be identical
7447    /// to the corresponding old one.
7448    pub builder: WidgetBuilder,
7449}
7450
7451impl Builder {
7452    /// Creates a `Builder`; Dart's optional named arguments are the setters.
7453    pub fn new(builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static) -> Builder {
7454        Builder {
7455            key: None,
7456            builder: Rc::new(builder),
7457        }
7458    }
7459
7460    /// Dart `Builder(key:)`.
7461    pub fn key(mut self, key: KeyRef) -> Builder {
7462        self.key = Some(key);
7463        self
7464    }
7465}
7466
7467impl StatelessWidget for Builder {
7468    fn key(&self) -> Option<&KeyRef> {
7469        self.key.as_ref()
7470    }
7471
7472    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
7473        (self.builder)(app, context)
7474    }
7475}
7476
7477impl Debug for Builder {
7478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7479        f.debug_struct("Builder")
7480            .field("key", &self.key)
7481            .finish_non_exhaustive()
7482    }
7483}
7484
7485/// The signature of the `set_state` a [`StatefulBuilder`] hands its builder; Dart's
7486/// `StateSetter`.
7487///
7488/// The callback runs before the state is marked for a rebuild, as Dart's `setState(fn)` runs
7489/// `fn` first.
7490pub type StateSetter = Rc<dyn Fn(&mut App, &mut dyn FnMut(&mut App))>;
7491
7492/// Signature for the builder callback used by [`StatefulBuilder`].
7493///
7494/// Call `set_state` to schedule the [`StatefulBuilder`] to rebuild.
7495pub type StatefulWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, StateSetter) -> WidgetRef>;
7496
7497/// A platonic widget that both has state and calls a closure to obtain its child widget.
7498///
7499/// The [`StateSetter`] function passed to the [`builder`](Self::builder) is used to invoke a
7500/// rebuild instead of a typical [`State`]'s `set_state`.
7501///
7502/// Since the [`builder`](Self::builder) is re-invoked when the [`StateSetter`] is called, any
7503/// variables that represents state should be kept outside the [`builder`](Self::builder)
7504/// function.
7505///
7506/// See also:
7507///
7508///  * [`Builder`], the platonic stateless widget.
7509pub struct StatefulBuilder {
7510    pub key: Option<KeyRef>,
7511    /// Called to obtain the child widget.
7512    ///
7513    /// This function is called whenever this widget is included in its parent's
7514    /// build and the old widget (if any) that it synchronizes with has a distinct
7515    /// object identity. Typically the parent's build method will construct
7516    /// a new tree of widgets and so a new Builder child will not be identical
7517    /// to the corresponding old one.
7518    pub builder: StatefulWidgetBuilder,
7519}
7520
7521impl StatefulBuilder {
7522    /// Creates a widget that both has state and delegates its build to a callback; Dart's
7523    /// optional named arguments are the setters.
7524    pub fn new(
7525        builder: impl Fn(&mut App, BuildContext, StateSetter) -> WidgetRef + 'static,
7526    ) -> StatefulBuilder {
7527        StatefulBuilder {
7528            key: None,
7529            builder: Rc::new(builder),
7530        }
7531    }
7532
7533    /// Dart `StatefulBuilder(key:)`.
7534    pub fn key(mut self, key: KeyRef) -> StatefulBuilder {
7535        self.key = Some(key);
7536        self
7537    }
7538}
7539
7540impl Debug for StatefulBuilder {
7541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7542        f.debug_struct("StatefulBuilder")
7543            .field("key", &self.key)
7544            .finish_non_exhaustive()
7545    }
7546}
7547
7548impl StatefulWidget for StatefulBuilder {
7549    type State = StatefulBuilderState;
7550
7551    fn key(&self) -> Option<&KeyRef> {
7552        self.key.as_ref()
7553    }
7554
7555    fn create_state(&self) -> StatefulBuilderState {
7556        StatefulBuilderState {
7557            state: StateData::new(),
7558        }
7559    }
7560}
7561
7562/// Dart's `_StatefulBuilderState`.
7563pub struct StatefulBuilderState {
7564    state: StateData<StatefulBuilder>,
7565}
7566
7567impl State for StatefulBuilderState {
7568    type Widget = StatefulBuilder;
7569    crate::state_accessors!();
7570
7571    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
7572        let builder = Rc::clone(&self.widget(app).builder);
7573        let set_state: StateSetter = Rc::new(move |app: &mut App, f: &mut dyn FnMut(&mut App)| {
7574            // `setState`'s lifecycle asserts run before the callback, as Dart's do.
7575            debug_assert!(
7576                self.mounted(app),
7577                "setState() called after dispose(): this error happens if you call setState() \
7578                 on a State object for a widget that no longer appears in the widget tree."
7579            );
7580            f(app);
7581            self.set_state(app, |_| {});
7582        });
7583        builder(app, context, set_state)
7584    }
7585}
7586
7587/// A widget that paints its area with a specified color and then draws its
7588/// child on top of that color.
7589///
7590/// Flutter's private `_RenderColoredBox` is rendering's [`RenderColoredBox`].
7591#[derive(Debug)]
7592pub struct ColoredBox {
7593    pub key: Option<KeyRef>,
7594    /// The color to paint the background area with.
7595    pub color: AnyColor,
7596    /// Whether to apply anti-aliasing when painting the box.
7597    ///
7598    /// Defaults to `true`.
7599    ///
7600    /// When `true`, the painted box will have smooth edges. This is crucial for
7601    /// animations and transformations (such as rotation or scaling) where the
7602    /// widget's edges may not align perfectly with the physical pixel grid.
7603    /// Anti-aliasing allows for sub-pixel rendering, which prevents a 'jagged'
7604    /// appearance during motion and ensures visually smooth transitions.
7605    ///
7606    /// Set this to `false` for specific use cases where multiple [`ColoredBox`]
7607    /// widgets are positioned adjacent to each other to form a larger, seamless
7608    /// area of solid color. With anti-aliasing enabled (`true`), faint seams or
7609    /// gaps might appear between the boxes due to the semi-transparent pixels at
7610    /// their edges. Disabling anti-aliasing ensures that the boxes align perfectly
7611    /// without such visual artifacts.
7612    ///
7613    /// See also:
7614    ///
7615    ///  * `Paint::is_anti_alias`, the underlying property that this controls.
7616    pub is_anti_alias: bool,
7617    pub child: Option<WidgetRef>,
7618}
7619
7620impl ColoredBox {
7621    /// Creates a widget that paints its area with the specified color; Dart's optional named
7622    /// arguments are the setters.
7623    pub fn new(color: impl Into<AnyColor>) -> ColoredBox {
7624        ColoredBox {
7625            key: None,
7626            color: color.into(),
7627            is_anti_alias: true,
7628            child: None,
7629        }
7630    }
7631
7632    /// Dart `ColoredBox(key:)`.
7633    pub fn key(mut self, key: KeyRef) -> ColoredBox {
7634        self.key = Some(key);
7635        self
7636    }
7637
7638    /// Dart `ColoredBox(isAntiAlias:)`.
7639    pub fn is_anti_alias(mut self, is_anti_alias: bool) -> ColoredBox {
7640        self.is_anti_alias = is_anti_alias;
7641        self
7642    }
7643
7644    /// Dart `ColoredBox(child:)`.
7645    #[cfg_attr(debug_assertions, track_caller)]
7646    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ColoredBox {
7647        self.child = Some(child.into_widget());
7648        self
7649    }
7650}
7651
7652impl RenderObjectWidget for ColoredBox {
7653    type RenderObject = RenderColoredBox;
7654
7655    fn key(&self) -> Option<&KeyRef> {
7656        self.key.as_ref()
7657    }
7658
7659    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
7660        properties.add(DiagnosticsProperty::new("color", self.color.color()));
7661        properties.add(
7662            DiagnosticsProperty::new("isAntiAlias", self.is_anti_alias).default_value(Some(true)),
7663        );
7664    }
7665
7666    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7667        RenderColoredBox::new(app, self.color.color(), self.is_anti_alias, None).as_object()
7668    }
7669
7670    fn update_render_object(
7671        &self,
7672        app: &mut App,
7673        _context: BuildContext,
7674        render_object: RenderHandle<RenderColoredBox>,
7675    ) {
7676        render_object.set_color(app, self.color.color());
7677        render_object.set_is_anti_alias(app, self.is_anti_alias);
7678    }
7679}
7680
7681impl SingleChildRenderObjectWidget for ColoredBox {
7682    fn child(&self) -> Option<&WidgetRef> {
7683        self.child.as_ref()
7684    }
7685}
7686
7687// LAYOUT NODES
7688
7689/// Returns the [`AxisDirection`] in the given [`Axis`] in the current
7690/// [`Directionality`] (or the reverse if `reverse` is true).
7691///
7692/// If `axis` is [`Axis::Vertical`], this function returns [`AxisDirection::Down`]
7693/// unless `reverse` is true, in which case this function returns
7694/// [`AxisDirection::Up`].
7695///
7696/// If `axis` is [`Axis::Horizontal`], this function checks the current
7697/// [`Directionality`]. If the current [`Directionality`] is right-to-left, then
7698/// this function returns [`AxisDirection::Left`] (unless `reverse` is true, in
7699/// which case it returns [`AxisDirection::Right`]). Similarly, if the current
7700/// [`Directionality`] is left-to-right, then this function returns
7701/// [`AxisDirection::Right`] (unless `reverse` is true, in which case it returns
7702/// [`AxisDirection::Left`]).
7703///
7704/// This function is used by a number of scrolling widgets (e.g. `ListView`,
7705/// `GridView`, `PageView`, and `SingleChildScrollView`) to translate their
7706/// [`Axis`] and `reverse` properties into a concrete [`AxisDirection`].
7707pub fn get_axis_direction_from_axis_reverse_and_directionality(
7708    app: &mut App,
7709    context: BuildContext,
7710    axis: Axis,
7711    reverse: bool,
7712) -> AxisDirection {
7713    match axis {
7714        Axis::Horizontal => {
7715            let text_direction = Directionality::of(app, context);
7716            let axis_direction = text_direction_to_axis_direction(text_direction);
7717            if reverse {
7718                flip_axis_direction(axis_direction)
7719            } else {
7720                axis_direction
7721            }
7722        }
7723        Axis::Vertical => {
7724            if reverse {
7725                AxisDirection::Up
7726            } else {
7727                AxisDirection::Down
7728            }
7729        }
7730    }
7731}
7732
7733/// A widget that positions its children relative to the edges of its box.
7734///
7735/// This class is useful if you want to overlap several children in a simple
7736/// way, for example having some text and an image, overlaid with a gradient and
7737/// a button attached to the bottom.
7738///
7739/// Each child of a [`Stack`] widget is either _positioned_ or _non-positioned_.
7740/// Positioned children are those wrapped in a [`Positioned`] widget that has at
7741/// least one non-`None` property. The stack sizes itself to contain all the
7742/// non-positioned children, which are positioned according to
7743/// [`alignment`](Self::alignment) (which defaults to the top-left corner in
7744/// left-to-right environments and the top-right corner in right-to-left
7745/// environments). The positioned children are then placed relative to the stack
7746/// according to their top, right, bottom, and left properties.
7747///
7748/// The stack paints its children in order with the first child being at the
7749/// bottom. If you want to change the order in which the children paint, you
7750/// can rebuild the stack with the children in the new order. If you reorder
7751/// the children in this way, consider giving the children non-`None` keys.
7752/// These keys will cause the framework to move the underlying objects for
7753/// the children to their new locations rather than recreate them at their
7754/// new location.
7755///
7756/// For more details about the stack layout algorithm, see `RenderStack`.
7757///
7758/// See also:
7759///
7760///  * [`Align`], which sizes itself based on its child's size and positions
7761///    the child according to an `Alignment` value.
7762///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
7763#[derive(Debug)]
7764pub struct Stack {
7765    pub key: Option<KeyRef>,
7766    /// How to align the non-positioned and partially-positioned children in the stack.
7767    ///
7768    /// The non-positioned children are placed relative to each other such that the points
7769    /// determined by [`alignment`](Self::alignment) are co-located. For example, if the
7770    /// alignment is `AlignmentGeometry::TOP_LEFT`, then the top left corner of each
7771    /// non-positioned child will be located at the same global coordinate.
7772    ///
7773    /// Partially-positioned children, those that do not specify an alignment in a particular
7774    /// axis (e.g. that have neither `top` nor `bottom` set), use the alignment to determine how
7775    /// they should be positioned in that under-specified axis.
7776    ///
7777    /// Defaults to `AlignmentGeometry::TOP_START`.
7778    pub alignment: AlignmentGeometry,
7779    /// The text direction with which to resolve [`alignment`](Self::alignment).
7780    ///
7781    /// Defaults to the ambient [`Directionality`].
7782    pub text_direction: Option<TextDirection>,
7783    /// How to size the non-positioned children in the stack.
7784    ///
7785    /// The constraints passed into the [`Stack`] from its parent are either loosened
7786    /// ([`StackFit::Loose`]) or tightened to their biggest size ([`StackFit::Expand`]).
7787    pub fit: StackFit,
7788    /// Stacks only clip children whose _geometry_ overflows the stack. A child that paints
7789    /// outside its bounds (e.g. a box with a shadow) will not be clipped, regardless of the
7790    /// value of this property. Similarly, a child that itself has a descendant that overflows
7791    /// the stack will not be clipped, as only the geometry of the stack's direct children are
7792    /// considered.
7793    ///
7794    /// Even when this is set to [`Clip::None`], the stack itself does not extend its hit-test
7795    /// region: pointer events that fall outside the stack's own bounds will not reach a child
7796    /// even if that child is painted in that area.
7797    ///
7798    /// Defaults to [`Clip::HardEdge`].
7799    pub clip_behavior: Clip,
7800    pub children: Vec<WidgetRef>,
7801}
7802
7803impl Stack {
7804    /// Creates a `Stack`; Dart's named arguments are the setters.
7805    ///
7806    /// By default, the non-positioned children of the stack are aligned by their top left
7807    /// corners.
7808    pub fn new() -> Stack {
7809        Stack::default()
7810    }
7811
7812    /// Dart `Stack(key:)`.
7813    pub fn key(mut self, key: KeyRef) -> Stack {
7814        self.key = Some(key);
7815        self
7816    }
7817
7818    /// Dart `Stack(alignment:)`.
7819    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Stack {
7820        self.alignment = alignment;
7821        self
7822    }
7823
7824    /// Dart `Stack(textDirection:)`.
7825    pub fn text_direction(mut self, text_direction: TextDirection) -> Stack {
7826        self.text_direction = Some(text_direction);
7827        self
7828    }
7829
7830    /// Dart `Stack(fit:)`.
7831    pub fn fit(mut self, fit: StackFit) -> Stack {
7832        self.fit = fit;
7833        self
7834    }
7835
7836    /// Dart `Stack(clipBehavior:)`.
7837    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Stack {
7838        self.clip_behavior = clip_behavior;
7839        self
7840    }
7841
7842    /// Dart `Stack(children:)`.
7843    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> Stack {
7844        self.children = children.into_iter().collect();
7845        self
7846    }
7847
7848    /// `Stack.createRenderObject`'s body, shared with [`RawIndexedStack`]'s text direction.
7849    fn resolved_text_direction(
7850        text_direction: Option<TextDirection>,
7851        app: &mut App,
7852        context: BuildContext,
7853    ) -> Option<TextDirection> {
7854        text_direction.or_else(|| Directionality::maybe_of(app, context))
7855    }
7856}
7857
7858impl Default for Stack {
7859    fn default() -> Stack {
7860        Stack {
7861            key: None,
7862            alignment: AlignmentGeometry::TOP_START,
7863            text_direction: None,
7864            fit: StackFit::Loose,
7865            clip_behavior: Clip::HardEdge,
7866            children: Vec::new(),
7867        }
7868    }
7869}
7870
7871impl RenderObjectWidget for Stack {
7872    type RenderObject = RenderStack;
7873
7874    fn key(&self) -> Option<&KeyRef> {
7875        self.key.as_ref()
7876    }
7877
7878    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
7879        properties.add(DiagnosticsProperty::new("alignment", self.alignment));
7880        properties.add(
7881            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
7882                .default_value(None),
7883        );
7884        properties.add(EnumProperty::new("fit", self.fit));
7885        properties.add(
7886            EnumProperty::new("clipBehavior", self.clip_behavior)
7887                .default_value(Some(Clip::HardEdge)),
7888        );
7889    }
7890
7891    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
7892        let render_object = RenderStack::new(app);
7893        render_object.set_alignment(app, self.alignment);
7894        let text_direction = Stack::resolved_text_direction(self.text_direction, app, context);
7895        render_object.set_text_direction(app, text_direction);
7896        render_object.set_fit(app, self.fit);
7897        render_object.set_clip_behavior(app, self.clip_behavior);
7898        render_object.as_object()
7899    }
7900
7901    fn update_render_object(
7902        &self,
7903        app: &mut App,
7904        context: BuildContext,
7905        render_object: RenderHandle<RenderStack>,
7906    ) {
7907        render_object.set_alignment(app, self.alignment);
7908        let text_direction = Stack::resolved_text_direction(self.text_direction, app, context);
7909        render_object.set_text_direction(app, text_direction);
7910        render_object.set_fit(app, self.fit);
7911        render_object.set_clip_behavior(app, self.clip_behavior);
7912    }
7913}
7914
7915impl MultiChildRenderObjectWidget for Stack {
7916    fn children(&self) -> &[WidgetRef] {
7917        &self.children
7918    }
7919}
7920
7921/// A widget that controls where a child of a [`Stack`] is positioned.
7922///
7923/// A [`Positioned`] widget must be a descendant of a [`Stack`], and the path from the
7924/// [`Positioned`] widget to its enclosing [`Stack`] must contain only stateless or stateful
7925/// widgets (not other kinds of widgets, like render object widgets).
7926///
7927/// If a widget is wrapped in a [`Positioned`], then it is a _positioned_ widget in its
7928/// [`Stack`]. If the [`top`](Self::top) property is non-`None`, the top edge of this child
7929/// will be positioned [`top`](Self::top) layout units from the top of the stack widget. The
7930/// [`right`](Self::right), [`bottom`](Self::bottom), and [`left`](Self::left) properties work
7931/// analogously.
7932///
7933/// If both the [`top`](Self::top) and [`bottom`](Self::bottom) properties are non-`None`, then
7934/// the child will be forced to have exactly the height required to satisfy both constraints.
7935/// Similarly, setting the [`right`](Self::right) and [`left`](Self::left) properties to
7936/// non-`None` values will force the child to have a particular width. Alternatively the
7937/// [`width`](Self::width) and [`height`](Self::height) properties can be used to give the
7938/// dimensions, with one corresponding position property (e.g. [`top`](Self::top) and
7939/// [`height`](Self::height)).
7940///
7941/// If all three values on a particular axis are `None`, then the [`Stack::alignment`] property
7942/// is used to position the child.
7943///
7944/// If all six values are `None`, the child is a non-positioned child. The [`Stack`] uses only
7945/// the non-positioned children to size itself.
7946///
7947/// Only two out of the three horizontal values ([`left`](Self::left), [`right`](Self::right),
7948/// [`width`](Self::width)), and only two out of the three vertical values
7949/// ([`top`](Self::top), [`bottom`](Self::bottom), [`height`](Self::height)), can be set. In
7950/// each case, at least one of the three must be `None`.
7951#[derive(Debug)]
7952pub struct Positioned {
7953    pub key: Option<KeyRef>,
7954    /// The distance that the child's left edge is inset from the left of the stack.
7955    ///
7956    /// Only two out of the three horizontal values ([`left`](Self::left),
7957    /// [`right`](Self::right), [`width`](Self::width)) can be set. The third must be `None`.
7958    ///
7959    /// If all three are `None`, the [`Stack::alignment`] is used to position the child
7960    /// horizontally.
7961    pub left: Option<f64>,
7962    /// The distance that the child's top edge is inset from the top of the stack.
7963    ///
7964    /// Only two out of the three vertical values ([`top`](Self::top), [`bottom`](Self::bottom),
7965    /// [`height`](Self::height)) can be set. The third must be `None`.
7966    ///
7967    /// If all three are `None`, the [`Stack::alignment`] is used to position the child
7968    /// vertically.
7969    pub top: Option<f64>,
7970    /// The distance that the child's right edge is inset from the right of the stack.
7971    ///
7972    /// See [`left`](Self::left).
7973    pub right: Option<f64>,
7974    /// The distance that the child's bottom edge is inset from the bottom of the stack.
7975    ///
7976    /// See [`top`](Self::top).
7977    pub bottom: Option<f64>,
7978    /// The child's width.
7979    ///
7980    /// See [`left`](Self::left).
7981    pub width: Option<f64>,
7982    /// The child's height.
7983    ///
7984    /// See [`top`](Self::top).
7985    pub height: Option<f64>,
7986    pub child: WidgetRef,
7987}
7988
7989impl Positioned {
7990    /// Creates a widget that controls where a child of a [`Stack`] is positioned; Dart's
7991    /// optional named arguments are the setters.
7992    #[cfg_attr(debug_assertions, track_caller)]
7993    pub fn new<K>(child: impl IntoWidget<K>) -> Positioned {
7994        Positioned {
7995            key: None,
7996            left: None,
7997            top: None,
7998            right: None,
7999            bottom: None,
8000            width: None,
8001            height: None,
8002            child: child.into_widget(),
8003        }
8004    }
8005
8006    /// Creates a `Positioned` object with the values from the given `Rect`.
8007    ///
8008    /// This sets the [`left`](Self::left), [`top`](Self::top), [`width`](Self::width), and
8009    /// [`height`](Self::height) properties from the given `Rect`. The [`right`](Self::right)
8010    /// and [`bottom`](Self::bottom) properties are set to `None`.
8011    #[cfg_attr(debug_assertions, track_caller)]
8012    pub fn from_rect<K>(rect: Rect, child: impl IntoWidget<K>) -> Positioned {
8013        Positioned {
8014            key: None,
8015            left: Some(rect.left),
8016            top: Some(rect.top),
8017            right: None,
8018            bottom: None,
8019            width: Some(rect.width()),
8020            height: Some(rect.height()),
8021            child: child.into_widget(),
8022        }
8023    }
8024
8025    /// Creates a `Positioned` object with the values from the given [`RelativeRect`].
8026    ///
8027    /// This sets the [`left`](Self::left), [`top`](Self::top), [`right`](Self::right), and
8028    /// [`bottom`](Self::bottom) properties from the given [`RelativeRect`]. The
8029    /// [`height`](Self::height) and [`width`](Self::width) properties are set to `None`.
8030    #[cfg_attr(debug_assertions, track_caller)]
8031    pub fn from_relative_rect<K>(rect: RelativeRect, child: impl IntoWidget<K>) -> Positioned {
8032        Positioned {
8033            key: None,
8034            left: Some(rect.left),
8035            top: Some(rect.top),
8036            right: Some(rect.right),
8037            bottom: Some(rect.bottom),
8038            width: None,
8039            height: None,
8040            child: child.into_widget(),
8041        }
8042    }
8043
8044    /// Creates a `Positioned` object with [`left`](Self::left), [`top`](Self::top),
8045    /// [`right`](Self::right), and [`bottom`](Self::bottom) set to 0.0 unless a value for them
8046    /// is passed.
8047    #[cfg_attr(debug_assertions, track_caller)]
8048    pub fn fill<K>(child: impl IntoWidget<K>) -> Positioned {
8049        Positioned {
8050            key: None,
8051            left: Some(0.0),
8052            top: Some(0.0),
8053            right: Some(0.0),
8054            bottom: Some(0.0),
8055            width: None,
8056            height: None,
8057            child: child.into_widget(),
8058        }
8059    }
8060
8061    /// Creates a widget that controls where a child of a [`Stack`] is positioned, taking
8062    /// `start` and `end` rather than [`left`](Self::left) and [`right`](Self::right).
8063    ///
8064    /// If `text_direction` is `TextDirection::Rtl`, then the `start` argument is used for the
8065    /// [`right`](Self::right) property and the `end` argument is used for the
8066    /// [`left`](Self::left) property. Otherwise, if `text_direction` is `TextDirection::Ltr`,
8067    /// then the `start` argument is used for the [`left`](Self::left) property and the `end`
8068    /// argument is used for the [`right`](Self::right) property.
8069    ///
8070    /// Dart `Positioned.directional(textDirection:, start:, end:, child:)`; `start` and `end`
8071    /// are arguments rather than setters because resolving them needs the text direction.
8072    #[cfg_attr(debug_assertions, track_caller)]
8073    pub fn directional<K>(
8074        text_direction: TextDirection,
8075        start: Option<f64>,
8076        end: Option<f64>,
8077        child: impl IntoWidget<K>,
8078    ) -> Positioned {
8079        let (left, right) = match text_direction {
8080            TextDirection::Rtl => (end, start),
8081            TextDirection::Ltr => (start, end),
8082        };
8083        Positioned {
8084            key: None,
8085            left,
8086            top: None,
8087            right,
8088            bottom: None,
8089            width: None,
8090            height: None,
8091            child: child.into_widget(),
8092        }
8093    }
8094
8095    /// Dart `Positioned(key:)`.
8096    pub fn key(mut self, key: KeyRef) -> Positioned {
8097        self.key = Some(key);
8098        self
8099    }
8100
8101    /// Dart `Positioned(left:)`.
8102    pub fn left(mut self, left: f64) -> Positioned {
8103        self.left = Some(left);
8104        self.debug_check_axes();
8105        self
8106    }
8107
8108    /// Dart `Positioned(top:)`.
8109    pub fn top(mut self, top: f64) -> Positioned {
8110        self.top = Some(top);
8111        self.debug_check_axes();
8112        self
8113    }
8114
8115    /// Dart `Positioned(right:)`.
8116    pub fn right(mut self, right: f64) -> Positioned {
8117        self.right = Some(right);
8118        self.debug_check_axes();
8119        self
8120    }
8121
8122    /// Dart `Positioned(bottom:)`.
8123    pub fn bottom(mut self, bottom: f64) -> Positioned {
8124        self.bottom = Some(bottom);
8125        self.debug_check_axes();
8126        self
8127    }
8128
8129    /// Dart `Positioned(width:)`.
8130    pub fn width(mut self, width: f64) -> Positioned {
8131        self.width = Some(width);
8132        self.debug_check_axes();
8133        self
8134    }
8135
8136    /// Dart `Positioned(height:)`.
8137    pub fn height(mut self, height: f64) -> Positioned {
8138        self.height = Some(height);
8139        self.debug_check_axes();
8140        self
8141    }
8142
8143    /// The constructor asserts: at most two of the three values on each axis.
8144    fn debug_check_axes(&self) {
8145        debug_assert!(self.left.is_none() || self.right.is_none() || self.width.is_none());
8146        debug_assert!(self.top.is_none() || self.bottom.is_none() || self.height.is_none());
8147    }
8148}
8149
8150impl ParentDataWidget for Positioned {
8151    type ParentData = StackParentData;
8152
8153    fn key(&self) -> Option<&KeyRef> {
8154        self.key.as_ref()
8155    }
8156
8157    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
8158        properties.add(DoubleProperty::new("left", self.left).default_value(None));
8159        properties.add(DoubleProperty::new("top", self.top).default_value(None));
8160        properties.add(DoubleProperty::new("right", self.right).default_value(None));
8161        properties.add(DoubleProperty::new("bottom", self.bottom).default_value(None));
8162        properties.add(DoubleProperty::new("width", self.width).default_value(None));
8163        properties.add(DoubleProperty::new("height", self.height).default_value(None));
8164    }
8165
8166    fn child(&self) -> &WidgetRef {
8167        &self.child
8168    }
8169
8170    fn debug_is_valid_render_object(&self, app: &App, render_object: AnyRenderObject) -> bool {
8171        render_object.parent_data_is::<StackParentData>(app)
8172            || render_object.parent_data_is::<TheaterParentData>(app)
8173    }
8174
8175    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
8176        // Dart's `_TheaterParentData extends StackParentData`, so an `Overlay` entry and an
8177        // `OverlayPortal` overlay child can be positioned too.
8178        let parent_data = if render_object.parent_data_is::<StackParentData>(app) {
8179            render_object.parent_data_of_mut::<StackParentData>(app)
8180        } else {
8181            render_object
8182                .parent_data_of_mut::<TheaterParentData>(app)
8183                .stack_mut()
8184        };
8185        let mut needs_layout = false;
8186
8187        if parent_data.left != self.left {
8188            parent_data.left = self.left;
8189            needs_layout = true;
8190        }
8191
8192        if parent_data.top != self.top {
8193            parent_data.top = self.top;
8194            needs_layout = true;
8195        }
8196
8197        if parent_data.right != self.right {
8198            parent_data.right = self.right;
8199            needs_layout = true;
8200        }
8201
8202        if parent_data.bottom != self.bottom {
8203            parent_data.bottom = self.bottom;
8204            needs_layout = true;
8205        }
8206
8207        if parent_data.width != self.width {
8208            parent_data.width = self.width;
8209            needs_layout = true;
8210        }
8211
8212        if parent_data.height != self.height {
8213            parent_data.height = self.height;
8214            needs_layout = true;
8215        }
8216
8217        if needs_layout && let Some(parent) = render_object.parent(app) {
8218            parent.mark_needs_layout(app);
8219        }
8220    }
8221}
8222
8223/// The `RenderFlex` configuration a [`Flex`], [`Row`], or [`Column`] pushes: every field Dart's
8224/// `Flex` declares except the key and the children, which the element manages.
8225#[derive(Clone, Copy, Debug)]
8226struct FlexConfiguration {
8227    direction: Axis,
8228    main_axis_alignment: MainAxisAlignment,
8229    main_axis_size: MainAxisSize,
8230    cross_axis_alignment: CrossAxisAlignment,
8231    text_direction: Option<TextDirection>,
8232    vertical_direction: VerticalDirection,
8233    text_baseline: Option<TextBaseline>,
8234    clip_behavior: Clip,
8235    spacing: f64,
8236}
8237
8238impl FlexConfiguration {
8239    /// Dart's `Flex.debugFillProperties`, which `Row` and `Column` inherit.
8240    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
8241        properties.add(EnumProperty::new("direction", self.direction));
8242        properties.add(EnumProperty::new(
8243            "mainAxisAlignment",
8244            self.main_axis_alignment,
8245        ));
8246        properties.add(
8247            EnumProperty::new("mainAxisSize", self.main_axis_size)
8248                .default_value(Some(MainAxisSize::Max)),
8249        );
8250        properties.add(EnumProperty::new(
8251            "crossAxisAlignment",
8252            self.cross_axis_alignment,
8253        ));
8254        properties.add(
8255            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
8256                .default_value(None),
8257        );
8258        properties.add(
8259            EnumProperty::new("verticalDirection", self.vertical_direction)
8260                .default_value(Some(VerticalDirection::Down)),
8261        );
8262        properties.add(
8263            EnumProperty::<TextBaseline>::new("textBaseline", self.text_baseline)
8264                .default_value(None),
8265        );
8266        properties.add(
8267            EnumProperty::new("clipBehavior", self.clip_behavior).default_value(Some(Clip::None)),
8268        );
8269        properties.add(DoubleProperty::new("spacing", self.spacing).default_value(Some(0.0)));
8270    }
8271
8272    /// A flex laid out along `direction`, with every other field at Dart's default.
8273    fn new(direction: Axis) -> FlexConfiguration {
8274        FlexConfiguration {
8275            direction,
8276            main_axis_alignment: MainAxisAlignment::Start,
8277            main_axis_size: MainAxisSize::Max,
8278            cross_axis_alignment: CrossAxisAlignment::Center,
8279            text_direction: None,
8280            vertical_direction: VerticalDirection::Down,
8281            text_baseline: None,
8282            clip_behavior: Clip::None,
8283            spacing: 0.0,
8284        }
8285    }
8286
8287    /// Dart's `Flex._needTextDirection`.
8288    fn need_text_direction(&self) -> bool {
8289        match self.direction {
8290            // because it affects the layout order.
8291            Axis::Horizontal => true,
8292            Axis::Vertical => {
8293                self.cross_axis_alignment == CrossAxisAlignment::Start
8294                    || self.cross_axis_alignment == CrossAxisAlignment::End
8295            }
8296        }
8297    }
8298
8299    /// Dart's `Flex.getEffectiveTextDirection`.
8300    fn get_effective_text_direction(
8301        &self,
8302        app: &mut App,
8303        context: BuildContext,
8304    ) -> Option<TextDirection> {
8305        self.text_direction.or_else(|| {
8306            self.need_text_direction()
8307                .then(|| Directionality::maybe_of(app, context))
8308                .flatten()
8309        })
8310    }
8311
8312    /// `Flex.createRenderObject`'s body.
8313    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
8314        let render_object = RenderFlex::new(app);
8315        self.push(app, context, render_object);
8316        render_object.as_object()
8317    }
8318
8319    /// `Flex.updateRenderObject`'s body; also the shape of Dart's constructor cascade. It first
8320    /// checks the constructor's assert, which needs two fields and so cannot run on a setter.
8321    fn push(&self, app: &mut App, context: BuildContext, render_object: RenderHandle<RenderFlex>) {
8322        debug_assert!(
8323            self.cross_axis_alignment != CrossAxisAlignment::Baseline
8324                || self.text_baseline.is_some(),
8325            "textBaseline is required if you specify the crossAxisAlignment with \
8326             CrossAxisAlignment.baseline"
8327        );
8328        render_object.set_direction(app, self.direction);
8329        render_object.set_main_axis_alignment(app, self.main_axis_alignment);
8330        render_object.set_main_axis_size(app, self.main_axis_size);
8331        render_object.set_cross_axis_alignment(app, self.cross_axis_alignment);
8332        let text_direction = self.get_effective_text_direction(app, context);
8333        render_object.set_text_direction(app, text_direction);
8334        render_object.set_vertical_direction(app, self.vertical_direction);
8335        render_object.set_text_baseline(app, self.text_baseline);
8336        render_object.set_clip_behavior(app, self.clip_behavior);
8337        render_object.set_spacing(app, self.spacing);
8338    }
8339}
8340
8341/// A widget that positions its child within a [`Stack`] by text direction.
8342///
8343/// Much like [`Positioned`], this widget controls where a child of a [`Stack`]
8344/// is positioned. Unlike [`Positioned`], this widget positions its child by
8345/// distances from the start and end edges, which depend on the ambient
8346/// [`Directionality`].
8347///
8348/// See also:
8349///
8350///  * [`Positioned::directional`], which also provides a directional
8351///    alternative to [`Positioned`], but takes an explicit [`TextDirection`].
8352#[derive(Debug)]
8353pub struct PositionedDirectional {
8354    pub key: Option<KeyRef>,
8355    /// The distance that the child's leading edge is inset from the leading edge
8356    /// of the stack.
8357    ///
8358    /// Only two out of the three horizontal values ([`start`](Self::start),
8359    /// [`end`](Self::end), [`width`](Self::width)) can be set. The third must be `None`.
8360    pub start: Option<f64>,
8361    /// The distance that the child's top edge is inset from the top of the stack.
8362    ///
8363    /// Only two out of the three vertical values ([`top`](Self::top),
8364    /// [`bottom`](Self::bottom), [`height`](Self::height)) can be set. The third must be
8365    /// `None`.
8366    pub top: Option<f64>,
8367    /// The distance that the child's trailing edge is inset from the trailing
8368    /// edge of the stack.
8369    ///
8370    /// Only two out of the three horizontal values ([`start`](Self::start),
8371    /// [`end`](Self::end), [`width`](Self::width)) can be set. The third must be `None`.
8372    pub end: Option<f64>,
8373    /// The distance that the child's bottom edge is inset from the bottom of the stack.
8374    ///
8375    /// Only two out of the three vertical values ([`top`](Self::top),
8376    /// [`bottom`](Self::bottom), [`height`](Self::height)) can be set. The third must be
8377    /// `None`.
8378    pub bottom: Option<f64>,
8379    /// The child's width.
8380    ///
8381    /// Only two out of the three horizontal values ([`start`](Self::start),
8382    /// [`end`](Self::end), [`width`](Self::width)) can be set. The third must be `None`.
8383    pub width: Option<f64>,
8384    /// The child's height.
8385    ///
8386    /// Only two out of the three vertical values ([`top`](Self::top),
8387    /// [`bottom`](Self::bottom), [`height`](Self::height)) can be set. The third must be
8388    /// `None`.
8389    pub height: Option<f64>,
8390    /// The widget below this widget in the tree.
8391    pub child: WidgetRef,
8392}
8393
8394impl PositionedDirectional {
8395    /// Creates a widget that controls where a child of a [`Stack`] is positioned; Dart's
8396    /// optional named arguments are the setters.
8397    #[cfg_attr(debug_assertions, track_caller)]
8398    pub fn new<K>(child: impl IntoWidget<K>) -> PositionedDirectional {
8399        PositionedDirectional {
8400            key: None,
8401            start: None,
8402            top: None,
8403            end: None,
8404            bottom: None,
8405            width: None,
8406            height: None,
8407            child: child.into_widget(),
8408        }
8409    }
8410
8411    /// Dart `PositionedDirectional(key:)`.
8412    pub fn key(mut self, key: KeyRef) -> PositionedDirectional {
8413        self.key = Some(key);
8414        self
8415    }
8416
8417    /// Dart `PositionedDirectional(start:)`.
8418    pub fn start(mut self, start: f64) -> PositionedDirectional {
8419        self.start = Some(start);
8420        self
8421    }
8422
8423    /// Dart `PositionedDirectional(top:)`.
8424    pub fn top(mut self, top: f64) -> PositionedDirectional {
8425        self.top = Some(top);
8426        self
8427    }
8428
8429    /// Dart `PositionedDirectional(end:)`.
8430    pub fn end(mut self, end: f64) -> PositionedDirectional {
8431        self.end = Some(end);
8432        self
8433    }
8434
8435    /// Dart `PositionedDirectional(bottom:)`.
8436    pub fn bottom(mut self, bottom: f64) -> PositionedDirectional {
8437        self.bottom = Some(bottom);
8438        self
8439    }
8440
8441    /// Dart `PositionedDirectional(width:)`.
8442    pub fn width(mut self, width: f64) -> PositionedDirectional {
8443        self.width = Some(width);
8444        self
8445    }
8446
8447    /// Dart `PositionedDirectional(height:)`.
8448    pub fn height(mut self, height: f64) -> PositionedDirectional {
8449        self.height = Some(height);
8450        self
8451    }
8452}
8453
8454impl StatelessWidget for PositionedDirectional {
8455    fn key(&self) -> Option<&KeyRef> {
8456        self.key.as_ref()
8457    }
8458
8459    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
8460        let mut positioned = Positioned::directional(
8461            Directionality::of(app, context),
8462            self.start,
8463            self.end,
8464            self.child.clone(),
8465        );
8466        // Through the setters, which run `Positioned`'s two-of-three asserts.
8467        if let Some(top) = self.top {
8468            positioned = positioned.top(top);
8469        }
8470        if let Some(bottom) = self.bottom {
8471            positioned = positioned.bottom(bottom);
8472        }
8473        if let Some(width) = self.width {
8474            positioned = positioned.width(width);
8475        }
8476        if let Some(height) = self.height {
8477            positioned = positioned.height(height);
8478        }
8479        positioned.into_widget()
8480    }
8481}
8482
8483/// A widget that arranges its children sequentially along a given axis, forcing
8484/// them to the dimension of the parent in the other axis.
8485///
8486/// This widget is rarely used directly. Instead, consider using `ListView`,
8487/// which combines a similar layout algorithm with scrolling behavior, or
8488/// [`Column`], which gives you more flexible control over the layout of a
8489/// vertical set of boxes.
8490///
8491/// See also:
8492///
8493///  * `RenderListBody`, which implements this layout algorithm and the
8494///    documentation for which describes some of its subtleties.
8495///  * `SingleChildScrollView`, which is sometimes used with [`ListBody`] to
8496///    make the contents scrollable.
8497///  * [`Column`] and [`Row`], which implement a more elaborate version of
8498///    this layout algorithm (at the cost of being slightly less efficient).
8499///  * `ListView`, which implements an efficient scrolling version of this
8500///    layout algorithm.
8501#[derive(Debug)]
8502pub struct ListBody {
8503    pub key: Option<KeyRef>,
8504    /// The direction to use as the main axis.
8505    pub main_axis: Axis,
8506    /// Whether the list body positions children in the reading direction.
8507    ///
8508    /// For example, if the reading direction is left-to-right and
8509    /// [`main_axis`](Self::main_axis) is [`Axis::Horizontal`], then the list body positions
8510    /// children from left to right when [`reverse`](Self::reverse) is false and from right to
8511    /// left when [`reverse`](Self::reverse) is true.
8512    ///
8513    /// Similarly, if [`main_axis`](Self::main_axis) is [`Axis::Vertical`], then the list body
8514    /// positions from top to bottom when [`reverse`](Self::reverse) is false and from bottom
8515    /// to top when [`reverse`](Self::reverse) is true.
8516    ///
8517    /// Defaults to false.
8518    pub reverse: bool,
8519    pub children: Vec<WidgetRef>,
8520}
8521
8522impl ListBody {
8523    /// Creates a layout widget that arranges its children sequentially along a given axis;
8524    /// Dart's optional named arguments are the setters.
8525    ///
8526    /// By default, the [`main_axis`](Self::main_axis) is [`Axis::Vertical`].
8527    pub fn new() -> ListBody {
8528        ListBody {
8529            key: None,
8530            main_axis: Axis::Vertical,
8531            reverse: false,
8532            children: Vec::new(),
8533        }
8534    }
8535
8536    /// Dart `ListBody(key:)`.
8537    pub fn key(mut self, key: KeyRef) -> ListBody {
8538        self.key = Some(key);
8539        self
8540    }
8541
8542    /// Dart `ListBody(mainAxis:)`.
8543    pub fn main_axis(mut self, main_axis: Axis) -> ListBody {
8544        self.main_axis = main_axis;
8545        self
8546    }
8547
8548    /// Dart `ListBody(reverse:)`.
8549    pub fn reverse(mut self, reverse: bool) -> ListBody {
8550        self.reverse = reverse;
8551        self
8552    }
8553
8554    /// Dart `ListBody(children:)`.
8555    pub fn children(mut self, children: Vec<WidgetRef>) -> ListBody {
8556        self.children = children;
8557        self
8558    }
8559
8560    fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
8561        get_axis_direction_from_axis_reverse_and_directionality(
8562            app,
8563            context,
8564            self.main_axis,
8565            self.reverse,
8566        )
8567    }
8568}
8569
8570impl Default for ListBody {
8571    fn default() -> ListBody {
8572        ListBody::new()
8573    }
8574}
8575
8576impl RenderObjectWidget for ListBody {
8577    type RenderObject = RenderListBody;
8578
8579    fn key(&self) -> Option<&KeyRef> {
8580        self.key.as_ref()
8581    }
8582
8583    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
8584        let axis_direction = self.get_direction(app, context);
8585        RenderListBody::new(app, axis_direction).as_object()
8586    }
8587
8588    fn update_render_object(
8589        &self,
8590        app: &mut App,
8591        context: BuildContext,
8592        render_object: RenderHandle<RenderListBody>,
8593    ) {
8594        let axis_direction = self.get_direction(app, context);
8595        render_object.set_axis_direction(app, axis_direction);
8596    }
8597}
8598
8599impl MultiChildRenderObjectWidget for ListBody {
8600    fn children(&self) -> &[WidgetRef] {
8601        &self.children
8602    }
8603}
8604
8605/// A widget that displays its children in a one-dimensional array.
8606///
8607/// The [`Flex`] widget allows you to control the axis along which the children are placed
8608/// (horizontal or vertical). This is referred to as the _main axis_. If you know the main axis
8609/// in advance, then consider using a [`Row`] (if it's horizontal) or [`Column`] (if it's
8610/// vertical) instead, because that will be less verbose.
8611///
8612/// To cause a child to expand to fill the available space in the [`direction`](Self::direction)
8613/// of this widget's main axis, wrap the child in an [`Expanded`] widget.
8614///
8615/// The [`Flex`] widget does not scroll (and in general it is considered an error to have more
8616/// children in a [`Flex`] than will fit in the available room). If you have some widgets and
8617/// want them to be able to scroll if there is insufficient room, consider using a `ListView`.
8618///
8619/// If you only have one child, then rather than using [`Flex`], [`Row`] or [`Column`], consider
8620/// using [`Align`] or [`Center`] to position the child.
8621///
8622/// ## Layout algorithm
8623///
8624/// _This section describes how a [`Flex`] is rendered by the framework._
8625///
8626/// Layout for a [`Flex`] proceeds in six steps:
8627///
8628/// 1. Layout each child with a `None` or zero flex factor with unbounded main axis constraints
8629///    and the incoming cross axis constraints. If the [`cross_axis_alignment`](Self::cross_axis_alignment)
8630///    is `CrossAxisAlignment::Stretch`, instead use tight cross axis constraints that match the
8631///    incoming max extent in the cross axis.
8632/// 2. Divide the remaining main axis space among the children with non-zero flex factors
8633///    according to their flex factor.
8634/// 3. Layout each of the remaining children with the same cross axis constraints as in step 1,
8635///    but instead of using unbounded main axis constraints, use max axis constraints based on
8636///    the amount of space allocated in step 2.
8637/// 4. The width of the [`Flex`] is determined by the [`main_axis_size`](Self::main_axis_size)
8638///    property.
8639/// 5. Determine the position for each child according to the
8640///    [`main_axis_alignment`](Self::main_axis_alignment) and the
8641///    [`cross_axis_alignment`](Self::cross_axis_alignment).
8642///
8643/// See also:
8644///
8645///  * [`Row`], for a version of this widget that is always horizontal.
8646///  * [`Column`], for a version of this widget that is always vertical.
8647///  * [`Expanded`], to indicate children that should take all the remaining room.
8648///  * [`Flexible`], to indicate children that should share the remaining room.
8649///  * [`Spacer`], a widget that takes up space proportional to its flex value.
8650#[derive(Debug)]
8651pub struct Flex {
8652    pub key: Option<KeyRef>,
8653    /// The direction to use as the main axis.
8654    ///
8655    /// If you know the axis in advance, then consider using a [`Row`] (if it's horizontal) or
8656    /// [`Column`] (if it's vertical) instead of a [`Flex`], since that will be less verbose.
8657    pub direction: Axis,
8658    /// How the children should be placed along the main axis.
8659    ///
8660    /// For example, [`MainAxisAlignment::Start`], the default, places the children at the start
8661    /// (i.e., the left for a [`Row`] or the top for a [`Column`]) of the main axis.
8662    pub main_axis_alignment: MainAxisAlignment,
8663    /// How much space should be occupied in the main axis.
8664    ///
8665    /// After allocating space to children, there might be some remaining free space. This value
8666    /// controls whether to maximize or minimize the amount of free space, subject to the
8667    /// incoming layout constraints.
8668    pub main_axis_size: MainAxisSize,
8669    /// How the children should be placed along the cross axis.
8670    ///
8671    /// For example, [`CrossAxisAlignment::Center`], the default, centers the children in the
8672    /// cross axis (e.g., horizontally for a [`Column`]).
8673    pub cross_axis_alignment: CrossAxisAlignment,
8674    /// Determines the order to lay children out horizontally and how to interpret `start` and
8675    /// `end` in the horizontal direction.
8676    ///
8677    /// Defaults to the ambient [`Directionality`].
8678    ///
8679    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the order in
8680    /// which the children are positioned (left-to-right or right-to-left), and the meaning of
8681    /// the [`main_axis_alignment`](Self::main_axis_alignment) property's
8682    /// [`MainAxisAlignment::Start`] and [`MainAxisAlignment::End`] values.
8683    ///
8684    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls the meaning of
8685    /// the [`cross_axis_alignment`](Self::cross_axis_alignment) property's
8686    /// [`CrossAxisAlignment::Start`] and [`CrossAxisAlignment::End`] values.
8687    pub text_direction: Option<TextDirection>,
8688    /// Determines the order to lay children out vertically and how to interpret `start` and
8689    /// `end` in the vertical direction.
8690    ///
8691    /// Defaults to [`VerticalDirection::Down`].
8692    pub vertical_direction: VerticalDirection,
8693    /// If aligning items according to their baseline, which baseline to use.
8694    ///
8695    /// This must be set if using baseline alignment. There is no default because there is no
8696    /// way for the framework to know the correct baseline _a priori_.
8697    pub text_baseline: Option<TextBaseline>,
8698    /// Defaults to [`Clip::None`].
8699    pub clip_behavior: Clip,
8700    /// How much space to place between children in the main axis.
8701    pub spacing: f64,
8702    pub children: Vec<WidgetRef>,
8703}
8704
8705impl Flex {
8706    /// Creates a flex layout; Dart's optional named arguments are the setters.
8707    ///
8708    /// The [`direction`](Self::direction) is required.
8709    ///
8710    /// The [`text_direction`](Self::text_direction) defaults to the ambient [`Directionality`],
8711    /// if any. If there is no ambient directionality, and a text direction is going to be
8712    /// necessary to decide which direction to lay the children in or to disambiguate `start` or
8713    /// `end` values for the main or cross axis directions, the
8714    /// [`text_direction`](Self::text_direction) must not be `None`.
8715    pub fn new(direction: Axis) -> Flex {
8716        let configuration = FlexConfiguration::new(direction);
8717        Flex {
8718            key: None,
8719            direction: configuration.direction,
8720            main_axis_alignment: configuration.main_axis_alignment,
8721            main_axis_size: configuration.main_axis_size,
8722            cross_axis_alignment: configuration.cross_axis_alignment,
8723            text_direction: configuration.text_direction,
8724            vertical_direction: configuration.vertical_direction,
8725            text_baseline: configuration.text_baseline,
8726            clip_behavior: configuration.clip_behavior,
8727            spacing: configuration.spacing,
8728            children: Vec::new(),
8729        }
8730    }
8731
8732    /// Dart `Flex(key:)`.
8733    pub fn key(mut self, key: KeyRef) -> Flex {
8734        self.key = Some(key);
8735        self
8736    }
8737
8738    /// Dart `Flex(mainAxisAlignment:)`.
8739    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> Flex {
8740        self.main_axis_alignment = main_axis_alignment;
8741        self
8742    }
8743
8744    /// Dart `Flex(mainAxisSize:)`.
8745    pub fn main_axis_size(mut self, main_axis_size: MainAxisSize) -> Flex {
8746        self.main_axis_size = main_axis_size;
8747        self
8748    }
8749
8750    /// Dart `Flex(crossAxisAlignment:)`.
8751    pub fn cross_axis_alignment(mut self, cross_axis_alignment: CrossAxisAlignment) -> Flex {
8752        self.cross_axis_alignment = cross_axis_alignment;
8753        self
8754    }
8755
8756    /// Dart `Flex(textDirection:)`.
8757    pub fn text_direction(mut self, text_direction: TextDirection) -> Flex {
8758        self.text_direction = Some(text_direction);
8759        self
8760    }
8761
8762    /// Dart `Flex(verticalDirection:)`.
8763    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> Flex {
8764        self.vertical_direction = vertical_direction;
8765        self
8766    }
8767
8768    /// Dart `Flex(textBaseline:)`.
8769    pub fn text_baseline(mut self, text_baseline: TextBaseline) -> Flex {
8770        self.text_baseline = Some(text_baseline);
8771        self
8772    }
8773
8774    /// Dart `Flex(clipBehavior:)`.
8775    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Flex {
8776        self.clip_behavior = clip_behavior;
8777        self
8778    }
8779
8780    /// Dart `Flex(spacing:)`.
8781    pub fn spacing(mut self, spacing: f64) -> Flex {
8782        self.spacing = spacing;
8783        self
8784    }
8785
8786    /// Dart `Flex(children:)`.
8787    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> Flex {
8788        self.children = children.into_iter().collect();
8789        self
8790    }
8791
8792    /// The value to pass to `RenderFlex::set_text_direction`.
8793    ///
8794    /// This value is derived from the [`text_direction`](Self::text_direction) property and the
8795    /// ambient [`Directionality`]. The value is `None` if there is no need to specify the text
8796    /// direction. In practice there's always a need to specify the direction except for
8797    /// vertical flexes (e.g. [`Column`]s) whose
8798    /// [`cross_axis_alignment`](Self::cross_axis_alignment) is not dependent on the text
8799    /// direction (not `start` or `end`). In particular, a [`Row`] always needs a text direction
8800    /// because the text direction controls its layout order. (For [`Column`]s, the layout order
8801    /// is controlled by [`vertical_direction`](Self::vertical_direction), which is always
8802    /// specified as it does not depend on an inherited widget and defaults to
8803    /// [`VerticalDirection::Down`].)
8804    pub fn get_effective_text_direction(
8805        &self,
8806        app: &mut App,
8807        context: BuildContext,
8808    ) -> Option<TextDirection> {
8809        self.configuration()
8810            .get_effective_text_direction(app, context)
8811    }
8812
8813    fn configuration(&self) -> FlexConfiguration {
8814        FlexConfiguration {
8815            direction: self.direction,
8816            main_axis_alignment: self.main_axis_alignment,
8817            main_axis_size: self.main_axis_size,
8818            cross_axis_alignment: self.cross_axis_alignment,
8819            text_direction: self.text_direction,
8820            vertical_direction: self.vertical_direction,
8821            text_baseline: self.text_baseline,
8822            clip_behavior: self.clip_behavior,
8823            spacing: self.spacing,
8824        }
8825    }
8826}
8827
8828impl RenderObjectWidget for Flex {
8829    type RenderObject = RenderFlex;
8830
8831    fn key(&self) -> Option<&KeyRef> {
8832        self.key.as_ref()
8833    }
8834
8835    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
8836        self.configuration().debug_fill_properties(properties);
8837    }
8838
8839    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
8840        self.configuration().create_render_object(app, context)
8841    }
8842
8843    fn update_render_object(
8844        &self,
8845        app: &mut App,
8846        context: BuildContext,
8847        render_object: RenderHandle<RenderFlex>,
8848    ) {
8849        self.configuration().push(app, context, render_object);
8850    }
8851}
8852
8853impl MultiChildRenderObjectWidget for Flex {
8854    fn children(&self) -> &[WidgetRef] {
8855        &self.children
8856    }
8857}
8858
8859/// A widget that displays its children in a horizontal array.
8860///
8861/// To cause a child to expand to fill the available horizontal space, wrap the child in an
8862/// [`Expanded`] widget.
8863///
8864/// The [`Row`] widget does not scroll (and in general it is considered an error to have more
8865/// children in a [`Row`] than will fit in the available room). If you have a line of widgets and
8866/// want them to be able to scroll if there is insufficient room, consider using a `ListView`.
8867///
8868/// For a vertical variant, see [`Column`].
8869///
8870/// If you only have one child, then consider using [`Align`] or [`Center`] to position the
8871/// child.
8872///
8873/// See also:
8874///
8875///  * [`Flexible`], to indicate children that should share the remaining room.
8876///  * [`Expanded`], to indicate children that should take all the remaining room.
8877///  * [`Spacer`], a widget that takes up space proportional to its flex value.
8878///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
8879///
8880/// Dart's `class Row extends Flex`: a distinct widget type whose behaviour is [`Flex`]'s with
8881/// the direction fixed at [`Axis::Horizontal`].
8882#[derive(Debug)]
8883pub struct Row {
8884    pub key: Option<KeyRef>,
8885    /// See [`Flex::main_axis_alignment`].
8886    pub main_axis_alignment: MainAxisAlignment,
8887    /// See [`Flex::main_axis_size`].
8888    pub main_axis_size: MainAxisSize,
8889    /// See [`Flex::cross_axis_alignment`].
8890    pub cross_axis_alignment: CrossAxisAlignment,
8891    /// See [`Flex::text_direction`].
8892    pub text_direction: Option<TextDirection>,
8893    /// See [`Flex::vertical_direction`].
8894    pub vertical_direction: VerticalDirection,
8895    /// See [`Flex::text_baseline`].
8896    pub text_baseline: Option<TextBaseline>,
8897    /// See [`Flex::spacing`].
8898    pub spacing: f64,
8899    pub children: Vec<WidgetRef>,
8900}
8901
8902impl Row {
8903    /// Creates a horizontal array of children; Dart's named arguments are the setters.
8904    pub fn new() -> Row {
8905        Row::default()
8906    }
8907
8908    /// Dart `Row(key:)`.
8909    pub fn key(mut self, key: KeyRef) -> Row {
8910        self.key = Some(key);
8911        self
8912    }
8913
8914    /// Dart `Row(mainAxisAlignment:)`.
8915    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> Row {
8916        self.main_axis_alignment = main_axis_alignment;
8917        self
8918    }
8919
8920    /// Dart `Row(mainAxisSize:)`.
8921    pub fn main_axis_size(mut self, main_axis_size: MainAxisSize) -> Row {
8922        self.main_axis_size = main_axis_size;
8923        self
8924    }
8925
8926    /// Dart `Row(crossAxisAlignment:)`.
8927    pub fn cross_axis_alignment(mut self, cross_axis_alignment: CrossAxisAlignment) -> Row {
8928        self.cross_axis_alignment = cross_axis_alignment;
8929        self
8930    }
8931
8932    /// Dart `Row(textDirection:)`.
8933    pub fn text_direction(mut self, text_direction: TextDirection) -> Row {
8934        self.text_direction = Some(text_direction);
8935        self
8936    }
8937
8938    /// Dart `Row(verticalDirection:)`.
8939    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> Row {
8940        self.vertical_direction = vertical_direction;
8941        self
8942    }
8943
8944    /// Dart `Row(textBaseline:)`.
8945    pub fn text_baseline(mut self, text_baseline: TextBaseline) -> Row {
8946        self.text_baseline = Some(text_baseline);
8947        self
8948    }
8949
8950    /// Dart `Row(spacing:)`.
8951    pub fn spacing(mut self, spacing: f64) -> Row {
8952        self.spacing = spacing;
8953        self
8954    }
8955
8956    /// Dart `Row(children:)`.
8957    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> Row {
8958        self.children = children.into_iter().collect();
8959        self
8960    }
8961
8962    /// The direction to use as the main axis: always [`Axis::Horizontal`] (the inherited
8963    /// [`Flex::direction`]).
8964    pub fn direction(&self) -> Axis {
8965        Axis::Horizontal
8966    }
8967
8968    /// See [`Flex::get_effective_text_direction`].
8969    pub fn get_effective_text_direction(
8970        &self,
8971        app: &mut App,
8972        context: BuildContext,
8973    ) -> Option<TextDirection> {
8974        self.configuration()
8975            .get_effective_text_direction(app, context)
8976    }
8977
8978    fn configuration(&self) -> FlexConfiguration {
8979        FlexConfiguration {
8980            direction: self.direction(),
8981            main_axis_alignment: self.main_axis_alignment,
8982            main_axis_size: self.main_axis_size,
8983            cross_axis_alignment: self.cross_axis_alignment,
8984            text_direction: self.text_direction,
8985            vertical_direction: self.vertical_direction,
8986            text_baseline: self.text_baseline,
8987            spacing: self.spacing,
8988            ..FlexConfiguration::new(self.direction())
8989        }
8990    }
8991}
8992
8993impl Default for Row {
8994    fn default() -> Row {
8995        let configuration = FlexConfiguration::new(Axis::Horizontal);
8996        Row {
8997            key: None,
8998            main_axis_alignment: configuration.main_axis_alignment,
8999            main_axis_size: configuration.main_axis_size,
9000            cross_axis_alignment: configuration.cross_axis_alignment,
9001            text_direction: configuration.text_direction,
9002            vertical_direction: configuration.vertical_direction,
9003            text_baseline: configuration.text_baseline,
9004            spacing: configuration.spacing,
9005            children: Vec::new(),
9006        }
9007    }
9008}
9009
9010impl RenderObjectWidget for Row {
9011    type RenderObject = RenderFlex;
9012
9013    fn key(&self) -> Option<&KeyRef> {
9014        self.key.as_ref()
9015    }
9016
9017    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
9018        self.configuration().debug_fill_properties(properties);
9019    }
9020
9021    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
9022        self.configuration().create_render_object(app, context)
9023    }
9024
9025    fn update_render_object(
9026        &self,
9027        app: &mut App,
9028        context: BuildContext,
9029        render_object: RenderHandle<RenderFlex>,
9030    ) {
9031        self.configuration().push(app, context, render_object);
9032    }
9033}
9034
9035impl MultiChildRenderObjectWidget for Row {
9036    fn children(&self) -> &[WidgetRef] {
9037        &self.children
9038    }
9039}
9040
9041/// A widget that displays its children in a vertical array.
9042///
9043/// To cause a child to expand to fill the available vertical space, wrap the child in an
9044/// [`Expanded`] widget.
9045///
9046/// The [`Column`] widget does not scroll (and in general it is considered an error to have more
9047/// children in a [`Column`] than will fit in the available room). If you have a line of widgets
9048/// and want them to be able to scroll if there is insufficient room, consider using a
9049/// `ListView`.
9050///
9051/// For a horizontal variant, see [`Row`].
9052///
9053/// If you only have one child, then consider using [`Align`] or [`Center`] to position the
9054/// child.
9055///
9056/// See also:
9057///
9058///  * [`Flexible`], to indicate children that should share the remaining room.
9059///  * [`Expanded`], to indicate children that should take all the remaining room.
9060///  * [`Spacer`], a widget that takes up space proportional to its flex value.
9061///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
9062///
9063/// Dart's `class Column extends Flex`: a distinct widget type whose behaviour is [`Flex`]'s
9064/// with the direction fixed at [`Axis::Vertical`].
9065#[derive(Debug)]
9066pub struct Column {
9067    pub key: Option<KeyRef>,
9068    /// See [`Flex::main_axis_alignment`].
9069    pub main_axis_alignment: MainAxisAlignment,
9070    /// See [`Flex::main_axis_size`].
9071    pub main_axis_size: MainAxisSize,
9072    /// See [`Flex::cross_axis_alignment`].
9073    pub cross_axis_alignment: CrossAxisAlignment,
9074    /// See [`Flex::text_direction`].
9075    pub text_direction: Option<TextDirection>,
9076    /// See [`Flex::vertical_direction`].
9077    pub vertical_direction: VerticalDirection,
9078    /// See [`Flex::text_baseline`].
9079    pub text_baseline: Option<TextBaseline>,
9080    /// See [`Flex::spacing`].
9081    pub spacing: f64,
9082    pub children: Vec<WidgetRef>,
9083}
9084
9085impl Column {
9086    /// Creates a vertical array of children; Dart's named arguments are the setters.
9087    pub fn new() -> Column {
9088        Column::default()
9089    }
9090
9091    /// Dart `Column(key:)`.
9092    pub fn key(mut self, key: KeyRef) -> Column {
9093        self.key = Some(key);
9094        self
9095    }
9096
9097    /// Dart `Column(mainAxisAlignment:)`.
9098    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> Column {
9099        self.main_axis_alignment = main_axis_alignment;
9100        self
9101    }
9102
9103    /// Dart `Column(mainAxisSize:)`.
9104    pub fn main_axis_size(mut self, main_axis_size: MainAxisSize) -> Column {
9105        self.main_axis_size = main_axis_size;
9106        self
9107    }
9108
9109    /// Dart `Column(crossAxisAlignment:)`.
9110    pub fn cross_axis_alignment(mut self, cross_axis_alignment: CrossAxisAlignment) -> Column {
9111        self.cross_axis_alignment = cross_axis_alignment;
9112        self
9113    }
9114
9115    /// Dart `Column(textDirection:)`.
9116    pub fn text_direction(mut self, text_direction: TextDirection) -> Column {
9117        self.text_direction = Some(text_direction);
9118        self
9119    }
9120
9121    /// Dart `Column(verticalDirection:)`.
9122    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> Column {
9123        self.vertical_direction = vertical_direction;
9124        self
9125    }
9126
9127    /// Dart `Column(textBaseline:)`.
9128    pub fn text_baseline(mut self, text_baseline: TextBaseline) -> Column {
9129        self.text_baseline = Some(text_baseline);
9130        self
9131    }
9132
9133    /// Dart `Column(spacing:)`.
9134    pub fn spacing(mut self, spacing: f64) -> Column {
9135        self.spacing = spacing;
9136        self
9137    }
9138
9139    /// Dart `Column(children:)`.
9140    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> Column {
9141        self.children = children.into_iter().collect();
9142        self
9143    }
9144
9145    /// The direction to use as the main axis: always [`Axis::Vertical`] (the inherited
9146    /// [`Flex::direction`]).
9147    pub fn direction(&self) -> Axis {
9148        Axis::Vertical
9149    }
9150
9151    /// See [`Flex::get_effective_text_direction`].
9152    pub fn get_effective_text_direction(
9153        &self,
9154        app: &mut App,
9155        context: BuildContext,
9156    ) -> Option<TextDirection> {
9157        self.configuration()
9158            .get_effective_text_direction(app, context)
9159    }
9160
9161    fn configuration(&self) -> FlexConfiguration {
9162        FlexConfiguration {
9163            direction: self.direction(),
9164            main_axis_alignment: self.main_axis_alignment,
9165            main_axis_size: self.main_axis_size,
9166            cross_axis_alignment: self.cross_axis_alignment,
9167            text_direction: self.text_direction,
9168            vertical_direction: self.vertical_direction,
9169            text_baseline: self.text_baseline,
9170            spacing: self.spacing,
9171            ..FlexConfiguration::new(self.direction())
9172        }
9173    }
9174}
9175
9176impl Default for Column {
9177    fn default() -> Column {
9178        let configuration = FlexConfiguration::new(Axis::Vertical);
9179        Column {
9180            key: None,
9181            main_axis_alignment: configuration.main_axis_alignment,
9182            main_axis_size: configuration.main_axis_size,
9183            cross_axis_alignment: configuration.cross_axis_alignment,
9184            text_direction: configuration.text_direction,
9185            vertical_direction: configuration.vertical_direction,
9186            text_baseline: configuration.text_baseline,
9187            spacing: configuration.spacing,
9188            children: Vec::new(),
9189        }
9190    }
9191}
9192
9193impl RenderObjectWidget for Column {
9194    type RenderObject = RenderFlex;
9195
9196    fn key(&self) -> Option<&KeyRef> {
9197        self.key.as_ref()
9198    }
9199
9200    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
9201        self.configuration().debug_fill_properties(properties);
9202    }
9203
9204    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
9205        self.configuration().create_render_object(app, context)
9206    }
9207
9208    fn update_render_object(
9209        &self,
9210        app: &mut App,
9211        context: BuildContext,
9212        render_object: RenderHandle<RenderFlex>,
9213    ) {
9214        self.configuration().push(app, context, render_object);
9215    }
9216}
9217
9218impl MultiChildRenderObjectWidget for Column {
9219    fn children(&self) -> &[WidgetRef] {
9220        &self.children
9221    }
9222}
9223
9224/// A widget that controls how a child of a [`Row`], [`Column`], or [`Flex`] flexes.
9225///
9226/// Using a [`Flexible`] widget gives a child of a [`Row`], [`Column`], or [`Flex`] the
9227/// flexibility to expand to fill the available space in the main axis (e.g., horizontally for a
9228/// [`Row`] or vertically for a [`Column`]), but, unlike [`Expanded`], [`Flexible`] does not
9229/// require the child to fill the available space.
9230///
9231/// A [`Flexible`] widget must be a descendant of a [`Row`], [`Column`], or [`Flex`], and the
9232/// path from the [`Flexible`] widget to its enclosing [`Row`], [`Column`], or [`Flex`] must
9233/// contain only stateless or stateful widgets (not other kinds of widgets, like render object
9234/// widgets).
9235///
9236/// See also:
9237///
9238///  * [`Expanded`], which forces the child to expand to fill the available space.
9239///  * [`Spacer`], a widget that takes up space proportional to its flex value.
9240///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
9241#[derive(Debug)]
9242pub struct Flexible {
9243    pub key: Option<KeyRef>,
9244    /// The flex factor to use for this child.
9245    ///
9246    /// If zero, the child is inflexible and determines its own size. If non-zero, the amount of
9247    /// space the child can occupy in the main axis is determined by dividing the free space
9248    /// (after placing the inflexible children) according to the flex factors of the flexible
9249    /// children.
9250    pub flex: i32,
9251    /// How a flexible child is inscribed into the available space.
9252    ///
9253    /// If [`flex`](Self::flex) is non-zero, the [`fit`](Self::fit) determines whether the child
9254    /// fills the space the parent makes available during layout. If the fit is
9255    /// [`FlexFit::Tight`], the child is required to fill the available space. If the fit is
9256    /// [`FlexFit::Loose`], the child can be at most as large as the available space (but is
9257    /// allowed to be smaller).
9258    pub fit: FlexFit,
9259    pub child: WidgetRef,
9260}
9261
9262impl Flexible {
9263    /// Creates a widget that controls how a child of a [`Row`], [`Column`], or [`Flex`] flexes;
9264    /// Dart's optional named arguments are the setters.
9265    #[cfg_attr(debug_assertions, track_caller)]
9266    pub fn new<K>(child: impl IntoWidget<K>) -> Flexible {
9267        Flexible {
9268            key: None,
9269            flex: 1,
9270            fit: FlexFit::Loose,
9271            child: child.into_widget(),
9272        }
9273    }
9274
9275    /// Dart `Flexible(key:)`.
9276    pub fn key(mut self, key: KeyRef) -> Flexible {
9277        self.key = Some(key);
9278        self
9279    }
9280
9281    /// Dart `Flexible(flex:)`.
9282    pub fn flex(mut self, flex: i32) -> Flexible {
9283        self.flex = flex;
9284        self
9285    }
9286
9287    /// Dart `Flexible(fit:)`.
9288    pub fn fit(mut self, fit: FlexFit) -> Flexible {
9289        self.fit = fit;
9290        self
9291    }
9292
9293    /// Dart's `Flexible.debugFillProperties`, which [`Expanded`] inherits.
9294    fn fill_properties(flex: i32, properties: &mut DiagnosticPropertiesBuilder) {
9295        properties.add(IntProperty::new("flex", flex));
9296    }
9297
9298    /// `Flexible.applyParentData`'s body, shared with [`Expanded`].
9299    fn apply_flex_parent_data(
9300        app: &mut App,
9301        render_object: AnyRenderObject,
9302        flex: i32,
9303        fit: FlexFit,
9304    ) {
9305        debug_assert!(render_object.parent_data_is::<FlexParentData>(app));
9306        let parent_data = render_object.parent_data_of_mut::<FlexParentData>(app);
9307        let mut needs_layout = false;
9308
9309        if parent_data.flex != Some(flex) {
9310            parent_data.flex = Some(flex);
9311            needs_layout = true;
9312        }
9313
9314        if parent_data.fit != Some(fit) {
9315            parent_data.fit = Some(fit);
9316            needs_layout = true;
9317        }
9318
9319        if needs_layout && let Some(parent) = render_object.parent(app) {
9320            parent.mark_needs_layout(app);
9321        }
9322    }
9323}
9324
9325impl ParentDataWidget for Flexible {
9326    type ParentData = FlexParentData;
9327
9328    fn key(&self) -> Option<&KeyRef> {
9329        self.key.as_ref()
9330    }
9331
9332    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
9333        Flexible::fill_properties(self.flex, properties);
9334    }
9335
9336    fn child(&self) -> &WidgetRef {
9337        &self.child
9338    }
9339
9340    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
9341        Flexible::apply_flex_parent_data(app, render_object, self.flex, self.fit);
9342    }
9343}
9344
9345/// A widget that expands a child of a [`Row`], [`Column`], or [`Flex`] so that the child fills
9346/// the available space.
9347///
9348/// Using an [`Expanded`] widget makes a child of a [`Row`], [`Column`], or [`Flex`] expand to
9349/// fill the available space along the main axis (e.g., horizontally for a [`Row`] or vertically
9350/// for a [`Column`]). If multiple children are expanded, the available space is divided among
9351/// them according to the [`flex`](Self::flex) factor.
9352///
9353/// An [`Expanded`] widget must be a descendant of a [`Row`], [`Column`], or [`Flex`], and the
9354/// path from the [`Expanded`] widget to its enclosing [`Row`], [`Column`], or [`Flex`] must
9355/// contain only stateless or stateful widgets (not other kinds of widgets, like render object
9356/// widgets).
9357///
9358/// See also:
9359///
9360///  * [`Flexible`], which does not force the child to fill the available space.
9361///  * [`Spacer`], a widget that takes up space proportional to its flex value.
9362///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
9363///
9364/// Dart's `class Expanded extends Flexible`: a distinct widget type whose behaviour is
9365/// [`Flexible`]'s with the fit fixed at [`FlexFit::Tight`].
9366#[derive(Debug)]
9367pub struct Expanded {
9368    pub key: Option<KeyRef>,
9369    /// See [`Flexible::flex`].
9370    pub flex: i32,
9371    pub child: WidgetRef,
9372}
9373
9374impl Expanded {
9375    /// Creates a widget that expands a child of a [`Row`], [`Column`], or [`Flex`] so that the
9376    /// child fills the available space along the flex widget's main axis.
9377    #[cfg_attr(debug_assertions, track_caller)]
9378    pub fn new<K>(child: impl IntoWidget<K>) -> Expanded {
9379        Expanded {
9380            key: None,
9381            flex: 1,
9382            child: child.into_widget(),
9383        }
9384    }
9385
9386    /// Dart `Expanded(key:)`.
9387    pub fn key(mut self, key: KeyRef) -> Expanded {
9388        self.key = Some(key);
9389        self
9390    }
9391
9392    /// Dart `Expanded(flex:)`.
9393    pub fn flex(mut self, flex: i32) -> Expanded {
9394        self.flex = flex;
9395        self
9396    }
9397
9398    /// How the child is inscribed into the available space: always [`FlexFit::Tight`] (the
9399    /// inherited [`Flexible::fit`]).
9400    pub fn fit(&self) -> FlexFit {
9401        FlexFit::Tight
9402    }
9403}
9404
9405impl ParentDataWidget for Expanded {
9406    type ParentData = FlexParentData;
9407
9408    fn key(&self) -> Option<&KeyRef> {
9409        self.key.as_ref()
9410    }
9411
9412    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
9413        Flexible::fill_properties(self.flex, properties);
9414    }
9415
9416    fn child(&self) -> &WidgetRef {
9417        &self.child
9418    }
9419
9420    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
9421        Flexible::apply_flex_parent_data(app, render_object, self.flex, self.fit());
9422    }
9423}
9424
9425/// A widget that displays its children in multiple horizontal or vertical runs.
9426///
9427/// A [`Wrap`] lays out each child and attempts to place the child adjacent to the previous child
9428/// in the main axis, given by [`direction`](Self::direction), leaving
9429/// [`spacing`](Self::spacing) space in between. If there is not enough space to fit the child,
9430/// [`Wrap`] creates a new _run_ adjacent to the existing children in the cross axis.
9431///
9432/// After all the children have been allocated to runs, the children within the runs are
9433/// positioned according to the [`alignment`](Self::alignment) in the main axis and according
9434/// to the [`cross_axis_alignment`](Self::cross_axis_alignment) in the cross axis.
9435///
9436/// The runs themselves are then positioned in the cross axis according to the
9437/// [`run_spacing`](Self::run_spacing) and [`run_alignment`](Self::run_alignment).
9438///
9439/// See also:
9440///
9441///  * [`Row`], which places children in one line, and gives control over their alignment and
9442///    spacing.
9443///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
9444#[derive(Debug)]
9445pub struct Wrap {
9446    pub key: Option<KeyRef>,
9447    /// The direction to use as the main axis.
9448    ///
9449    /// For example, if [`direction`](Self::direction) is [`Axis::Horizontal`], the default, the
9450    /// children are placed adjacent to one another in a horizontal run until the available
9451    /// horizontal space is consumed, at which point a subsequent children are placed in a new
9452    /// run vertically adjacent to the previous run.
9453    pub direction: Axis,
9454    /// How the children within a run should be placed in the main axis.
9455    ///
9456    /// For example, if [`alignment`](Self::alignment) is [`WrapAlignment::Center`], the
9457    /// children in each run are grouped together in the center of their run in the main axis.
9458    ///
9459    /// Defaults to [`WrapAlignment::Start`].
9460    ///
9461    /// See also:
9462    ///
9463    ///  * [`run_alignment`](Self::run_alignment), which controls how the runs are placed
9464    ///    relative to each other in the cross axis.
9465    ///  * [`cross_axis_alignment`](Self::cross_axis_alignment), which controls how the children
9466    ///    within each run are placed relative to each other in the cross axis.
9467    pub alignment: WrapAlignment,
9468    /// How much space to place between children in a run in the main axis.
9469    ///
9470    /// For example, if [`spacing`](Self::spacing) is 10.0, the children will be spaced at least
9471    /// 10.0 logical pixels apart in the main axis.
9472    ///
9473    /// If there is additional free space in a run (e.g., because the wrap has a minimum size
9474    /// that is not filled or because some runs are longer than others), the additional free
9475    /// space will be allocated according to the [`alignment`](Self::alignment).
9476    ///
9477    /// Defaults to 0.0.
9478    pub spacing: f64,
9479    /// How the runs themselves should be placed in the cross axis.
9480    ///
9481    /// For example, if [`run_alignment`](Self::run_alignment) is [`WrapAlignment::Center`], the
9482    /// runs are grouped together in the center of the overall [`Wrap`] in the cross axis.
9483    ///
9484    /// Defaults to [`WrapAlignment::Start`].
9485    ///
9486    /// See also:
9487    ///
9488    ///  * [`alignment`](Self::alignment), which controls how the children within each run are
9489    ///    placed relative to each other in the main axis.
9490    ///  * [`cross_axis_alignment`](Self::cross_axis_alignment), which controls how the children
9491    ///    within each run are placed relative to each other in the cross axis.
9492    pub run_alignment: WrapAlignment,
9493    /// How much space to place between the runs themselves in the cross axis.
9494    ///
9495    /// For example, if [`run_spacing`](Self::run_spacing) is 10.0, the runs will be spaced at
9496    /// least 10.0 logical pixels apart in the cross axis.
9497    ///
9498    /// If there is additional free space in the overall [`Wrap`] (e.g., because the wrap has a
9499    /// minimum size that is not filled), the additional free space will be allocated according
9500    /// to the [`run_alignment`](Self::run_alignment).
9501    ///
9502    /// Defaults to 0.0.
9503    pub run_spacing: f64,
9504    /// How the children within a run should be aligned relative to each other in the cross
9505    /// axis.
9506    ///
9507    /// For example, if this is set to [`WrapCrossAlignment::End`], and the
9508    /// [`direction`](Self::direction) is [`Axis::Horizontal`], then the children within each
9509    /// run will have their bottom edges aligned to the bottom edge of the run.
9510    ///
9511    /// Defaults to [`WrapCrossAlignment::Start`].
9512    ///
9513    /// See also:
9514    ///
9515    ///  * [`alignment`](Self::alignment), which controls how the children within each run are
9516    ///    placed relative to each other in the main axis.
9517    ///  * [`run_alignment`](Self::run_alignment), which controls how the runs are placed
9518    ///    relative to each other in the cross axis.
9519    pub cross_axis_alignment: WrapCrossAlignment,
9520    /// Determines the order to lay children out horizontally and how to interpret `start` and
9521    /// `end` in the horizontal direction.
9522    ///
9523    /// Defaults to the ambient [`Directionality`].
9524    ///
9525    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls order in
9526    /// which the children are positioned (left-to-right or right-to-left), and the meaning of
9527    /// the [`alignment`](Self::alignment) property's [`WrapAlignment::Start`] and
9528    /// [`WrapAlignment::End`] values.
9529    ///
9530    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], and either the
9531    /// [`alignment`](Self::alignment) is either [`WrapAlignment::Start`] or
9532    /// [`WrapAlignment::End`], or there's more than one child, then the
9533    /// [`text_direction`](Self::text_direction) (or the ambient [`Directionality`]) must not be
9534    /// `None`.
9535    ///
9536    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls the order in
9537    /// which runs are positioned, the meaning of the [`run_alignment`](Self::run_alignment)
9538    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values, as well as the
9539    /// [`cross_axis_alignment`](Self::cross_axis_alignment) property's
9540    /// [`WrapCrossAlignment::Start`] and [`WrapCrossAlignment::End`] values.
9541    ///
9542    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], and either the
9543    /// [`run_alignment`](Self::run_alignment) is either [`WrapAlignment::Start`] or
9544    /// [`WrapAlignment::End`], the [`cross_axis_alignment`](Self::cross_axis_alignment) is
9545    /// either [`WrapCrossAlignment::Start`] or [`WrapCrossAlignment::End`], or there's more
9546    /// than one child, then the [`text_direction`](Self::text_direction) (or the ambient
9547    /// [`Directionality`]) must not be `None`.
9548    pub text_direction: Option<TextDirection>,
9549    /// Determines the order to lay children out vertically and how to interpret `start` and
9550    /// `end` in the vertical direction.
9551    ///
9552    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls which order
9553    /// children are painted in (down or up), the meaning of the [`alignment`](Self::alignment)
9554    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values.
9555    ///
9556    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the order
9557    /// in which runs are positioned, the meaning of the [`run_alignment`](Self::run_alignment)
9558    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values, as well as the
9559    /// [`cross_axis_alignment`](Self::cross_axis_alignment) property's
9560    /// [`WrapCrossAlignment::Start`] and [`WrapCrossAlignment::End`] values.
9561    pub vertical_direction: VerticalDirection,
9562    /// The content will be clipped (or not) according to this option.
9563    ///
9564    /// Defaults to [`Clip::None`].
9565    pub clip_behavior: Clip,
9566    pub children: Vec<WidgetRef>,
9567}
9568
9569impl Wrap {
9570    /// Creates a wrap layout; Dart's named arguments are the setters.
9571    ///
9572    /// By default, the wrap layout is horizontal and both the children and the runs are aligned
9573    /// to the start.
9574    ///
9575    /// The [`text_direction`](Self::text_direction) defaults to the ambient [`Directionality`],
9576    /// if any. If there is no ambient directionality, and a text direction is going to be
9577    /// necessary to decide which direction to lay the children in or to disambiguate `start` or
9578    /// `end` values for the main or cross axis directions, the
9579    /// [`text_direction`](Self::text_direction) must not be `None`.
9580    pub fn new() -> Wrap {
9581        Wrap::default()
9582    }
9583
9584    /// Dart `Wrap(key:)`.
9585    pub fn key(mut self, key: KeyRef) -> Wrap {
9586        self.key = Some(key);
9587        self
9588    }
9589
9590    /// Dart `Wrap(direction:)`.
9591    pub fn direction(mut self, direction: Axis) -> Wrap {
9592        self.direction = direction;
9593        self
9594    }
9595
9596    /// Dart `Wrap(alignment:)`.
9597    pub fn alignment(mut self, alignment: WrapAlignment) -> Wrap {
9598        self.alignment = alignment;
9599        self
9600    }
9601
9602    /// Dart `Wrap(spacing:)`.
9603    pub fn spacing(mut self, spacing: f64) -> Wrap {
9604        self.spacing = spacing;
9605        self
9606    }
9607
9608    /// Dart `Wrap(runAlignment:)`.
9609    pub fn run_alignment(mut self, run_alignment: WrapAlignment) -> Wrap {
9610        self.run_alignment = run_alignment;
9611        self
9612    }
9613
9614    /// Dart `Wrap(runSpacing:)`.
9615    pub fn run_spacing(mut self, run_spacing: f64) -> Wrap {
9616        self.run_spacing = run_spacing;
9617        self
9618    }
9619
9620    /// Dart `Wrap(crossAxisAlignment:)`.
9621    pub fn cross_axis_alignment(mut self, cross_axis_alignment: WrapCrossAlignment) -> Wrap {
9622        self.cross_axis_alignment = cross_axis_alignment;
9623        self
9624    }
9625
9626    /// Dart `Wrap(textDirection:)`.
9627    pub fn text_direction(mut self, text_direction: TextDirection) -> Wrap {
9628        self.text_direction = Some(text_direction);
9629        self
9630    }
9631
9632    /// Dart `Wrap(verticalDirection:)`.
9633    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> Wrap {
9634        self.vertical_direction = vertical_direction;
9635        self
9636    }
9637
9638    /// Dart `Wrap(clipBehavior:)`.
9639    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Wrap {
9640        self.clip_behavior = clip_behavior;
9641        self
9642    }
9643
9644    /// Dart `Wrap(children:)`.
9645    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> Wrap {
9646        self.children = children.into_iter().collect();
9647        self
9648    }
9649}
9650
9651impl Default for Wrap {
9652    fn default() -> Wrap {
9653        Wrap {
9654            key: None,
9655            direction: Axis::Horizontal,
9656            alignment: WrapAlignment::Start,
9657            spacing: 0.0,
9658            run_alignment: WrapAlignment::Start,
9659            run_spacing: 0.0,
9660            cross_axis_alignment: WrapCrossAlignment::Start,
9661            text_direction: None,
9662            vertical_direction: VerticalDirection::Down,
9663            clip_behavior: Clip::None,
9664            children: Vec::new(),
9665        }
9666    }
9667}
9668
9669impl RenderObjectWidget for Wrap {
9670    type RenderObject = RenderWrap;
9671
9672    fn key(&self) -> Option<&KeyRef> {
9673        self.key.as_ref()
9674    }
9675
9676    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
9677        properties.add(EnumProperty::new("direction", self.direction));
9678        properties.add(EnumProperty::new("alignment", self.alignment));
9679        properties.add(DoubleProperty::new("spacing", self.spacing));
9680        properties.add(EnumProperty::new("runAlignment", self.run_alignment));
9681        properties.add(DoubleProperty::new("runSpacing", self.run_spacing));
9682        properties.add(EnumProperty::new(
9683            "crossAxisAlignment",
9684            self.cross_axis_alignment,
9685        ));
9686        properties.add(
9687            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
9688                .default_value(None),
9689        );
9690        properties.add(
9691            EnumProperty::new("verticalDirection", self.vertical_direction)
9692                .default_value(Some(VerticalDirection::Down)),
9693        );
9694    }
9695
9696    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
9697        let render_object = RenderWrap::new(app);
9698        self.update_render_object(app, context, render_object);
9699        render_object.as_object()
9700    }
9701
9702    fn update_render_object(
9703        &self,
9704        app: &mut App,
9705        context: BuildContext,
9706        render_object: RenderHandle<RenderWrap>,
9707    ) {
9708        render_object.set_direction(app, self.direction);
9709        render_object.set_alignment(app, self.alignment);
9710        render_object.set_spacing(app, self.spacing);
9711        render_object.set_run_alignment(app, self.run_alignment);
9712        render_object.set_run_spacing(app, self.run_spacing);
9713        render_object.set_cross_axis_alignment(app, self.cross_axis_alignment);
9714        let text_direction = self
9715            .text_direction
9716            .or_else(|| Directionality::maybe_of(app, context));
9717        render_object.set_text_direction(app, text_direction);
9718        render_object.set_vertical_direction(app, self.vertical_direction);
9719        render_object.set_clip_behavior(app, self.clip_behavior);
9720    }
9721}
9722
9723impl MultiChildRenderObjectWidget for Wrap {
9724    fn children(&self) -> &[WidgetRef] {
9725        &self.children
9726    }
9727}
9728
9729/// Creates an adjustable, empty spacer that can be used to tune the spacing between widgets in
9730/// a [`Flex`] container, like [`Row`] or [`Column`].
9731///
9732/// The [`Spacer`] widget will take up any available space, so setting the
9733/// [`Flex::main_axis_alignment`] on a flex container that contains a [`Spacer`] to
9734/// [`MainAxisAlignment::SpaceAround`], [`MainAxisAlignment::SpaceBetween`], or
9735/// [`MainAxisAlignment::SpaceEvenly`] will not have any visible effect: the [`Spacer`] has
9736/// taken up all of the additional space, therefore there is none left to redistribute.
9737///
9738/// See also:
9739///
9740///  * [`Row`] and [`Column`], which are the most common containers to use a `Spacer` in.
9741///  * [`SizedBox`], to create a box with a specific size and an optional child.
9742///
9743/// Flutter's `widgets/spacer.dart`; it lives here until that file has a home of its own.
9744#[derive(Debug)]
9745pub struct Spacer {
9746    pub key: Option<KeyRef>,
9747    /// The flex factor to use in determining how much space to take up.
9748    ///
9749    /// The amount of space the [`Spacer`] can occupy in the main axis is determined by dividing
9750    /// the free space proportionately, after placing the inflexible children, according to the
9751    /// flex factors of the flexible children.
9752    ///
9753    /// Defaults to one.
9754    pub flex: i32,
9755}
9756
9757impl Spacer {
9758    /// Creates a flexible space to insert into a [`Flexible`] widget; Dart's named arguments
9759    /// are the setters.
9760    pub fn new() -> Spacer {
9761        Spacer::default()
9762    }
9763
9764    /// Dart `Spacer(key:)`.
9765    pub fn key(mut self, key: KeyRef) -> Spacer {
9766        self.key = Some(key);
9767        self
9768    }
9769
9770    /// Dart `Spacer(flex:)`.
9771    pub fn flex(mut self, flex: i32) -> Spacer {
9772        debug_assert!(flex > 0);
9773        self.flex = flex;
9774        self
9775    }
9776}
9777
9778impl Default for Spacer {
9779    fn default() -> Spacer {
9780        Spacer { key: None, flex: 1 }
9781    }
9782}
9783
9784impl StatelessWidget for Spacer {
9785    fn key(&self) -> Option<&KeyRef> {
9786        self.key.as_ref()
9787    }
9788
9789    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
9790        Expanded::new(SizedBox::shrink())
9791            .flex(self.flex)
9792            .into_widget()
9793    }
9794}
9795
9796/// A [`Stack`] that shows a single child from a list of children.
9797///
9798/// The displayed child is the one with the given [`index`](Self::index). The stack is always as
9799/// big as the largest child.
9800///
9801/// If the index is `None`, then nothing is displayed.
9802///
9803/// See also:
9804///
9805///  * [`Stack`], for more details about stacks.
9806///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
9807///
9808/// Flutter's `widgets/indexed_stack.dart`; it lives here until that file has a home of its own.
9809#[derive(Debug)]
9810pub struct IndexedStack {
9811    pub key: Option<KeyRef>,
9812    /// How to align the non-positioned and partially-positioned children in the stack.
9813    ///
9814    /// Defaults to `AlignmentGeometry::TOP_START`. See [`Stack::alignment`].
9815    pub alignment: AlignmentGeometry,
9816    /// The text direction with which to resolve [`alignment`](Self::alignment).
9817    ///
9818    /// Defaults to the ambient [`Directionality`].
9819    pub text_direction: Option<TextDirection>,
9820    /// Defaults to [`Clip::HardEdge`].
9821    pub clip_behavior: Clip,
9822    /// How to size the non-positioned children in the stack.
9823    ///
9824    /// Defaults to [`StackFit::Loose`]. See [`Stack::fit`].
9825    pub sizing: StackFit,
9826    /// The index of the child to show.
9827    ///
9828    /// If this is `None`, none of the children will be shown.
9829    pub index: Option<i32>,
9830    /// The child widgets of the stack.
9831    ///
9832    /// Only the child at index [`index`](Self::index) will be shown.
9833    pub children: Vec<WidgetRef>,
9834}
9835
9836impl IndexedStack {
9837    /// Creates a [`Stack`] widget that paints a single child; Dart's named arguments are the
9838    /// setters.
9839    pub fn new() -> IndexedStack {
9840        IndexedStack::default()
9841    }
9842
9843    /// Dart `IndexedStack(key:)`.
9844    pub fn key(mut self, key: KeyRef) -> IndexedStack {
9845        self.key = Some(key);
9846        self
9847    }
9848
9849    /// Dart `IndexedStack(alignment:)`.
9850    pub fn alignment(mut self, alignment: AlignmentGeometry) -> IndexedStack {
9851        self.alignment = alignment;
9852        self
9853    }
9854
9855    /// Dart `IndexedStack(textDirection:)`.
9856    pub fn text_direction(mut self, text_direction: TextDirection) -> IndexedStack {
9857        self.text_direction = Some(text_direction);
9858        self
9859    }
9860
9861    /// Dart `IndexedStack(clipBehavior:)`.
9862    pub fn clip_behavior(mut self, clip_behavior: Clip) -> IndexedStack {
9863        self.clip_behavior = clip_behavior;
9864        self
9865    }
9866
9867    /// Dart `IndexedStack(sizing:)`.
9868    pub fn sizing(mut self, sizing: StackFit) -> IndexedStack {
9869        self.sizing = sizing;
9870        self
9871    }
9872
9873    /// Dart `IndexedStack(index:)`; `None` shows no child, which the default (`Some(0)`) does
9874    /// not express.
9875    pub fn index(mut self, index: Option<i32>) -> IndexedStack {
9876        self.index = index;
9877        self
9878    }
9879
9880    /// Dart `IndexedStack(children:)`.
9881    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> IndexedStack {
9882        self.children = children.into_iter().collect();
9883        self
9884    }
9885}
9886
9887impl Default for IndexedStack {
9888    fn default() -> IndexedStack {
9889        IndexedStack {
9890            key: None,
9891            alignment: AlignmentGeometry::TOP_START,
9892            text_direction: None,
9893            clip_behavior: Clip::HardEdge,
9894            sizing: StackFit::Loose,
9895            index: Some(0),
9896            children: Vec::new(),
9897        }
9898    }
9899}
9900
9901impl StatelessWidget for IndexedStack {
9902    fn key(&self) -> Option<&KeyRef> {
9903        self.key.as_ref()
9904    }
9905
9906    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
9907        // Each child is wrapped with a visibility scope (so `Visibility.of` reports the child
9908        // as hidden when it is not the selected index) and with `ExcludeFocus` (so
9909        // non-selected children cannot receive focus). Both of these do not introduce any
9910        // render objects between the child and the enclosing `RenderIndexedStack`.
9911        //
9912        // This allows parent data widgets such as `Positioned` to correctly apply their
9913        // `StackParentData` to the `IndexedStack`'s render object.
9914        //
9915        // Painting, hit-testing, and semantics for non-selected children are already handled
9916        // by `RenderIndexedStack`, so no additional render-object wrappers are needed.
9917        let wrapped_children = self.children.iter().enumerate().map(|(i, child)| {
9918            let is_selected = Some(i as i32) == self.index;
9919            VisibilityScope {
9920                is_visible: is_selected,
9921                child: ExcludeFocus::new(child.clone())
9922                    .excluding(!is_selected)
9923                    .into_widget(),
9924            }
9925            .into_widget()
9926        });
9927        RawIndexedStack::new(self.sizing)
9928            .alignment(self.alignment)
9929            .index(self.index)
9930            .children(wrapped_children)
9931            .clip_behavior(self.clip_behavior)
9932            .with_text_direction(self.text_direction)
9933            .into_widget()
9934    }
9935}
9936
9937/// The render object widget that backs [`IndexedStack`].
9938///
9939/// Dart's `class _RawIndexedStack extends Stack`: a distinct widget type whose behaviour is
9940/// [`Stack`]'s over a `RenderIndexedStack`, with the fit taken from `sizing`.
9941#[derive(Debug)]
9942struct RawIndexedStack {
9943    key: Option<KeyRef>,
9944    /// See [`Stack::alignment`].
9945    alignment: AlignmentGeometry,
9946    /// See [`Stack::text_direction`].
9947    text_direction: Option<TextDirection>,
9948    /// See [`Stack::clip_behavior`].
9949    clip_behavior: Clip,
9950    /// See [`Stack::fit`]; Dart's `super(fit: sizing)`.
9951    fit: StackFit,
9952    /// The index of the child to show.
9953    index: Option<i32>,
9954    children: Vec<WidgetRef>,
9955}
9956
9957impl RawIndexedStack {
9958    fn new(sizing: StackFit) -> RawIndexedStack {
9959        let stack = Stack::new();
9960        RawIndexedStack {
9961            key: None,
9962            alignment: stack.alignment,
9963            text_direction: stack.text_direction,
9964            clip_behavior: stack.clip_behavior,
9965            fit: sizing,
9966            index: Some(0),
9967            children: Vec::new(),
9968        }
9969    }
9970
9971    fn alignment(mut self, alignment: AlignmentGeometry) -> RawIndexedStack {
9972        self.alignment = alignment;
9973        self
9974    }
9975
9976    fn with_text_direction(mut self, text_direction: Option<TextDirection>) -> RawIndexedStack {
9977        self.text_direction = text_direction;
9978        self
9979    }
9980
9981    fn clip_behavior(mut self, clip_behavior: Clip) -> RawIndexedStack {
9982        self.clip_behavior = clip_behavior;
9983        self
9984    }
9985
9986    fn index(mut self, index: Option<i32>) -> RawIndexedStack {
9987        self.index = index;
9988        self
9989    }
9990
9991    fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> RawIndexedStack {
9992        self.children = children.into_iter().collect();
9993        self
9994    }
9995
9996    /// The constructor assert: the index must be `None` or within the range of children.
9997    fn debug_check_index(&self) {
9998        debug_assert!(
9999            self.index.is_none_or(|index| {
10000                (index == 0 && self.children.is_empty())
10001                    || (index >= 0 && (index as usize) < self.children.len())
10002            }),
10003            "The index must be null or within the range of children."
10004        );
10005    }
10006}
10007
10008impl RenderObjectWidget for RawIndexedStack {
10009    type RenderObject = RenderIndexedStack;
10010
10011    fn key(&self) -> Option<&KeyRef> {
10012        self.key.as_ref()
10013    }
10014
10015    /// Dart's `_IndexedStackElement.debugVisitOnstageChildren`: if the index is null, no child
10016    /// is onstage; otherwise only the child at the selected index is.
10017    fn debug_visit_onstage_children(
10018        &self,
10019        _app: &App,
10020        children: &[crate::AnyElement],
10021        visitor: &mut dyn FnMut(crate::AnyElement),
10022    ) {
10023        if let Some(child) = self
10024            .index
10025            .and_then(|index| usize::try_from(index).ok())
10026            .and_then(|index| children.get(index))
10027        {
10028            visitor(*child);
10029        }
10030    }
10031
10032    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
10033        self.debug_check_index();
10034        let render_object = RenderIndexedStack::new(app);
10035        render_object.set_index(app, self.index);
10036        render_object.set_fit(app, self.fit);
10037        render_object.set_clip_behavior(app, self.clip_behavior);
10038        render_object.set_alignment(app, self.alignment);
10039        let text_direction = Stack::resolved_text_direction(self.text_direction, app, context);
10040        render_object.set_text_direction(app, text_direction);
10041        render_object.as_object()
10042    }
10043
10044    fn update_render_object(
10045        &self,
10046        app: &mut App,
10047        context: BuildContext,
10048        render_object: RenderHandle<RenderIndexedStack>,
10049    ) {
10050        self.debug_check_index();
10051        render_object.set_index(app, self.index);
10052        render_object.set_fit(app, self.fit);
10053        render_object.set_clip_behavior(app, self.clip_behavior);
10054        render_object.set_alignment(app, self.alignment);
10055        let text_direction = Stack::resolved_text_direction(self.text_direction, app, context);
10056        render_object.set_text_direction(app, text_direction);
10057    }
10058}
10059
10060impl MultiChildRenderObjectWidget for RawIndexedStack {
10061    fn children(&self) -> &[WidgetRef] {
10062        &self.children
10063    }
10064}
10065
10066/// Inherited widget that allows descendants to find their visibility status.
10067///
10068/// Used by [`Visibility`](crate::Visibility) and [`IndexedStack`] to propagate visibility
10069/// information to descendants (Dart's `_VisibilityScope`).
10070#[derive(Debug)]
10071pub(crate) struct VisibilityScope {
10072    pub(crate) is_visible: bool,
10073    pub(crate) child: WidgetRef,
10074}
10075
10076impl InheritedWidget for VisibilityScope {
10077    fn child(&self) -> &WidgetRef {
10078        &self.child
10079    }
10080
10081    fn update_should_notify(&self, old_widget: &VisibilityScope) -> bool {
10082        self.is_visible != old_widget.is_visible
10083    }
10084}
10085
10086#[cfg(test)]
10087mod tests {
10088    use std::any::Any;
10089    use std::cell::Cell;
10090    use std::rc::Rc;
10091
10092    use waft_embedder::{Color, Offset, Radius, Size};
10093    use waft_foundation::{App, AppCell, Handle};
10094    use waft_gestures::{HitTestEntry, HitTestResult, PointerDownEvent, PointerEvent};
10095    use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
10096    use waft_rendering::{
10097        AnyRenderBox, BoxHitTestEntry, BoxHitTestResult, BoxParentData, ContainerBoxParentData,
10098        ContainerRenderObjectMixin, ErasedRenderObject, RenderBox, RenderObject,
10099        RenderObjectWithChildMixin,
10100    };
10101    use waft_services::SystemMouseCursors;
10102
10103    use super::*;
10104    use crate::framework::{
10105        GlobalKey, IntoWidget, State, StateData, StatefulWidget, downcast_widget,
10106    };
10107    use crate::test_harness::{Harness, padding_under_root};
10108    use crate::testing::test_widgets;
10109
10110    /// The render object directly under the test root, typed.
10111    fn render_object_under_root<T: RenderObject>(harness: &Harness, app: &App) -> RenderHandle<T> {
10112        harness
10113            .render_root(app)
10114            .child(app)
10115            .expect("a child")
10116            .as_object()
10117            .downcast::<T>(app)
10118            .expect("the widget's render object")
10119    }
10120
10121    /// The offset a shifted box gave its child.
10122    fn child_offset<T: RenderObject + RenderObjectWithChildMixin>(
10123        parent: RenderHandle<T>,
10124        app: &App,
10125    ) -> Offset {
10126        parent
10127            .child(app)
10128            .expect("a child")
10129            .as_object()
10130            .parent_data_of::<BoxParentData>(app)
10131            .offset
10132    }
10133
10134    fn sized(width: f64, height: f64) -> WidgetRef {
10135        SizedBox {
10136            width: Some(width),
10137            height: Some(height),
10138            ..Default::default()
10139        }
10140        .into_widget()
10141    }
10142
10143    /// Reads `Directionality::of`, counting builds and recording what it saw.
10144    #[derive(Debug)]
10145    struct DirectionReader {
10146        builds: Rc<Cell<u32>>,
10147        seen: Rc<Cell<Option<TextDirection>>>,
10148    }
10149
10150    impl StatelessWidget for DirectionReader {
10151        fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
10152            self.builds.set(self.builds.get() + 1);
10153            self.seen.set(Some(Directionality::of(app, context)));
10154            sized(10.0, 10.0)
10155        }
10156    }
10157
10158    #[test]
10159    fn padding_insets_its_child_and_updates_in_place() {
10160        let cell = AppCell::new();
10161        let mut app = cell.borrow_mut();
10162        let padded = |inset: f64| {
10163            Padding {
10164                key: None,
10165                padding: EdgeInsetsGeometry::all(inset),
10166                child: Some(sized(10.0, 10.0)),
10167            }
10168            .into_widget()
10169        };
10170        let harness = Harness::mount(&mut app, padded(4.0));
10171        harness.pump(&mut app);
10172        let before = padding_under_root(&harness, &app);
10173        assert_eq!(before.size(&app), Size::new(18.0, 18.0));
10174        assert_eq!(
10175            before.text_direction(&app),
10176            None,
10177            "no Directionality ancestor"
10178        );
10179
10180        harness.set_child(&mut app, padded(6.0));
10181        harness.pump(&mut app);
10182        let after = padding_under_root(&harness, &app);
10183        assert_eq!(after, before, "the same RenderPadding is reconfigured");
10184        assert_eq!(after.padding(&app), EdgeInsetsGeometry::all(6.0));
10185        assert_eq!(after.size(&app), Size::new(22.0, 22.0));
10186    }
10187
10188    /// A `Padding` takes `EdgeInsets` or `EdgeInsetsDirectional` where Flutter takes an
10189    /// `EdgeInsetsGeometry`, without an `EdgeInsetsGeometry::from` at the call.
10190    #[test]
10191    fn padding_takes_either_kind_of_insets() {
10192        let cell = AppCell::new();
10193        let mut app = cell.borrow_mut();
10194        let harness = Harness::mount(
10195            &mut app,
10196            Padding::new(EdgeInsets::all(4.0))
10197                .child(sized(10.0, 10.0))
10198                .into_widget(),
10199        );
10200        harness.pump(&mut app);
10201        let padding = padding_under_root(&harness, &app);
10202        assert_eq!(padding.padding(&app).resolve(None), EdgeInsets::all(4.0));
10203
10204        harness.set_child(
10205            &mut app,
10206            Directionality::new(
10207                TextDirection::Ltr,
10208                Padding::new(EdgeInsetsDirectional::only(8.0, 0.0, 0.0, 0.0))
10209                    .child(sized(10.0, 10.0))
10210                    .into_widget(),
10211            )
10212            .into_widget(),
10213        );
10214        harness.pump(&mut app);
10215        let padding = padding_under_root(&harness, &app);
10216        assert_eq!(
10217            child_offset(padding, &app),
10218            Offset::new(8.0, 0.0),
10219            "the directional insets reach the widget"
10220        );
10221    }
10222
10223    #[test]
10224    fn padding_resolves_directional_insets_through_directionality() {
10225        let cell = AppCell::new();
10226        let mut app = cell.borrow_mut();
10227        let directional = |text_direction: TextDirection| {
10228            Directionality {
10229                key: None,
10230                text_direction,
10231                child: Padding {
10232                    key: None,
10233                    padding: EdgeInsetsGeometry::directional(8.0, 0.0, 0.0, 0.0),
10234                    child: Some(sized(10.0, 10.0)),
10235                }
10236                .into_widget(),
10237            }
10238            .into_widget()
10239        };
10240        let harness = Harness::mount(&mut app, directional(TextDirection::Rtl));
10241        harness.pump(&mut app);
10242        let padding = padding_under_root(&harness, &app);
10243        assert_eq!(padding.text_direction(&app), Some(TextDirection::Rtl));
10244        assert_eq!(
10245            child_offset(padding, &app),
10246            Offset::new(0.0, 0.0),
10247            "start is the right"
10248        );
10249
10250        harness.set_child(&mut app, directional(TextDirection::Ltr));
10251        harness.pump(&mut app);
10252        assert_eq!(padding.text_direction(&app), Some(TextDirection::Ltr));
10253        assert_eq!(
10254            child_offset(padding, &app),
10255            Offset::new(8.0, 0.0),
10256            "start is the left"
10257        );
10258    }
10259
10260    #[test]
10261    fn center_positions_its_child_in_the_middle() {
10262        let cell = AppCell::new();
10263        let mut app = cell.borrow_mut();
10264        let harness = Harness::mount(
10265            &mut app,
10266            Center {
10267                child: Some(sized(10.0, 10.0)),
10268                ..Default::default()
10269            }
10270            .into_widget(),
10271        );
10272        harness.pump(&mut app);
10273        let positioned = render_object_under_root::<RenderPositionedBox>(&harness, &app);
10274        assert_eq!(positioned.alignment(&app), AlignmentGeometry::CENTER);
10275        assert_eq!(
10276            positioned.size(&app),
10277            Size::new(300.0, 200.0),
10278            "fills the root"
10279        );
10280        assert_eq!(child_offset(positioned, &app), Offset::new(145.0, 95.0));
10281    }
10282
10283    #[test]
10284    fn align_positions_its_child_and_updates_in_place() {
10285        let cell = AppCell::new();
10286        let mut app = cell.borrow_mut();
10287        let aligned = |alignment: AlignmentGeometry, width_factor: Option<f64>| {
10288            Align {
10289                alignment,
10290                width_factor,
10291                child: Some(sized(10.0, 10.0)),
10292                ..Default::default()
10293            }
10294            .into_widget()
10295        };
10296        let harness = Harness::mount(&mut app, aligned(AlignmentGeometry::BOTTOM_RIGHT, None));
10297        harness.pump(&mut app);
10298        let positioned = render_object_under_root::<RenderPositionedBox>(&harness, &app);
10299        assert_eq!(child_offset(positioned, &app), Offset::new(290.0, 190.0));
10300
10301        harness.set_child(&mut app, aligned(AlignmentGeometry::TOP_LEFT, Some(2.0)));
10302        harness.pump(&mut app);
10303        let same = render_object_under_root::<RenderPositionedBox>(&harness, &app);
10304        assert_eq!(
10305            same, positioned,
10306            "the same RenderPositionedBox is reconfigured"
10307        );
10308        assert_eq!(
10309            positioned.size(&app),
10310            Size::new(20.0, 200.0),
10311            "twice the child's width"
10312        );
10313        assert_eq!(child_offset(positioned, &app), Offset::new(0.0, 0.0));
10314    }
10315
10316    #[test]
10317    fn sized_box_constrains_its_child() {
10318        let cell = AppCell::new();
10319        let mut app = cell.borrow_mut();
10320        let harness = Harness::mount(&mut app, sized(50.0, 20.0));
10321        harness.pump(&mut app);
10322        let constrained = render_object_under_root::<RenderConstrainedBox>(&harness, &app);
10323        assert_eq!(
10324            constrained.additional_constraints(&app),
10325            BoxConstraints::tight_for(Some(50.0), Some(20.0))
10326        );
10327        assert_eq!(constrained.size(&app), Size::new(50.0, 20.0));
10328
10329        harness.set_child(&mut app, SizedBox::expand().into_widget());
10330        harness.pump(&mut app);
10331        assert_eq!(
10332            constrained.size(&app),
10333            Size::new(300.0, 200.0),
10334            "as large as the root allows"
10335        );
10336
10337        harness.set_child(&mut app, SizedBox::shrink().into_widget());
10338        harness.pump(&mut app);
10339        assert_eq!(constrained.size(&app), Size::new(0.0, 0.0));
10340    }
10341
10342    #[test]
10343    fn sized_box_named_constructors_match_dart() {
10344        let square = SizedBox::square(Some(7.0));
10345        assert_eq!((square.width, square.height), (Some(7.0), Some(7.0)));
10346        let from_size = SizedBox::from_size(Some(Size::new(3.0, 4.0)));
10347        assert_eq!((from_size.width, from_size.height), (Some(3.0), Some(4.0)));
10348        let unspecified = SizedBox::from_size(None);
10349        assert_eq!((unspecified.width, unspecified.height), (None, None));
10350        assert!(format!("{:?}", SizedBox::expand()).starts_with("SizedBox.expand"));
10351        assert!(format!("{:?}", SizedBox::shrink()).starts_with("SizedBox.shrink"));
10352        assert!(format!("{square:?}").starts_with("SizedBox {"));
10353    }
10354
10355    #[test]
10356    fn constrained_box_imposes_its_constraints() {
10357        let cell = AppCell::new();
10358        let mut app = cell.borrow_mut();
10359        let harness = Harness::mount(
10360            &mut app,
10361            ConstrainedBox {
10362                key: None,
10363                constraints: BoxConstraints::new().min_width(120.0).min_height(30.0),
10364                child: Some(sized(10.0, 10.0)),
10365            }
10366            .into_widget(),
10367        );
10368        harness.pump(&mut app);
10369        let constrained = render_object_under_root::<RenderConstrainedBox>(&harness, &app);
10370        assert_eq!(constrained.size(&app), Size::new(120.0, 30.0));
10371    }
10372
10373    #[test]
10374    fn listener_receives_a_pointer_down_through_its_render_object() {
10375        let cell = AppCell::new();
10376        let mut app = cell.borrow_mut();
10377        let downs = Rc::new(Cell::new(0));
10378        let seen_at = Rc::new(Cell::new(Offset::ZERO));
10379        let harness = Harness::mount(
10380            &mut app,
10381            Listener {
10382                on_pointer_down: Some(Rc::new({
10383                    let downs = Rc::clone(&downs);
10384                    let seen_at = Rc::clone(&seen_at);
10385                    move |_app: &mut App, event: PointerDownEvent| {
10386                        downs.set(downs.get() + 1);
10387                        seen_at.set(event.position);
10388                    }
10389                })),
10390                behavior: HitTestBehavior::Opaque,
10391                child: Some(sized(10.0, 10.0)),
10392                ..Default::default()
10393            }
10394            .into_widget(),
10395        );
10396        harness.pump(&mut app);
10397        let listener = render_object_under_root::<RenderPointerListener>(&harness, &app);
10398        assert!(listener.on_pointer_down(&app).is_some());
10399        assert!(listener.on_pointer_up(&app).is_none());
10400
10401        let event = PointerEvent::Down(PointerDownEvent {
10402            position: Offset::new(3.0, 4.0),
10403            ..PointerDownEvent::default()
10404        });
10405        let entry = BoxHitTestEntry::new(listener.as_box(), Offset::new(3.0, 4.0));
10406        listener.as_box().handle_event(&mut app, &event, &entry);
10407        assert_eq!(downs.get(), 1);
10408        assert_eq!(seen_at.get(), Offset::new(3.0, 4.0));
10409
10410        harness.set_child(
10411            &mut app,
10412            Listener {
10413                child: Some(sized(10.0, 10.0)),
10414                ..Default::default()
10415            }
10416            .into_widget(),
10417        );
10418        harness.pump(&mut app);
10419        assert!(
10420            listener.on_pointer_down(&app).is_none(),
10421            "the callback is cleared in place"
10422        );
10423        listener.as_box().handle_event(&mut app, &event, &entry);
10424        assert_eq!(downs.get(), 1);
10425    }
10426
10427    #[test]
10428    fn mouse_region_forwards_its_configuration() {
10429        let cell = AppCell::new();
10430        let mut app = cell.borrow_mut();
10431        let harness = Harness::mount(
10432            &mut app,
10433            MouseRegion {
10434                on_enter: Some(Rc::new(|_app, _event| {})),
10435                cursor: Rc::new(SystemMouseCursors::CLICK),
10436                opaque: false,
10437                hit_test_behavior: Some(HitTestBehavior::Translucent),
10438                child: Some(sized(10.0, 10.0)),
10439                ..Default::default()
10440            }
10441            .into_widget(),
10442        );
10443        harness.pump(&mut app);
10444        let region = render_object_under_root::<RenderMouseRegion>(&harness, &app);
10445        assert!(region.on_enter(&app).is_some());
10446        assert!(region.on_hover(&app).is_none());
10447        assert!(!region.cursor(&app).is_defer());
10448        assert!(!region.opaque(&app));
10449        assert_eq!(
10450            region.hit_test_behavior(&app),
10451            Some(HitTestBehavior::Translucent)
10452        );
10453
10454        harness.set_child(
10455            &mut app,
10456            MouseRegion {
10457                child: Some(sized(10.0, 10.0)),
10458                ..Default::default()
10459            }
10460            .into_widget(),
10461        );
10462        harness.pump(&mut app);
10463        assert!(region.on_enter(&app).is_none());
10464        assert!(region.cursor(&app).is_defer());
10465        assert!(region.opaque(&app));
10466        assert_eq!(
10467            region.hit_test_behavior(&app),
10468            Some(HitTestBehavior::Opaque)
10469        );
10470    }
10471
10472    #[test]
10473    fn opacity_forwards_its_value() {
10474        let cell = AppCell::new();
10475        let mut app = cell.borrow_mut();
10476        let faded = |opacity: f64| {
10477            Opacity {
10478                key: None,
10479                opacity,
10480                child: Some(sized(10.0, 10.0)),
10481            }
10482            .into_widget()
10483        };
10484        let harness = Harness::mount(&mut app, faded(0.5));
10485        harness.pump(&mut app);
10486        let opacity = render_object_under_root::<RenderOpacity>(&harness, &app);
10487        assert_eq!(opacity.opacity(&app), 0.5);
10488
10489        harness.set_child(&mut app, faded(0.25));
10490        harness.pump(&mut app);
10491        assert_eq!(opacity.opacity(&app), 0.25);
10492    }
10493
10494    #[test]
10495    fn nested_opacities_appearing_together_paint_inside_a_clip() {
10496        let cell = AppCell::new();
10497        let mut app = cell.borrow_mut();
10498        let nested = |outer: f64, inner: f64| {
10499            Opacity::new(outer)
10500                .child(
10501                    ClipRRect::new()
10502                        .border_radius(crate::BorderRadius::circular(4.0).into())
10503                        .child(Opacity::new(inner).child(sized(20.0, 20.0))),
10504                )
10505                .into_widget()
10506        };
10507        let harness = Harness::mount(&mut app, nested(1.0, 1.0));
10508        harness.pump(&mut app);
10509        harness.set_child(&mut app, nested(0.0, 0.0));
10510        harness.pump(&mut app);
10511        harness.set_child(&mut app, nested(1.0, 1.0));
10512        harness.pump(&mut app);
10513    }
10514
10515    #[test]
10516    fn repaint_boundary_isolates_repaints() {
10517        let cell = AppCell::new();
10518        let mut app = cell.borrow_mut();
10519        let harness = Harness::mount(
10520            &mut app,
10521            RepaintBoundary {
10522                key: None,
10523                child: Some(sized(10.0, 10.0)),
10524            }
10525            .into_widget(),
10526        );
10527        harness.pump(&mut app);
10528        let boundary = render_object_under_root::<RenderRepaintBoundary>(&harness, &app);
10529        assert!(boundary.as_object().is_repaint_boundary(&app));
10530        assert_eq!(boundary.size(&app), Size::new(10.0, 10.0));
10531    }
10532
10533    #[test]
10534    fn directionality_of_resolves_through_the_tree_and_notifies_on_change() {
10535        let cell = AppCell::new();
10536        let mut app = cell.borrow_mut();
10537        let builds = Rc::new(Cell::new(0));
10538        let seen = Rc::new(Cell::new(None));
10539        // One reader instance, reused like a `const` widget, so only the Directionality
10540        // decides rebuilds.
10541        let reader: WidgetRef = DirectionReader {
10542            builds: Rc::clone(&builds),
10543            seen: Rc::clone(&seen),
10544        }
10545        .into_widget();
10546        let directional = |text_direction: TextDirection| {
10547            Directionality {
10548                key: None,
10549                text_direction,
10550                child: reader.clone(),
10551            }
10552            .into_widget()
10553        };
10554        let harness = Harness::mount(&mut app, directional(TextDirection::Ltr));
10555        harness.pump(&mut app);
10556        assert_eq!(builds.get(), 1);
10557        assert_eq!(seen.get(), Some(TextDirection::Ltr));
10558
10559        harness.set_child(&mut app, directional(TextDirection::Ltr));
10560        harness.pump(&mut app);
10561        assert_eq!(builds.get(), 1, "an equal direction does not notify");
10562
10563        harness.set_child(&mut app, directional(TextDirection::Rtl));
10564        harness.pump(&mut app);
10565        assert_eq!(
10566            builds.get(),
10567            2,
10568            "a changed direction rebuilds the dependent"
10569        );
10570        assert_eq!(seen.get(), Some(TextDirection::Rtl));
10571    }
10572
10573    #[test]
10574    fn builder_builds_with_its_context() {
10575        let cell = AppCell::new();
10576        let mut app = cell.borrow_mut();
10577        let harness = Harness::mount(
10578            &mut app,
10579            Builder {
10580                key: None,
10581                builder: Rc::new(|_app, context| {
10582                    let widget = context.widget(_app).clone();
10583                    assert!(
10584                        downcast_widget::<Builder>(&*widget).is_some(),
10585                        "the context is the Builder's own element"
10586                    );
10587                    Padding {
10588                        key: None,
10589                        padding: EdgeInsetsGeometry::all(2.0),
10590                        child: Some(sized(10.0, 10.0)),
10591                    }
10592                    .into_widget()
10593                }),
10594            }
10595            .into_widget(),
10596        );
10597        harness.pump(&mut app);
10598        let padding = padding_under_root(&harness, &app);
10599        assert_eq!(padding.padding(&app), EdgeInsetsGeometry::all(2.0));
10600        assert_eq!(padding.size(&app), Size::new(14.0, 14.0));
10601    }
10602    // ---- multi-child widgets ----
10603
10604    /// The children of a container render object, in list order.
10605    fn container_children<T: ContainerRenderObjectMixin<ChildType = AnyRenderBox>>(
10606        parent: RenderHandle<T>,
10607        app: &App,
10608    ) -> Vec<AnyRenderBox> {
10609        let mut children = Vec::new();
10610        let mut child = parent.first_child(app);
10611        while let Some(current) = child {
10612            children.push(current);
10613            child = parent.child_after(app, current);
10614        }
10615        children
10616    }
10617
10618    /// The offset a flex gave one of its children.
10619    fn flex_offset(child: AnyRenderBox, app: &App) -> Offset {
10620        child
10621            .as_object()
10622            .parent_data_of::<FlexParentData>(app)
10623            .offset()
10624    }
10625
10626    /// The offset a stack gave one of its children.
10627    fn stack_offset(child: AnyRenderBox, app: &App) -> Offset {
10628        child
10629            .as_object()
10630            .parent_data_of::<StackParentData>(app)
10631            .offset()
10632    }
10633
10634    /// The boxes a hit test walked, innermost first.
10635    fn hit_boxes(result: &HitTestResult) -> Vec<AnyRenderBox> {
10636        result
10637            .path()
10638            .iter()
10639            .filter_map(|entry: &HitTestEntry| {
10640                let target: &dyn Any = entry.target();
10641                target
10642                    .downcast_ref::<BoxHitTestEntry>()
10643                    .map(BoxHitTestEntry::target)
10644            })
10645            .collect()
10646    }
10647
10648    fn ltr(child: WidgetRef) -> WidgetRef {
10649        Directionality::new(TextDirection::Ltr, child).into_widget()
10650    }
10651
10652    /// A box that answers a hit test, so a hit can tell which child was reached.
10653    fn opaque(width: f64, height: f64) -> WidgetRef {
10654        Listener {
10655            behavior: HitTestBehavior::Opaque,
10656            child: Some(sized(width, height)),
10657            ..Default::default()
10658        }
10659        .into_widget()
10660    }
10661
10662    /// The `TileState` a global key names, through the harness's own build owner.
10663    fn tile_state(harness: &Harness, app: &App, key: &GlobalKey) -> Option<Handle<TileState>> {
10664        harness
10665            .owner
10666            .global_key_element(app, key)
10667            .and_then(|element| element.state_handle::<TileState>(app))
10668    }
10669
10670    /// A stateful leaf that counts its builds, so a move can be told from a rebirth.
10671    #[derive(Debug)]
10672    struct Tile {
10673        key: Option<KeyRef>,
10674        width: f64,
10675    }
10676
10677    impl Tile {
10678        fn keyed(key: &GlobalKey, width: f64) -> WidgetRef {
10679            Tile {
10680                key: Some(key.clone().into()),
10681                width,
10682            }
10683            .into_widget()
10684        }
10685    }
10686
10687    impl StatefulWidget for Tile {
10688        type State = TileState;
10689
10690        fn key(&self) -> Option<&KeyRef> {
10691            self.key.as_ref()
10692        }
10693
10694        fn create_state(&self) -> TileState {
10695            TileState {
10696                state: StateData::new(),
10697                builds: 0,
10698            }
10699        }
10700    }
10701
10702    struct TileState {
10703        state: StateData<Tile>,
10704        builds: u32,
10705    }
10706
10707    impl State for TileState {
10708        type Widget = Tile;
10709        crate::state_accessors!();
10710
10711        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
10712            app.get_mut(self).builds += 1;
10713            let width = self.widget(app).width;
10714            sized(width, 20.0)
10715        }
10716    }
10717
10718    #[test]
10719    fn row_lays_out_fixed_and_expanded_children() {
10720        let cell = AppCell::new();
10721        let mut app = cell.borrow_mut();
10722        let harness = Harness::mount(
10723            &mut app,
10724            ltr(Row::new()
10725                .children([
10726                    sized(50.0, 20.0),
10727                    Expanded::new(sized(10.0, 20.0)).into_widget(),
10728                    sized(30.0, 20.0),
10729                ])
10730                .into_widget()),
10731        );
10732        harness.pump(&mut app);
10733
10734        let row = render_object_under_root::<RenderFlex>(&harness, &app);
10735        assert_eq!(row.size(&app), Size::new(300.0, 20.0), "mainAxisSize.max");
10736        let children = container_children(row, &app);
10737        assert_eq!(children.len(), 3);
10738        assert_eq!(children[0].size(&app), Size::new(50.0, 20.0));
10739        assert_eq!(
10740            children[1].size(&app),
10741            Size::new(220.0, 20.0),
10742            "the expanded child takes the free space, tightly"
10743        );
10744        assert_eq!(children[2].size(&app), Size::new(30.0, 20.0));
10745        assert_eq!(flex_offset(children[0], &app), Offset::new(0.0, 0.0));
10746        assert_eq!(flex_offset(children[1], &app), Offset::new(50.0, 0.0));
10747        assert_eq!(flex_offset(children[2], &app), Offset::new(270.0, 0.0));
10748    }
10749
10750    #[test]
10751    fn a_loose_flexible_child_keeps_its_own_size() {
10752        let cell = AppCell::new();
10753        let mut app = cell.borrow_mut();
10754        let harness = Harness::mount(
10755            &mut app,
10756            ltr(Row::new()
10757                .children([
10758                    sized(50.0, 20.0),
10759                    Flexible::new(sized(10.0, 20.0))
10760                        .fit(FlexFit::Loose)
10761                        .into_widget(),
10762                ])
10763                .into_widget()),
10764        );
10765        harness.pump(&mut app);
10766
10767        let row = render_object_under_root::<RenderFlex>(&harness, &app);
10768        let children = container_children(row, &app);
10769        assert_eq!(
10770            children[1].size(&app),
10771            Size::new(10.0, 20.0),
10772            "FlexFit::Loose only offers the space, it does not force it"
10773        );
10774        assert_eq!(flex_offset(children[1], &app), Offset::new(50.0, 0.0));
10775
10776        harness.set_child(
10777            &mut app,
10778            ltr(Row::new()
10779                .children([
10780                    sized(50.0, 20.0),
10781                    Flexible::new(sized(10.0, 20.0))
10782                        .fit(FlexFit::Tight)
10783                        .into_widget(),
10784                ])
10785                .into_widget()),
10786        );
10787        harness.pump(&mut app);
10788        let children = container_children(row, &app);
10789        assert_eq!(
10790            children[1].size(&app),
10791            Size::new(250.0, 20.0),
10792            "FlexFit::Tight fills the offered space"
10793        );
10794    }
10795
10796    #[test]
10797    fn a_column_space_between_spreads_its_children() {
10798        let cell = AppCell::new();
10799        let mut app = cell.borrow_mut();
10800        let harness = Harness::mount(
10801            &mut app,
10802            Column::new()
10803                .main_axis_alignment(MainAxisAlignment::SpaceBetween)
10804                .children([sized(10.0, 20.0), sized(10.0, 30.0)])
10805                .into_widget(),
10806        );
10807        harness.pump(&mut app);
10808
10809        let column = render_object_under_root::<RenderFlex>(&harness, &app);
10810        assert_eq!(
10811            column.text_direction(&app),
10812            None,
10813            "a centred column needs no text direction"
10814        );
10815        assert_eq!(column.size(&app), Size::new(10.0, 200.0));
10816        let children = container_children(column, &app);
10817        assert_eq!(flex_offset(children[0], &app), Offset::new(0.0, 0.0));
10818        assert_eq!(flex_offset(children[1], &app), Offset::new(0.0, 170.0));
10819    }
10820
10821    /// `basic_test.dart`: `Row` `multiple baseline aligned children`. A large one-line text and
10822    /// a small seven-line one share the first line's baseline, so the small one hangs below it,
10823    /// and the row is just tall enough for both.
10824    #[test]
10825    fn a_baseline_aligned_row_puts_texts_of_different_sizes_on_one_baseline() {
10826        let cell = AppCell::new();
10827        let mut app = cell.borrow_mut();
10828        let binding = waft_painting::PaintingBinding::instance(&mut app);
10829        binding.install_fonts(&mut app, |fonts| {
10830            fonts.add_source(valo_system_fonts::SystemFonts::load());
10831        });
10832        let text = |data: &str, font_size: f64| {
10833            crate::Text::new(data)
10834                .style(
10835                    waft_painting::TextStyle::new()
10836                        .font_size(font_size)
10837                        .height(1.0),
10838                )
10839                .into_widget()
10840        };
10841        let harness = Harness::mount(
10842            &mut app,
10843            ltr(Row::new()
10844                .cross_axis_alignment(CrossAxisAlignment::Baseline)
10845                .text_baseline(TextBaseline::Alphabetic)
10846                .children([
10847                    text("big text", 52.0),
10848                    text("one\ntwo\nthree\nfour\nfive\nsix\nseven", 12.0),
10849                ])
10850                .into_widget()),
10851        );
10852        harness.pump(&mut app);
10853
10854        let row = render_object_under_root::<RenderFlex>(&harness, &app);
10855        let texts = container_children(row, &app);
10856        let mut above_baseline = |text: AnyRenderBox| {
10857            text.get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, true)
10858                .expect("a text has a baseline")
10859        };
10860        let (above_baseline_1, above_baseline_2) =
10861            (above_baseline(texts[0]), above_baseline(texts[1]));
10862        let below_baseline_1 = texts[0].size(&app).height() - above_baseline_1;
10863        let below_baseline_2 = texts[1].size(&app).height() - above_baseline_2;
10864        assert!(above_baseline_1 > above_baseline_2 && below_baseline_2 > below_baseline_1);
10865        assert!(row.size(&app).height() > texts[0].size(&app).height());
10866        assert!(row.size(&app).height() > texts[1].size(&app).height());
10867        assert_eq!(row.size(&app).height(), above_baseline_1 + below_baseline_2);
10868        assert_eq!(flex_offset(texts[0], &app).dy(), 0.0);
10869        assert_eq!(
10870            flex_offset(texts[1], &app).dy(),
10871            above_baseline_1 - above_baseline_2
10872        );
10873    }
10874
10875    #[test]
10876    #[should_panic(expected = "textBaseline is required")]
10877    fn a_baseline_aligned_row_needs_a_text_baseline() {
10878        let cell = AppCell::new();
10879        let mut app = cell.borrow_mut();
10880        let harness = Harness::mount(
10881            &mut app,
10882            ltr(Row::new()
10883                .cross_axis_alignment(CrossAxisAlignment::Baseline)
10884                .children([sized(10.0, 10.0)])
10885                .into_widget()),
10886        );
10887        harness.pump(&mut app);
10888    }
10889
10890    #[test]
10891    fn reordering_keyed_children_moves_elements_and_render_children() {
10892        let cell = AppCell::new();
10893        let mut app = cell.borrow_mut();
10894        let (first, second, third) = (GlobalKey::new(), GlobalKey::new(), GlobalKey::new());
10895        let row = |order: [&GlobalKey; 3]| {
10896            let widths = [10.0, 20.0, 30.0];
10897            let by_key = |key: &GlobalKey| {
10898                let index = [&first, &second, &third]
10899                    .iter()
10900                    .position(|candidate| *candidate == key)
10901                    .expect("one of the three keys");
10902                Tile::keyed(key, widths[index])
10903            };
10904            ltr(Row::new().children(order.map(by_key)).into_widget())
10905        };
10906
10907        let harness = Harness::mount(&mut app, row([&first, &second, &third]));
10908        harness.pump(&mut app);
10909        let flex = render_object_under_root::<RenderFlex>(&harness, &app);
10910        let before = container_children(flex, &app);
10911        assert_eq!(
10912            before
10913                .iter()
10914                .map(|child| child.size(&app).width())
10915                .collect::<Vec<f64>>(),
10916            vec![10.0, 20.0, 30.0]
10917        );
10918        let state = tile_state(&harness, &app, &first).expect("the first tile's state");
10919        assert_eq!(app.get(state).builds, 1);
10920
10921        harness.set_child(&mut app, row([&third, &first, &second]));
10922        harness.pump(&mut app);
10923
10924        assert_eq!(
10925            tile_state(&harness, &app, &first),
10926            Some(state),
10927            "the moved element keeps its State"
10928        );
10929        assert_eq!(
10930            app.get(state).builds,
10931            2,
10932            "it was rebuilt in place, not created afresh"
10933        );
10934        let after = container_children(flex, &app);
10935        assert_eq!(
10936            after,
10937            vec![before[2], before[0], before[1]],
10938            "the same render objects, in the new order"
10939        );
10940        assert_eq!(flex_offset(after[0], &app), Offset::new(0.0, 0.0));
10941        assert_eq!(flex_offset(after[1], &app), Offset::new(30.0, 0.0));
10942        assert_eq!(flex_offset(after[2], &app), Offset::new(40.0, 0.0));
10943    }
10944
10945    #[test]
10946    fn a_child_can_be_added_and_removed_in_the_middle() {
10947        let cell = AppCell::new();
10948        let mut app = cell.borrow_mut();
10949        let (first, middle, last) = (GlobalKey::new(), GlobalKey::new(), GlobalKey::new());
10950        let ends = || {
10951            ltr(Row::new()
10952                .children([Tile::keyed(&first, 10.0), Tile::keyed(&last, 30.0)])
10953                .into_widget())
10954        };
10955        let all_three = || {
10956            ltr(Row::new()
10957                .children([
10958                    Tile::keyed(&first, 10.0),
10959                    Tile::keyed(&middle, 20.0),
10960                    Tile::keyed(&last, 30.0),
10961                ])
10962                .into_widget())
10963        };
10964
10965        let harness = Harness::mount(&mut app, ends());
10966        harness.pump(&mut app);
10967        let flex = render_object_under_root::<RenderFlex>(&harness, &app);
10968        let before = container_children(flex, &app);
10969        assert_eq!(before.len(), 2);
10970
10971        harness.set_child(&mut app, all_three());
10972        harness.pump(&mut app);
10973        let inserted = container_children(flex, &app);
10974        assert_eq!(inserted.len(), 3);
10975        assert_eq!(inserted[0], before[0], "the first child was kept");
10976        assert_eq!(inserted[2], before[1], "the last child was kept");
10977        assert_eq!(inserted[1].size(&app).width(), 20.0);
10978        assert_eq!(flex_offset(inserted[2], &app), Offset::new(30.0, 0.0));
10979
10980        harness.set_child(&mut app, ends());
10981        harness.pump(&mut app);
10982        let removed = container_children(flex, &app);
10983        assert_eq!(removed, vec![before[0], before[1]]);
10984        assert_eq!(flex_offset(removed[1], &app), Offset::new(10.0, 0.0));
10985        assert!(
10986            tile_state(&harness, &app, &middle).is_none(),
10987            "the removed child was unmounted"
10988        );
10989    }
10990
10991    /// A `Wrap` takes its text direction from the ambient `Directionality` and moves a child
10992    /// that does not fit its run to the next one.
10993    #[test]
10994    fn a_wrap_starts_a_new_run_for_a_child_that_does_not_fit() {
10995        let cell = AppCell::new();
10996        let mut app = cell.borrow_mut();
10997        let harness = Harness::mount(
10998            &mut app,
10999            ltr(Align::new()
11000                .alignment(AlignmentGeometry::TOP_LEFT)
11001                .child(
11002                    Wrap::new()
11003                        .spacing(10.0)
11004                        .run_spacing(10.0)
11005                        .children((0..4).map(|_| sized(80.0, 40.0))),
11006                )
11007                .into_widget()),
11008        );
11009        harness.pump(&mut app);
11010
11011        let align = render_object_under_root::<RenderPositionedBox>(&harness, &app);
11012        let wrap = align
11013            .child(&app)
11014            .expect("the wrap")
11015            .as_object()
11016            .downcast::<RenderWrap>(&app)
11017            .expect("a RenderWrap");
11018        assert_eq!(wrap.text_direction(&app), Some(TextDirection::Ltr));
11019        // Three 80 wide children and two gaps fill 260 of the 300 wide view; the fourth wraps.
11020        assert_eq!(wrap.size(&app), Size::new(260.0, 90.0));
11021        let offsets: Vec<Offset> = container_children(wrap, &app)
11022            .into_iter()
11023            .map(|child| child.box_parent_data(&app).offset)
11024            .collect();
11025        assert_eq!(
11026            offsets,
11027            [
11028                Offset::new(0.0, 0.0),
11029                Offset::new(90.0, 0.0),
11030                Offset::new(180.0, 0.0),
11031                Offset::new(0.0, 50.0)
11032            ]
11033        );
11034    }
11035
11036    #[test]
11037    fn a_stack_sizes_its_non_positioned_child_by_its_fit() {
11038        // Loose leaves the child alone, Expand forces the biggest size, Passthrough hands the
11039        // stack's own constraints down (whose minimum is larger than the child).
11040        for (fit, child_size, stack_size) in [
11041            (StackFit::Loose, Size::new(10.0, 5.0), Size::new(20.0, 10.0)),
11042            (
11043                StackFit::Expand,
11044                Size::new(100.0, 80.0),
11045                Size::new(100.0, 80.0),
11046            ),
11047            (
11048                StackFit::Passthrough,
11049                Size::new(20.0, 10.0),
11050                Size::new(20.0, 10.0),
11051            ),
11052        ] {
11053            let cell = AppCell::new();
11054            let mut app = cell.borrow_mut();
11055            let harness = Harness::mount(
11056                &mut app,
11057                ltr(ConstrainedBox::new(
11058                    BoxConstraints::new()
11059                        .min_width(20.0)
11060                        .max_width(100.0)
11061                        .min_height(10.0)
11062                        .max_height(80.0),
11063                )
11064                .child(Stack::new().fit(fit).children([
11065                    sized(10.0, 5.0),
11066                    Positioned::fill(sized(1.0, 1.0)).into_widget(),
11067                ]))
11068                .into_widget()),
11069            );
11070            harness.pump(&mut app);
11071
11072            let constrained = render_object_under_root::<RenderConstrainedBox>(&harness, &app);
11073            let stack: RenderHandle<RenderStack> = constrained
11074                .child(&app)
11075                .expect("a child")
11076                .as_object()
11077                .downcast(&app)
11078                .expect("a RenderStack");
11079            assert_eq!(stack.size(&app), stack_size, "{fit:?}");
11080            let children = container_children(stack, &app);
11081            assert_eq!(children[0].size(&app), child_size, "{fit:?}");
11082            assert_eq!(stack_offset(children[0], &app), Offset::ZERO, "{fit:?}");
11083            assert_eq!(
11084                children[1].size(&app),
11085                stack_size,
11086                "Positioned.fill fills the stack ({fit:?})"
11087            );
11088            assert_eq!(stack_offset(children[1], &app), Offset::ZERO, "{fit:?}");
11089        }
11090    }
11091
11092    /// `stack_test.dart`: `Clip.none` is respected by `describeApproximateClip`; a hard edge
11093    /// clips the overflowing positioned child to the stack's bounds.
11094    #[test]
11095    fn clip_none_is_respected_by_describe_approximate_paint_clip() {
11096        let cell = AppCell::new();
11097        let mut app = cell.borrow_mut();
11098        let harness = Harness::mount(
11099            &mut app,
11100            ltr(Stack::new()
11101                .children([Positioned::new(sized(2000.0, 2000.0))
11102                    .left(1000.0)
11103                    .into_widget()])
11104                .into_widget()),
11105        );
11106        harness.pump(&mut app);
11107
11108        let stack = render_object_under_root::<RenderStack>(&harness, &app);
11109        assert_eq!(stack.clip_behavior(&app), Clip::HardEdge);
11110        let child = container_children(stack, &app)[0];
11111        assert_eq!(
11112            stack
11113                .as_object()
11114                .describe_approximate_paint_clip(&app, child.as_object()),
11115            Some(Offset::ZERO & stack.size(&app))
11116        );
11117
11118        stack.set_clip_behavior(&mut app, Clip::None);
11119        assert_eq!(
11120            stack
11121                .as_object()
11122                .describe_approximate_paint_clip(&app, child.as_object()),
11123            None
11124        );
11125    }
11126
11127    #[test]
11128    fn an_indexed_stack_lays_out_every_child_but_shows_one() {
11129        let cell = AppCell::new();
11130        let mut app = cell.borrow_mut();
11131        let stack = |index: i32| {
11132            ltr(IndexedStack::new()
11133                .index(Some(index))
11134                .children([opaque(40.0, 30.0), opaque(20.0, 50.0)])
11135                .into_widget())
11136        };
11137        let harness = Harness::mount(&mut app, stack(1));
11138        harness.pump(&mut app);
11139
11140        let indexed = render_object_under_root::<RenderIndexedStack>(&harness, &app);
11141        assert_eq!(indexed.index(&app), Some(1));
11142        let children = container_children(indexed, &app);
11143        assert_eq!(children.len(), 2, "every child is laid out");
11144        assert_eq!(children[0].size(&app), Size::new(40.0, 30.0));
11145        assert_eq!(children[1].size(&app), Size::new(20.0, 50.0));
11146        assert_eq!(
11147            indexed.size(&app),
11148            Size::new(40.0, 50.0),
11149            "as big as the largest child"
11150        );
11151
11152        // Only the child at the index answers a hit test: (30, 10) is inside the first child
11153        // and outside the second.
11154        let mut result = HitTestResult::new();
11155        assert!(!indexed.hit_test(
11156            &mut app,
11157            &mut BoxHitTestResult::wrap(&mut result),
11158            Offset::new(30.0, 10.0)
11159        ));
11160        let mut result = HitTestResult::new();
11161        assert!(indexed.hit_test(
11162            &mut app,
11163            &mut BoxHitTestResult::wrap(&mut result),
11164            Offset::new(10.0, 10.0)
11165        ));
11166        assert_eq!(hit_boxes(&result), vec![children[1], indexed.as_box()]);
11167
11168        harness.set_child(&mut app, stack(0));
11169        harness.pump(&mut app);
11170        assert_eq!(indexed.index(&app), Some(0));
11171        let mut result = HitTestResult::new();
11172        assert!(indexed.hit_test(
11173            &mut app,
11174            &mut BoxHitTestResult::wrap(&mut result),
11175            Offset::new(30.0, 10.0)
11176        ));
11177        assert_eq!(hit_boxes(&result), vec![children[0], indexed.as_box()]);
11178    }
11179
11180    #[test]
11181    fn clip_rect_and_clip_rrect_configure_their_render_objects() {
11182        let cell = AppCell::new();
11183        let mut app = cell.borrow_mut();
11184        let clipped = |behavior: Clip| {
11185            ClipRect::new()
11186                .clip_behavior(behavior)
11187                .child(sized(10.0, 10.0))
11188                .into_widget()
11189        };
11190        let harness = Harness::mount(&mut app, clipped(Clip::HardEdge));
11191        harness.pump(&mut app);
11192        let clip = render_object_under_root::<RenderClipRect>(&harness, &app);
11193        assert_eq!(clip.clip_behavior(&app), Clip::HardEdge, "Dart's default");
11194        assert!(clip.clipper(&app).is_none());
11195
11196        harness.set_child(&mut app, clipped(Clip::AntiAliasWithSaveLayer));
11197        harness.pump(&mut app);
11198        assert_eq!(
11199            render_object_under_root::<RenderClipRect>(&harness, &app),
11200            clip,
11201            "the same RenderClipRect is reconfigured"
11202        );
11203        assert_eq!(clip.clip_behavior(&app), Clip::AntiAliasWithSaveLayer);
11204        assert_eq!(clip.size(&app), Size::new(10.0, 10.0), "sized to its child");
11205    }
11206
11207    #[test]
11208    fn clip_rrect_resolves_its_radius_through_directionality() {
11209        let cell = AppCell::new();
11210        let mut app = cell.borrow_mut();
11211        let corner = Radius::circular(4.0);
11212        let radius = BorderRadiusGeometry::directional(corner, corner, corner, corner);
11213        let rounded = |text_direction: TextDirection| {
11214            Directionality::new(
11215                text_direction,
11216                ClipRRect::new()
11217                    .border_radius(radius)
11218                    .child(sized(10.0, 10.0)),
11219            )
11220            .into_widget()
11221        };
11222        let harness = Harness::mount(&mut app, rounded(TextDirection::Rtl));
11223        harness.pump(&mut app);
11224        let clip = render_object_under_root::<RenderClipRRect>(&harness, &app);
11225        assert_eq!(clip.clip_behavior(&app), Clip::AntiAlias, "Dart's default");
11226        assert_eq!(clip.border_radius(&app), radius);
11227        assert_eq!(clip.text_direction(&app), Some(TextDirection::Rtl));
11228
11229        harness.set_child(&mut app, rounded(TextDirection::Ltr));
11230        harness.pump(&mut app);
11231        assert_eq!(clip.text_direction(&app), Some(TextDirection::Ltr));
11232    }
11233
11234    #[test]
11235    fn transform_named_constructors_match_dart() {
11236        assert_eq!(Transform::rotate(0.0).transform, Matrix4::IDENTITY);
11237        assert_eq!(
11238            Transform::rotate(std::f64::consts::FRAC_PI_2).transform,
11239            Matrix4::from_flutter_array(&[
11240                0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
11241            ]),
11242            "a quarter turn is exact"
11243        );
11244        assert_eq!(
11245            Transform::rotate(0.0).alignment,
11246            Some(AlignmentGeometry::CENTER)
11247        );
11248
11249        let translated = Transform::translate(Offset::new(3.0, 4.0));
11250        assert_eq!(translated.transform, Matrix4::translation(3.0, 4.0));
11251        assert_eq!(translated.alignment, None, "Dart leaves it unset");
11252        assert_eq!(translated.origin, None);
11253
11254        assert_eq!(
11255            Transform::scale(Some(0.5), None, None).transform,
11256            Matrix4::scale(0.5, 0.5)
11257        );
11258        assert_eq!(
11259            Transform::scale(None, Some(2.0), None).transform,
11260            Matrix4::scale(2.0, 1.0),
11261            "the unset axis stays at 1.0"
11262        );
11263        assert_eq!(
11264            Transform::flip(true, false).transform,
11265            Matrix4::scale(-1.0, 1.0)
11266        );
11267        assert_eq!(
11268            Transform::flip(true, false).alignment,
11269            Some(AlignmentGeometry::CENTER)
11270        );
11271    }
11272
11273    /// Dart's `tester.layers.whereType<ImageFilterLayer>()`: the image filter layers in the
11274    /// layer tree from the root, depth first.
11275    fn image_filter_layers(app: &mut App) -> Vec<Handle<waft_rendering::ImageFilterLayer>> {
11276        let root = crate::binding::WidgetsBinding::instance(app)
11277            .root_element(app)
11278            .and_then(|root| root.find_render_object(app))
11279            .and_then(|view| view.layer(app))
11280            .expect("the view's layer");
11281        crate::test_harness::layer_tree(app, root)
11282            .into_iter()
11283            .filter_map(|layer| app.handle::<waft_rendering::ImageFilterLayer>(layer.id()))
11284            .collect()
11285    }
11286
11287    /// Dart's `extractMatrix(layer.imageFilter)`: the matrix of the one image filter layer, in
11288    /// `Matrix4.storage` order.
11289    fn the_filter_matrix(app: &mut App) -> [f32; 16] {
11290        let layers = image_filter_layers(app);
11291        assert_eq!(layers.len(), 1);
11292        match layers[0].image_filter(app) {
11293            Some(ImageFilter::Matrix { data, .. }) => data.to_flutter_array(),
11294            other => panic!("a matrix filter: {other:?}"),
11295        }
11296    }
11297
11298    /// Dart's `moreOrLessEquals` on each entry. The filter's matrix is valo's `f32`, the product
11299    /// of the transform and the translations about the view's centre, each rounded to `f32`
11300    /// where Dart's are `f64`: an entry is within two `f32` steps of Dart's, relative to it.
11301    fn assert_matrix_near(actual: [f32; 16], expected: [f64; 16]) {
11302        const F32_STEPS: f64 = 2.0;
11303        for (actual, expected) in actual.iter().zip(expected) {
11304            let step = f64::from(f32::EPSILON) * expected.abs().max(1.0);
11305            let steps = (f64::from(*actual) - expected).abs() / step;
11306            assert!(steps <= F32_STEPS, "{actual:?} is not {expected:?}");
11307        }
11308    }
11309
11310    fn square(dimension: f64) -> SizedBox {
11311        SizedBox::new().width(dimension).height(dimension)
11312    }
11313
11314    #[test]
11315    fn transform_translate_with_filter_quality_produces_filter_layer() {
11316        test_widgets(|tester| {
11317            tester.pump_widget(
11318                Transform::translate(Offset::new(25.0, 25.0))
11319                    .filter_quality(FilterQuality::Low)
11320                    .child(square(100.0))
11321                    .into_widget(),
11322            );
11323            let mut app = tester.cell.borrow_mut();
11324            assert_matrix_near(
11325                the_filter_matrix(&mut app),
11326                [
11327                    1.0, 0.0, 0.0, 0.0, //
11328                    0.0, 1.0, 0.0, 0.0, //
11329                    0.0, 0.0, 1.0, 0.0, //
11330                    25.0, 25.0, 0.0, 1.0,
11331                ],
11332            );
11333        });
11334    }
11335
11336    #[test]
11337    #[allow(
11338        clippy::approx_constant,
11339        reason = "Dart's case scales by 3.14159, not by pi"
11340    )]
11341    fn transform_scale_with_filter_quality_produces_filter_layer() {
11342        test_widgets(|tester| {
11343            tester.pump_widget(
11344                Transform::scale(Some(3.14159), None, None)
11345                    .filter_quality(FilterQuality::Low)
11346                    .child(square(100.0))
11347                    .into_widget(),
11348            );
11349            let mut app = tester.cell.borrow_mut();
11350            assert_matrix_near(
11351                the_filter_matrix(&mut app),
11352                [
11353                    3.14159, 0.0, 0.0, 0.0, //
11354                    0.0, 3.14159, 0.0, 0.0, //
11355                    0.0, 0.0, 1.0, 0.0, //
11356                    -856.636, -642.477, 0.0, 1.0,
11357                ],
11358            );
11359        });
11360    }
11361
11362    /// The matrix both rotate cases expect: a quarter of a half turn about the window's center.
11363    #[allow(
11364        clippy::approx_constant,
11365        reason = "Dart's expected entries, as it writes them"
11366    )]
11367    const ROTATED_ABOUT_THE_WINDOWS_CENTER: [f64; 16] = [
11368        0.7071067811865476,
11369        0.7071067811865475,
11370        0.0,
11371        0.0,
11372        -0.7071067811865475,
11373        0.7071067811865476,
11374        0.0,
11375        0.0,
11376        0.0,
11377        0.0,
11378        1.0,
11379        0.0,
11380        329.28932188134524,
11381        -194.97474683058329,
11382        0.0,
11383        1.0,
11384    ];
11385
11386    #[test]
11387    fn transform_rotate_with_filter_quality_produces_filter_layer() {
11388        test_widgets(|tester| {
11389            tester.pump_widget(
11390                Transform::rotate(std::f64::consts::FRAC_PI_4)
11391                    .filter_quality(FilterQuality::Low)
11392                    .child(square(100.0))
11393                    .into_widget(),
11394            );
11395            let mut app = tester.cell.borrow_mut();
11396            assert_matrix_near(
11397                the_filter_matrix(&mut app),
11398                ROTATED_ABOUT_THE_WINDOWS_CENTER,
11399            );
11400        });
11401    }
11402
11403    #[test]
11404    fn offset_transform_rotate_with_filter_quality_produces_filter_layer() {
11405        test_widgets(|tester| {
11406            tester.pump_widget(
11407                square(400.0)
11408                    .child(
11409                        Center::new().child(
11410                            Transform::rotate(std::f64::consts::FRAC_PI_4)
11411                                .filter_quality(FilterQuality::Low)
11412                                .child(square(100.0)),
11413                        ),
11414                    )
11415                    .into_widget(),
11416            );
11417            let mut app = tester.cell.borrow_mut();
11418            assert_matrix_near(
11419                the_filter_matrix(&mut app),
11420                ROTATED_ABOUT_THE_WINDOWS_CENTER,
11421            );
11422        });
11423    }
11424
11425    #[test]
11426    fn transform_layers_update_to_match_child_and_filter_quality() {
11427        test_widgets(|tester| {
11428            let rotated = || Transform::rotate(std::f64::consts::FRAC_PI_4);
11429            tester.pump_widget(
11430                rotated()
11431                    .filter_quality(FilterQuality::Low)
11432                    .child(square(100.0))
11433                    .into_widget(),
11434            );
11435            let mut app = tester.cell.borrow_mut();
11436            assert_eq!(image_filter_layers(&mut app).len(), 1);
11437
11438            drop(app);
11439            tester.pump_widget(rotated().child(square(100.0)).into_widget());
11440            let mut app = tester.cell.borrow_mut();
11441            assert!(image_filter_layers(&mut app).is_empty());
11442
11443            drop(app);
11444            tester.pump_widget(rotated().filter_quality(FilterQuality::Low).into_widget());
11445            let mut app = tester.cell.borrow_mut();
11446            assert!(image_filter_layers(&mut app).is_empty());
11447
11448            drop(app);
11449            tester.pump_widget(
11450                rotated()
11451                    .filter_quality(FilterQuality::Low)
11452                    .child(square(100.0))
11453                    .into_widget(),
11454            );
11455            let mut app = tester.cell.borrow_mut();
11456            assert_eq!(image_filter_layers(&mut app).len(), 1);
11457        });
11458    }
11459
11460    #[test]
11461    fn transform_moves_hit_tests_with_its_child() {
11462        let cell = AppCell::new();
11463        let mut app = cell.borrow_mut();
11464        let translated = |transform_hit_tests: bool| {
11465            Transform::translate(Offset::new(20.0, 0.0))
11466                .transform_hit_tests(transform_hit_tests)
11467                .child(opaque(10.0, 10.0))
11468                .into_widget()
11469        };
11470        let harness = Harness::mount(&mut app, translated(true));
11471        harness.pump(&mut app);
11472        let transform = render_object_under_root::<RenderTransform>(&harness, &app);
11473        assert!(transform.transform_hit_tests(&app));
11474
11475        let mut result = HitTestResult::new();
11476        assert!(
11477            transform.hit_test(
11478                &mut app,
11479                &mut BoxHitTestResult::wrap(&mut result),
11480                Offset::new(25.0, 5.0),
11481            ),
11482            "the child is hit where it is painted"
11483        );
11484        let mut result = HitTestResult::new();
11485        assert!(!transform.hit_test(
11486            &mut app,
11487            &mut BoxHitTestResult::wrap(&mut result),
11488            Offset::new(5.0, 5.0),
11489        ));
11490
11491        harness.set_child(&mut app, translated(false));
11492        harness.pump(&mut app);
11493        assert!(!transform.transform_hit_tests(&app));
11494        let mut result = HitTestResult::new();
11495        assert!(
11496            transform.hit_test(
11497                &mut app,
11498                &mut BoxHitTestResult::wrap(&mut result),
11499                Offset::new(5.0, 5.0),
11500            ),
11501            "the child is hit where it was laid out"
11502        );
11503    }
11504
11505    #[test]
11506    fn fractional_translation_forwards_its_configuration() {
11507        let cell = AppCell::new();
11508        let mut app = cell.borrow_mut();
11509        let harness = Harness::mount(
11510            &mut app,
11511            FractionalTranslation::new(Offset::new(0.25, 0.0))
11512                .transform_hit_tests(false)
11513                .child(sized(40.0, 10.0))
11514                .into_widget(),
11515        );
11516        harness.pump(&mut app);
11517        let translation = render_object_under_root::<RenderFractionalTranslation>(&harness, &app);
11518        assert_eq!(translation.translation(&app), Offset::new(0.25, 0.0));
11519        assert!(!translation.transform_hit_tests(&app));
11520
11521        harness.set_child(
11522            &mut app,
11523            FractionalTranslation::new(Offset::new(0.5, 0.5))
11524                .child(sized(40.0, 10.0))
11525                .into_widget(),
11526        );
11527        harness.pump(&mut app);
11528        assert_eq!(translation.translation(&app), Offset::new(0.5, 0.5));
11529        assert!(
11530            translation.transform_hit_tests(&app),
11531            "back to Dart's default"
11532        );
11533    }
11534
11535    #[test]
11536    fn ignore_pointer_and_absorb_pointer_stop_hit_tests_differently() {
11537        let cell = AppCell::new();
11538        let mut app = cell.borrow_mut();
11539        let harness = Harness::mount(
11540            &mut app,
11541            IgnorePointer::new().child(opaque(10.0, 10.0)).into_widget(),
11542        );
11543        harness.pump(&mut app);
11544        let ignoring = render_object_under_root::<RenderIgnorePointer>(&harness, &app);
11545        assert!(ignoring.ignoring(&app), "Dart's default");
11546        let mut result = HitTestResult::new();
11547        assert!(!ignoring.hit_test(
11548            &mut app,
11549            &mut BoxHitTestResult::wrap(&mut result),
11550            Offset::new(5.0, 5.0),
11551        ));
11552        assert!(hit_boxes(&result).is_empty());
11553
11554        harness.set_child(
11555            &mut app,
11556            IgnorePointer::new()
11557                .ignoring(false)
11558                .child(opaque(10.0, 10.0))
11559                .into_widget(),
11560        );
11561        harness.pump(&mut app);
11562        assert!(!ignoring.ignoring(&app));
11563        let mut result = HitTestResult::new();
11564        assert!(ignoring.hit_test(
11565            &mut app,
11566            &mut BoxHitTestResult::wrap(&mut result),
11567            Offset::new(5.0, 5.0),
11568        ));
11569        assert!(!hit_boxes(&result).is_empty(), "the child answers again");
11570
11571        let cell = AppCell::new();
11572        let mut app = cell.borrow_mut();
11573        let harness = Harness::mount(
11574            &mut app,
11575            AbsorbPointer::new().child(opaque(10.0, 10.0)).into_widget(),
11576        );
11577        harness.pump(&mut app);
11578        let absorbing = render_object_under_root::<RenderAbsorbPointer>(&harness, &app);
11579        assert!(absorbing.absorbing(&app), "Dart's default");
11580        let mut result = HitTestResult::new();
11581        assert!(
11582            absorbing.hit_test(
11583                &mut app,
11584                &mut BoxHitTestResult::wrap(&mut result),
11585                Offset::new(5.0, 5.0),
11586            ),
11587            "absorbing itself answers the hit"
11588        );
11589        assert!(
11590            hit_boxes(&result).is_empty(),
11591            "the subtree is not reached, and nothing is added to the path"
11592        );
11593    }
11594
11595    #[test]
11596    fn limited_box_caps_an_unbounded_child() {
11597        let cell = AppCell::new();
11598        let mut app = cell.borrow_mut();
11599        let limited = |max_width: f64| {
11600            ltr(Row::new()
11601                .children([LimitedBox::new()
11602                    .max_width(max_width)
11603                    .child(SizedBox::expand())
11604                    .into_widget()])
11605                .into_widget())
11606        };
11607        let harness = Harness::mount(&mut app, limited(50.0));
11608        harness.pump(&mut app);
11609        let flex = render_object_under_root::<RenderFlex>(&harness, &app);
11610        let child = container_children(flex, &app)[0]
11611            .as_object()
11612            .downcast::<RenderLimitedBox>(&app)
11613            .expect("a RenderLimitedBox");
11614        assert_eq!(child.max_width(&app), 50.0);
11615        assert_eq!(child.max_height(&app), f64::INFINITY, "Dart's default");
11616        assert_eq!(
11617            child.size(&app).width(),
11618            50.0,
11619            "the row's unbounded width is capped"
11620        );
11621
11622        harness.set_child(&mut app, limited(30.0));
11623        harness.pump(&mut app);
11624        assert_eq!(child.max_width(&app), 30.0);
11625        assert_eq!(child.size(&app).width(), 30.0);
11626    }
11627
11628    #[test]
11629    fn colored_box_forwards_its_color_and_anti_aliasing() {
11630        let cell = AppCell::new();
11631        let mut app = cell.borrow_mut();
11632        let red = Color::from_argb(255, 255, 0, 0);
11633        let blue = Color::from_argb(255, 0, 0, 255);
11634        let harness = Harness::mount(
11635            &mut app,
11636            ColoredBox::new(red).child(sized(10.0, 10.0)).into_widget(),
11637        );
11638        harness.pump(&mut app);
11639        let colored = render_object_under_root::<RenderColoredBox>(&harness, &app);
11640        assert_eq!(colored.color(&app), red);
11641        assert!(colored.is_anti_alias(&app), "Dart's default");
11642
11643        harness.set_child(
11644            &mut app,
11645            ColoredBox::new(blue)
11646                .is_anti_alias(false)
11647                .child(sized(10.0, 10.0))
11648                .into_widget(),
11649        );
11650        harness.pump(&mut app);
11651        assert_eq!(colored.color(&app), blue, "the same box is reconfigured");
11652        assert!(!colored.is_anti_alias(&app));
11653    }
11654
11655    #[test]
11656    fn offstage_takes_no_room_and_hides_its_child() {
11657        let cell = AppCell::new();
11658        let mut app = cell.borrow_mut();
11659        let staged = |offstage: bool| {
11660            Offstage::new()
11661                .offstage(offstage)
11662                .child(opaque(10.0, 10.0))
11663                .into_widget()
11664        };
11665        let harness = Harness::mount(&mut app, staged(true));
11666        harness.pump(&mut app);
11667        let offstage = render_object_under_root::<RenderOffstage>(&harness, &app);
11668        assert!(offstage.offstage(&app), "Dart's default");
11669        assert_eq!(offstage.size(&app), Size::ZERO, "no room in the parent");
11670        let child = offstage.child(&app).expect("laid out as if in the tree");
11671        assert_eq!(child.size(&app), Size::new(10.0, 10.0));
11672        assert!(!offstage.as_object().paints_child(&app, child.as_object()));
11673
11674        harness.set_child(&mut app, staged(false));
11675        harness.pump(&mut app);
11676        assert_eq!(offstage.size(&app), Size::new(10.0, 10.0));
11677        assert!(offstage.as_object().paints_child(&app, child.as_object()));
11678    }
11679
11680    /// Counts its paint calls and records the size it was handed.
11681    #[derive(Debug)]
11682    struct RecordingPainter {
11683        paints: Rc<Cell<u32>>,
11684        painted: Rc<Cell<Size>>,
11685    }
11686
11687    impl CustomPainter for RecordingPainter {
11688        fn paint(&self, _app: &mut App, _canvas: &mut waft_embedder::Canvas, size: Size) {
11689            self.paints.set(self.paints.get() + 1);
11690            self.painted.set(size);
11691        }
11692
11693        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
11694            true
11695        }
11696
11697        fn as_any(&self) -> &dyn Any {
11698            self
11699        }
11700    }
11701
11702    #[test]
11703    fn custom_paint_sizes_itself_and_runs_its_painter() {
11704        let cell = AppCell::new();
11705        let mut app = cell.borrow_mut();
11706        let paints = Rc::new(Cell::new(0));
11707        let painted = Rc::new(Cell::new(Size::ZERO));
11708        let painter = || RecordingPainter {
11709            paints: Rc::clone(&paints),
11710            painted: Rc::clone(&painted),
11711        };
11712        let harness = Harness::mount(
11713            &mut app,
11714            CustomPaint::new()
11715                .painter(painter())
11716                .size(Size::new(40.0, 30.0))
11717                .into_widget(),
11718        );
11719        harness.pump(&mut app);
11720        let custom = render_object_under_root::<RenderCustomPaint>(&harness, &app);
11721        assert_eq!(
11722            custom.size(&app),
11723            Size::new(40.0, 30.0),
11724            "the preferred size, with no child"
11725        );
11726        assert_eq!(paints.get(), 1);
11727        assert_eq!(painted.get(), Size::new(40.0, 30.0));
11728        assert!(custom.foreground_painter(&app).is_none());
11729
11730        harness.set_child(
11731            &mut app,
11732            CustomPaint::new()
11733                .foreground_painter(painter())
11734                .child(sized(10.0, 10.0))
11735                .into_widget(),
11736        );
11737        harness.pump(&mut app);
11738        assert!(custom.painter(&app).is_none(), "the painter is cleared");
11739        assert!(custom.foreground_painter(&app).is_some());
11740        assert_eq!(
11741            custom.size(&app),
11742            Size::new(10.0, 10.0),
11743            "the child's size wins"
11744        );
11745        assert_eq!(paints.get(), 2);
11746        assert_eq!(painted.get(), Size::new(10.0, 10.0));
11747    }
11748
11749    #[test]
11750    #[cfg(debug_assertions)]
11751    #[should_panic(expected = "Incorrect use of ParentDataWidget")]
11752    fn a_flexible_under_a_non_flex_parent_asserts() {
11753        let cell = AppCell::new();
11754        let mut app = cell.borrow_mut();
11755        let harness = Harness::mount(
11756            &mut app,
11757            Padding::new(EdgeInsetsGeometry::all(1.0))
11758                .child(Flexible::new(sized(10.0, 10.0)))
11759                .into_widget(),
11760        );
11761        harness.pump(&mut app);
11762    }
11763
11764    #[test]
11765    fn meta_data_reaches_its_render_object_and_updates() {
11766        let cell = AppCell::new();
11767        let mut app = cell.borrow_mut();
11768        let harness = Harness::mount(
11769            &mut app,
11770            MetaData::new()
11771                .meta_data(Rc::new(String::from("tag")))
11772                .behavior(HitTestBehavior::Opaque)
11773                .child(SizedBox::shrink())
11774                .into_widget(),
11775        );
11776        harness.pump(&mut app);
11777        let render_object = render_object_under_root::<RenderMetaData>(&harness, &app);
11778        assert_eq!(
11779            render_object
11780                .meta_data(&app)
11781                .and_then(|data| data.downcast::<String>().ok())
11782                .as_deref(),
11783            Some(&String::from("tag"))
11784        );
11785        harness.set_child(
11786            &mut app,
11787            MetaData::new().child(SizedBox::shrink()).into_widget(),
11788        );
11789        harness.pump(&mut app);
11790        assert!(render_object.meta_data(&app).is_none());
11791    }
11792
11793    #[test]
11794    fn a_backdrop_filter_reaches_its_render_object_and_a_grouped_one_shares_the_group_key() {
11795        let cell = AppCell::new();
11796        let mut app = cell.borrow_mut();
11797        let harness = Harness::mount(
11798            &mut app,
11799            BackdropFilter::filter(ImageFilter::blur(3.0, 3.0))
11800                .child(SizedBox::shrink())
11801                .into_widget(),
11802        );
11803        harness.pump(&mut app);
11804        let render_object = render_object_under_root::<RenderBackdropFilter>(&harness, &app);
11805        assert_eq!(render_object.filter(&app), ImageFilter::blur(3.0, 3.0));
11806        assert!(render_object.backdrop_key(&app).is_none());
11807
11808        let key = BackdropKey::new();
11809        harness.set_child(
11810            &mut app,
11811            BackdropGroup::new(
11812                BackdropFilter::grouped(ImageFilterConfig::blur().sigma_x(2.0).sigma_y(2.0))
11813                    .child(SizedBox::shrink()),
11814            )
11815            .backdrop_key(key)
11816            .into_widget(),
11817        );
11818        harness.pump(&mut app);
11819        let inherited = harness
11820            .render_root(&app)
11821            .child(&app)
11822            .expect("the filter under the group")
11823            .as_object()
11824            .downcast::<RenderBackdropFilter>(&app)
11825            .expect("a RenderBackdropFilter");
11826        assert_eq!(inherited.backdrop_key(&app), Some(key));
11827    }
11828    /// `SliverPadding` insets its sliver child on every side: the padded sliver's scroll extent
11829    /// grows by the main-axis insets, and the child is narrowed by the cross-axis ones.
11830    #[test]
11831    fn a_sliver_padding_insets_its_child_on_every_side() {
11832        use waft_embedder::TextDirection;
11833        use waft_rendering::{
11834            ContainerRenderObjectMixin, FixedViewportOffset, RenderSliver, RenderSliverPadding,
11835            RenderSliverToBoxAdapter, RenderViewport, ScrollCacheExtent,
11836        };
11837
11838        use crate::widgets::viewport::Viewport;
11839
11840        let cell = AppCell::new();
11841        let mut app = cell.borrow_mut();
11842        let offset = FixedViewportOffset::zero(&mut app);
11843        let tree = Directionality::new(
11844            TextDirection::Ltr,
11845            Viewport::new(offset.erase())
11846                .scroll_cache_extent(ScrollCacheExtent::Pixels(0.0))
11847                .slivers(vec![
11848                    SliverPadding::new(EdgeInsetsGeometry::only(10.0, 20.0, 30.0, 40.0))
11849                        .sliver(SliverToBoxAdapter::new().child(SizedBox::new().height(50.0)))
11850                        .into_widget(),
11851                ]),
11852        )
11853        .into_widget();
11854        let harness = Harness::mount(&mut app, tree);
11855        harness.pump(&mut app);
11856
11857        let padding = render_object_under_root::<RenderViewport>(&harness, &app)
11858            .first_child(&app)
11859            .expect("the padding")
11860            .as_object()
11861            .downcast::<RenderSliverPadding>(&app)
11862            .expect("a RenderSliverPadding");
11863        // 20 above and 40 below the 50-pixel child.
11864        assert_eq!(padding.geometry(&app).scroll_extent, 110.0);
11865        let adapter = padding
11866            .child(&app)
11867            .expect("the adapter")
11868            .as_object()
11869            .downcast::<RenderSliverToBoxAdapter>(&app)
11870            .expect("a RenderSliverToBoxAdapter");
11871        // 10 on the left and 30 on the right of the 300-pixel viewport.
11872        assert_eq!(
11873            adapter.child(&app).expect("the box").size(&app).width(),
11874            260.0
11875        );
11876    }
11877
11878    #[test]
11879    fn fitted_box_scales_its_child_to_the_space_it_is_given() {
11880        let cell = AppCell::new();
11881        let mut app = cell.borrow_mut();
11882        let harness = Harness::mount(
11883            &mut app,
11884            FittedBox::new().child(sized(600.0, 400.0)).into_widget(),
11885        );
11886        harness.pump(&mut app);
11887        let fitted = render_object_under_root::<RenderFittedBox>(&harness, &app);
11888        assert_eq!(
11889            fitted.size(&app),
11890            Size::new(300.0, 200.0),
11891            "the 3:2 child fills the 300x200 root"
11892        );
11893        let child = fitted.child(&app).expect("a child");
11894        assert_eq!(
11895            child.size(&app),
11896            Size::new(600.0, 400.0),
11897            "the child lays out unconstrained"
11898        );
11899        assert_eq!(
11900            child.local_to_global(&app, Offset::new(600.0, 400.0), Some(fitted.as_object())),
11901            Offset::new(300.0, 200.0),
11902            "half scale"
11903        );
11904    }
11905
11906    #[test]
11907    fn constraints_transform_box_transforms_are_dart_s() {
11908        let constraints = BoxConstraints::new()
11909            .min_width(10.0)
11910            .max_width(20.0)
11911            .min_height(30.0)
11912            .max_height(40.0);
11913        assert_eq!(
11914            ConstraintsTransformBox::unmodified(constraints),
11915            constraints
11916        );
11917        assert_eq!(
11918            ConstraintsTransformBox::unconstrained(constraints),
11919            BoxConstraints::new()
11920        );
11921        assert_eq!(
11922            ConstraintsTransformBox::width_unconstrained(constraints),
11923            constraints.height_constraints()
11924        );
11925        assert_eq!(
11926            ConstraintsTransformBox::height_unconstrained(constraints),
11927            constraints.width_constraints()
11928        );
11929        assert_eq!(
11930            ConstraintsTransformBox::max_height_unconstrained(constraints),
11931            constraints.copy_with().max_height(f64::INFINITY)
11932        );
11933        assert_eq!(
11934            ConstraintsTransformBox::max_width_unconstrained(constraints),
11935            constraints.copy_with().max_width(f64::INFINITY)
11936        );
11937        assert_eq!(
11938            ConstraintsTransformBox::max_unconstrained(constraints),
11939            constraints
11940                .copy_with()
11941                .max_width(f64::INFINITY)
11942                .max_height(f64::INFINITY)
11943        );
11944    }
11945
11946    #[test]
11947    fn unconstrained_box_lets_its_child_size_itself_under_a_tight_parent() {
11948        let cell = AppCell::new();
11949        let mut app = cell.borrow_mut();
11950        let tight = |child: WidgetRef| {
11951            SizedBox::new()
11952                .width(50.0)
11953                .height(50.0)
11954                .child(child)
11955                .into_widget()
11956        };
11957        let harness = Harness::mount(
11958            &mut app,
11959            tight(
11960                UnconstrainedBox::new()
11961                    .child(sized(120.0, 30.0))
11962                    .into_widget(),
11963            ),
11964        );
11965        harness.pump(&mut app);
11966        let unconstrained = render_object_under_root::<RenderConstrainedBox>(&harness, &app)
11967            .child(&app)
11968            .expect("the transform box")
11969            .as_object()
11970            .downcast::<RenderConstraintsTransformBox>(&app)
11971            .expect("a RenderConstraintsTransformBox");
11972        assert_eq!(
11973            unconstrained.size(&app),
11974            Size::new(50.0, 50.0),
11975            "the box still obeys the tight parent"
11976        );
11977        assert_eq!(
11978            unconstrained.child(&app).expect("a child").size(&app),
11979            Size::new(120.0, 30.0),
11980            "the child is laid out unconstrained"
11981        );
11982
11983        assert_eq!(
11984            unconstrained
11985                .child(&app)
11986                .expect("a child")
11987                .constraints(&app),
11988            BoxConstraints::new(),
11989            "no axis keeps its constraints"
11990        );
11991
11992        harness.set_child(
11993            &mut app,
11994            tight(
11995                UnconstrainedBox::new()
11996                    .constrained_axis(Axis::Horizontal)
11997                    .child(sized(120.0, 30.0))
11998                    .into_widget(),
11999            ),
12000        );
12001        harness.pump(&mut app);
12002        let horizontal = render_object_under_root::<RenderConstrainedBox>(&harness, &app)
12003            .child(&app)
12004            .expect("the transform box")
12005            .as_object()
12006            .downcast::<RenderConstraintsTransformBox>(&app)
12007            .expect("a RenderConstraintsTransformBox");
12008        assert_eq!(
12009            horizontal.child(&app).expect("a child").constraints(&app),
12010            BoxConstraints::new().min_width(50.0).max_width(50.0),
12011            "the horizontal constraints are retained"
12012        );
12013        assert_eq!(
12014            horizontal.child(&app).expect("a child").size(&app),
12015            Size::new(50.0, 30.0)
12016        );
12017    }
12018
12019    #[test]
12020    fn fractionally_sized_box_tightens_its_child_to_a_fraction() {
12021        let cell = AppCell::new();
12022        let mut app = cell.borrow_mut();
12023        let harness = Harness::mount(
12024            &mut app,
12025            FractionallySizedBox::new()
12026                .width_factor(0.5)
12027                .height_factor(0.25)
12028                .child(SizedBox::expand())
12029                .into_widget(),
12030        );
12031        harness.pump(&mut app);
12032        let fraction =
12033            render_object_under_root::<RenderFractionallySizedOverflowBox>(&harness, &app);
12034        assert_eq!(
12035            fraction.child(&app).expect("a child").size(&app),
12036            Size::new(150.0, 50.0),
12037            "half the width and a quarter of the height of the root"
12038        );
12039        assert_eq!(fraction.size(&app), Size::new(150.0, 50.0));
12040    }
12041
12042    #[test]
12043    fn overflow_box_gives_its_child_its_own_constraints() {
12044        let cell = AppCell::new();
12045        let mut app = cell.borrow_mut();
12046        let harness = Harness::mount(
12047            &mut app,
12048            OverflowBox::new()
12049                .min_width(400.0)
12050                .max_width(400.0)
12051                .min_height(300.0)
12052                .max_height(300.0)
12053                .child(SizedBox::expand())
12054                .into_widget(),
12055        );
12056        harness.pump(&mut app);
12057        let overflow = render_object_under_root::<RenderConstrainedOverflowBox>(&harness, &app);
12058        assert_eq!(
12059            overflow.size(&app),
12060            Size::new(300.0, 200.0),
12061            "the box is as large as the root allows"
12062        );
12063        assert_eq!(
12064            overflow.child(&app).expect("a child").size(&app),
12065            Size::new(400.0, 300.0),
12066            "the child overflows"
12067        );
12068        assert_eq!(child_offset(overflow, &app), Offset::new(-50.0, -50.0));
12069
12070        harness.set_child(
12071            &mut app,
12072            OverflowBox::new()
12073                .fit(OverflowBoxFit::DeferToChild)
12074                .max_width(40.0)
12075                .max_height(20.0)
12076                .child(SizedBox::expand())
12077                .into_widget(),
12078        );
12079        harness.pump(&mut app);
12080        assert_eq!(
12081            render_object_under_root::<RenderConstrainedOverflowBox>(&harness, &app).size(&app),
12082            Size::new(40.0, 20.0),
12083            "deferring to the child takes the child's size"
12084        );
12085    }
12086
12087    #[test]
12088    fn overflow_box_can_start_deferring_to_its_child() {
12089        let cell = AppCell::new();
12090        let mut app = cell.borrow_mut();
12091        let harness = Harness::mount(
12092            &mut app,
12093            Center::new()
12094                .child(
12095                    OverflowBox::new()
12096                        .fit(OverflowBoxFit::DeferToChild)
12097                        .max_width(40.0)
12098                        .max_height(20.0)
12099                        .child(SizedBox::expand()),
12100                )
12101                .into_widget(),
12102        );
12103        harness.pump(&mut app);
12104        let center = render_object_under_root::<RenderPositionedBox>(&harness, &app);
12105        assert_eq!(
12106            center.child(&app).expect("the overflow box").size(&app),
12107            Size::new(40.0, 20.0)
12108        );
12109    }
12110
12111    #[test]
12112    fn sized_overflow_box_takes_its_requested_size() {
12113        let cell = AppCell::new();
12114        let mut app = cell.borrow_mut();
12115        let harness = Harness::mount(
12116            &mut app,
12117            Directionality::new(
12118                TextDirection::Ltr,
12119                SizedOverflowBox::new(Size::new(40.0, 20.0)).child(sized(100.0, 60.0)),
12120            )
12121            .into_widget(),
12122        );
12123        harness.pump(&mut app);
12124        let sized_overflow = render_object_under_root::<RenderSizedOverflowBox>(&harness, &app);
12125        assert_eq!(sized_overflow.size(&app), Size::new(40.0, 20.0));
12126        assert_eq!(
12127            sized_overflow.child(&app).expect("a child").size(&app),
12128            Size::new(100.0, 60.0),
12129            "the original constraints reach the child"
12130        );
12131    }
12132
12133    #[test]
12134    fn aspect_ratio_picks_the_widest_size_that_keeps_the_ratio() {
12135        let cell = AppCell::new();
12136        let mut app = cell.borrow_mut();
12137        let harness = Harness::mount(&mut app, AspectRatio::new(2.0).into_widget());
12138        harness.pump(&mut app);
12139        assert_eq!(
12140            render_object_under_root::<RenderAspectRatio>(&harness, &app).size(&app),
12141            Size::new(300.0, 150.0)
12142        );
12143
12144        harness.set_child(&mut app, AspectRatio::new(0.5).into_widget());
12145        harness.pump(&mut app);
12146        assert_eq!(
12147            render_object_under_root::<RenderAspectRatio>(&harness, &app).size(&app),
12148            Size::new(100.0, 200.0),
12149            "the height is clamped and the width follows from it"
12150        );
12151    }
12152
12153    #[test]
12154    fn intrinsic_width_sizes_to_the_child_s_max_intrinsic_width() {
12155        let cell = AppCell::new();
12156        let mut app = cell.borrow_mut();
12157        let harness = Harness::mount(
12158            &mut app,
12159            IntrinsicWidth::new().child(sized(40.0, 10.0)).into_widget(),
12160        );
12161        harness.pump(&mut app);
12162        assert_eq!(
12163            render_object_under_root::<RenderIntrinsicWidth>(&harness, &app).size(&app),
12164            Size::new(40.0, 10.0)
12165        );
12166
12167        harness.set_child(
12168            &mut app,
12169            IntrinsicWidth::new()
12170                .step_width(30.0)
12171                .child(sized(40.0, 10.0))
12172                .into_widget(),
12173        );
12174        harness.pump(&mut app);
12175        assert_eq!(
12176            render_object_under_root::<RenderIntrinsicWidth>(&harness, &app).size(&app),
12177            Size::new(60.0, 10.0),
12178            "the width is snapped up to a multiple of the step"
12179        );
12180
12181        harness.set_child(
12182            &mut app,
12183            IntrinsicWidth::new()
12184                .step_width(0.0)
12185                .child(sized(40.0, 10.0))
12186                .into_widget(),
12187        );
12188        harness.pump(&mut app);
12189        assert_eq!(
12190            render_object_under_root::<RenderIntrinsicWidth>(&harness, &app).step_width(&app),
12191            None,
12192            "Dart's `_stepWidth` reads a zero step as no step"
12193        );
12194    }
12195
12196    #[test]
12197    fn intrinsic_height_sizes_to_the_child_s_max_intrinsic_height() {
12198        let cell = AppCell::new();
12199        let mut app = cell.borrow_mut();
12200        let harness = Harness::mount(
12201            &mut app,
12202            IntrinsicHeight::new()
12203                .child(sized(40.0, 10.0))
12204                .into_widget(),
12205        );
12206        harness.pump(&mut app);
12207        assert_eq!(
12208            render_object_under_root::<RenderIntrinsicHeight>(&harness, &app).size(&app),
12209            Size::new(40.0, 10.0)
12210        );
12211    }
12212
12213    #[test]
12214    fn baseline_shifts_its_child_down_to_the_requested_baseline() {
12215        let cell = AppCell::new();
12216        let mut app = cell.borrow_mut();
12217        let harness = Harness::mount(
12218            &mut app,
12219            Baseline::new(30.0, TextBaseline::Alphabetic)
12220                .child(sized(10.0, 10.0))
12221                .into_widget(),
12222        );
12223        harness.pump(&mut app);
12224        let baseline = render_object_under_root::<RenderBaseline>(&harness, &app);
12225        assert_eq!(
12226            baseline.size(&app),
12227            Size::new(10.0, 30.0),
12228            "a child with no baseline reports its bottom"
12229        );
12230        assert_eq!(child_offset(baseline, &app), Offset::new(0.0, 20.0));
12231    }
12232
12233    #[test]
12234    fn the_clip_widgets_reach_their_render_objects_and_a_shape_clip_resolves_its_direction() {
12235        let cell = AppCell::new();
12236        let mut app = cell.borrow_mut();
12237        let harness = Harness::mount(
12238            &mut app,
12239            ClipOval::new().child(SizedBox::shrink()).into_widget(),
12240        );
12241        harness.pump(&mut app);
12242        assert!(
12243            render_object_under_root::<RenderClipOval>(&harness, &app).clip_behavior(&app)
12244                == Clip::AntiAlias
12245        );
12246
12247        harness.set_child(
12248            &mut app,
12249            ClipRSuperellipse::new()
12250                .border_radius(waft_painting::BorderRadiusGeometry::circular(8.0))
12251                .child(SizedBox::shrink())
12252                .into_widget(),
12253        );
12254        harness.pump(&mut app);
12255        let superellipse = render_object_under_root::<RenderClipRSuperellipse>(&harness, &app);
12256        assert_eq!(
12257            superellipse.border_radius(&app),
12258            waft_painting::BorderRadiusGeometry::circular(8.0)
12259        );
12260
12261        let shape: ShapeBorderRef =
12262            ShapeBorderRef::new(waft_painting::RoundedRectangleBorder::new(
12263                waft_painting::BorderSide::NONE,
12264                waft_painting::BorderRadiusGeometry::circular(4.0),
12265            ));
12266        harness.set_child(
12267            &mut app,
12268            Directionality::new(
12269                TextDirection::Rtl,
12270                ClipPath::shape(shape)
12271                    .clip_behavior(Clip::HardEdge)
12272                    .child(SizedBox::shrink()),
12273            )
12274            .into_widget(),
12275        );
12276        harness.pump(&mut app);
12277        let clip_path = harness
12278            .render_root(&app)
12279            .child(&app)
12280            .expect("the clip under the directionality")
12281            .as_object()
12282            .downcast::<RenderClipPath>(&app)
12283            .expect("a RenderClipPath");
12284        assert_eq!(clip_path.clip_behavior(&app), Clip::HardEdge);
12285        let clipper = clip_path.clipper(&app).expect("the shape clipper");
12286        let clipper = clipper
12287            .as_any()
12288            .downcast_ref::<ShapeBorderClipper>()
12289            .expect("a ShapeBorderClipper");
12290        assert_eq!(clipper.text_direction, Some(TextDirection::Rtl));
12291    }
12292
12293    const DEBUG_BLACK: Color = Color::new(0xFF000000);
12294
12295    /// `physical_model_test.dart`: "PhysicalModel updates clipBehavior in updateRenderObject".
12296    #[test]
12297    fn a_physical_model_updates_its_clip_behavior() {
12298        let cell = AppCell::new();
12299        let mut app = cell.borrow_mut();
12300        let harness = Harness::mount(&mut app, PhysicalModel::new(DEBUG_BLACK).into_widget());
12301        harness.pump(&mut app);
12302        let render = render_object_under_root::<RenderPhysicalModel>(&harness, &app);
12303        assert_eq!(render.clip_behavior(&app), Clip::None);
12304
12305        harness.set_child(
12306            &mut app,
12307            PhysicalModel::new(DEBUG_BLACK)
12308                .clip_behavior(Clip::AntiAlias)
12309                .into_widget(),
12310        );
12311        harness.pump(&mut app);
12312        assert_eq!(render.clip_behavior(&app), Clip::AntiAlias);
12313    }
12314
12315    fn circle_clipper() -> Rc<dyn CustomClipper<Path>> {
12316        Rc::new(ShapeBorderClipper::new(
12317            ShapeBorderRef::new(waft_painting::CircleBorder::new(
12318                waft_painting::BorderSide::NONE,
12319                0.0,
12320            )),
12321            None,
12322        ))
12323    }
12324
12325    /// `physical_model_test.dart`: "PhysicalShape updates clipBehavior in updateRenderObject".
12326    #[test]
12327    fn a_physical_shape_updates_its_clip_behavior() {
12328        let cell = AppCell::new();
12329        let mut app = cell.borrow_mut();
12330        let harness = Harness::mount(
12331            &mut app,
12332            PhysicalShape::new(circle_clipper(), DEBUG_BLACK).into_widget(),
12333        );
12334        harness.pump(&mut app);
12335        let render = render_object_under_root::<RenderPhysicalShape>(&harness, &app);
12336        assert_eq!(render.clip_behavior(&app), Clip::None);
12337
12338        harness.set_child(
12339            &mut app,
12340            PhysicalShape::new(circle_clipper(), DEBUG_BLACK)
12341                .clip_behavior(Clip::AntiAlias)
12342                .into_widget(),
12343        );
12344        harness.pump(&mut app);
12345        assert_eq!(render.clip_behavior(&app), Clip::AntiAlias);
12346    }
12347
12348    /// `physical_model_test.dart`: "PhysicalModel does not crash at zero area", with a centred
12349    /// childless model, which sizes to nothing.
12350    #[test]
12351    fn a_childless_physical_model_and_shape_take_no_space() {
12352        let cell = AppCell::new();
12353        let mut app = cell.borrow_mut();
12354        let harness = Harness::mount(
12355            &mut app,
12356            Directionality::new(
12357                TextDirection::Ltr,
12358                Center::new().child(PhysicalModel::new(Color::new(0xAABBCC00))),
12359            )
12360            .into_widget(),
12361        );
12362        harness.pump(&mut app);
12363        let center = render_object_under_root::<RenderPositionedBox>(&harness, &app);
12364        let model = center.child(&app).expect("the model");
12365        assert_eq!(model.size(&app), Size::ZERO);
12366
12367        harness.set_child(
12368            &mut app,
12369            Directionality::new(
12370                TextDirection::Ltr,
12371                Center::new().child(PhysicalShape::new(circle_clipper(), Color::new(0xAABBCC00))),
12372            )
12373            .into_widget(),
12374        );
12375        harness.pump(&mut app);
12376        let center = render_object_under_root::<RenderPositionedBox>(&harness, &app);
12377        let shape = center.child(&app).expect("the shape");
12378        assert_eq!(shape.size(&app), Size::ZERO);
12379    }
12380
12381    fn keyed_size(app: &mut App, key: &GlobalKey) -> Size {
12382        key.current_context(app)
12383            .expect("mounted")
12384            .find_render_object(app)
12385            .expect("a render object")
12386            .as_box()
12387            .expect("a box")
12388            .size(app)
12389    }
12390
12391    /// `physical_model_test.dart`: "PhysicalModel does not crash at zero area" and
12392    /// "PhysicalShape does not crash at zero area", in a view of no area.
12393    #[test]
12394    fn a_physical_model_and_shape_in_a_view_of_no_area_take_no_space() {
12395        test_widgets(|tester| {
12396            tester.view().set_physical_size(Size::ZERO);
12397            let key = GlobalKey::new();
12398            tester.pump_widget(Directionality::new(
12399                TextDirection::Ltr,
12400                Center::new()
12401                    .child(PhysicalModel::new(Color::new(0xAABBCC00)).key(key.clone().into())),
12402            ));
12403            assert_eq!(keyed_size(&mut tester.cell.borrow_mut(), &key), Size::ZERO);
12404        });
12405
12406        test_widgets(|tester| {
12407            tester.view().set_physical_size(Size::ZERO);
12408            let key = GlobalKey::new();
12409            tester.pump_widget(Directionality::new(
12410                TextDirection::Ltr,
12411                Center::new().child(
12412                    PhysicalShape::new(circle_clipper(), Color::new(0xAABBCC00))
12413                        .key(key.clone().into()),
12414                ),
12415            ));
12416            assert_eq!(keyed_size(&mut tester.cell.borrow_mut(), &key), Size::ZERO);
12417        });
12418    }
12419
12420    fn list_children(width: f64, height: f64) -> Vec<WidgetRef> {
12421        (0..4).map(|_| sized(width, height)).collect()
12422    }
12423
12424    /// The rectangles of a list body's children, in child order, in the list body's space.
12425    fn list_body_rects(app: &App, list_body: AnyRenderBox) -> Vec<Rect> {
12426        let list_body = list_body
12427            .as_object()
12428            .downcast::<RenderListBody>(app)
12429            .expect("a list body");
12430        let mut rects = Vec::new();
12431        let mut child = list_body.first_child(app);
12432        while let Some(current) = child {
12433            let offset = current
12434                .as_object()
12435                .parent_data_of::<waft_rendering::ListBodyParentData>(app)
12436                .offset();
12437            rects.push(offset & current.size(app));
12438            child = list_body.child_after(app, current);
12439        }
12440        rects
12441    }
12442
12443    /// `list_body_test.dart`: "ListBody down" and "ListBody up", in a 300x200 view with
12444    /// children 40 high.
12445    #[test]
12446    fn a_vertical_list_body_stacks_its_children_down_or_reversed_up() {
12447        for (reverse, tops) in [
12448            (false, [0.0, 40.0, 80.0, 120.0]),
12449            (true, [120.0, 80.0, 40.0, 0.0]),
12450        ] {
12451            let cell = AppCell::new();
12452            let mut app = cell.borrow_mut();
12453            let harness = Harness::mount(
12454                &mut app,
12455                Directionality::new(
12456                    TextDirection::Ltr,
12457                    Column::new().children(vec![
12458                        ListBody::new()
12459                            .reverse(reverse)
12460                            .children(list_children(200.0, 40.0))
12461                            .into_widget(),
12462                    ]),
12463                )
12464                .into_widget(),
12465            );
12466            harness.pump(&mut app);
12467            let flex = render_object_under_root::<waft_rendering::RenderFlex>(&harness, &app);
12468            let list_body = flex.first_child(&app).expect("the list body");
12469            let expected: Vec<Rect> = tops
12470                .iter()
12471                .map(|top| Rect::from_ltwh(0.0, *top, VIEW_WIDTH, 40.0))
12472                .collect();
12473            assert_eq!(
12474                list_body_rects(&app, list_body),
12475                expected,
12476                "reverse {reverse}"
12477            );
12478        }
12479    }
12480
12481    /// `list_body_test.dart`: "ListBody right" and "ListBody left", children 60 wide.
12482    #[test]
12483    fn a_horizontal_list_body_follows_the_ambient_text_direction() {
12484        for (text_direction, lefts) in [
12485            (TextDirection::Ltr, [0.0, 60.0, 120.0, 180.0]),
12486            (TextDirection::Rtl, [180.0, 120.0, 60.0, 0.0]),
12487        ] {
12488            let cell = AppCell::new();
12489            let mut app = cell.borrow_mut();
12490            let harness = Harness::mount(
12491                &mut app,
12492                Directionality::new(
12493                    TextDirection::Ltr,
12494                    Row::new().children(vec![
12495                        Directionality::new(
12496                            text_direction,
12497                            ListBody::new()
12498                                .main_axis(Axis::Horizontal)
12499                                .children(list_children(60.0, 150.0)),
12500                        )
12501                        .into_widget(),
12502                    ]),
12503                )
12504                .into_widget(),
12505            );
12506            harness.pump(&mut app);
12507            let flex = render_object_under_root::<waft_rendering::RenderFlex>(&harness, &app);
12508            let list_body = flex.first_child(&app).expect("the list body");
12509            let expected: Vec<Rect> = lefts
12510                .iter()
12511                .map(|left| Rect::from_ltwh(*left, 0.0, 60.0, VIEW_HEIGHT))
12512                .collect();
12513            assert_eq!(
12514                list_body_rects(&app, list_body),
12515                expected,
12516                "{text_direction:?}"
12517            );
12518        }
12519    }
12520
12521    /// `list_body_test.dart`: "Limited space along main axis error".
12522    #[test]
12523    #[should_panic(expected = "RenderListBody must have unlimited space along its main axis.")]
12524    fn a_list_body_with_a_bounded_main_axis_panics() {
12525        let cell = AppCell::new();
12526        let mut app = cell.borrow_mut();
12527        let harness = Harness::mount(
12528            &mut app,
12529            SizedBox::square(Some(100.0))
12530                .child(Directionality::new(
12531                    TextDirection::Rtl,
12532                    ListBody::new()
12533                        .main_axis(Axis::Horizontal)
12534                        .children(list_children(200.0, 150.0)),
12535                ))
12536                .into_widget(),
12537        );
12538        harness.pump(&mut app);
12539    }
12540
12541    /// `list_body_test.dart`: "Nested ListBody unbounded cross axis error".
12542    #[test]
12543    #[should_panic(expected = "RenderListBody must have a bounded constraint for its cross axis.")]
12544    fn a_list_body_nested_across_another_with_an_unbounded_cross_axis_panics() {
12545        let cell = AppCell::new();
12546        let mut app = cell.borrow_mut();
12547        let inner = Column::new().children(vec![
12548            Directionality::new(
12549                TextDirection::Ltr,
12550                ListBody::new().children(list_children(200.0, 150.0)),
12551            )
12552            .into_widget(),
12553        ]);
12554        let harness = Harness::mount(
12555            &mut app,
12556            Directionality::new(
12557                TextDirection::Ltr,
12558                Row::new().children(vec![
12559                    Directionality::new(
12560                        TextDirection::Ltr,
12561                        ListBody::new()
12562                            .main_axis(Axis::Horizontal)
12563                            .children(vec![inner.into_widget()]),
12564                    )
12565                    .into_widget(),
12566                ]),
12567            )
12568            .into_widget(),
12569        );
12570        harness.pump(&mut app);
12571    }
12572
12573    const VIEW_WIDTH: f64 = crate::test_harness::VIEW_WIDTH;
12574    const VIEW_HEIGHT: f64 = crate::test_harness::VIEW_HEIGHT;
12575
12576    /// A `PositionedDirectional` places its start edge on the right under a right-to-left
12577    /// directionality; `positioned_test.dart` checks the same through `Positioned.directional`.
12578    #[test]
12579    fn positioned_directional_resolves_start_and_end_against_the_directionality() {
12580        for (text_direction, left) in [(TextDirection::Ltr, 10.0), (TextDirection::Rtl, 270.0)] {
12581            let cell = AppCell::new();
12582            let mut app = cell.borrow_mut();
12583            let harness = Harness::mount(
12584                &mut app,
12585                Directionality::new(
12586                    text_direction,
12587                    Stack::new().children(vec![
12588                        PositionedDirectional::new(sized(20.0, 20.0))
12589                            .start(10.0)
12590                            .top(5.0)
12591                            .into_widget(),
12592                    ]),
12593                )
12594                .into_widget(),
12595            );
12596            harness.pump(&mut app);
12597            let stack = render_object_under_root::<RenderStack>(&harness, &app);
12598            let child = stack.first_child(&app).expect("the positioned child");
12599            let offset = child
12600                .as_object()
12601                .parent_data_of::<StackParentData>(&app)
12602                .offset();
12603            assert_eq!(offset, Offset::new(left, 5.0), "{text_direction:?}");
12604        }
12605    }
12606
12607    /// `PositionedDirectional` builds a `Positioned`, whose constructor asserts that at most
12608    /// two of start, end and width are set.
12609    #[test]
12610    #[should_panic]
12611    fn positioned_directional_with_start_end_and_width_panics() {
12612        let cell = AppCell::new();
12613        let mut app = cell.borrow_mut();
12614        let harness = Harness::mount(
12615            &mut app,
12616            Directionality::new(
12617                TextDirection::Ltr,
12618                Stack::new().children(vec![
12619                    PositionedDirectional::new(sized(20.0, 20.0))
12620                        .start(10.0)
12621                        .end(10.0)
12622                        .width(20.0)
12623                        .into_widget(),
12624                ]),
12625            )
12626            .into_widget(),
12627        );
12628        harness.pump(&mut app);
12629    }
12630
12631    /// A `StatefulBuilder`'s `set_state` runs its callback and rebuilds the builder.
12632    #[test]
12633    fn a_stateful_builder_rebuilds_when_its_setter_is_called() {
12634        let cell = AppCell::new();
12635        let mut app = cell.borrow_mut();
12636        let builds = Rc::new(Cell::new(0));
12637        let setter: Rc<std::cell::RefCell<Option<StateSetter>>> = Rc::default();
12638        let width = Rc::new(Cell::new(10.0));
12639        let harness = Harness::mount(
12640            &mut app,
12641            Center::new()
12642                .child(StatefulBuilder::new({
12643                    let (builds, setter, width) =
12644                        (Rc::clone(&builds), Rc::clone(&setter), Rc::clone(&width));
12645                    move |_app, _context, set_state| {
12646                        builds.set(builds.get() + 1);
12647                        *setter.borrow_mut() = Some(set_state);
12648                        sized(width.get(), 10.0)
12649                    }
12650                }))
12651                .into_widget(),
12652        );
12653        harness.pump(&mut app);
12654        assert_eq!(builds.get(), 1);
12655
12656        let set_state = setter.borrow().clone().expect("the builder ran");
12657        set_state(&mut app, &mut |_app| width.set(30.0));
12658        harness.pump(&mut app);
12659        assert_eq!(builds.get(), 2);
12660        let center = render_object_under_root::<RenderPositionedBox>(&harness, &app);
12661        assert_eq!(
12662            center.child(&app).expect("the box").size(&app),
12663            Size::new(30.0, 10.0)
12664        );
12665    }
12666
12667    fn keyed_sized(key: impl Into<KeyRef>) -> WidgetRef {
12668        SizedBox {
12669            key: Some(key.into()),
12670            ..Default::default()
12671        }
12672        .into_widget()
12673    }
12674
12675    #[test]
12676    fn a_wrapped_index_key_never_equals_a_callers_own_int_key() {
12677        let wrapped = KeyedSubtree::wrap(sized(1.0, 1.0), 3);
12678        let callers: KeyRef = ValueKey::new(3_i64).into();
12679        assert!(wrapped.key.as_ref() != Some(&callers));
12680        assert!(wrapped.key == KeyedSubtree::wrap(sized(2.0, 2.0), 3).key);
12681        assert!(wrapped.key != KeyedSubtree::wrap(sized(1.0, 1.0), 4).key);
12682    }
12683
12684    #[test]
12685    fn a_wrapped_child_key_never_equals_a_wrapped_index_key() {
12686        let child_key: KeyRef = ValueKey::new(3_i64).into();
12687        let by_child_key = KeyedSubtree::wrap(keyed_sized(child_key.clone()), 0);
12688        assert!(by_child_key.key != KeyedSubtree::wrap(sized(1.0, 1.0), 3).key);
12689        assert!(by_child_key.key != Some(child_key.clone()));
12690        assert!(by_child_key.key == KeyedSubtree::wrap(keyed_sized(child_key), 7).key);
12691    }
12692
12693    #[test]
12694    fn ensure_unique_keys_for_list_keys_each_item_by_its_key_or_its_index_plus_the_base() {
12695        assert!(KeyedSubtree::ensure_unique_keys_for_list(Vec::new(), 5).is_empty());
12696
12697        let child_key: KeyRef = ValueKey::new("a".to_string()).into();
12698        let items = vec![
12699            sized(1.0, 1.0),
12700            keyed_sized(child_key.clone()),
12701            sized(2.0, 2.0),
12702        ];
12703        let wrapped = KeyedSubtree::ensure_unique_keys_for_list(items, 5);
12704        let keys: Vec<Option<KeyRef>> = wrapped.iter().map(|item| item.key().cloned()).collect();
12705        assert!(keys[0] == KeyedSubtree::wrap(sized(1.0, 1.0), 5).key);
12706        assert!(keys[1] == KeyedSubtree::wrap(keyed_sized(child_key), 0).key);
12707        assert!(keys[2] == KeyedSubtree::wrap(sized(1.0, 1.0), 7).key);
12708        assert!(downcast_widget::<KeyedSubtree>(&*wrapped[0]).is_some());
12709    }
12710
12711    #[test]
12712    #[cfg(debug_assertions)]
12713    #[should_panic(expected = "Duplicate key found")]
12714    fn ensure_unique_keys_for_list_asserts_on_duplicate_keys() {
12715        let key = || ValueKey::new("a".to_string());
12716        KeyedSubtree::ensure_unique_keys_for_list(vec![keyed_sized(key()), keyed_sized(key())], 0);
12717    }
12718
12719    fn semantics_under_root(
12720        harness: &Harness,
12721        app: &App,
12722    ) -> RenderHandle<RenderSemanticsAnnotations> {
12723        render_object_under_root::<RenderSemanticsAnnotations>(harness, app)
12724    }
12725
12726    // semantics_test.dart: 'Semantics and Directionality - RTL'
12727    #[test]
12728    fn a_semantics_label_takes_the_ambient_rtl_direction() {
12729        let cell = AppCell::new();
12730        let mut app = cell.borrow_mut();
12731        let harness = Harness::mount(
12732            &mut app,
12733            Directionality::new(
12734                TextDirection::Rtl,
12735                Semantics::new().label("test1").child(sized(10.0, 10.0)),
12736            )
12737            .into_widget(),
12738        );
12739        harness.pump(&mut app);
12740        let semantics = semantics_under_root(&harness, &app);
12741        assert_eq!(
12742            semantics.attributed_label(&app),
12743            Some(AttributedString::new("test1"))
12744        );
12745        assert_eq!(semantics.text_direction(&app), Some(TextDirection::Rtl));
12746    }
12747
12748    // semantics_test.dart: 'Semantics and Directionality - LTR'
12749    #[test]
12750    fn a_semantics_label_takes_the_ambient_ltr_direction() {
12751        let cell = AppCell::new();
12752        let mut app = cell.borrow_mut();
12753        let harness = Harness::mount(
12754            &mut app,
12755            Directionality::new(
12756                TextDirection::Ltr,
12757                Semantics::new().label("test1").child(sized(10.0, 10.0)),
12758            )
12759            .into_widget(),
12760        );
12761        harness.pump(&mut app);
12762        let semantics = semantics_under_root(&harness, &app);
12763        assert_eq!(
12764            semantics.attributed_label(&app),
12765            Some(AttributedString::new("test1"))
12766        );
12767        assert_eq!(semantics.text_direction(&app), Some(TextDirection::Ltr));
12768    }
12769
12770    // semantics_test.dart: 'Semantics and Directionality - cannot override RTL with LTR'
12771    #[test]
12772    fn a_semantics_text_direction_overrides_an_ambient_rtl() {
12773        let cell = AppCell::new();
12774        let mut app = cell.borrow_mut();
12775        let harness = Harness::mount(
12776            &mut app,
12777            Directionality::new(
12778                TextDirection::Rtl,
12779                Semantics::new()
12780                    .label("test1")
12781                    .text_direction(TextDirection::Ltr)
12782                    .child(sized(10.0, 10.0)),
12783            )
12784            .into_widget(),
12785        );
12786        harness.pump(&mut app);
12787        let semantics = semantics_under_root(&harness, &app);
12788        assert_eq!(semantics.text_direction(&app), Some(TextDirection::Ltr));
12789    }
12790
12791    // semantics_test.dart: 'Semantics and Directionality - cannot override LTR with RTL'
12792    #[test]
12793    fn a_semantics_text_direction_overrides_an_ambient_ltr() {
12794        let cell = AppCell::new();
12795        let mut app = cell.borrow_mut();
12796        let harness = Harness::mount(
12797            &mut app,
12798            Directionality::new(
12799                TextDirection::Ltr,
12800                Semantics::new()
12801                    .label("test1")
12802                    .text_direction(TextDirection::Rtl)
12803                    .child(sized(10.0, 10.0)),
12804            )
12805            .into_widget(),
12806        );
12807        harness.pump(&mut app);
12808        let semantics = semantics_under_root(&harness, &app);
12809        assert_eq!(semantics.text_direction(&app), Some(TextDirection::Rtl));
12810    }
12811
12812    #[test]
12813    fn a_semantics_without_text_takes_no_text_direction() {
12814        let cell = AppCell::new();
12815        let mut app = cell.borrow_mut();
12816        let harness = Harness::mount(
12817            &mut app,
12818            Directionality::new(
12819                TextDirection::Rtl,
12820                Semantics::new().button(true).child(sized(10.0, 10.0)),
12821            )
12822            .into_widget(),
12823        );
12824        harness.pump(&mut app);
12825        let semantics = semantics_under_root(&harness, &app);
12826        assert_eq!(semantics.text_direction(&app), None);
12827        assert_eq!(semantics.properties(&app).button, Some(true));
12828    }
12829
12830    // semantics_test.dart: 'Semantics excludeSemantics ignores children', and the tap and
12831    // long-press hints of 'onTapHint and onLongPressHint create custom actions', as stored.
12832    #[test]
12833    fn a_semantics_widget_hands_its_configuration_to_its_render_object() {
12834        let cell = AppCell::new();
12835        let mut app = cell.borrow_mut();
12836        let tapped = Rc::new(Cell::new(0));
12837        let on_tap: VoidCallback = {
12838            let tapped = tapped.clone();
12839            Rc::new(move |_app: &mut App| tapped.set(tapped.get() + 1))
12840        };
12841        let harness = Harness::mount(
12842            &mut app,
12843            Semantics::new()
12844                .container(true)
12845                .exclude_semantics(true)
12846                .label("label")
12847                .on_tap_hint("scan")
12848                .on_long_press_hint("fill")
12849                .on_tap(on_tap)
12850                .child(sized(10.0, 10.0))
12851                .into_widget(),
12852        );
12853        harness.pump(&mut app);
12854        let semantics = semantics_under_root(&harness, &app);
12855        assert!(semantics.container(&app));
12856        assert!(semantics.exclude_semantics(&app));
12857        assert!(!semantics.explicit_child_nodes(&app));
12858        assert!(!semantics.block_user_actions(&app));
12859        let properties = semantics.properties(&app);
12860        assert_eq!(
12861            properties.hint_overrides,
12862            Some(
12863                waft_rendering::SemanticsHintOverrides::new()
12864                    .on_tap_hint("scan")
12865                    .on_long_press_hint("fill")
12866            )
12867        );
12868        (properties.on_tap.clone().expect("the tap handler is kept"))(&mut app);
12869        assert_eq!(tapped.get(), 1);
12870
12871        harness.set_child(
12872            &mut app,
12873            Semantics::new()
12874                .block_user_actions(true)
12875                .child(sized(10.0, 10.0))
12876                .into_widget(),
12877        );
12878        harness.pump(&mut app);
12879        assert!(!semantics.container(&app));
12880        assert!(!semantics.exclude_semantics(&app));
12881        assert!(semantics.block_user_actions(&app));
12882        assert_eq!(semantics.attributed_label(&app), None);
12883        assert!(semantics.properties(&app).on_tap.is_none());
12884    }
12885
12886    #[test]
12887    fn a_semantics_render_object_keeps_the_same_properties_object() {
12888        let cell = AppCell::new();
12889        let mut app = cell.borrow_mut();
12890        let properties = Rc::new(SemanticsProperties::new().label("shared"));
12891        let harness = Harness::mount(
12892            &mut app,
12893            Semantics::from_properties(properties.clone())
12894                .child(sized(10.0, 10.0))
12895                .into_widget(),
12896        );
12897        harness.pump(&mut app);
12898        let semantics = semantics_under_root(&harness, &app);
12899        assert!(Rc::ptr_eq(&semantics.properties(&app), &properties));
12900    }
12901
12902    #[test]
12903    #[should_panic(expected = "Only one of hint or attributedHint should be provided")]
12904    fn a_semantics_widget_checks_its_properties_when_handed_over() {
12905        let _ = Semantics::new()
12906            .hint("a")
12907            .attributed_hint(AttributedString::new("a"))
12908            .into_widget();
12909    }
12910
12911    #[test]
12912    fn the_merge_block_exclude_and_indexed_semantics_widgets_configure_their_render_objects() {
12913        let cell = AppCell::new();
12914        let mut app = cell.borrow_mut();
12915        let harness = Harness::mount(
12916            &mut app,
12917            BlockSemantics::new().child(sized(10.0, 10.0)).into_widget(),
12918        );
12919        harness.pump(&mut app);
12920        let block = render_object_under_root::<RenderBlockSemantics>(&harness, &app);
12921        assert!(block.blocking(&app), "Dart's default");
12922        harness.set_child(
12923            &mut app,
12924            BlockSemantics::new()
12925                .blocking(false)
12926                .child(sized(10.0, 10.0))
12927                .into_widget(),
12928        );
12929        harness.pump(&mut app);
12930        assert!(!block.blocking(&app));
12931
12932        harness.set_child(
12933            &mut app,
12934            ExcludeSemantics::new()
12935                .child(sized(10.0, 10.0))
12936                .into_widget(),
12937        );
12938        harness.pump(&mut app);
12939        let exclude = render_object_under_root::<RenderExcludeSemantics>(&harness, &app);
12940        assert!(exclude.excluding(&app), "Dart's default");
12941        harness.set_child(
12942            &mut app,
12943            ExcludeSemantics::new()
12944                .excluding(false)
12945                .child(sized(10.0, 10.0))
12946                .into_widget(),
12947        );
12948        harness.pump(&mut app);
12949        assert!(!exclude.excluding(&app));
12950
12951        harness.set_child(
12952            &mut app,
12953            IndexedSemantics::new(2)
12954                .child(sized(10.0, 10.0))
12955                .into_widget(),
12956        );
12957        harness.pump(&mut app);
12958        let indexed = render_object_under_root::<RenderIndexedSemantics>(&harness, &app);
12959        assert_eq!(indexed.index(&app), 2);
12960        harness.set_child(
12961            &mut app,
12962            IndexedSemantics::new(5)
12963                .child(sized(10.0, 10.0))
12964                .into_widget(),
12965        );
12966        harness.pump(&mut app);
12967        assert_eq!(indexed.index(&app), 5);
12968
12969        harness.set_child(
12970            &mut app,
12971            MergeSemantics::new().child(sized(10.0, 10.0)).into_widget(),
12972        );
12973        harness.pump(&mut app);
12974        let _ = render_object_under_root::<RenderMergeSemantics>(&harness, &app);
12975    }
12976}
12977
12978#[cfg(test)]
12979mod diagnostics_tests {
12980    use waft_foundation::DiagnosticPropertiesBuilder;
12981
12982    use super::*;
12983    use crate::testing::describe_properties;
12984
12985    /// `basic_test.dart`, "ColoredBox - debugFillProperties".
12986    #[test]
12987    fn a_colored_box_puts_its_color_first() {
12988        let color = Color::new(0xFF00FF00);
12989        let colored = ColoredBox::new(color);
12990        let mut properties = DiagnosticPropertiesBuilder::new();
12991        let cell = waft_foundation::AppCell::new();
12992        let app = cell.borrow();
12993        colored.debug_fill_properties(&app, &mut properties);
12994        let value = properties
12995            .properties
12996            .first()
12997            .expect("a property")
12998            .value()
12999            .expect("a value");
13000        assert_eq!(value.downcast_ref::<Color>(), Some(&color));
13001    }
13002
13003    /// `basic_test.dart`, "Wrap implements debugFillProperties".
13004    #[test]
13005    fn a_wrap_describes_its_layout() {
13006        let wrap = Wrap::new()
13007            .spacing(8.0)
13008            .run_spacing(4.0)
13009            .text_direction(TextDirection::Ltr)
13010            .vertical_direction(VerticalDirection::Up);
13011        let cell = waft_foundation::AppCell::new();
13012        let app = cell.borrow();
13013        assert_eq!(
13014            describe_properties(|properties| wrap.debug_fill_properties(&app, properties)),
13015            [
13016                "direction: horizontal",
13017                "alignment: start",
13018                "spacing: 8.0",
13019                "runAlignment: start",
13020                "runSpacing: 4.0",
13021                "crossAxisAlignment: start",
13022                "textDirection: ltr",
13023                "verticalDirection: up",
13024            ]
13025        );
13026    }
13027}