Skip to main content

waft_rendering/
flex.rs

1//! Flutter counterpart: `rendering/flex.dart` (`FlexFit`, `FlexParentData`, `MainAxisSize`,
2//! `MainAxisAlignment`, `CrossAxisAlignment`, `RenderFlex`).
3
4use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::fmt::{self, Debug};
7use std::ops::Add;
8
9use waft_embedder::{Clip, Offset, Rect, Size, TextBaseline, TextDirection};
10use waft_foundation::{
11    App, DiagnosticPropertiesBuilder, DoubleProperty, EnumProperty, Handle,
12    PRECISION_ERROR_TOLERANCE, describe_enum, display_or_null,
13};
14use waft_painting::{Axis, VerticalDirection};
15
16use crate::box_::{
17    AnyRenderBox, BaselineOffset, BoxConstraints, BoxHitTestResult, BoxParentData,
18    ContainerBoxParentData, DryLayoutFailure, RenderBox, RenderBoxContainerDefaultsMixin,
19    RenderBoxData,
20};
21use crate::layer::{ClipRectLayer, LayerHandle};
22use crate::layout_helper::{ChildBaselineGetter, ChildLayoutHelper};
23use crate::object::{
24    AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectData,
25    ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, RenderObjectData,
26    debug_checking_intrinsics,
27};
28use crate::painting_context::PaintingContext;
29use crate::pipeline_owner::PipelineOwner;
30
31/// A 2D vector that uses a [`RenderFlex`]'s main axis and cross axis as its first and second
32/// coordinate axes. It represents the same vector as `(main_axis_extent, cross_axis_extent)`.
33#[derive(Clone, Copy)]
34struct AxisSize(Size);
35
36impl AxisSize {
37    const EMPTY: AxisSize = AxisSize(Size::ZERO);
38
39    fn new(main_axis_extent: f64, cross_axis_extent: f64) -> AxisSize {
40        AxisSize(Size::new(main_axis_extent, cross_axis_extent))
41    }
42
43    fn from_size(size: Size, direction: Axis) -> AxisSize {
44        AxisSize(AxisSize::convert(size, direction))
45    }
46
47    fn convert(size: Size, direction: Axis) -> Size {
48        match direction {
49            Axis::Horizontal => size,
50            Axis::Vertical => size.flipped(),
51        }
52    }
53
54    fn main_axis_extent(self) -> f64 {
55        self.0.width()
56    }
57
58    fn cross_axis_extent(self) -> f64 {
59        self.0.height()
60    }
61
62    fn to_size(self, direction: Axis) -> Size {
63        AxisSize::convert(self.0, direction)
64    }
65
66    fn apply_constraints(self, constraints: BoxConstraints, direction: Axis) -> AxisSize {
67        let effective_constraints = match direction {
68            Axis::Horizontal => constraints,
69            Axis::Vertical => constraints.flipped(),
70        };
71        AxisSize(effective_constraints.constrain(self.0))
72    }
73}
74
75impl Add for AxisSize {
76    type Output = AxisSize;
77
78    fn add(self, other: AxisSize) -> AxisSize {
79        AxisSize(Size::new(
80            self.0.width() + other.0.width(),
81            self.0.height().max(other.0.height()),
82        ))
83    }
84}
85
86/// The ascent and descent of a baseline-aligned child.
87///
88/// Baseline-aligned children contributes to the cross axis extent of a [`RenderFlex`]
89/// differently from children with other [`CrossAxisAlignment`]s.
90#[derive(Clone, Copy)]
91struct AscentDescent(Option<(f64, f64)>);
92
93impl AscentDescent {
94    const NONE: AscentDescent = AscentDescent(None);
95
96    fn new(baseline_offset: Option<f64>, cross_size: f64) -> AscentDescent {
97        match baseline_offset {
98            None => AscentDescent::NONE,
99            Some(baseline_offset) => {
100                AscentDescent(Some((baseline_offset, cross_size - baseline_offset)))
101            }
102        }
103    }
104
105    fn baseline_offset(self) -> Option<f64> {
106        self.0.map(|(ascent, _)| ascent)
107    }
108}
109
110impl Add for AscentDescent {
111    type Output = AscentDescent;
112
113    fn add(self, other: AscentDescent) -> AscentDescent {
114        match (self.0, other.0) {
115            (None, _) => other,
116            (_, None) => self,
117            (Some((x_ascent, x_descent)), Some((y_ascent, y_descent))) => {
118                AscentDescent(Some((x_ascent.max(y_ascent), x_descent.max(y_descent))))
119            }
120        }
121    }
122}
123
124/// Flutter's `_ChildSizingFunction`: a method that finds a child's size in the sizing
125/// direction, given the extent in the other direction.
126type ChildSizingFunction = fn(AnyRenderBox, &mut App, f64) -> f64;
127
128/// What [`RenderFlexMixin::compute_sizes`] worked out about a layout.
129pub struct LayoutSizes {
130    /// The final constrained [`AxisSize`] of the [`RenderFlex`].
131    axis_size: AxisSize,
132
133    /// The free space along the main axis. If the value is positive, the free space will be
134    /// distributed according to the [`MainAxisAlignment`] specified. A negative value indicates
135    /// the [`RenderFlex`] overflows along the main axis.
136    main_axis_free_space: f64,
137
138    /// `None` if the [`RenderFlex`] is not baseline aligned, or none of its children has a valid
139    /// baseline of the given [`TextBaseline`] type.
140    baseline_offset: Option<f64>,
141
142    /// The allocated space for flex children.
143    space_per_flex: Option<f64>,
144}
145
146/// How the child is inscribed into the available space.
147///
148/// See also:
149///
150///  * [`RenderFlex`], the flex render object.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub enum FlexFit {
153    /// The child is forced to fill the available space.
154    Tight,
155
156    /// The child can be at most as large as the available space (but is allowed to be smaller).
157    Loose,
158}
159
160/// Dart's enum `toString`: `FlexFit.tight`.
161impl fmt::Display for FlexFit {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        write!(f, "FlexFit.{}", describe_enum(self))
164    }
165}
166
167/// Parent data for use with [`RenderFlex`].
168#[derive(Debug)]
169pub struct FlexParentData {
170    box_parent_data: BoxParentData,
171    container_parent_data: ContainerParentData<AnyRenderBox>,
172
173    /// The flex factor to use for this child.
174    ///
175    /// If `None` or zero, the child is inflexible and determines its own size. If non-zero, the
176    /// amount of space the child's can occupy in the main axis is determined by dividing the
177    /// free space (after placing the inflexible children) according to the flex factors of the
178    /// flexible children.
179    pub flex: Option<i32>,
180
181    /// How a flexible child is inscribed into the available space.
182    ///
183    /// If [`flex`](Self::flex) is non-zero, the fit determines whether the child fills the space
184    /// the parent makes available during layout. If the fit is [`FlexFit::Tight`], the child is
185    /// required to fill the available space. If the fit is [`FlexFit::Loose`], the child can be
186    /// at most as large as the available space (but is allowed to be smaller).
187    pub fit: Option<FlexFit>,
188}
189
190impl FlexParentData {
191    /// Creates flex parent data with no flex factor and no fit.
192    pub const fn new() -> FlexParentData {
193        FlexParentData {
194            box_parent_data: BoxParentData::new(),
195            container_parent_data: ContainerParentData::new(),
196            flex: None,
197            fit: None,
198        }
199    }
200}
201
202impl Default for FlexParentData {
203    fn default() -> FlexParentData {
204        FlexParentData::new()
205    }
206}
207
208impl ParentData for FlexParentData {
209    fn detach(&mut self) {
210        ContainerParentDataMixin::detach(self);
211    }
212
213    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
214        if id == TypeId::of::<FlexParentData>() {
215            return Some(self);
216        }
217        self.box_parent_data.provide(id)
218    }
219
220    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
221        if id == TypeId::of::<FlexParentData>() {
222            return Some(self);
223        }
224        self.box_parent_data.provide_mut(id)
225    }
226}
227
228impl ContainerParentDataMixin for FlexParentData {
229    type ChildType = AnyRenderBox;
230
231    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
232        &self.container_parent_data
233    }
234
235    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
236        &mut self.container_parent_data
237    }
238}
239
240impl ContainerBoxParentData for FlexParentData {
241    fn box_parent_data(&self) -> &BoxParentData {
242        &self.box_parent_data
243    }
244
245    fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
246        &mut self.box_parent_data
247    }
248}
249
250impl fmt::Display for FlexParentData {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        write!(
253            f,
254            "{}; flex={}; fit={}",
255            self.box_parent_data,
256            display_or_null(&self.flex),
257            display_or_null(&self.fit)
258        )
259    }
260}
261
262/// How much space should be occupied in the main axis.
263///
264/// During a flex layout, available space along the main axis is allocated to children. After
265/// allocating space, there might be some remaining free space. This value controls whether to
266/// maximize or minimize the amount of free space, subject to the incoming layout constraints.
267///
268/// See also:
269///
270///  * [`RenderFlex`], the flex render object.
271///  * [`MainAxisAlignment`], which controls how the free space is distributed.
272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273pub enum MainAxisSize {
274    /// Minimize the amount of free space along the main axis, subject to the incoming layout
275    /// constraints.
276    ///
277    /// If the incoming layout constraints have a large enough [`BoxConstraints::min_width`] or
278    /// [`BoxConstraints::min_height`], there might still be a non-zero amount of free space.
279    ///
280    /// If the incoming layout constraints are unbounded, and any children have a non-zero
281    /// [`FlexParentData::flex`] and a [`FlexFit::Tight`] fit, the [`RenderFlex`] will assert,
282    /// because there would be infinite remaining free space and boxes cannot be given infinite
283    /// size.
284    Min,
285
286    /// Maximize the amount of free space along the main axis, subject to the incoming layout
287    /// constraints.
288    ///
289    /// If the incoming layout constraints have a small enough [`BoxConstraints::max_width`] or
290    /// [`BoxConstraints::max_height`], there might still be no free space.
291    ///
292    /// If the incoming layout constraints are unbounded, the [`RenderFlex`] will assert, because
293    /// there would be infinite remaining free space and boxes cannot be given infinite size.
294    Max,
295}
296
297/// How the children should be placed along the main axis in a flex layout.
298///
299/// See also:
300///
301///  * [`RenderFlex`], the flex render object.
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303pub enum MainAxisAlignment {
304    /// Place the children as close to the start of the main axis as possible.
305    ///
306    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available to
307    /// determine if the start is the left or the right.
308    ///
309    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
310    /// to determine if the start is the top or the bottom.
311    Start,
312
313    /// Place the children as close to the end of the main axis as possible.
314    ///
315    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available to
316    /// determine if the end is the left or the right.
317    ///
318    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
319    /// to determine if the end is the top or the bottom.
320    End,
321
322    /// Place the children as close to the middle of the main axis as possible.
323    Center,
324
325    /// Place the free space evenly between the children.
326    SpaceBetween,
327
328    /// Place the free space evenly between the children as well as half of that space before and
329    /// after the first and last child.
330    SpaceAround,
331
332    /// Place the free space evenly between the children as well as before and after the first
333    /// and last child.
334    SpaceEvenly,
335}
336
337impl MainAxisAlignment {
338    fn distribute_space(
339        self,
340        free_space: f64,
341        item_count: usize,
342        flipped: bool,
343        spacing: f64,
344    ) -> (f64, f64) {
345        let items = item_count as f64;
346        match self {
347            MainAxisAlignment::Start => {
348                if flipped {
349                    (free_space, spacing)
350                } else {
351                    (0.0, spacing)
352                }
353            }
354            MainAxisAlignment::End => {
355                MainAxisAlignment::Start.distribute_space(free_space, item_count, !flipped, spacing)
356            }
357            MainAxisAlignment::SpaceBetween if item_count < 2 => {
358                MainAxisAlignment::Start.distribute_space(free_space, item_count, flipped, spacing)
359            }
360            MainAxisAlignment::SpaceAround if item_count == 0 => {
361                MainAxisAlignment::Start.distribute_space(free_space, item_count, flipped, spacing)
362            }
363            MainAxisAlignment::Center => (free_space / 2.0, spacing),
364            MainAxisAlignment::SpaceBetween => (0.0, free_space / (items - 1.0) + spacing),
365            MainAxisAlignment::SpaceAround => {
366                (free_space / items / 2.0, free_space / items + spacing)
367            }
368            MainAxisAlignment::SpaceEvenly => (
369                free_space / (items + 1.0),
370                free_space / (items + 1.0) + spacing,
371            ),
372        }
373    }
374}
375
376/// How the children should be placed along the cross axis in a flex layout.
377///
378/// See also:
379///
380///  * [`RenderFlex`], the flex render object.
381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
382pub enum CrossAxisAlignment {
383    /// Place the children with their start edge aligned with the start side of the cross axis.
384    ///
385    /// For example, in a column (a flex with a vertical axis) whose [`TextDirection`] is
386    /// [`TextDirection::Ltr`], this aligns the left edge of the children along the left edge of
387    /// the column.
388    ///
389    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available to
390    /// determine if the start is the left or the right.
391    ///
392    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
393    /// to determine if the start is the top or the bottom.
394    Start,
395
396    /// Place the children as close to the end of the cross axis as possible.
397    ///
398    /// For example, in a column (a flex with a vertical axis) whose [`TextDirection`] is
399    /// [`TextDirection::Ltr`], this aligns the right edge of the children along the right edge
400    /// of the column.
401    ///
402    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available to
403    /// determine if the end is the left or the right.
404    ///
405    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
406    /// to determine if the end is the top or the bottom.
407    End,
408
409    /// Place the children so that their centers align with the middle of the cross axis.
410    ///
411    /// This is the default cross-axis alignment.
412    Center,
413
414    /// Require the children to fill the cross axis.
415    ///
416    /// This causes the constraints passed to the children to be tight in the cross axis.
417    Stretch,
418
419    /// Place the children along the cross axis such that their baselines match.
420    ///
421    /// Consider using this value for any horizontal main axis (as with a row) where the children
422    /// primarily contain text. If the different children have text with different font metrics
423    /// (for example because they differ in font size or other text style properties, or because
424    /// they use different fonts due to being written in different scripts), then this typically
425    /// produces better visual alignment than the other [`CrossAxisAlignment`] values, which use
426    /// no information about where the text sits vertically within its bounding box.
427    ///
428    /// The baseline of a widget is typically the typographic baseline of the first text in the
429    /// first text widget it encloses, if any. The typographic baseline is a horizontal line used
430    /// for aligning text, which is specified by each font; for alphabetic scripts, it ordinarily
431    /// runs along the bottom of letters excluding any descenders.
432    ///
433    /// Because baselines are always horizontal, this alignment is intended for horizontal main
434    /// axes (as with a row). If the main axis is vertical (as with a column), then this value is
435    /// treated like [`Start`](Self::Start).
436    ///
437    /// For horizontal main axes, if the minimum height constraint passed to the flex layout
438    /// exceeds the intrinsic height of the cross axis, children will be aligned as close to the
439    /// top as they can be while honoring the baseline alignment. In other words, the extra space
440    /// will be below all the children.
441    ///
442    /// Children who report no baseline will be top-aligned.
443    ///
444    /// See also:
445    ///
446    ///  * [`AnyRenderBox::get_distance_to_baseline`], which defines the baseline of a box.
447    Baseline,
448}
449
450impl CrossAxisAlignment {
451    /// This method should not be used to position baseline-aligned children.
452    fn get_child_cross_axis_offset(self, free_space: f64, flipped: bool) -> f64 {
453        match self {
454            CrossAxisAlignment::Stretch | CrossAxisAlignment::Baseline => 0.0,
455            CrossAxisAlignment::Start => {
456                if flipped {
457                    free_space
458                } else {
459                    0.0
460                }
461            }
462            CrossAxisAlignment::Center => free_space / 2.0,
463            CrossAxisAlignment::End => {
464                CrossAxisAlignment::Start.get_child_cross_axis_offset(free_space, !flipped)
465            }
466        }
467    }
468}
469
470/// The fields of a [`RenderFlex`].
471///
472/// A render object that inherits the flex layout holds this bag and implements
473/// [`RenderFlexMixin`].
474pub struct RenderFlexData {
475    direction: Axis,
476    main_axis_alignment: MainAxisAlignment,
477    main_axis_size: MainAxisSize,
478    cross_axis_alignment: CrossAxisAlignment,
479    text_direction: Option<TextDirection>,
480    vertical_direction: VerticalDirection,
481    text_baseline: Option<TextBaseline>,
482    clip_behavior: Clip,
483    spacing: f64,
484    /// Set during layout if overflow occurred on the main axis.
485    overflow: f64,
486    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
487}
488
489impl RenderFlexData {
490    /// Creates the flex fields with their defaults.
491    ///
492    /// The layout is horizontal and children are aligned to the start of the main axis and the
493    /// center of the cross axis.
494    pub fn new() -> RenderFlexData {
495        RenderFlexData {
496            direction: Axis::Horizontal,
497            main_axis_alignment: MainAxisAlignment::Start,
498            main_axis_size: MainAxisSize::Max,
499            cross_axis_alignment: CrossAxisAlignment::Center,
500            text_direction: None,
501            vertical_direction: VerticalDirection::Down,
502            text_baseline: None,
503            clip_behavior: Clip::None,
504            spacing: 0.0,
505            overflow: 0.0,
506            clip_rect_layer: LayerHandle::new(),
507        }
508    }
509}
510
511impl Default for RenderFlexData {
512    fn default() -> RenderFlexData {
513        RenderFlexData::new()
514    }
515}
516
517impl RenderFlexData {
518    /// Dart `RenderFlex(direction:)`.
519    pub fn direction(mut self, direction: Axis) -> RenderFlexData {
520        self.direction = direction;
521        self
522    }
523
524    /// Dart `RenderFlex(mainAxisAlignment:)`.
525    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> RenderFlexData {
526        self.main_axis_alignment = main_axis_alignment;
527        self
528    }
529
530    /// Dart `RenderFlex(mainAxisSize:)`.
531    pub fn main_axis_size(mut self, main_axis_size: MainAxisSize) -> RenderFlexData {
532        self.main_axis_size = main_axis_size;
533        self
534    }
535
536    /// Dart `RenderFlex(crossAxisAlignment:)`.
537    pub fn cross_axis_alignment(
538        mut self,
539        cross_axis_alignment: CrossAxisAlignment,
540    ) -> RenderFlexData {
541        self.cross_axis_alignment = cross_axis_alignment;
542        self
543    }
544
545    /// Dart `RenderFlex(textDirection:)`.
546    pub fn text_direction(mut self, text_direction: Option<TextDirection>) -> RenderFlexData {
547        self.text_direction = text_direction;
548        self
549    }
550
551    /// Dart `RenderFlex(verticalDirection:)`.
552    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> RenderFlexData {
553        self.vertical_direction = vertical_direction;
554        self
555    }
556
557    /// Dart `RenderFlex(textBaseline:)`.
558    pub fn text_baseline(mut self, text_baseline: Option<TextBaseline>) -> RenderFlexData {
559        self.text_baseline = text_baseline;
560        self
561    }
562
563    /// Dart `RenderFlex(clipBehavior:)`.
564    pub fn clip_behavior(mut self, clip_behavior: Clip) -> RenderFlexData {
565        self.clip_behavior = clip_behavior;
566        self
567    }
568
569    /// Dart `RenderFlex(spacing:)`.
570    pub fn spacing(mut self, spacing: f64) -> RenderFlexData {
571        self.spacing = spacing;
572        self
573    }
574}
575
576/// Displays its children in a one-dimensional array.
577///
578/// Flutter's `RenderFlex`: the shared bodies of the flex layout. A leaf holds a
579/// [`RenderFlexData`], implements this trait, and calls these where Dart would run the inherited
580/// method: `RenderFlexMixin::perform_layout(self, app)`.
581///
582/// See [`RenderFlex`] for the layout algorithm.
583pub trait RenderFlexMixin:
584    RenderBox
585    + ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType = FlexParentData>
586    + RenderBoxContainerDefaultsMixin
587{
588    /// Mixin field access.
589    fn flex_data(self: RenderHandle<Self>, app: &App) -> &RenderFlexData;
590
591    /// See [`flex_data`](Self::flex_data).
592    fn flex_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderFlexData;
593
594    /// Dart's `RenderFlex.debugFillProperties`, which a subclass of `RenderFlex` reaches through
595    /// its super call.
596    fn debug_fill_properties(
597        self: RenderHandle<Self>,
598        app: &App,
599        properties: &mut DiagnosticPropertiesBuilder,
600    ) {
601        let this = self.flex_data(app);
602        properties.add(EnumProperty::<Axis>::new("direction", this.direction));
603        properties.add(EnumProperty::<MainAxisAlignment>::new(
604            "mainAxisAlignment",
605            this.main_axis_alignment,
606        ));
607        properties.add(EnumProperty::<MainAxisSize>::new(
608            "mainAxisSize",
609            this.main_axis_size,
610        ));
611        properties.add(EnumProperty::<CrossAxisAlignment>::new(
612            "crossAxisAlignment",
613            this.cross_axis_alignment,
614        ));
615        properties.add(
616            EnumProperty::<TextDirection>::new("textDirection", this.text_direction)
617                .default_value(None),
618        );
619        properties.add(EnumProperty::<VerticalDirection>::new(
620            "verticalDirection",
621            Some(this.vertical_direction),
622        ));
623        properties.add(
624            EnumProperty::<TextBaseline>::new("textBaseline", this.text_baseline)
625                .default_value(None),
626        );
627        properties.add(DoubleProperty::new("spacing", this.spacing).default_value(None));
628    }
629
630    /// The direction to use as the main axis.
631    fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
632        self.flex_data(app).direction
633    }
634
635    /// Sets [`direction`](Self::direction).
636    fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
637        if self.flex_data(app).direction != value {
638            self.flex_data_mut(app).direction = value;
639            self.mark_needs_layout(app);
640        }
641    }
642
643    /// How the children should be placed along the main axis.
644    ///
645    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], and the alignment is either
646    /// [`MainAxisAlignment::Start`] or [`MainAxisAlignment::End`], then the
647    /// [`text_direction`](Self::text_direction) must not be `None`.
648    fn main_axis_alignment(self: RenderHandle<Self>, app: &App) -> MainAxisAlignment {
649        self.flex_data(app).main_axis_alignment
650    }
651
652    /// Sets [`main_axis_alignment`](Self::main_axis_alignment).
653    fn set_main_axis_alignment(self: RenderHandle<Self>, app: &mut App, value: MainAxisAlignment) {
654        if self.flex_data(app).main_axis_alignment != value {
655            self.flex_data_mut(app).main_axis_alignment = value;
656            self.mark_needs_layout(app);
657        }
658    }
659
660    /// How much space should be occupied in the main axis.
661    ///
662    /// After allocating space to children, there might be some remaining free space. This value
663    /// controls whether to maximize or minimize the amount of free space, subject to the incoming
664    /// layout constraints.
665    fn main_axis_size(self: RenderHandle<Self>, app: &App) -> MainAxisSize {
666        self.flex_data(app).main_axis_size
667    }
668
669    /// Sets [`main_axis_size`](Self::main_axis_size).
670    fn set_main_axis_size(self: RenderHandle<Self>, app: &mut App, value: MainAxisSize) {
671        if self.flex_data(app).main_axis_size != value {
672            self.flex_data_mut(app).main_axis_size = value;
673            self.mark_needs_layout(app);
674        }
675    }
676
677    /// How the children should be placed along the cross axis.
678    ///
679    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], and the alignment is either
680    /// [`CrossAxisAlignment::Start`] or [`CrossAxisAlignment::End`], then the
681    /// [`text_direction`](Self::text_direction) must not be `None`.
682    fn cross_axis_alignment(self: RenderHandle<Self>, app: &App) -> CrossAxisAlignment {
683        self.flex_data(app).cross_axis_alignment
684    }
685
686    /// Sets [`cross_axis_alignment`](Self::cross_axis_alignment).
687    fn set_cross_axis_alignment(
688        self: RenderHandle<Self>,
689        app: &mut App,
690        value: CrossAxisAlignment,
691    ) {
692        if self.flex_data(app).cross_axis_alignment != value {
693            self.flex_data_mut(app).cross_axis_alignment = value;
694            self.mark_needs_layout(app);
695        }
696    }
697
698    /// Determines the order to lay children out horizontally and how to interpret `start` and
699    /// `end` in the horizontal direction.
700    ///
701    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the order in
702    /// which children are positioned (left-to-right or right-to-left), and the meaning of the
703    /// [`main_axis_alignment`](Self::main_axis_alignment) property's
704    /// [`MainAxisAlignment::Start`] and [`MainAxisAlignment::End`] values.
705    ///
706    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls the meaning of
707    /// the [`cross_axis_alignment`](Self::cross_axis_alignment) property's
708    /// [`CrossAxisAlignment::Start`] and [`CrossAxisAlignment::End`] values.
709    fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
710        self.flex_data(app).text_direction
711    }
712
713    /// Sets [`text_direction`](Self::text_direction).
714    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: Option<TextDirection>) {
715        if self.flex_data(app).text_direction != value {
716            self.flex_data_mut(app).text_direction = value;
717            self.mark_needs_layout(app);
718        }
719    }
720
721    /// Determines the order to lay children out vertically and how to interpret `start` and `end`
722    /// in the vertical direction.
723    ///
724    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls which order
725    /// children are painted in (down or up), and the meaning of the
726    /// [`main_axis_alignment`](Self::main_axis_alignment) property's
727    /// [`MainAxisAlignment::Start`] and [`MainAxisAlignment::End`] values.
728    ///
729    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the meaning
730    /// of the [`cross_axis_alignment`](Self::cross_axis_alignment) property's
731    /// [`CrossAxisAlignment::Start`] and [`CrossAxisAlignment::End`] values.
732    fn vertical_direction(self: RenderHandle<Self>, app: &App) -> VerticalDirection {
733        self.flex_data(app).vertical_direction
734    }
735
736    /// Sets [`vertical_direction`](Self::vertical_direction).
737    fn set_vertical_direction(self: RenderHandle<Self>, app: &mut App, value: VerticalDirection) {
738        if self.flex_data(app).vertical_direction != value {
739            self.flex_data_mut(app).vertical_direction = value;
740            self.mark_needs_layout(app);
741        }
742    }
743
744    /// If aligning items according to their baseline, which baseline to use.
745    ///
746    /// Must not be `None` if [`cross_axis_alignment`](Self::cross_axis_alignment) is
747    /// [`CrossAxisAlignment::Baseline`].
748    fn text_baseline(self: RenderHandle<Self>, app: &App) -> Option<TextBaseline> {
749        self.flex_data(app).text_baseline
750    }
751
752    /// Sets [`text_baseline`](Self::text_baseline).
753    fn set_text_baseline(self: RenderHandle<Self>, app: &mut App, value: Option<TextBaseline>) {
754        debug_assert!(
755            self.flex_data(app).cross_axis_alignment != CrossAxisAlignment::Baseline
756                || value.is_some()
757        );
758        if self.flex_data(app).text_baseline != value {
759            self.flex_data_mut(app).text_baseline = value;
760            self.mark_needs_layout(app);
761        }
762    }
763
764    /// Whether the flex overflowed along the main axis.
765    ///
766    /// Values below an epsilon are treated as not overflowing. Internal to the flex layout; a
767    /// leaf does not republish it.
768    fn has_overflow(self: RenderHandle<Self>, app: &App) -> bool {
769        self.flex_data(app).overflow > PRECISION_ERROR_TOLERANCE
770    }
771
772    /// How to clip the children that overflow along the main axis.
773    ///
774    /// Defaults to [`Clip::None`].
775    fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
776        self.flex_data(app).clip_behavior
777    }
778
779    /// Sets [`clip_behavior`](Self::clip_behavior).
780    fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
781        if value != self.flex_data(app).clip_behavior {
782            self.flex_data_mut(app).clip_behavior = value;
783            self.mark_needs_paint(app);
784        }
785    }
786
787    /// How much space to place between children in the main axis.
788    ///
789    /// The spacing is only applied between children in the main axis: not before the first child
790    /// or after the last one. When it is non-zero, the layout size will be larger than the sum of
791    /// the children's layout sizes in the main axis, and the children overflow when their sizes
792    /// plus the total spacing exceed the maximum main axis constraint.
793    ///
794    /// Defaults to 0.0.
795    fn spacing(self: RenderHandle<Self>, app: &App) -> f64 {
796        self.flex_data(app).spacing
797    }
798
799    /// Sets [`spacing`](Self::spacing).
800    fn set_spacing(self: RenderHandle<Self>, app: &mut App, value: f64) {
801        debug_assert!(value >= 0.0);
802        if self.flex_data(app).spacing == value {
803            return;
804        }
805        self.flex_data_mut(app).spacing = value;
806        self.mark_needs_layout(app);
807    }
808
809    /// Flutter's `_debugHasNecessaryDirections`: asserts the directions the current alignment
810    /// needs are available. Always returns true. Internal to the flex layout.
811    fn debug_has_necessary_directions(self: RenderHandle<Self>, app: &App) -> bool {
812        if debug_checking_intrinsics() {
813            return true;
814        }
815        let direction = self.direction(app);
816        if self.first_child(app).is_some() && self.last_child(app) != self.first_child(app) {
817            // i.e. there's more than one child
818            if direction == Axis::Horizontal {
819                debug_assert!(
820                    self.text_direction(app).is_some(),
821                    "Horizontal RenderFlex with multiple children has a null textDirection, so \
822                     the layout order is undefined."
823                );
824            }
825        }
826        let main_axis_alignment = self.main_axis_alignment(app);
827        if (main_axis_alignment == MainAxisAlignment::Start
828            || main_axis_alignment == MainAxisAlignment::End)
829            && direction == Axis::Horizontal
830        {
831            debug_assert!(
832                self.text_direction(app).is_some(),
833                "Horizontal RenderFlex with {main_axis_alignment:?} has a null textDirection, so \
834                 the alignment cannot be resolved."
835            );
836        }
837        let cross_axis_alignment = self.cross_axis_alignment(app);
838        if (cross_axis_alignment == CrossAxisAlignment::Start
839            || cross_axis_alignment == CrossAxisAlignment::End)
840            && direction == Axis::Vertical
841        {
842            debug_assert!(
843                self.text_direction(app).is_some(),
844                "Vertical RenderFlex with {cross_axis_alignment:?} has a null textDirection, so \
845                 the alignment cannot be resolved."
846            );
847        }
848        true
849    }
850
851    /// Whether the children are placed on a shared baseline: a [`CrossAxisAlignment::Baseline`]
852    /// along a horizontal main axis. Internal to the flex layout.
853    fn is_baseline_aligned(self: RenderHandle<Self>, app: &App) -> bool {
854        match self.cross_axis_alignment(app) {
855            CrossAxisAlignment::Baseline => match self.direction(app) {
856                Axis::Horizontal => true,
857                Axis::Vertical => false,
858            },
859            CrossAxisAlignment::Start
860            | CrossAxisAlignment::Center
861            | CrossAxisAlignment::End
862            | CrossAxisAlignment::Stretch => false,
863        }
864    }
865
866    /// The extent of `size` along the cross axis. Internal to the flex layout.
867    fn get_cross_size(self: RenderHandle<Self>, app: &App, size: Size) -> f64 {
868        match self.direction(app) {
869            Axis::Horizontal => size.height(),
870            Axis::Vertical => size.width(),
871        }
872    }
873
874    /// The extent of `size` along the main axis. Internal to the flex layout.
875    fn get_main_size(self: RenderHandle<Self>, app: &App, size: Size) -> f64 {
876        match self.direction(app) {
877            Axis::Horizontal => size.width(),
878            Axis::Vertical => size.height(),
879        }
880    }
881
882    /// Whether to lay out left-to-right / top-to-bottom (`false`), or right-to-left /
883    /// bottom-to-top (`true`). `false` when the layout direction does not matter (for instance,
884    /// there is no child). Internal to the flex layout.
885    fn flip_main_axis(self: RenderHandle<Self>, app: &App) -> bool {
886        self.first_child(app).is_some()
887            && match self.direction(app) {
888                Axis::Horizontal => self.text_direction(app) == Some(TextDirection::Rtl),
889                Axis::Vertical => self.vertical_direction(app) == VerticalDirection::Up,
890            }
891    }
892
893    /// The cross axis counterpart of [`flip_main_axis`](Self::flip_main_axis). Internal to the
894    /// flex layout.
895    fn flip_cross_axis(self: RenderHandle<Self>, app: &App) -> bool {
896        self.first_child(app).is_some()
897            && match self.direction(app) {
898                Axis::Vertical => self.text_direction(app) == Some(TextDirection::Rtl),
899                Axis::Horizontal => self.vertical_direction(app) == VerticalDirection::Up,
900            }
901    }
902
903    /// The constraints an inflexible child is laid out with. Internal to the flex layout.
904    fn constraints_for_non_flex_child(
905        self: RenderHandle<Self>,
906        app: &App,
907        constraints: BoxConstraints,
908    ) -> BoxConstraints {
909        let fill_cross_axis = self.cross_axis_alignment(app) == CrossAxisAlignment::Stretch;
910        match self.direction(app) {
911            Axis::Horizontal => {
912                if fill_cross_axis {
913                    BoxConstraints::tight_for(None, Some(constraints.max_height))
914                } else {
915                    BoxConstraints::new().max_height(constraints.max_height)
916                }
917            }
918            Axis::Vertical => {
919                if fill_cross_axis {
920                    BoxConstraints::tight_for(Some(constraints.max_width), None)
921                } else {
922                    BoxConstraints::new().max_width(constraints.max_width)
923                }
924            }
925        }
926    }
927
928    /// The constraints a flexible child is laid out with, given the main axis extent it was
929    /// allocated. Internal to the flex layout.
930    fn constraints_for_flex_child(
931        self: RenderHandle<Self>,
932        app: &App,
933        child: AnyRenderBox,
934        constraints: BoxConstraints,
935        max_child_extent: f64,
936    ) -> BoxConstraints {
937        debug_assert!(get_flex(app, child) > 0);
938        debug_assert!(max_child_extent >= 0.0);
939        let min_child_extent = match get_fit(app, child) {
940            FlexFit::Tight => max_child_extent,
941            FlexFit::Loose => 0.0,
942        };
943        let fill_cross_axis = self.cross_axis_alignment(app) == CrossAxisAlignment::Stretch;
944        match self.direction(app) {
945            Axis::Horizontal => BoxConstraints {
946                min_width: min_child_extent,
947                max_width: max_child_extent,
948                min_height: if fill_cross_axis {
949                    constraints.max_height
950                } else {
951                    0.0
952                },
953                max_height: constraints.max_height,
954            },
955            Axis::Vertical => BoxConstraints {
956                min_width: if fill_cross_axis {
957                    constraints.max_width
958                } else {
959                    0.0
960                },
961                max_width: constraints.max_width,
962                min_height: min_child_extent,
963                max_height: max_child_extent,
964            },
965        }
966    }
967
968    /// Flutter's `_getIntrinsicSize`: the intrinsic extent along `sizing_direction`, given the
969    /// `extent` in the other direction and a `child_size` that measures one child. Internal to
970    /// the flex layout.
971    fn get_intrinsic_size(
972        self: RenderHandle<Self>,
973        app: &mut App,
974        sizing_direction: Axis,
975        extent: f64,
976        child_size: ChildSizingFunction,
977    ) -> f64 {
978        let direction = self.direction(app);
979        if direction == sizing_direction {
980            // INTRINSIC MAIN SIZE
981            // Intrinsic main size is the smallest size the flex container can take while
982            // maintaining the min/max-content contributions of its flex items.
983            let mut total_flex = 0.0;
984            let mut inflexible_space = self.spacing(app) * (self.child_count(app) as f64 - 1.0);
985            let mut max_flex_fraction_so_far: f64 = 0.0;
986            let mut child = self.first_child(app);
987            while let Some(current) = child {
988                let flex = get_flex(app, current);
989                total_flex += f64::from(flex);
990                if flex > 0 {
991                    let flex_fraction = child_size(current, app, extent) / f64::from(flex);
992                    max_flex_fraction_so_far = max_flex_fraction_so_far.max(flex_fraction);
993                } else {
994                    inflexible_space += child_size(current, app, extent);
995                }
996                child = self.child_after(app, current);
997            }
998            return max_flex_fraction_so_far * total_flex + inflexible_space;
999        }
1000
1001        // INTRINSIC CROSS SIZE
1002        // Intrinsic cross size is the max of the intrinsic cross sizes of the children, after
1003        // the flexible children are fit into the available space, with the children sized using
1004        // their max intrinsic dimensions.
1005        let is_horizontal = direction == Axis::Horizontal;
1006        let layout_child = |app: &mut App, child: AnyRenderBox, constraints: BoxConstraints| {
1007            let main_axis_size_from_constraints = if is_horizontal {
1008                constraints.max_width
1009            } else {
1010                constraints.max_height
1011            };
1012            // An infinite main_axis_size_from_constraints means this child is flexible (or
1013            // extent is infinite).
1014            debug_assert_eq!(
1015                get_flex(app, child) != 0 && extent.is_finite(),
1016                main_axis_size_from_constraints.is_finite()
1017            );
1018            let max_main_axis_size = if main_axis_size_from_constraints.is_finite() {
1019                main_axis_size_from_constraints
1020            } else if is_horizontal {
1021                child.get_max_intrinsic_width(app, f64::INFINITY)
1022            } else {
1023                child.get_max_intrinsic_height(app, f64::INFINITY)
1024            };
1025            let cross_size = child_size(child, app, max_main_axis_size);
1026            if is_horizontal {
1027                Size::new(max_main_axis_size, cross_size)
1028            } else {
1029                Size::new(cross_size, max_main_axis_size)
1030            }
1031        };
1032        let constraints = if is_horizontal {
1033            BoxConstraints::new().max_width(extent)
1034        } else {
1035            BoxConstraints::new().max_height(extent)
1036        };
1037        self.compute_sizes(
1038            app,
1039            constraints,
1040            layout_child,
1041            ChildLayoutHelper::get_dry_baseline,
1042        )
1043        .axis_size
1044        .cross_axis_extent()
1045    }
1046
1047    /// Flutter's `_debugCheckConstraints`: the error to report when a child has a non-zero flex
1048    /// factor while the incoming main axis constraint is unbounded and that child would have to
1049    /// fill it, or `None` when the constraints are usable. Internal to the flex layout.
1050    fn debug_check_constraints(
1051        self: RenderHandle<Self>,
1052        app: &App,
1053        constraints: BoxConstraints,
1054    ) -> Option<String> {
1055        let direction = self.direction(app);
1056        let max_main_size = match direction {
1057            Axis::Horizontal => constraints.max_width,
1058            Axis::Vertical => constraints.max_height,
1059        };
1060        let can_flex = max_main_size < f64::INFINITY;
1061        let mut child = self.first_child(app);
1062        while let Some(current) = child {
1063            if get_flex(app, current) > 0
1064                && !can_flex
1065                && (self.main_axis_size(app) == MainAxisSize::Max
1066                    || get_fit(app, current) == FlexFit::Tight)
1067            {
1068                let (identity, axis, dimension) = match direction {
1069                    Axis::Horizontal => ("row", "horizontal", "width"),
1070                    Axis::Vertical => ("column", "vertical", "height"),
1071                };
1072                return Some(format!(
1073                    "RenderFlex children have non-zero flex but incoming {dimension} constraints \
1074                     are unbounded.\n\
1075                     When a {identity} is in a parent that does not provide a finite {dimension} \
1076                     constraint, for example if it is in a {axis} scrollable, it will try to \
1077                     shrink-wrap its children along the {axis} axis. Setting a flex on a child \
1078                     (e.g. using Expanded) indicates that the child is to expand to fill the \
1079                     remaining space in the {axis} direction.\n\
1080                     These two directives are mutually exclusive. If a parent is to shrink-wrap \
1081                     its child, the child cannot simultaneously expand to fit its parent.\n\
1082                     Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose \
1083                     fits for the flexible children (using Flexible rather than Expanded). This \
1084                     will allow the flexible children to size themselves to less than the \
1085                     infinite remaining space they would otherwise be forced to take, and then \
1086                     will cause the RenderFlex to shrink-wrap the children rather than expanding \
1087                     to fit the maximum constraints provided by the parent."
1088                ));
1089            }
1090            child = self.child_after(app, current);
1091        }
1092        None
1093    }
1094
1095    /// Flutter's `_computeSizes`: measures the children with `layout_child`, reads their
1096    /// baselines with `get_baseline` when they are baseline aligned, and works out this flex's
1097    /// own size. Internal to the flex layout.
1098    ///
1099    /// # Panics
1100    ///
1101    /// If the children are baseline aligned and [`text_baseline`](Self::text_baseline) is `None`.
1102    fn compute_sizes(
1103        self: RenderHandle<Self>,
1104        app: &mut App,
1105        constraints: BoxConstraints,
1106        mut layout_child: impl FnMut(&mut App, AnyRenderBox, BoxConstraints) -> Size,
1107        get_baseline: ChildBaselineGetter,
1108    ) -> LayoutSizes {
1109        debug_assert!(self.debug_has_necessary_directions(app));
1110
1111        // Determine used flex factor, size inflexible items, calculate free space.
1112        let direction = self.direction(app);
1113        let max_main_size = self.get_main_size(app, constraints.biggest());
1114        let can_flex = max_main_size.is_finite();
1115        let non_flex_child_constraints = self.constraints_for_non_flex_child(app, constraints);
1116        // None indicates the children are not baseline aligned.
1117        let text_baseline = if self.is_baseline_aligned(app) {
1118            Some(self.text_baseline(app).expect(
1119                "To use CrossAxisAlignment.baseline, you must also specify which baseline to use \
1120                 using the \"textBaseline\" argument.",
1121            ))
1122        } else {
1123            None
1124        };
1125
1126        // The first pass lays out non-flex children and computes total flex.
1127        let mut total_flex = 0;
1128        let mut first_flex_child: Option<AnyRenderBox> = None;
1129        let mut accumulated_ascent_descent = AscentDescent::NONE;
1130        // Initially, accumulated_size is the sum of the spaces between children in the main axis.
1131        let mut accumulated_size = AxisSize::new(
1132            self.spacing(app) * (self.child_count(app) as f64 - 1.0),
1133            0.0,
1134        );
1135        let mut child = self.first_child(app);
1136        while let Some(current) = child {
1137            let flex = get_flex(app, current);
1138            if can_flex && flex > 0 {
1139                total_flex += flex;
1140                first_flex_child.get_or_insert(current);
1141            } else {
1142                let child_size = AxisSize::from_size(
1143                    layout_child(app, current, non_flex_child_constraints),
1144                    direction,
1145                );
1146                accumulated_size = accumulated_size + child_size;
1147                // Baseline-aligned children contributes to the cross axis extent separately.
1148                let baseline_offset = text_baseline.and_then(|text_baseline| {
1149                    get_baseline(app, current, non_flex_child_constraints, text_baseline)
1150                });
1151                accumulated_ascent_descent = accumulated_ascent_descent
1152                    + AscentDescent::new(baseline_offset, child_size.cross_axis_extent());
1153            }
1154            child = self.child_after(app, current);
1155        }
1156
1157        debug_assert_eq!(total_flex == 0, first_flex_child.is_none());
1158        // If we are given infinite space there's no need for this extra step.
1159        debug_assert!(first_flex_child.is_none() || can_flex);
1160
1161        // The second pass distributes free space to flexible children.
1162        let flex_space = (max_main_size - accumulated_size.main_axis_extent()).max(0.0);
1163        let space_per_flex = flex_space / total_flex as f64;
1164        let mut child = first_flex_child;
1165        while let Some(current) = child {
1166            if total_flex == 0 {
1167                break;
1168            }
1169            let flex = get_flex(app, current);
1170            if flex != 0 {
1171                total_flex -= flex;
1172                debug_assert!(space_per_flex.is_finite());
1173                let max_child_extent = space_per_flex * f64::from(flex);
1174                debug_assert!(
1175                    get_fit(app, current) == FlexFit::Loose || max_child_extent < f64::INFINITY
1176                );
1177                let child_constraints =
1178                    self.constraints_for_flex_child(app, current, constraints, max_child_extent);
1179                let child_size =
1180                    AxisSize::from_size(layout_child(app, current, child_constraints), direction);
1181                accumulated_size = accumulated_size + child_size;
1182                let baseline_offset = text_baseline.and_then(|text_baseline| {
1183                    get_baseline(app, current, child_constraints, text_baseline)
1184                });
1185                accumulated_ascent_descent = accumulated_ascent_descent
1186                    + AscentDescent::new(baseline_offset, child_size.cross_axis_extent());
1187            }
1188            child = self.child_after(app, current);
1189        }
1190        debug_assert_eq!(total_flex, 0);
1191
1192        // The overall height of baseline-aligned children contributes to the cross axis extent.
1193        accumulated_size = accumulated_size
1194            + match accumulated_ascent_descent.0 {
1195                None => AxisSize::EMPTY,
1196                Some((ascent, descent)) => AxisSize::new(0.0, ascent + descent),
1197            };
1198
1199        let ideal_main_size = match self.main_axis_size(app) {
1200            MainAxisSize::Max if max_main_size.is_finite() => max_main_size,
1201            MainAxisSize::Max | MainAxisSize::Min => accumulated_size.main_axis_extent(),
1202        };
1203
1204        let constrained_size = AxisSize::new(ideal_main_size, accumulated_size.cross_axis_extent())
1205            .apply_constraints(constraints, direction);
1206        let space_per_flex = first_flex_child.map(|_| space_per_flex);
1207        debug_assert!(space_per_flex.is_none_or(f64::is_finite));
1208        LayoutSizes {
1209            axis_size: constrained_size,
1210            main_axis_free_space: constrained_size.main_axis_extent()
1211                - accumulated_size.main_axis_extent(),
1212            baseline_offset: accumulated_ascent_descent.baseline_offset(),
1213            space_per_flex,
1214        }
1215    }
1216
1217    /// Sizes this flex and positions its children; see [`RenderFlex`] for the algorithm.
1218    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1219        let constraints = self.constraints(app);
1220        if cfg!(debug_assertions)
1221            && let Some(error) = self.debug_check_constraints(app, constraints)
1222        {
1223            panic!("{error}");
1224        }
1225
1226        let sizes = self.compute_sizes(
1227            app,
1228            constraints,
1229            ChildLayoutHelper::layout_child,
1230            ChildLayoutHelper::get_baseline,
1231        );
1232
1233        let direction = self.direction(app);
1234        let cross_axis_extent = sizes.axis_size.cross_axis_extent();
1235        self.set_size(app, sizes.axis_size.to_size(direction));
1236        self.flex_data_mut(app).overflow = (-sizes.main_axis_free_space).max(0.0);
1237
1238        let remaining_space = sizes.main_axis_free_space.max(0.0);
1239        let flip_main_axis = self.flip_main_axis(app);
1240        let flip_cross_axis = self.flip_cross_axis(app);
1241        let cross_axis_alignment = self.cross_axis_alignment(app);
1242        let (leading_space, between_space) = self.main_axis_alignment(app).distribute_space(
1243            remaining_space,
1244            self.child_count(app),
1245            flip_main_axis,
1246            self.spacing(app),
1247        );
1248        let top_left_child = if flip_main_axis {
1249            self.last_child(app)
1250        } else {
1251            self.first_child(app)
1252        };
1253        let baseline_offset = sizes.baseline_offset;
1254        debug_assert!(
1255            baseline_offset.is_none()
1256                || (cross_axis_alignment == CrossAxisAlignment::Baseline
1257                    && direction == Axis::Horizontal)
1258        );
1259        let text_baseline = self.text_baseline(app);
1260
1261        // Position all children in visual order: starting from the top-left child and work
1262        // towards the child that's farthest away from the origin.
1263        let mut child_main_position = leading_space;
1264        let mut child = top_left_child;
1265        while let Some(current) = child {
1266            let child_baseline_offset = match baseline_offset {
1267                Some(_) => current.get_distance_to_baseline(
1268                    app,
1269                    text_baseline.expect("a baseline-aligned flex has a text baseline"),
1270                    true,
1271                ),
1272                None => None,
1273            };
1274            let child_size = current.size(app);
1275            let free_cross_space = cross_axis_extent - self.get_cross_size(app, child_size);
1276            let child_cross_position = if let (Some(baseline_offset), Some(child_baseline_offset)) =
1277                (baseline_offset, child_baseline_offset)
1278            {
1279                baseline_offset - child_baseline_offset
1280            } else if cross_axis_alignment == CrossAxisAlignment::Baseline
1281                && direction == Axis::Horizontal
1282            {
1283                // In a baseline-aligned horizontal flex, a child without a baseline is aligned to
1284                // the top of the cross axis (dy = 0), regardless of verticalDirection or
1285                // crossAxisAlignment. That is, we intentionally ignore flip_cross_axis here.
1286                CrossAxisAlignment::Start.get_child_cross_axis_offset(free_cross_space, false)
1287            } else {
1288                // Non-baseline alignment respects the configured cross_axis_alignment.
1289                cross_axis_alignment.get_child_cross_axis_offset(free_cross_space, flip_cross_axis)
1290            };
1291            let offset = match direction {
1292                Axis::Horizontal => Offset::new(child_main_position, child_cross_position),
1293                Axis::Vertical => Offset::new(child_cross_position, child_main_position),
1294            };
1295            current
1296                .parent_data_of_mut::<FlexParentData>(app)
1297                .set_offset(offset);
1298            child_main_position += self.get_main_size(app, child_size) + between_space;
1299            child = if flip_main_axis {
1300                self.child_before(app, current)
1301            } else {
1302                self.child_after(app, current)
1303            };
1304        }
1305    }
1306
1307    /// Paints the children, clipping them to this flex when they overflow the main axis.
1308    fn paint(
1309        self: RenderHandle<Self>,
1310        app: &mut App,
1311        context: &mut PaintingContext,
1312        offset: Offset,
1313    ) {
1314        if !self.has_overflow(app) {
1315            self.default_paint(app, context, offset);
1316            return;
1317        }
1318
1319        // There's no point in drawing the children if we're empty.
1320        let size = self.size(app);
1321        if size.is_empty() {
1322            return;
1323        }
1324
1325        let clip_behavior = self.clip_behavior(app);
1326        let old = self.flex_data(app).clip_rect_layer.layer();
1327        let layer = context.push_clip_rect(
1328            app,
1329            self.as_object().needs_compositing(app),
1330            offset,
1331            Offset::ZERO & size,
1332            |app, context, offset| self.default_paint(app, context, offset),
1333            clip_behavior,
1334            old,
1335        );
1336        LayerHandle::set_layer(
1337            app,
1338            |app| &mut self.flex_data_mut(app).clip_rect_layer,
1339            layer,
1340        );
1341    }
1342
1343    /// Flutter's `dispose`: drop the clip layer handle, then `super.dispose()`.
1344    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1345        LayerHandle::set_layer(
1346            app,
1347            |app| &mut self.flex_data_mut(app).clip_rect_layer,
1348            None,
1349        );
1350        crate::object::RenderObjectBase::dispose(self, app);
1351    }
1352
1353    /// Dart's `describeApproximatePaintClip`: the main axis overflow is clipped to the flex's
1354    /// bounds, and only when it overflowed.
1355    fn describe_approximate_paint_clip(
1356        self: RenderHandle<Self>,
1357        app: &App,
1358        _child: AnyRenderObject,
1359    ) -> Option<Rect> {
1360        match self.clip_behavior(app) {
1361            Clip::None => None,
1362            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => self
1363                .has_overflow(app)
1364                .then(|| Offset::ZERO & self.size(app)),
1365        }
1366    }
1367
1368    /// A flex child gets a [`FlexParentData`].
1369    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1370        if !child.parent_data_is::<FlexParentData>(app) {
1371            child.set_parent_data(app, FlexParentData::new());
1372        }
1373    }
1374
1375    /// The minimum intrinsic width of the children laid out in a flex.
1376    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1377        self.get_intrinsic_size(
1378            app,
1379            Axis::Horizontal,
1380            height,
1381            AnyRenderBox::get_min_intrinsic_width,
1382        )
1383    }
1384
1385    /// The maximum intrinsic width of the children laid out in a flex.
1386    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1387        self.get_intrinsic_size(
1388            app,
1389            Axis::Horizontal,
1390            height,
1391            AnyRenderBox::get_max_intrinsic_width,
1392        )
1393    }
1394
1395    /// The minimum intrinsic height of the children laid out in a flex.
1396    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1397        self.get_intrinsic_size(
1398            app,
1399            Axis::Vertical,
1400            width,
1401            AnyRenderBox::get_min_intrinsic_height,
1402        )
1403    }
1404
1405    /// The maximum intrinsic height of the children laid out in a flex.
1406    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1407        self.get_intrinsic_size(
1408            app,
1409            Axis::Vertical,
1410            width,
1411            AnyRenderBox::get_max_intrinsic_height,
1412        )
1413    }
1414
1415    /// A row's highest child baseline, or a column's first child baseline.
1416    fn compute_distance_to_actual_baseline(
1417        self: RenderHandle<Self>,
1418        app: &mut App,
1419        baseline: TextBaseline,
1420    ) -> Option<f64> {
1421        match self.direction(app) {
1422            Axis::Horizontal => {
1423                self.default_compute_distance_to_highest_actual_baseline(app, baseline)
1424            }
1425            Axis::Vertical => self.default_compute_distance_to_first_actual_baseline(app, baseline),
1426        }
1427    }
1428
1429    /// The baseline [`compute_distance_to_actual_baseline`](Self::compute_distance_to_actual_baseline)
1430    /// would answer, measuring the children dry; a baseline-aligned flex answers its shared
1431    /// baseline.
1432    fn compute_dry_baseline(
1433        self: RenderHandle<Self>,
1434        app: &mut App,
1435        constraints: BoxConstraints,
1436        baseline: TextBaseline,
1437    ) -> Option<f64> {
1438        let sizes = self.compute_sizes(
1439            app,
1440            constraints,
1441            ChildLayoutHelper::dry_layout_child,
1442            ChildLayoutHelper::get_dry_baseline,
1443        );
1444
1445        if self.is_baseline_aligned(app) {
1446            return sizes.baseline_offset;
1447        }
1448
1449        // For non-baseline-aligned, match the logic of compute_distance_to_actual_baseline
1450        // exactly.
1451        match self.direction(app) {
1452            Axis::Horizontal => {
1453                self.compute_dry_distance_to_highest_baseline(app, constraints, baseline, &sizes)
1454            }
1455            Axis::Vertical => {
1456                self.compute_dry_distance_to_first_baseline(app, constraints, baseline, &sizes)
1457            }
1458        }
1459    }
1460
1461    /// Dry layout equivalent of
1462    /// [`default_compute_distance_to_highest_actual_baseline`](RenderBoxContainerDefaultsMixin::default_compute_distance_to_highest_actual_baseline).
1463    /// Internal to the flex layout.
1464    fn compute_dry_distance_to_highest_baseline(
1465        self: RenderHandle<Self>,
1466        app: &mut App,
1467        constraints: BoxConstraints,
1468        baseline: TextBaseline,
1469        sizes: &LayoutSizes,
1470    ) -> Option<f64> {
1471        // Simulate the exact logic from default_compute_distance_to_highest_actual_baseline.
1472        // The key insight: the actual method uses the child's parent data offset.dy, so we need
1473        // to simulate that.
1474
1475        let non_flex_constraints = self.constraints_for_non_flex_child(app, constraints);
1476        let space_per_flex = sizes.space_per_flex;
1477        let constraints_for_child = |app: &App, child: AnyRenderBox| {
1478            let flex = get_flex(app, child);
1479            match space_per_flex {
1480                Some(space_per_flex) if flex > 0 => self.constraints_for_flex_child(
1481                    app,
1482                    child,
1483                    constraints,
1484                    f64::from(flex) * space_per_flex,
1485                ),
1486                _ => non_flex_constraints,
1487            }
1488        };
1489
1490        // Simulate the layout positioning logic from perform_layout.
1491        let flip_main_axis = self.flip_main_axis(app);
1492        let flip_cross_axis = self.flip_cross_axis(app);
1493        let top_left_child = if flip_main_axis {
1494            self.last_child(app)
1495        } else {
1496            self.first_child(app)
1497        };
1498        let is_baseline_aligned = self.is_baseline_aligned(app);
1499        let text_baseline = self.text_baseline(app);
1500        let baseline_offset = if is_baseline_aligned && text_baseline.is_some() {
1501            sizes.baseline_offset
1502        } else {
1503            None
1504        };
1505        let cross_axis_alignment = self.cross_axis_alignment(app);
1506        let direction = self.direction(app);
1507
1508        let mut min_baseline = BaselineOffset::NO_BASELINE;
1509
1510        let mut child = top_left_child;
1511        while let Some(current) = child {
1512            let child_constraints = constraints_for_child(app, current);
1513            let child_baseline = current.get_dry_baseline(app, child_constraints, baseline);
1514            if let Some(child_baseline) = child_baseline {
1515                // Calculate cross-axis position to match perform_layout exactly.
1516                let child_baseline_offset = match text_baseline {
1517                    Some(text_baseline) if is_baseline_aligned => {
1518                        current.get_dry_baseline(app, child_constraints, text_baseline)
1519                    }
1520                    _ => None,
1521                };
1522
1523                let child_cross_position =
1524                    if let (Some(baseline_offset), Some(child_baseline_offset)) =
1525                        (baseline_offset, child_baseline_offset)
1526                    {
1527                        baseline_offset - child_baseline_offset
1528                    } else if cross_axis_alignment == CrossAxisAlignment::Baseline
1529                        && direction == Axis::Horizontal
1530                    {
1531                        // Baseline mode with a child that lacks a baseline: align to the top
1532                        // (dy = 0), regardless of vertical_direction. Ignore flip_cross_axis here to
1533                        // match perform_layout.
1534                        let child_size = current.get_dry_layout(app, child_constraints);
1535                        CrossAxisAlignment::Start.get_child_cross_axis_offset(
1536                            sizes.axis_size.cross_axis_extent()
1537                                - self.get_cross_size(app, child_size),
1538                            false,
1539                        )
1540                    } else {
1541                        // Non-baseline: respect configured cross_axis_alignment.
1542                        let child_size = current.get_dry_layout(app, child_constraints);
1543                        cross_axis_alignment.get_child_cross_axis_offset(
1544                            sizes.axis_size.cross_axis_extent()
1545                                - self.get_cross_size(app, child_size),
1546                            flip_cross_axis,
1547                        )
1548                    };
1549
1550                // For horizontal flex: offset.dy = child_cross_position. This simulates the
1551                // child's parent data offset.dy from the actual method.
1552                let candidate = BaselineOffset(Some(child_baseline)) + child_cross_position;
1553                min_baseline = min_baseline.min_of(candidate);
1554            }
1555
1556            // Main-axis advancement is irrelevant for highest-baseline computation.
1557            child = if flip_main_axis {
1558                self.child_before(app, current)
1559            } else {
1560                self.child_after(app, current)
1561            };
1562        }
1563
1564        min_baseline.offset()
1565    }
1566
1567    /// Dry layout equivalent of
1568    /// [`default_compute_distance_to_first_actual_baseline`](RenderBoxContainerDefaultsMixin::default_compute_distance_to_first_actual_baseline).
1569    /// Internal to the flex layout.
1570    fn compute_dry_distance_to_first_baseline(
1571        self: RenderHandle<Self>,
1572        app: &mut App,
1573        constraints: BoxConstraints,
1574        baseline: TextBaseline,
1575        sizes: &LayoutSizes,
1576    ) -> Option<f64> {
1577        // We must mimic default_compute_distance_to_first_actual_baseline which walks children
1578        // in child-list order (not painting order) but uses actual offsets.
1579        let non_flex_constraints = self.constraints_for_non_flex_child(app, constraints);
1580        let space_per_flex = sizes.space_per_flex;
1581        let constraints_for_child = |app: &App, child: AnyRenderBox| {
1582            let flex = get_flex(app, child);
1583            match space_per_flex {
1584                Some(space_per_flex) if flex > 0 => self.constraints_for_flex_child(
1585                    app,
1586                    child,
1587                    constraints,
1588                    f64::from(flex) * space_per_flex,
1589                ),
1590                _ => non_flex_constraints,
1591            }
1592        };
1593
1594        // First, compute each child's main-axis position in painting order.
1595        let remaining_space = sizes.main_axis_free_space.max(0.0);
1596        let flip_main_axis = self.flip_main_axis(app);
1597        let (leading_space, between_space) = self.main_axis_alignment(app).distribute_space(
1598            remaining_space,
1599            self.child_count(app),
1600            flip_main_axis,
1601            self.spacing(app),
1602        );
1603
1604        let mut main_positions: HashMap<AnyRenderBox, f64> = HashMap::new();
1605        let start_child = if flip_main_axis {
1606            self.last_child(app)
1607        } else {
1608            self.first_child(app)
1609        };
1610        let mut pos = leading_space;
1611        let mut child = start_child;
1612        while let Some(current) = child {
1613            main_positions.insert(current, pos);
1614            let cc = constraints_for_child(app, current);
1615            let cs = current.get_dry_layout(app, cc);
1616            pos += self.get_main_size(app, cs) + between_space;
1617            child = if flip_main_axis {
1618                self.child_before(app, current)
1619            } else {
1620                self.child_after(app, current)
1621            };
1622        }
1623
1624        // Then, find the first child with a baseline in child-list order and return its
1625        // baseline + position.
1626        let mut child = self.first_child(app);
1627        while let Some(current) = child {
1628            let cc = constraints_for_child(app, current);
1629            if let Some(child_baseline) = current.get_dry_baseline(app, cc, baseline) {
1630                let position = main_positions.get(&current).copied();
1631                // If somehow missing (no children), fall back to leading_space.
1632                return Some(child_baseline + position.unwrap_or(leading_space));
1633            }
1634            child = self.child_after(app, current);
1635        }
1636        None
1637    }
1638
1639    /// The size this flex would take, measuring the children dry.
1640    fn compute_dry_layout(
1641        self: RenderHandle<Self>,
1642        app: &mut App,
1643        constraints: BoxConstraints,
1644    ) -> Size {
1645        if cfg!(debug_assertions)
1646            && let Some(error) = self.debug_check_constraints(app, constraints)
1647        {
1648            self.debug_cannot_compute_dry_layout(DryLayoutFailure::Error(&error));
1649            return Size::ZERO;
1650        }
1651        let direction = self.direction(app);
1652        self.compute_sizes(
1653            app,
1654            constraints,
1655            ChildLayoutHelper::dry_layout_child,
1656            ChildLayoutHelper::get_dry_baseline,
1657        )
1658        .axis_size
1659        .to_size(direction)
1660    }
1661
1662    /// Hit tests the children in paint order.
1663    fn hit_test_children(
1664        self: RenderHandle<Self>,
1665        app: &mut App,
1666        result: &mut BoxHitTestResult<'_>,
1667        position: Offset,
1668    ) -> bool {
1669        self.default_hit_test_children(app, result, position)
1670    }
1671}
1672
1673/// Flutter's `RenderFlex._getFlex`.
1674fn get_flex(app: &App, child: AnyRenderBox) -> i32 {
1675    child
1676        .as_object()
1677        .parent_data_of::<FlexParentData>(app)
1678        .flex
1679        .unwrap_or(0)
1680}
1681
1682/// Flutter's `RenderFlex._getFit`.
1683fn get_fit(app: &App, child: AnyRenderBox) -> FlexFit {
1684    child
1685        .as_object()
1686        .parent_data_of::<FlexParentData>(app)
1687        .fit
1688        .unwrap_or(FlexFit::Tight)
1689}
1690
1691/// Displays its children in a one-dimensional array.
1692///
1693/// ## Layout algorithm
1694///
1695/// _This section describes how the framework causes [`RenderFlex`] to position its children._
1696/// _See [`BoxConstraints`] for an introduction to box layout models._
1697///
1698/// Layout for a [`RenderFlex`] proceeds in six steps:
1699///
1700/// 1. Layout each child with a null or zero flex factor with unbounded main axis constraints and
1701///    the incoming cross axis constraints. If the [`cross_axis_alignment`](Self::cross_axis_alignment)
1702///    is [`CrossAxisAlignment::Stretch`], instead use tight cross axis constraints that match the
1703///    incoming max extent in the cross axis.
1704/// 2. Divide the remaining main axis space among the children with non-zero flex factors
1705///    according to their flex factor. For example, a child with a flex factor of 2.0 will receive
1706///    twice the amount of main axis space as a child with a flex factor of 1.0.
1707/// 3. Layout each of the remaining children with the same cross axis constraints as in step 1,
1708///    but instead of using unbounded main axis constraints, use max axis constraints based on the
1709///    amount of space allocated in step 2. Children with [`FlexFit::Tight`] are given tight
1710///    constraints (i.e., forced to fill the allocated space), and children with [`FlexFit::Loose`]
1711///    are given loose constraints (i.e., not forced to fill the allocated space).
1712/// 4. The cross axis extent of the [`RenderFlex`] is the maximum cross axis extent of the
1713///    children (which will always satisfy the incoming constraints).
1714/// 5. The main axis extent of the [`RenderFlex`] is determined by the
1715///    [`main_axis_size`](Self::main_axis_size) property. If it is [`MainAxisSize::Max`], then the
1716///    main axis extent of the [`RenderFlex`] is the max extent of the incoming main axis
1717///    constraints. If it is [`MainAxisSize::Min`], then the main axis extent is the sum of the
1718///    main axis extents of the children (subject to the incoming constraints).
1719/// 6. Determine the position for each child according to the
1720///    [`main_axis_alignment`](Self::main_axis_alignment) and the
1721///    [`cross_axis_alignment`](Self::cross_axis_alignment). For example, if the
1722///    [`main_axis_alignment`](Self::main_axis_alignment) is [`MainAxisAlignment::SpaceBetween`],
1723///    any main axis space that has not been allocated to children is divided evenly and placed
1724///    between the children.
1725pub struct RenderFlex {
1726    render_object: RenderObjectData,
1727    render_box: RenderBoxData,
1728    container: ContainerRenderObjectData<AnyRenderBox>,
1729    flex: RenderFlexData,
1730}
1731
1732impl RenderFlex {
1733    /// Creates a flex render object.
1734    ///
1735    /// By default, the flex layout is horizontal and children are aligned to the start of the
1736    /// main axis and the center of the cross axis. Add children with
1737    /// [`add`](ContainerRenderObjectMixin::add) or
1738    /// [`add_all`](ContainerRenderObjectMixin::add_all); Dart's constructor takes them.
1739    pub fn new(app: &mut App) -> RenderHandle<RenderFlex> {
1740        RenderHandle::new_box(
1741            app,
1742            RenderFlex {
1743                render_object: RenderObjectData::new(),
1744                render_box: RenderBoxData::new(),
1745                container: ContainerRenderObjectData::new(),
1746                flex: RenderFlexData::new(),
1747            },
1748        )
1749    }
1750
1751    /// See [`RenderFlexMixin::direction`].
1752    pub fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
1753        RenderFlexMixin::direction(self, app)
1754    }
1755
1756    /// See [`RenderFlexMixin::set_direction`].
1757    pub fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
1758        RenderFlexMixin::set_direction(self, app, value)
1759    }
1760
1761    /// See [`RenderFlexMixin::main_axis_alignment`].
1762    pub fn main_axis_alignment(self: RenderHandle<Self>, app: &App) -> MainAxisAlignment {
1763        RenderFlexMixin::main_axis_alignment(self, app)
1764    }
1765
1766    /// See [`RenderFlexMixin::set_main_axis_alignment`].
1767    pub fn set_main_axis_alignment(
1768        self: RenderHandle<Self>,
1769        app: &mut App,
1770        value: MainAxisAlignment,
1771    ) {
1772        RenderFlexMixin::set_main_axis_alignment(self, app, value)
1773    }
1774
1775    /// See [`RenderFlexMixin::main_axis_size`].
1776    pub fn main_axis_size(self: RenderHandle<Self>, app: &App) -> MainAxisSize {
1777        RenderFlexMixin::main_axis_size(self, app)
1778    }
1779
1780    /// See [`RenderFlexMixin::set_main_axis_size`].
1781    pub fn set_main_axis_size(self: RenderHandle<Self>, app: &mut App, value: MainAxisSize) {
1782        RenderFlexMixin::set_main_axis_size(self, app, value)
1783    }
1784
1785    /// See [`RenderFlexMixin::cross_axis_alignment`].
1786    pub fn cross_axis_alignment(self: RenderHandle<Self>, app: &App) -> CrossAxisAlignment {
1787        RenderFlexMixin::cross_axis_alignment(self, app)
1788    }
1789
1790    /// See [`RenderFlexMixin::set_cross_axis_alignment`].
1791    pub fn set_cross_axis_alignment(
1792        self: RenderHandle<Self>,
1793        app: &mut App,
1794        value: CrossAxisAlignment,
1795    ) {
1796        RenderFlexMixin::set_cross_axis_alignment(self, app, value)
1797    }
1798
1799    /// See [`RenderFlexMixin::text_direction`].
1800    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
1801        RenderFlexMixin::text_direction(self, app)
1802    }
1803
1804    /// See [`RenderFlexMixin::set_text_direction`].
1805    pub fn set_text_direction(
1806        self: RenderHandle<Self>,
1807        app: &mut App,
1808        value: Option<TextDirection>,
1809    ) {
1810        RenderFlexMixin::set_text_direction(self, app, value)
1811    }
1812
1813    /// See [`RenderFlexMixin::vertical_direction`].
1814    pub fn vertical_direction(self: RenderHandle<Self>, app: &App) -> VerticalDirection {
1815        RenderFlexMixin::vertical_direction(self, app)
1816    }
1817
1818    /// See [`RenderFlexMixin::set_vertical_direction`].
1819    pub fn set_vertical_direction(
1820        self: RenderHandle<Self>,
1821        app: &mut App,
1822        value: VerticalDirection,
1823    ) {
1824        RenderFlexMixin::set_vertical_direction(self, app, value)
1825    }
1826
1827    /// See [`RenderFlexMixin::text_baseline`].
1828    pub fn text_baseline(self: RenderHandle<Self>, app: &App) -> Option<TextBaseline> {
1829        RenderFlexMixin::text_baseline(self, app)
1830    }
1831
1832    /// See [`RenderFlexMixin::set_text_baseline`].
1833    pub fn set_text_baseline(self: RenderHandle<Self>, app: &mut App, value: Option<TextBaseline>) {
1834        RenderFlexMixin::set_text_baseline(self, app, value)
1835    }
1836
1837    /// See [`RenderFlexMixin::clip_behavior`].
1838    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
1839        RenderFlexMixin::clip_behavior(self, app)
1840    }
1841
1842    /// See [`RenderFlexMixin::set_clip_behavior`].
1843    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
1844        RenderFlexMixin::set_clip_behavior(self, app, value)
1845    }
1846
1847    /// See [`RenderFlexMixin::spacing`].
1848    pub fn spacing(self: RenderHandle<Self>, app: &App) -> f64 {
1849        RenderFlexMixin::spacing(self, app)
1850    }
1851
1852    /// See [`RenderFlexMixin::set_spacing`].
1853    pub fn set_spacing(self: RenderHandle<Self>, app: &mut App, value: f64) {
1854        RenderFlexMixin::set_spacing(self, app, value)
1855    }
1856}
1857
1858impl ContainerRenderObjectMixin for RenderFlex {
1859    type ChildType = AnyRenderBox;
1860    type ParentDataType = FlexParentData;
1861
1862    fn container_data(
1863        self: RenderHandle<Self>,
1864        app: &App,
1865    ) -> &ContainerRenderObjectData<AnyRenderBox> {
1866        &self.get(app).container
1867    }
1868
1869    fn container_data_mut(
1870        self: RenderHandle<Self>,
1871        app: &mut App,
1872    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1873        &mut self.get_mut(app).container
1874    }
1875}
1876
1877impl RenderBoxContainerDefaultsMixin for RenderFlex {}
1878
1879impl RenderFlexMixin for RenderFlex {
1880    fn flex_data(self: RenderHandle<Self>, app: &App) -> &RenderFlexData {
1881        &self.get(app).flex
1882    }
1883
1884    fn flex_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderFlexData {
1885        &mut self.get_mut(app).flex
1886    }
1887}
1888
1889impl RenderObject for RenderFlex {
1890    crate::render_object_accessors!();
1891
1892    fn debug_fill_properties(
1893        self: RenderHandle<Self>,
1894        app: &App,
1895        properties: &mut DiagnosticPropertiesBuilder,
1896    ) {
1897        RenderFlexMixin::debug_fill_properties(self, app, properties);
1898    }
1899
1900    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1901        RenderFlexMixin::perform_layout(self, app)
1902    }
1903
1904    fn visit_children(
1905        self: RenderHandle<Self>,
1906        app: &App,
1907        visitor: &mut dyn FnMut(AnyRenderObject),
1908    ) {
1909        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1910    }
1911
1912    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1913        ContainerRenderObjectMixin::did_attach(self, app, owner)
1914    }
1915
1916    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1917        ContainerRenderObjectMixin::did_detach(self, app)
1918    }
1919
1920    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1921        ContainerRenderObjectMixin::redepth_children(self, app)
1922    }
1923
1924    fn paint(
1925        self: RenderHandle<Self>,
1926        app: &mut App,
1927        context: &mut PaintingContext,
1928        offset: Offset,
1929    ) {
1930        RenderFlexMixin::paint(self, app, context, offset)
1931    }
1932
1933    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1934        RenderFlexMixin::dispose(self, app)
1935    }
1936
1937    fn describe_approximate_paint_clip(
1938        self: RenderHandle<Self>,
1939        app: &App,
1940        child: AnyRenderObject,
1941    ) -> Option<Rect> {
1942        RenderFlexMixin::describe_approximate_paint_clip(self, app, child)
1943    }
1944}
1945
1946impl RenderBox for RenderFlex {
1947    crate::render_box_accessors!();
1948
1949    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1950        RenderFlexMixin::setup_parent_data(self, app, child)
1951    }
1952
1953    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1954        RenderFlexMixin::compute_min_intrinsic_width(self, app, height)
1955    }
1956
1957    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1958        RenderFlexMixin::compute_max_intrinsic_width(self, app, height)
1959    }
1960
1961    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1962        RenderFlexMixin::compute_min_intrinsic_height(self, app, width)
1963    }
1964
1965    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1966        RenderFlexMixin::compute_max_intrinsic_height(self, app, width)
1967    }
1968
1969    fn compute_distance_to_actual_baseline(
1970        self: RenderHandle<Self>,
1971        app: &mut App,
1972        baseline: TextBaseline,
1973    ) -> Option<f64> {
1974        RenderFlexMixin::compute_distance_to_actual_baseline(self, app, baseline)
1975    }
1976
1977    fn compute_dry_baseline(
1978        self: RenderHandle<Self>,
1979        app: &mut App,
1980        constraints: BoxConstraints,
1981        baseline: TextBaseline,
1982    ) -> Option<f64> {
1983        RenderFlexMixin::compute_dry_baseline(self, app, constraints, baseline)
1984    }
1985
1986    fn compute_dry_layout(
1987        self: RenderHandle<Self>,
1988        app: &mut App,
1989        constraints: BoxConstraints,
1990    ) -> Size {
1991        RenderFlexMixin::compute_dry_layout(self, app, constraints)
1992    }
1993
1994    fn hit_test_children(
1995        self: RenderHandle<Self>,
1996        app: &mut App,
1997        result: &mut BoxHitTestResult<'_>,
1998        position: Offset,
1999    ) -> bool {
2000        RenderFlexMixin::hit_test_children(self, app, result, position)
2001    }
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006    use std::any::Any;
2007    use waft_foundation::AppCell;
2008
2009    use waft_gestures::{HitTestEntry, HitTestResult};
2010    use waft_painting::AlignmentGeometry;
2011
2012    use super::*;
2013    use crate::box_::BoxHitTestEntry;
2014    use crate::testing::{
2015        EnginePhase, ignoring_hash_codes, layout, layout_with, painted_ops, pump_frame,
2016    };
2017    use waft_embedder::valo::Op;
2018
2019    /// A flex child's parent data reads as Dart's `toString`: `null` for what is unset, and an
2020    /// enum by its type and case.
2021    #[test]
2022    fn flex_parent_data_reads_as_darts() {
2023        let mut parent_data = FlexParentData::default();
2024        assert_eq!(
2025            parent_data.to_string(),
2026            "offset=Offset(0.0, 0.0); flex=null; fit=null"
2027        );
2028        parent_data.flex = Some(2);
2029        parent_data.fit = Some(FlexFit::Tight);
2030        assert_eq!(
2031            parent_data.to_string(),
2032            "offset=Offset(0.0, 0.0); flex=2; fit=FlexFit.tight"
2033        );
2034    }
2035
2036    /// `flex_test.dart`: "Defaults".
2037    #[test]
2038    fn a_flex_dump_shows_its_defaults() {
2039        let cell = AppCell::new();
2040        let mut app = cell.borrow_mut();
2041        let flex = RenderFlex::new(&mut app);
2042        assert_eq!(
2043            ignoring_hash_codes(&flex.as_object().to_string_deep(&app)),
2044            "RenderFlex#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n\
2045             \u{20}  parentData: MISSING\n\
2046             \u{20}  constraints: MISSING\n\
2047             \u{20}  size: MISSING\n\
2048             \u{20}  direction: horizontal\n\
2049             \u{20}  mainAxisAlignment: start\n\
2050             \u{20}  mainAxisSize: max\n\
2051             \u{20}  crossAxisAlignment: center\n\
2052             \u{20}  verticalDirection: down\n\
2053             \u{20}  spacing: 0.0\n"
2054        );
2055    }
2056
2057    /// A leaf that takes its preferred size where the constraints allow, and answers hit tests
2058    /// within its bounds.
2059    struct SizedTestBox {
2060        render_object: RenderObjectData,
2061        render_box: RenderBoxData,
2062        preferred_size: Size,
2063    }
2064
2065    impl RenderObject for SizedTestBox {
2066        crate::render_object_accessors!();
2067
2068        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2069            let preferred_size = self.get(app).preferred_size;
2070            let size = self.constraints(app).constrain(preferred_size);
2071            self.set_size(app, size);
2072        }
2073    }
2074
2075    impl RenderBox for SizedTestBox {
2076        crate::render_box_accessors!();
2077
2078        fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
2079            true
2080        }
2081    }
2082
2083    fn sized_box(app: &mut App, size: Size) -> AnyRenderBox {
2084        RenderHandle::new_box(
2085            app,
2086            SizedTestBox {
2087                render_object: RenderObjectData::new(),
2088                render_box: RenderBoxData::new(),
2089                preferred_size: size,
2090            },
2091        )
2092        .as_box()
2093    }
2094
2095    /// A left-to-right [`RenderFlex`] holding `children`.
2096    fn row(app: &mut App, children: Vec<AnyRenderBox>) -> RenderHandle<RenderFlex> {
2097        let flex = RenderFlex::new(app);
2098        flex.set_text_direction(app, Some(TextDirection::Ltr));
2099        flex.add_all(app, Some(children));
2100        flex
2101    }
2102
2103    fn offset_of(app: &App, child: AnyRenderBox) -> Offset {
2104        child.box_parent_data(app).offset
2105    }
2106
2107    /// Whether `render`, painted on its own, clips.
2108    fn picture_has_clip(app: &mut App, render: AnyRenderObject) -> bool {
2109        painted_ops(app, render)
2110            .iter()
2111            .any(|op| matches!(op, Op::ClipPath { .. }))
2112    }
2113
2114    fn hit_boxes(result: &HitTestResult) -> Vec<AnyRenderBox> {
2115        result
2116            .path()
2117            .iter()
2118            .filter_map(|entry: &HitTestEntry| {
2119                let target: &dyn Any = entry.target();
2120                target
2121                    .downcast_ref::<BoxHitTestEntry>()
2122                    .map(BoxHitTestEntry::target)
2123            })
2124            .collect()
2125    }
2126
2127    /// `object.dart`'s `ContainerRenderObjectMixin`: the child list is a doubly-linked list that
2128    /// `insert` / `move` / `remove` keep consistent from both ends.
2129    #[test]
2130    fn child_list_insert_move_and_remove() {
2131        let cell = AppCell::new();
2132        let mut app = cell.borrow_mut();
2133        let first = sized_box(&mut app, Size::new(10.0, 10.0));
2134        let middle = sized_box(&mut app, Size::new(10.0, 10.0));
2135        let last = sized_box(&mut app, Size::new(10.0, 10.0));
2136        let flex = RenderFlex::new(&mut app);
2137
2138        flex.add(&mut app, first);
2139        flex.insert(&mut app, last, Some(first));
2140        flex.insert(&mut app, middle, Some(first));
2141        assert_eq!(flex.child_count(&app), 3);
2142        assert_eq!(flex.children_as_list(&app), vec![first, middle, last]);
2143        assert_eq!(flex.first_child(&app), Some(first));
2144        assert_eq!(flex.last_child(&app), Some(last));
2145        assert_eq!(flex.child_after(&app, first), Some(middle));
2146        assert_eq!(flex.child_before(&app, last), Some(middle));
2147
2148        let mut visited = Vec::new();
2149        flex.as_object()
2150            .visit_children(&app, &mut |child| visited.push(child));
2151        assert_eq!(
2152            visited,
2153            vec![first.as_object(), middle.as_object(), last.as_object()]
2154        );
2155
2156        flex.move_child(&mut app, first, Some(last));
2157        assert_eq!(flex.children_as_list(&app), vec![middle, last, first]);
2158        flex.move_child(&mut app, first, None);
2159        assert_eq!(flex.children_as_list(&app), vec![first, middle, last]);
2160
2161        flex.remove(&mut app, middle);
2162        assert_eq!(flex.children_as_list(&app), vec![first, last]);
2163        assert_eq!(flex.child_count(&app), 2);
2164        assert!(middle.as_object().parent(&app).is_none());
2165
2166        flex.remove_all(&mut app);
2167        assert_eq!(flex.child_count(&app), 0);
2168        assert!(flex.first_child(&app).is_none());
2169        assert!(flex.last_child(&app).is_none());
2170        assert!(first.as_object().parent(&app).is_none());
2171        assert!(last.as_object().parent(&app).is_none());
2172    }
2173
2174    /// A box with fixed intrinsic dimensions that takes the size its constraints allow around
2175    /// them.
2176    struct IntrinsicTestBox {
2177        render_object: RenderObjectData,
2178        render_box: RenderBoxData,
2179        intrinsic: Size,
2180    }
2181
2182    impl RenderObject for IntrinsicTestBox {
2183        crate::render_object_accessors!();
2184
2185        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2186            let intrinsic = self.get(app).intrinsic;
2187            let size = self.constraints(app).constrain(intrinsic);
2188            self.set_size(app, size);
2189        }
2190    }
2191
2192    impl RenderBox for IntrinsicTestBox {
2193        crate::render_box_accessors!();
2194
2195        fn compute_min_intrinsic_width(
2196            self: RenderHandle<Self>,
2197            app: &mut App,
2198            _height: f64,
2199        ) -> f64 {
2200            self.get(app).intrinsic.width()
2201        }
2202
2203        fn compute_max_intrinsic_width(
2204            self: RenderHandle<Self>,
2205            app: &mut App,
2206            _height: f64,
2207        ) -> f64 {
2208            self.get(app).intrinsic.width()
2209        }
2210
2211        fn compute_min_intrinsic_height(
2212            self: RenderHandle<Self>,
2213            app: &mut App,
2214            _width: f64,
2215        ) -> f64 {
2216            self.get(app).intrinsic.height()
2217        }
2218
2219        fn compute_max_intrinsic_height(
2220            self: RenderHandle<Self>,
2221            app: &mut App,
2222            _width: f64,
2223        ) -> f64 {
2224            self.get(app).intrinsic.height()
2225        }
2226
2227        fn compute_dry_layout(
2228            self: RenderHandle<Self>,
2229            app: &mut App,
2230            constraints: BoxConstraints,
2231        ) -> Size {
2232            constraints.constrain(self.get(app).intrinsic)
2233        }
2234    }
2235
2236    fn intrinsic_box(app: &mut App, intrinsic: Size) -> AnyRenderBox {
2237        RenderHandle::new_box(
2238            app,
2239            IntrinsicTestBox {
2240                render_object: RenderObjectData::new(),
2241                render_box: RenderBoxData::new(),
2242                intrinsic,
2243            },
2244        )
2245        .as_box()
2246    }
2247
2248    /// A row of a fixed child and a flexible one: `flex_test.dart`'s intrinsics, where the main
2249    /// axis intrinsic is the inflexible space plus the largest flex fraction, and the cross axis
2250    /// intrinsic is the tallest child.
2251    #[test]
2252    fn row_intrinsics_add_the_inflexible_space_to_the_largest_flex_fraction() {
2253        let cell = AppCell::new();
2254        let mut app = cell.borrow_mut();
2255        let fixed = intrinsic_box(&mut app, Size::new(50.0, 20.0));
2256        let flexible = intrinsic_box(&mut app, Size::new(30.0, 10.0));
2257        let flex = row(&mut app, vec![fixed, flexible]);
2258        flexible.parent_data_of_mut::<FlexParentData>(&mut app).flex = Some(1);
2259
2260        let row = flex.as_box();
2261        assert_eq!(row.get_max_intrinsic_width(&mut app, f64::INFINITY), 80.0);
2262        assert_eq!(row.get_min_intrinsic_width(&mut app, f64::INFINITY), 80.0);
2263        assert_eq!(row.get_max_intrinsic_height(&mut app, 100.0), 20.0);
2264    }
2265
2266    /// The spacing between the children counts towards the main axis intrinsic.
2267    #[test]
2268    fn row_intrinsics_include_the_spacing() {
2269        let cell = AppCell::new();
2270        let mut app = cell.borrow_mut();
2271        let first = intrinsic_box(&mut app, Size::new(50.0, 20.0));
2272        let second = intrinsic_box(&mut app, Size::new(30.0, 10.0));
2273        let flex = row(&mut app, vec![first, second]);
2274        flex.set_spacing(&mut app, 10.0);
2275        assert_eq!(
2276            flex.as_box()
2277                .get_max_intrinsic_width(&mut app, f64::INFINITY),
2278            90.0
2279        );
2280    }
2281
2282    /// The dry layout takes the main axis size into account: a `Max` row fills the constraints,
2283    /// a `Min` row shrink-wraps its children, and both match what layout produces.
2284    #[test]
2285    fn row_dry_layout_follows_the_main_axis_size() {
2286        for (main_axis_size, expected) in [
2287            (MainAxisSize::Max, Size::new(200.0, 20.0)),
2288            (MainAxisSize::Min, Size::new(80.0, 20.0)),
2289        ] {
2290            let cell = AppCell::new();
2291            let mut app = cell.borrow_mut();
2292            let fixed = intrinsic_box(&mut app, Size::new(50.0, 20.0));
2293            let flexible = intrinsic_box(&mut app, Size::new(30.0, 10.0));
2294            let flex = row(&mut app, vec![fixed, flexible]);
2295            flex.set_main_axis_size(&mut app, main_axis_size);
2296            {
2297                let parent_data = flexible.parent_data_of_mut::<FlexParentData>(&mut app);
2298                parent_data.flex = Some(1);
2299                parent_data.fit = Some(FlexFit::Loose);
2300            }
2301
2302            let constraints = BoxConstraints::new().max_width(200.0).max_height(100.0);
2303            let dry = flex.as_box().get_dry_layout(&mut app, constraints);
2304            flex.layout(&mut app, constraints, false);
2305            assert_eq!(dry, expected);
2306            assert_eq!(dry, flex.size(&app), "the dry layout is the real layout");
2307        }
2308    }
2309
2310    /// `flex_test.dart`: a row gives the flexible child the space the fixed one leaves, and the
2311    /// spacing goes between them.
2312    #[test]
2313    fn row_lays_out_fixed_and_flexible_children_with_spacing() {
2314        let cell = AppCell::new();
2315        let mut app = cell.borrow_mut();
2316        let fixed = sized_box(&mut app, Size::new(50.0, 30.0));
2317        let flexible = sized_box(&mut app, Size::new(20.0, 10.0));
2318        let flex = row(&mut app, vec![fixed, flexible]);
2319        flexible.parent_data_of_mut::<FlexParentData>(&mut app).flex = Some(1);
2320        flex.set_spacing(&mut app, 10.0);
2321
2322        flex.layout(
2323            &mut app,
2324            BoxConstraints::tight(Size::new(200.0, 100.0)),
2325            false,
2326        );
2327
2328        assert_eq!(flex.size(&app), Size::new(200.0, 100.0));
2329        assert_eq!(fixed.size(&app), Size::new(50.0, 30.0));
2330        // 200 - 50 fixed - 10 spacing goes to the one flexible child, tightly.
2331        assert_eq!(flexible.size(&app), Size::new(140.0, 10.0));
2332        assert_eq!(offset_of(&app, fixed), Offset::new(0.0, 35.0));
2333        assert_eq!(offset_of(&app, flexible), Offset::new(60.0, 45.0));
2334    }
2335
2336    /// `flex_test.dart`: `Test Flex Widget MainAxisAlignment`.
2337    #[test]
2338    fn main_axis_alignment_positions_children() {
2339        let cases = [
2340            (MainAxisAlignment::Start, 0.0, 20.0),
2341            (MainAxisAlignment::End, 60.0, 80.0),
2342            (MainAxisAlignment::Center, 30.0, 50.0),
2343            (MainAxisAlignment::SpaceBetween, 0.0, 80.0),
2344            (MainAxisAlignment::SpaceAround, 15.0, 65.0),
2345            (MainAxisAlignment::SpaceEvenly, 20.0, 60.0),
2346        ];
2347        for (alignment, first_x, second_x) in cases {
2348            let cell = AppCell::new();
2349            let mut app = cell.borrow_mut();
2350            let first = sized_box(&mut app, Size::new(20.0, 20.0));
2351            let second = sized_box(&mut app, Size::new(20.0, 20.0));
2352            let flex = row(&mut app, vec![first, second]);
2353            flex.set_main_axis_alignment(&mut app, alignment);
2354
2355            flex.layout(
2356                &mut app,
2357                BoxConstraints::tight(Size::new(100.0, 20.0)),
2358                false,
2359            );
2360
2361            assert_eq!(
2362                (offset_of(&app, first).dx(), offset_of(&app, second).dx()),
2363                (first_x, second_x),
2364                "{alignment:?}"
2365            );
2366        }
2367    }
2368
2369    /// Each cross axis alignment places a child that is smaller than the row; a child with no
2370    /// baseline in a baseline-aligned row is top-aligned.
2371    #[test]
2372    fn cross_axis_alignment_positions_children() {
2373        let cases = [
2374            (CrossAxisAlignment::Start, 0.0, 20.0),
2375            (CrossAxisAlignment::Center, 40.0, 20.0),
2376            (CrossAxisAlignment::End, 80.0, 20.0),
2377            (CrossAxisAlignment::Stretch, 0.0, 100.0),
2378            (CrossAxisAlignment::Baseline, 0.0, 20.0),
2379        ];
2380        for (alignment, y, height) in cases {
2381            let cell = AppCell::new();
2382            let mut app = cell.borrow_mut();
2383            let child = sized_box(&mut app, Size::new(20.0, 20.0));
2384            let flex = row(&mut app, vec![child]);
2385            flex.set_cross_axis_alignment(&mut app, alignment);
2386            if alignment == CrossAxisAlignment::Baseline {
2387                flex.set_text_baseline(&mut app, Some(TextBaseline::Alphabetic));
2388            }
2389
2390            flex.layout(
2391                &mut app,
2392                BoxConstraints::tight(Size::new(100.0, 100.0)),
2393                false,
2394            );
2395
2396            assert_eq!(offset_of(&app, child).dy(), y, "{alignment:?}");
2397            assert_eq!(child.size(&app).height(), height, "{alignment:?}");
2398        }
2399    }
2400
2401    /// `flex_test.dart`: `Clip.none` versus a clip when the children overflow the main axis.
2402    #[test]
2403    fn overflow_is_clipped() {
2404        for (clip_behavior, clips) in [(Clip::None, false), (Clip::HardEdge, true)] {
2405            let cell = AppCell::new();
2406            let mut app = cell.borrow_mut();
2407            let first = sized_box(&mut app, Size::new(80.0, 20.0));
2408            let second = sized_box(&mut app, Size::new(80.0, 20.0));
2409            let flex = row(&mut app, vec![first, second]);
2410            flex.set_clip_behavior(&mut app, clip_behavior);
2411            layout_with(
2412                &mut app,
2413                flex.as_box(),
2414                Some(BoxConstraints::tight(Size::new(100.0, 20.0))),
2415                AlignmentGeometry::CENTER,
2416                EnginePhase::Paint,
2417            );
2418
2419            assert_eq!(flex.size(&app), Size::new(100.0, 20.0));
2420            let clipped = picture_has_clip(&mut app, flex.as_object());
2421            assert_eq!(clipped, clips, "{clip_behavior:?}");
2422        }
2423    }
2424
2425    /// `RenderFlex.describeApproximatePaintClip`: an overflowing flex is clipped to its bounds,
2426    /// and only when the clip behavior asks for a clip; a flex that fits is never clipped.
2427    #[test]
2428    fn describe_approximate_paint_clip_answers_an_overflowing_flex_only() {
2429        for (clip_behavior, overflow) in [
2430            (Clip::None, true),
2431            (Clip::HardEdge, true),
2432            (Clip::HardEdge, false),
2433        ] {
2434            let cell = AppCell::new();
2435            let mut app = cell.borrow_mut();
2436            let extents = if overflow {
2437                vec![Size::new(80.0, 20.0), Size::new(80.0, 20.0)]
2438            } else {
2439                vec![Size::new(80.0, 20.0)]
2440            };
2441            let children = extents
2442                .into_iter()
2443                .map(|size| sized_box(&mut app, size))
2444                .collect();
2445            let flex = row(&mut app, children);
2446            flex.set_clip_behavior(&mut app, clip_behavior);
2447            layout_with(
2448                &mut app,
2449                flex.as_box(),
2450                Some(BoxConstraints::tight(Size::new(100.0, 20.0))),
2451                AlignmentGeometry::CENTER,
2452                EnginePhase::Paint,
2453            );
2454
2455            let child = flex.first_child(&app).expect("a child");
2456            let expected =
2457                (clip_behavior != Clip::None && overflow).then(|| Offset::ZERO & flex.size(&app));
2458            assert_eq!(
2459                flex.as_object()
2460                    .describe_approximate_paint_clip(&app, child.as_object()),
2461                expected,
2462                "{clip_behavior:?}, overflow: {overflow}"
2463            );
2464        }
2465    }
2466
2467    /// `flex_test.dart`: a hit lands on the child that covers the position.
2468    #[test]
2469    fn hit_test_reaches_the_child_under_the_position() {
2470        let cell = AppCell::new();
2471        let mut app = cell.borrow_mut();
2472        let first = sized_box(&mut app, Size::new(50.0, 50.0));
2473        let second = sized_box(&mut app, Size::new(50.0, 50.0));
2474        let flex = row(&mut app, vec![first, second]);
2475
2476        flex.layout(
2477            &mut app,
2478            BoxConstraints::tight(Size::new(100.0, 50.0)),
2479            false,
2480        );
2481
2482        let mut result = HitTestResult::new();
2483        let hit = flex.hit_test(
2484            &mut app,
2485            &mut BoxHitTestResult::wrap(&mut result),
2486            Offset::new(75.0, 25.0),
2487        );
2488        assert!(hit);
2489        assert_eq!(hit_boxes(&result), vec![second, flex.as_box()]);
2490    }
2491
2492    /// The size of one cell of a [`FlowBaselineTestBox`].
2493    const GRID_SIZE: Size = Size::new(10.0, 10.0);
2494
2495    /// `flex_test.dart`'s `RenderFlowBaselineTestBox`: `grid_count` cells in rows as wide as
2496    /// the width allows, with the baseline `baseline_placer` gives for its height.
2497    struct FlowBaselineTestBox {
2498        render_object: RenderObjectData,
2499        render_box: RenderBoxData,
2500        grid_count: usize,
2501        baseline_placer: fn(f64) -> Option<f64>,
2502    }
2503
2504    impl FlowBaselineTestBox {
2505        fn line_grid_count(&self, width: f64) -> usize {
2506            let grids_per_line = if width >= self.grid_count as f64 * GRID_SIZE.width() {
2507                self.grid_count
2508            } else {
2509                (width / GRID_SIZE.width()) as usize
2510            };
2511            grids_per_line.max(1)
2512        }
2513
2514        fn line_count(&self, width: f64) -> usize {
2515            (self.grid_count as f64 / self.line_grid_count(width) as f64).ceil() as usize
2516        }
2517    }
2518
2519    impl RenderObject for FlowBaselineTestBox {
2520        crate::render_object_accessors!();
2521
2522        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2523            let constraints = self.constraints(app);
2524            let size = RenderBox::compute_dry_layout(self, app, constraints);
2525            self.set_size(app, size);
2526        }
2527    }
2528
2529    impl RenderBox for FlowBaselineTestBox {
2530        crate::render_box_accessors!();
2531
2532        fn compute_min_intrinsic_width(
2533            self: RenderHandle<Self>,
2534            _app: &mut App,
2535            _height: f64,
2536        ) -> f64 {
2537            GRID_SIZE.width()
2538        }
2539
2540        fn compute_max_intrinsic_width(
2541            self: RenderHandle<Self>,
2542            app: &mut App,
2543            _height: f64,
2544        ) -> f64 {
2545            GRID_SIZE.width() * self.get(app).grid_count as f64
2546        }
2547
2548        fn compute_min_intrinsic_height(
2549            self: RenderHandle<Self>,
2550            app: &mut App,
2551            width: f64,
2552        ) -> f64 {
2553            GRID_SIZE.height() * self.get(app).line_count(width) as f64
2554        }
2555
2556        fn compute_max_intrinsic_height(
2557            self: RenderHandle<Self>,
2558            app: &mut App,
2559            width: f64,
2560        ) -> f64 {
2561            RenderBox::compute_min_intrinsic_height(self, app, width)
2562        }
2563
2564        fn compute_dry_layout(
2565            self: RenderHandle<Self>,
2566            app: &mut App,
2567            constraints: BoxConstraints,
2568        ) -> Size {
2569            let this = self.get(app);
2570            constraints.constrain(Size::new(
2571                GRID_SIZE.width() * this.line_grid_count(constraints.max_width) as f64,
2572                GRID_SIZE.height() * this.line_count(constraints.max_width) as f64,
2573            ))
2574        }
2575
2576        fn compute_dry_baseline(
2577            self: RenderHandle<Self>,
2578            app: &mut App,
2579            constraints: BoxConstraints,
2580            _baseline: TextBaseline,
2581        ) -> Option<f64> {
2582            let height = self.as_box().get_dry_layout(app, constraints).height();
2583            (self.get(app).baseline_placer)(height)
2584        }
2585
2586        fn compute_distance_to_actual_baseline(
2587            self: RenderHandle<Self>,
2588            app: &mut App,
2589            _baseline: TextBaseline,
2590        ) -> Option<f64> {
2591            let height = self.size(app).height();
2592            (self.get(app).baseline_placer)(height)
2593        }
2594    }
2595
2596    fn flow_baseline_box(
2597        app: &mut App,
2598        grid_count: usize,
2599        baseline_placer: fn(f64) -> Option<f64>,
2600    ) -> AnyRenderBox {
2601        RenderHandle::new_box(
2602            app,
2603            FlowBaselineTestBox {
2604                render_object: RenderObjectData::new(),
2605                render_box: RenderBoxData::new(),
2606                grid_count,
2607                baseline_placer,
2608            },
2609        )
2610        .as_box()
2611    }
2612
2613    /// A left-to-right row of `children` whose children share the alphabetic baseline.
2614    fn baseline_row(app: &mut App, children: Vec<AnyRenderBox>) -> RenderHandle<RenderFlex> {
2615        let flex = row(app, children);
2616        flex.set_cross_axis_alignment(app, CrossAxisAlignment::Baseline);
2617        flex.set_text_baseline(app, Some(TextBaseline::Alphabetic));
2618        flex
2619    }
2620
2621    /// Gives `child` the flex factor `flex` and the fit `fit` in its flex.
2622    fn set_flex(app: &mut App, child: AnyRenderBox, flex: i32, fit: FlexFit) {
2623        let parent_data = child.parent_data_of_mut::<FlexParentData>(app);
2624        parent_data.flex = Some(flex);
2625        parent_data.fit = Some(fit);
2626    }
2627
2628    /// `flex_test.dart`: `children with no baselines are top-aligned`, whichever the vertical
2629    /// direction.
2630    #[test]
2631    fn children_with_no_baselines_are_top_aligned() {
2632        let cell = AppCell::new();
2633        let mut app = cell.borrow_mut();
2634        let first = sized_box(&mut app, Size::new(100.0, 100.0));
2635        let second = sized_box(&mut app, Size::new(100.0, 100.0));
2636        let flex = baseline_row(&mut app, vec![first, second]);
2637        flex.set_vertical_direction(&mut app, VerticalDirection::Up);
2638        layout(&mut app, flex.as_box());
2639
2640        // Not start-aligned.
2641        assert_eq!(offset_of(&app, first).dy(), 0.0);
2642        assert_eq!(offset_of(&app, second).dy(), 0.0);
2643
2644        flex.set_vertical_direction(&mut app, VerticalDirection::Down);
2645        pump_frame(&mut app, EnginePhase::Layout);
2646        assert_eq!(offset_of(&app, first).dy(), 0.0);
2647        assert_eq!(offset_of(&app, second).dy(), 0.0);
2648    }
2649
2650    /// `flex_test.dart`: `Vertical Flex Baseline`. A column's baseline is its first child's
2651    /// baseline, wherever the main axis alignment and the vertical direction place that child;
2652    /// the dry baseline and the laid-out one agree.
2653    #[test]
2654    fn a_column_s_baseline_is_its_first_child_s_baseline() {
2655        let cell = AppCell::new();
2656        let mut app = cell.borrow_mut();
2657        let square = BoxConstraints::tight_for(Some(100.0), Some(100.0));
2658        let boxed = |app: &mut App, baseline: Option<AnyRenderBox>| {
2659            crate::proxy_box::RenderConstrainedBox::new(app, square, baseline).as_box()
2660        };
2661        let first_inner = flow_baseline_box(&mut app, 1, |_| Some(10.0));
2662        let second_inner = flow_baseline_box(&mut app, 1, |_| Some(10.0));
2663        let children = vec![
2664            boxed(&mut app, None),
2665            boxed(&mut app, Some(first_inner)),
2666            boxed(&mut app, None),
2667            boxed(&mut app, Some(second_inner)),
2668            boxed(&mut app, None),
2669        ];
2670        let flex = RenderFlex::new(&mut app);
2671        flex.set_text_direction(&mut app, Some(TextDirection::Ltr));
2672        flex.set_direction(&mut app, Axis::Vertical);
2673        flex.add_all(&mut app, Some(children));
2674        let constraints = BoxConstraints::tight(Size::new(800.0, 600.0));
2675        layout_with(
2676            &mut app,
2677            flex.as_box(),
2678            None,
2679            AlignmentGeometry::CENTER,
2680            EnginePhase::Paint,
2681        );
2682        let flex_height = flex.size(&app).height();
2683
2684        let expect_baseline = |app: &mut App, expected: f64| {
2685            let column = flex.as_box();
2686            assert_eq!(
2687                column.get_dry_baseline(app, constraints, TextBaseline::Alphabetic),
2688                Some(expected)
2689            );
2690            assert_eq!(
2691                column.get_distance_to_baseline(app, TextBaseline::Alphabetic, true),
2692                Some(expected)
2693            );
2694        };
2695        expect_baseline(&mut app, 100.0 + 10.0);
2696
2697        flex.set_main_axis_alignment(&mut app, MainAxisAlignment::End);
2698        pump_frame(&mut app, EnginePhase::Paint);
2699        expect_baseline(&mut app, flex_height - 400.0 + 10.0);
2700
2701        flex.set_vertical_direction(&mut app, VerticalDirection::Up);
2702        pump_frame(&mut app, EnginePhase::Paint);
2703        expect_baseline(&mut app, 300.0 + 10.0);
2704
2705        flex.set_main_axis_alignment(&mut app, MainAxisAlignment::Start);
2706        pump_frame(&mut app, EnginePhase::Paint);
2707        expect_baseline(&mut app, flex_height - 200.0 + 10.0);
2708    }
2709
2710    /// `flex_test.dart`: `baseline aligned flex flow computeDryLayout`. The cross extent is the
2711    /// tallest ascent plus the deepest descent, and the dry baseline is the tallest ascent.
2712    #[test]
2713    fn baseline_aligned_dry_layout_adds_the_largest_ascent_and_descent() {
2714        let cell = AppCell::new();
2715        let mut app = cell.borrow_mut();
2716        // The first box has its baseline at its top, the second at its bottom.
2717        let first = flow_baseline_box(&mut app, 10, |_| Some(0.0));
2718        let second = flow_baseline_box(&mut app, 10, Some);
2719        let flex = baseline_row(&mut app, vec![first, second]);
2720        set_flex(&mut app, first, 2, FlexFit::Tight);
2721        set_flex(&mut app, second, 1, FlexFit::Loose);
2722        let flex = flex.as_box();
2723
2724        // The first box one line, the second two lines.
2725        let constraints = BoxConstraints::loose(Size::new(200.0, 100.0));
2726        assert_eq!(
2727            flex.get_dry_layout(&mut app, constraints),
2728            Size::new(200.0, 30.0)
2729        );
2730        assert_eq!(
2731            flex.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic),
2732            Some(20.0)
2733        );
2734        // Both boxes one line.
2735        let constraints = BoxConstraints::loose(Size::new(300.0, 100.0));
2736        assert_eq!(
2737            flex.get_dry_layout(&mut app, constraints),
2738            Size::new(300.0, 20.0)
2739        );
2740        assert_eq!(
2741            flex.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic),
2742            Some(10.0)
2743        );
2744    }
2745
2746    /// `flex_test.dart`: `baseline aligned children cross intrinsic size`.
2747    #[test]
2748    fn baseline_aligned_cross_intrinsics_add_the_largest_ascent_and_descent() {
2749        let cell = AppCell::new();
2750        let mut app = cell.borrow_mut();
2751        let first = flow_baseline_box(&mut app, 10, |_| Some(0.0));
2752        let second = flow_baseline_box(&mut app, 10, Some);
2753        let flex = baseline_row(&mut app, vec![first, second]);
2754        set_flex(&mut app, first, 2, FlexFit::Tight);
2755        set_flex(&mut app, second, 1, FlexFit::Loose);
2756        let flex = flex.as_box();
2757
2758        // The first box one line, the second two lines.
2759        assert_eq!(flex.get_max_intrinsic_height(&mut app, 200.0), 30.0);
2760        assert_eq!(flex.get_min_intrinsic_height(&mut app, 200.0), 30.0);
2761        // Both boxes one line.
2762        assert_eq!(flex.get_max_intrinsic_height(&mut app, 300.0), 20.0);
2763        assert_eq!(flex.get_min_intrinsic_height(&mut app, 300.0), 20.0);
2764    }
2765
2766    /// `flex_test.dart`: `children with no baselines do not affect the baseline location`; a
2767    /// taller child without one still counts towards the cross extent.
2768    #[test]
2769    fn children_with_no_baselines_do_not_affect_the_baseline_location() {
2770        let cell = AppCell::new();
2771        let mut app = cell.borrow_mut();
2772        let first = flow_baseline_box(&mut app, 10, Some);
2773        let second = flow_baseline_box(&mut app, 10, |_| None);
2774        let flex = baseline_row(&mut app, vec![first, second]);
2775        set_flex(&mut app, first, 2, FlexFit::Tight);
2776        set_flex(&mut app, second, 1, FlexFit::Loose);
2777        let flex = flex.as_box();
2778
2779        // The first box one line, the second two lines.
2780        let constraints = BoxConstraints::loose(Size::new(200.0, 100.0));
2781        assert_eq!(
2782            flex.get_dry_layout(&mut app, constraints),
2783            Size::new(200.0, 20.0)
2784        );
2785        assert_eq!(
2786            flex.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic),
2787            Some(10.0)
2788        );
2789        // Both boxes one line.
2790        let constraints = BoxConstraints::loose(Size::new(300.0, 100.0));
2791        assert_eq!(
2792            flex.get_dry_layout(&mut app, constraints),
2793            Size::new(300.0, 10.0)
2794        );
2795        assert_eq!(
2796            flex.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic),
2797            Some(10.0)
2798        );
2799    }
2800
2801    /// Laying a baseline-aligned row out puts each child's baseline on the row's baseline, a
2802    /// child without one at the top, and the extra cross space below them all; the dry layout
2803    /// and the dry baseline agree with it.
2804    #[test]
2805    fn layout_places_the_children_on_a_shared_baseline() {
2806        let cell = AppCell::new();
2807        let mut app = cell.borrow_mut();
2808        let tight_box = |app: &mut App, size: Size, child: Option<AnyRenderBox>| {
2809            crate::proxy_box::RenderConstrainedBox::new(app, BoxConstraints::tight(size), child)
2810                .as_box()
2811        };
2812        // 30 above the baseline and 10 below it; 10 above and 10 below; 50 tall with none.
2813        let deep_baseline = flow_baseline_box(&mut app, 1, |_| Some(30.0));
2814        let deep = tight_box(&mut app, Size::new(10.0, 40.0), Some(deep_baseline));
2815        let shallow_baseline = flow_baseline_box(&mut app, 1, |_| Some(10.0));
2816        let shallow = tight_box(&mut app, Size::new(10.0, 20.0), Some(shallow_baseline));
2817        let without = tight_box(&mut app, Size::new(10.0, 50.0), None);
2818        let flex = baseline_row(&mut app, vec![deep, shallow, without]);
2819        let row = flex.as_box();
2820        let loose = BoxConstraints::loose(Size::new(200.0, 100.0));
2821        let dry_size = row.get_dry_layout(&mut app, loose);
2822        let dry_baseline = row.get_dry_baseline(&mut app, loose, TextBaseline::Alphabetic);
2823        layout_with(
2824            &mut app,
2825            row,
2826            Some(loose),
2827            AlignmentGeometry::CENTER,
2828            EnginePhase::Layout,
2829        );
2830
2831        assert_eq!(flex.size(&app), Size::new(200.0, 50.0));
2832        assert_eq!(offset_of(&app, deep).dy(), 0.0);
2833        assert_eq!(offset_of(&app, shallow).dy(), 20.0);
2834        assert_eq!(offset_of(&app, without).dy(), 0.0);
2835        let baseline = row.get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, true);
2836        assert_eq!(baseline, Some(30.0));
2837        assert_eq!(
2838            (dry_size, dry_baseline),
2839            (flex.size(&app), baseline),
2840            "the dry layout is the real layout"
2841        );
2842
2843        let tall = BoxConstraints {
2844            min_height: 100.0,
2845            ..loose
2846        };
2847        row.layout(&mut app, tall, false);
2848        assert_eq!(flex.size(&app), Size::new(200.0, 100.0));
2849        assert_eq!(
2850            offset_of(&app, shallow).dy(),
2851            20.0,
2852            "the extra space is below the children"
2853        );
2854    }
2855}