Skip to main content

waft_rendering/
wrap.rs

1//! Flutter counterpart: `rendering/wrap.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt;
5use std::ops::{Add, Sub};
6
7use waft_embedder::{Clip, Offset, Size, TextBaseline, TextDirection};
8use waft_foundation::{
9    App, DiagnosticPropertiesBuilder, DoubleProperty, EnumProperty, Handle,
10    PRECISION_ERROR_TOLERANCE,
11};
12use waft_painting::{Axis, VerticalDirection};
13
14use crate::box_::{
15    AnyRenderBox, BaselineOffset, BoxConstraints, BoxHitTestResult, BoxParentData,
16    ContainerBoxParentData, RenderBox, RenderBoxContainerDefaultsMixin, RenderBoxData,
17};
18use crate::layer::{ClipRectLayer, LayerHandle};
19use crate::layout_helper::{ChildLayoutHelper, ChildLayouter};
20use crate::object::{
21    AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectData,
22    ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, RenderObjectData,
23};
24use crate::painting_context::PaintingContext;
25use crate::pipeline_owner::PipelineOwner;
26
27/// A 2D vector that uses a [`RenderWrap`]'s main axis and cross axis as its first and second
28/// coordinate axes. It represents the same vector as `(main_axis_extent, cross_axis_extent)`.
29#[derive(Clone, Copy)]
30struct AxisSize(Size);
31
32impl AxisSize {
33    const EMPTY: AxisSize = AxisSize(Size::ZERO);
34
35    fn new(main_axis_extent: f64, cross_axis_extent: f64) -> AxisSize {
36        AxisSize(Size::new(main_axis_extent, cross_axis_extent))
37    }
38
39    fn from_size(size: Size, direction: Axis) -> AxisSize {
40        AxisSize(AxisSize::convert(size, direction))
41    }
42
43    fn convert(size: Size, direction: Axis) -> Size {
44        match direction {
45            Axis::Horizontal => size,
46            Axis::Vertical => size.flipped(),
47        }
48    }
49
50    fn main_axis_extent(self) -> f64 {
51        self.0.width()
52    }
53
54    fn cross_axis_extent(self) -> f64 {
55        self.0.height()
56    }
57
58    fn to_size(self, direction: Axis) -> Size {
59        AxisSize::convert(self.0, direction)
60    }
61
62    fn apply_constraints(self, constraints: BoxConstraints, direction: Axis) -> AxisSize {
63        let effective_constraints = match direction {
64            Axis::Horizontal => constraints,
65            Axis::Vertical => constraints.flipped(),
66        };
67        AxisSize(effective_constraints.constrain(self.0))
68    }
69
70    fn flipped(self) -> AxisSize {
71        AxisSize(self.0.flipped())
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
86impl Sub for AxisSize {
87    type Output = AxisSize;
88
89    fn sub(self, other: AxisSize) -> AxisSize {
90        AxisSize(Size::new(
91            self.0.width() - other.0.width(),
92            self.0.height() - other.0.height(),
93        ))
94    }
95}
96
97/// How [`RenderWrap`] should align objects.
98///
99/// Used both to align children within a run in the main axis as well as to align the runs
100/// themselves in the cross axis.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
102pub enum WrapAlignment {
103    /// Place the objects as close to the start of the axis as possible.
104    ///
105    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available
106    /// to determine if the start is the left or the right.
107    ///
108    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
109    /// to determine if the start is the top or the bottom.
110    #[default]
111    Start,
112
113    /// Place the objects as close to the end of the axis as possible.
114    ///
115    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available
116    /// to determine if the end is the left or the right.
117    ///
118    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
119    /// to determine if the end is the top or the bottom.
120    End,
121
122    /// Place the objects as close to the middle of the axis as possible.
123    Center,
124
125    /// Place the free space evenly between the objects.
126    SpaceBetween,
127
128    /// Place the free space evenly between the objects as well as half of that space before and
129    /// after the first and last objects.
130    SpaceAround,
131
132    /// Place the free space evenly between the objects as well as before and after the first
133    /// and last objects.
134    SpaceEvenly,
135}
136
137impl WrapAlignment {
138    /// The space before the first object and between each two, for `item_count` objects.
139    fn distribute_space(
140        self,
141        free_space: f64,
142        item_spacing: f64,
143        item_count: usize,
144        flipped: bool,
145    ) -> (f64, f64) {
146        debug_assert!(item_count > 0);
147        let count = item_count as f64;
148        match self {
149            WrapAlignment::Start => (if flipped { free_space } else { 0.0 }, item_spacing),
150            WrapAlignment::End => WrapAlignment::Start.distribute_space(
151                free_space,
152                item_spacing,
153                item_count,
154                !flipped,
155            ),
156            WrapAlignment::SpaceBetween if item_count < 2 => {
157                WrapAlignment::Start.distribute_space(free_space, item_spacing, item_count, flipped)
158            }
159            WrapAlignment::Center => (free_space / 2.0, item_spacing),
160            WrapAlignment::SpaceBetween => (0.0, free_space / (count - 1.0) + item_spacing),
161            WrapAlignment::SpaceAround => {
162                (free_space / count / 2.0, free_space / count + item_spacing)
163            }
164            WrapAlignment::SpaceEvenly => (
165                free_space / (count + 1.0),
166                free_space / (count + 1.0) + item_spacing,
167            ),
168        }
169    }
170}
171
172/// Who [`RenderWrap`] should align children within a run in the cross axis.
173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
174pub enum WrapCrossAlignment {
175    /// Place the children as close to the start of the run in the cross axis as possible.
176    ///
177    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available
178    /// to determine if the start is the left or the right.
179    ///
180    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
181    /// to determine if the start is the top or the bottom.
182    #[default]
183    Start,
184
185    /// Place the children as close to the end of the run in the cross axis as possible.
186    ///
187    /// If this value is used in a horizontal direction, a [`TextDirection`] must be available
188    /// to determine if the end is the left or the right.
189    ///
190    /// If this value is used in a vertical direction, a [`VerticalDirection`] must be available
191    /// to determine if the end is the top or the bottom.
192    End,
193
194    /// Place the children as close to the middle of the run in the cross axis as possible.
195    Center,
196    // TODO(ianh): baseline.
197}
198
199impl WrapCrossAlignment {
200    fn flipped(self) -> WrapCrossAlignment {
201        match self {
202            WrapCrossAlignment::Start => WrapCrossAlignment::End,
203            WrapCrossAlignment::End => WrapCrossAlignment::Start,
204            WrapCrossAlignment::Center => WrapCrossAlignment::Center,
205        }
206    }
207
208    fn alignment(self) -> f64 {
209        match self {
210            WrapCrossAlignment::Start => 0.0,
211            WrapCrossAlignment::End => 1.0,
212            WrapCrossAlignment::Center => 0.5,
213        }
214    }
215}
216
217/// A run's extent, its number of children, and the child it starts placing from.
218struct RunMetrics {
219    axis_size: AxisSize,
220    child_count: usize,
221    leading_child: AnyRenderBox,
222}
223
224impl RunMetrics {
225    fn new(leading_child: AnyRenderBox, axis_size: AxisSize) -> RunMetrics {
226        RunMetrics {
227            axis_size,
228            child_count: 1,
229            leading_child,
230        }
231    }
232
233    // Look ahead, creates a new run if incorporating the child would exceed the allowed line
234    // width.
235    fn try_adding_new_child(
236        &mut self,
237        child: AnyRenderBox,
238        child_size: AxisSize,
239        flip_main_axis: bool,
240        spacing: f64,
241        max_main_extent: f64,
242    ) -> Option<RunMetrics> {
243        let needs_new_run =
244            self.axis_size.main_axis_extent() + child_size.main_axis_extent() + spacing
245                - max_main_extent
246                > PRECISION_ERROR_TOLERANCE;
247        if needs_new_run {
248            return Some(RunMetrics::new(child, child_size));
249        }
250        self.axis_size = self.axis_size + child_size + AxisSize::new(spacing, 0.0);
251        self.child_count += 1;
252        if flip_main_axis {
253            self.leading_child = child;
254        }
255        None
256    }
257}
258
259/// Parent data for use with [`RenderWrap`].
260#[derive(Debug, Default)]
261pub struct WrapParentData {
262    box_parent_data: BoxParentData,
263    container_parent_data: ContainerParentData<AnyRenderBox>,
264}
265
266impl WrapParentData {
267    /// Creates wrap parent data at offset zero, with no siblings.
268    pub const fn new() -> WrapParentData {
269        WrapParentData {
270            box_parent_data: BoxParentData::new(),
271            container_parent_data: ContainerParentData::new(),
272        }
273    }
274}
275
276impl ParentData for WrapParentData {
277    fn detach(&mut self) {
278        ContainerParentDataMixin::detach(self);
279    }
280
281    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
282        if id == TypeId::of::<WrapParentData>() {
283            return Some(self);
284        }
285        self.box_parent_data.provide(id)
286    }
287
288    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
289        if id == TypeId::of::<WrapParentData>() {
290            return Some(self);
291        }
292        self.box_parent_data.provide_mut(id)
293    }
294}
295
296impl ContainerParentDataMixin for WrapParentData {
297    type ChildType = AnyRenderBox;
298
299    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
300        &self.container_parent_data
301    }
302
303    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
304        &mut self.container_parent_data
305    }
306}
307
308impl ContainerBoxParentData for WrapParentData {
309    fn box_parent_data(&self) -> &BoxParentData {
310        &self.box_parent_data
311    }
312
313    fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
314        &mut self.box_parent_data
315    }
316}
317
318impl fmt::Display for WrapParentData {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        fmt::Display::fmt(&self.box_parent_data, f)
321    }
322}
323
324/// Displays its children in multiple horizontal or vertical runs.
325///
326/// A [`RenderWrap`] lays out each child and attempts to place the child adjacent to the previous
327/// child in the main axis, given by [`direction`](Self::direction), leaving
328/// [`spacing`](Self::spacing) space in between. If there is not enough space to fit the child,
329/// [`RenderWrap`] creates a new _run_ adjacent to the existing children in the cross axis.
330///
331/// After all the children have been allocated to runs, the children within the runs are
332/// positioned according to the [`alignment`](Self::alignment) in the main axis and according
333/// to the [`cross_axis_alignment`](Self::cross_axis_alignment) in the cross axis.
334///
335/// The runs themselves are then positioned in the cross axis according to the
336/// [`run_spacing`](Self::run_spacing) and [`run_alignment`](Self::run_alignment).
337pub struct RenderWrap {
338    render_object: RenderObjectData,
339    render_box: RenderBoxData,
340    container: ContainerRenderObjectData<AnyRenderBox>,
341    direction: Axis,
342    alignment: WrapAlignment,
343    spacing: f64,
344    run_alignment: WrapAlignment,
345    run_spacing: f64,
346    cross_axis_alignment: WrapCrossAlignment,
347    text_direction: Option<TextDirection>,
348    vertical_direction: VerticalDirection,
349    clip_behavior: Clip,
350    has_visual_overflow: bool,
351    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
352}
353
354impl RenderWrap {
355    /// Creates a wrap render object.
356    ///
357    /// By default, the wrap layout is horizontal and both the children and the runs are aligned
358    /// to the start. Add children with [`add`](ContainerRenderObjectMixin::add) or
359    /// [`add_all`](ContainerRenderObjectMixin::add_all); Dart's constructor takes them, and its
360    /// other named arguments are the setters.
361    pub fn new(app: &mut App) -> RenderHandle<RenderWrap> {
362        RenderHandle::new_box(
363            app,
364            RenderWrap {
365                render_object: RenderObjectData::new(),
366                render_box: RenderBoxData::new(),
367                container: ContainerRenderObjectData::new(),
368                direction: Axis::Horizontal,
369                alignment: WrapAlignment::Start,
370                spacing: 0.0,
371                run_alignment: WrapAlignment::Start,
372                run_spacing: 0.0,
373                cross_axis_alignment: WrapCrossAlignment::Start,
374                text_direction: None,
375                vertical_direction: VerticalDirection::Down,
376                clip_behavior: Clip::None,
377                has_visual_overflow: false,
378                clip_rect_layer: LayerHandle::new(),
379            },
380        )
381    }
382
383    /// The direction to use as the main axis.
384    ///
385    /// For example, if [`direction`](Self::direction) is [`Axis::Horizontal`], the default, the
386    /// children are placed adjacent to one another in a horizontal run until the available
387    /// horizontal space is consumed, at which point a subsequent children are placed in a new
388    /// run vertically adjacent to the previous run.
389    pub fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
390        self.get(app).direction
391    }
392
393    /// Sets [`direction`](Self::direction).
394    pub fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
395        if self.get(app).direction == value {
396            return;
397        }
398        self.get_mut(app).direction = value;
399        self.mark_needs_layout(app);
400    }
401
402    /// How the children within a run should be placed in the main axis.
403    ///
404    /// For example, if [`alignment`](Self::alignment) is [`WrapAlignment::Center`], the
405    /// children in each run are grouped together in the center of their run in the main axis.
406    ///
407    /// Defaults to [`WrapAlignment::Start`].
408    ///
409    /// See also:
410    ///
411    ///  * [`run_alignment`](Self::run_alignment), which controls how the runs are placed
412    ///    relative to each other in the cross axis.
413    ///  * [`cross_axis_alignment`](Self::cross_axis_alignment), which controls how the children
414    ///    within each run are placed relative to each other in the cross axis.
415    pub fn alignment(self: RenderHandle<Self>, app: &App) -> WrapAlignment {
416        self.get(app).alignment
417    }
418
419    /// Sets [`alignment`](Self::alignment).
420    pub fn set_alignment(self: RenderHandle<Self>, app: &mut App, value: WrapAlignment) {
421        if self.get(app).alignment == value {
422            return;
423        }
424        self.get_mut(app).alignment = value;
425        self.mark_needs_layout(app);
426    }
427
428    /// How much space to place between children in a run in the main axis.
429    ///
430    /// For example, if [`spacing`](Self::spacing) is 10.0, the children will be spaced at least
431    /// 10.0 logical pixels apart in the main axis.
432    ///
433    /// If there is additional free space in a run (e.g., because the wrap has a minimum size
434    /// that is not filled or because some runs are longer than others), the additional free
435    /// space will be allocated according to the [`alignment`](Self::alignment).
436    ///
437    /// Defaults to 0.0.
438    pub fn spacing(self: RenderHandle<Self>, app: &App) -> f64 {
439        self.get(app).spacing
440    }
441
442    /// Sets [`spacing`](Self::spacing).
443    pub fn set_spacing(self: RenderHandle<Self>, app: &mut App, value: f64) {
444        if self.get(app).spacing == value {
445            return;
446        }
447        self.get_mut(app).spacing = value;
448        self.mark_needs_layout(app);
449    }
450
451    /// How the runs themselves should be placed in the cross axis.
452    ///
453    /// For example, if [`run_alignment`](Self::run_alignment) is [`WrapAlignment::Center`], the
454    /// runs are grouped together in the center of the overall [`RenderWrap`] in the cross axis.
455    ///
456    /// Defaults to [`WrapAlignment::Start`].
457    ///
458    /// See also:
459    ///
460    ///  * [`alignment`](Self::alignment), which controls how the children within each run are
461    ///    placed relative to each other in the main axis.
462    ///  * [`cross_axis_alignment`](Self::cross_axis_alignment), which controls how the children
463    ///    within each run are placed relative to each other in the cross axis.
464    pub fn run_alignment(self: RenderHandle<Self>, app: &App) -> WrapAlignment {
465        self.get(app).run_alignment
466    }
467
468    /// Sets [`run_alignment`](Self::run_alignment).
469    pub fn set_run_alignment(self: RenderHandle<Self>, app: &mut App, value: WrapAlignment) {
470        if self.get(app).run_alignment == value {
471            return;
472        }
473        self.get_mut(app).run_alignment = value;
474        self.mark_needs_layout(app);
475    }
476
477    /// How much space to place between the runs themselves in the cross axis.
478    ///
479    /// For example, if [`run_spacing`](Self::run_spacing) is 10.0, the runs will be spaced at
480    /// least 10.0 logical pixels apart in the cross axis.
481    ///
482    /// If there is additional free space in the overall [`RenderWrap`] (e.g., because the wrap
483    /// has a minimum size that is not filled), the additional free space will be allocated
484    /// according to the [`run_alignment`](Self::run_alignment).
485    ///
486    /// Defaults to 0.0.
487    pub fn run_spacing(self: RenderHandle<Self>, app: &App) -> f64 {
488        self.get(app).run_spacing
489    }
490
491    /// Sets [`run_spacing`](Self::run_spacing).
492    pub fn set_run_spacing(self: RenderHandle<Self>, app: &mut App, value: f64) {
493        if self.get(app).run_spacing == value {
494            return;
495        }
496        self.get_mut(app).run_spacing = value;
497        self.mark_needs_layout(app);
498    }
499
500    /// How the children within a run should be aligned relative to each other in the cross
501    /// axis.
502    ///
503    /// For example, if this is set to [`WrapCrossAlignment::End`], and the
504    /// [`direction`](Self::direction) is [`Axis::Horizontal`], then the children within each
505    /// run will have their bottom edges aligned to the bottom edge of the run.
506    ///
507    /// Defaults to [`WrapCrossAlignment::Start`].
508    ///
509    /// See also:
510    ///
511    ///  * [`alignment`](Self::alignment), which controls how the children within each run are
512    ///    placed relative to each other in the main axis.
513    ///  * [`run_alignment`](Self::run_alignment), which controls how the runs are placed
514    ///    relative to each other in the cross axis.
515    pub fn cross_axis_alignment(self: RenderHandle<Self>, app: &App) -> WrapCrossAlignment {
516        self.get(app).cross_axis_alignment
517    }
518
519    /// Sets [`cross_axis_alignment`](Self::cross_axis_alignment).
520    pub fn set_cross_axis_alignment(
521        self: RenderHandle<Self>,
522        app: &mut App,
523        value: WrapCrossAlignment,
524    ) {
525        if self.get(app).cross_axis_alignment == value {
526            return;
527        }
528        self.get_mut(app).cross_axis_alignment = value;
529        self.mark_needs_layout(app);
530    }
531
532    /// Determines the order to lay children out horizontally and how to interpret `start` and
533    /// `end` in the horizontal direction.
534    ///
535    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the order in
536    /// which children are positioned (left-to-right or right-to-left), and the meaning of the
537    /// [`alignment`](Self::alignment) property's [`WrapAlignment::Start`] and
538    /// [`WrapAlignment::End`] values.
539    ///
540    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], and either the
541    /// [`alignment`](Self::alignment) is either [`WrapAlignment::Start`] or
542    /// [`WrapAlignment::End`], or there's more than one child, then the
543    /// [`text_direction`](Self::text_direction) must not be `None`.
544    ///
545    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls the order in
546    /// which runs are positioned, the meaning of the [`run_alignment`](Self::run_alignment)
547    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values, as well as the
548    /// [`cross_axis_alignment`](Self::cross_axis_alignment) property's
549    /// [`WrapCrossAlignment::Start`] and [`WrapCrossAlignment::End`] values.
550    ///
551    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], and either the
552    /// [`run_alignment`](Self::run_alignment) is either [`WrapAlignment::Start`] or
553    /// [`WrapAlignment::End`], the [`cross_axis_alignment`](Self::cross_axis_alignment) is
554    /// either [`WrapCrossAlignment::Start`] or [`WrapCrossAlignment::End`], or there's more
555    /// than one child, then the [`text_direction`](Self::text_direction) must not be `None`.
556    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
557        self.get(app).text_direction
558    }
559
560    /// Sets [`text_direction`](Self::text_direction).
561    pub fn set_text_direction(
562        self: RenderHandle<Self>,
563        app: &mut App,
564        value: Option<TextDirection>,
565    ) {
566        if self.get(app).text_direction != value {
567            self.get_mut(app).text_direction = value;
568            self.mark_needs_layout(app);
569        }
570    }
571
572    /// Determines the order to lay children out vertically and how to interpret `start` and
573    /// `end` in the vertical direction.
574    ///
575    /// If the [`direction`](Self::direction) is [`Axis::Vertical`], this controls which order
576    /// children are painted in (down or up), the meaning of the [`alignment`](Self::alignment)
577    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values.
578    ///
579    /// If the [`direction`](Self::direction) is [`Axis::Horizontal`], this controls the order
580    /// in which runs are positioned, the meaning of the [`run_alignment`](Self::run_alignment)
581    /// property's [`WrapAlignment::Start`] and [`WrapAlignment::End`] values, as well as the
582    /// [`cross_axis_alignment`](Self::cross_axis_alignment) property's
583    /// [`WrapCrossAlignment::Start`] and [`WrapCrossAlignment::End`] values.
584    pub fn vertical_direction(self: RenderHandle<Self>, app: &App) -> VerticalDirection {
585        self.get(app).vertical_direction
586    }
587
588    /// Sets [`vertical_direction`](Self::vertical_direction).
589    pub fn set_vertical_direction(
590        self: RenderHandle<Self>,
591        app: &mut App,
592        value: VerticalDirection,
593    ) {
594        if self.get(app).vertical_direction != value {
595            self.get_mut(app).vertical_direction = value;
596            self.mark_needs_layout(app);
597        }
598    }
599
600    /// The content will be clipped (or not) according to this option.
601    ///
602    /// Defaults to [`Clip::None`].
603    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
604        self.get(app).clip_behavior
605    }
606
607    /// Sets [`clip_behavior`](Self::clip_behavior).
608    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
609        if value != self.get(app).clip_behavior {
610            self.get_mut(app).clip_behavior = value;
611            self.mark_needs_paint(app);
612        }
613    }
614
615    /// Flutter's `_debugHasNecessaryDirections`: asserts the directions the current alignments
616    /// need are available. Always returns true.
617    fn debug_has_necessary_directions(self: RenderHandle<Self>, app: &App) -> bool {
618        let this = self.get(app);
619        let has_text_direction = this.text_direction.is_some();
620        if self.first_child(app).is_some() && self.last_child(app) != self.first_child(app) {
621            // i.e. there's more than one child
622            if this.direction == Axis::Horizontal {
623                debug_assert!(
624                    has_text_direction,
625                    "Horizontal RenderWrap with multiple children has a null textDirection, so \
626                     the layout order is undefined."
627                );
628            }
629        }
630        let alignment = this.alignment;
631        if matches!(alignment, WrapAlignment::Start | WrapAlignment::End)
632            && this.direction == Axis::Horizontal
633        {
634            debug_assert!(
635                has_text_direction,
636                "Horizontal RenderWrap with alignment {alignment:?} has a null textDirection, so \
637                 the alignment cannot be resolved."
638            );
639        }
640        let run_alignment = this.run_alignment;
641        if matches!(run_alignment, WrapAlignment::Start | WrapAlignment::End)
642            && this.direction == Axis::Vertical
643        {
644            debug_assert!(
645                has_text_direction,
646                "Vertical RenderWrap with runAlignment {run_alignment:?} has a null \
647                 textDirection, so the alignment cannot be resolved."
648            );
649        }
650        let cross_axis_alignment = this.cross_axis_alignment;
651        if matches!(
652            cross_axis_alignment,
653            WrapCrossAlignment::Start | WrapCrossAlignment::End
654        ) && this.direction == Axis::Vertical
655        {
656            debug_assert!(
657                has_text_direction,
658                "Vertical RenderWrap with crossAxisAlignment {cross_axis_alignment:?} has a \
659                 null textDirection, so the alignment cannot be resolved."
660            );
661        }
662        true
663    }
664
665    fn get_main_axis_extent(self: RenderHandle<Self>, app: &App, child_size: Size) -> f64 {
666        match self.direction(app) {
667            Axis::Horizontal => child_size.width(),
668            Axis::Vertical => child_size.height(),
669        }
670    }
671
672    fn get_cross_axis_extent(self: RenderHandle<Self>, app: &App, child_size: Size) -> f64 {
673        match self.direction(app) {
674            Axis::Horizontal => child_size.height(),
675            Axis::Vertical => child_size.width(),
676        }
677    }
678
679    fn get_offset(
680        self: RenderHandle<Self>,
681        app: &App,
682        main_axis_offset: f64,
683        cross_axis_offset: f64,
684    ) -> Offset {
685        match self.direction(app) {
686            Axis::Horizontal => Offset::new(main_axis_offset, cross_axis_offset),
687            Axis::Vertical => Offset::new(cross_axis_offset, main_axis_offset),
688        }
689    }
690
691    /// Whether the main axis and the cross axis run against their coordinates.
692    fn are_axes_flipped(self: RenderHandle<Self>, app: &App) -> (bool, bool) {
693        let this = self.get(app);
694        let flip_horizontal = match this.text_direction.unwrap_or(TextDirection::Ltr) {
695            TextDirection::Ltr => false,
696            TextDirection::Rtl => true,
697        };
698        let flip_vertical = match this.vertical_direction {
699            VerticalDirection::Down => false,
700            VerticalDirection::Up => true,
701        };
702        match this.direction {
703            Axis::Horizontal => (flip_horizontal, flip_vertical),
704            Axis::Vertical => (flip_vertical, flip_horizontal),
705        }
706    }
707
708    /// The constraints a child is laid out with, and the main axis extent a run fills.
709    fn child_constraints_and_main_axis_limit(
710        self: RenderHandle<Self>,
711        app: &App,
712        constraints: BoxConstraints,
713    ) -> (BoxConstraints, f64) {
714        match self.direction(app) {
715            Axis::Horizontal => (
716                BoxConstraints::new().max_width(constraints.max_width),
717                constraints.max_width,
718            ),
719            Axis::Vertical => (
720                BoxConstraints::new().max_height(constraints.max_height),
721                constraints.max_height,
722            ),
723        }
724    }
725
726    /// The size this wrap would take, measuring the children dry.
727    fn compute_dry_layout_size(
728        self: RenderHandle<Self>,
729        app: &mut App,
730        constraints: BoxConstraints,
731    ) -> Size {
732        let (child_constraints, main_axis_limit) =
733            self.child_constraints_and_main_axis_limit(app, constraints);
734        let (spacing, run_spacing) = (self.spacing(app), self.run_spacing(app));
735
736        let mut main_axis_extent: f64 = 0.0;
737        let mut cross_axis_extent = 0.0;
738        let mut run_main_axis_extent = 0.0;
739        let mut run_cross_axis_extent: f64 = 0.0;
740        let mut child_count = 0;
741        let mut child = self.first_child(app);
742        while let Some(current) = child {
743            let child_size = ChildLayoutHelper::dry_layout_child(app, current, child_constraints);
744            let child_main_axis_extent = self.get_main_axis_extent(app, child_size);
745            let child_cross_axis_extent = self.get_cross_axis_extent(app, child_size);
746            // There must be at least one child before we move on to the next run.
747            if child_count > 0
748                && run_main_axis_extent + child_main_axis_extent + spacing > main_axis_limit
749            {
750                main_axis_extent = main_axis_extent.max(run_main_axis_extent);
751                cross_axis_extent += run_cross_axis_extent + run_spacing;
752                run_main_axis_extent = 0.0;
753                run_cross_axis_extent = 0.0;
754                child_count = 0;
755            }
756            run_main_axis_extent += child_main_axis_extent;
757            run_cross_axis_extent = run_cross_axis_extent.max(child_cross_axis_extent);
758            if child_count > 0 {
759                run_main_axis_extent += spacing;
760            }
761            child_count += 1;
762            child = self.child_after(app, current);
763        }
764        cross_axis_extent += run_cross_axis_extent;
765        main_axis_extent = main_axis_extent.max(run_main_axis_extent);
766
767        constraints.constrain(match self.direction(app) {
768            Axis::Horizontal => Size::new(main_axis_extent, cross_axis_extent),
769            Axis::Vertical => Size::new(cross_axis_extent, main_axis_extent),
770        })
771    }
772
773    /// Lays out (or measures) the children with `layout_child` and splits them into runs:
774    /// the extent the runs take together, and each run.
775    fn compute_runs(
776        self: RenderHandle<Self>,
777        app: &mut App,
778        constraints: BoxConstraints,
779        layout_child: ChildLayouter,
780    ) -> (AxisSize, Vec<RunMetrics>) {
781        debug_assert!(self.first_child(app).is_some());
782        let (child_constraints, main_axis_limit) =
783            self.child_constraints_and_main_axis_limit(app, constraints);
784
785        let (flip_main_axis, _) = self.are_axes_flipped(app);
786        let direction = self.direction(app);
787        let spacing = self.spacing(app);
788        let mut run_metrics: Vec<RunMetrics> = Vec::new();
789
790        let mut children_axis_size = AxisSize::EMPTY;
791        let mut child = self.first_child(app);
792        while let Some(current) = child {
793            let child_size =
794                AxisSize::from_size(layout_child(app, current, child_constraints), direction);
795            let new_run = match run_metrics.last_mut() {
796                None => Some(RunMetrics::new(current, child_size)),
797                Some(current_run) => current_run.try_adding_new_child(
798                    current,
799                    child_size,
800                    flip_main_axis,
801                    spacing,
802                    main_axis_limit,
803                ),
804            };
805            if let Some(new_run) = new_run {
806                if let Some(current_run) = run_metrics.last() {
807                    children_axis_size = children_axis_size + current_run.axis_size.flipped();
808                }
809                run_metrics.push(new_run);
810            }
811            child = self.child_after(app, current);
812        }
813        debug_assert!(!run_metrics.is_empty());
814        let total_run_spacing = self.run_spacing(app) * (run_metrics.len() - 1) as f64;
815        let current_run = run_metrics.last().expect("at least one run");
816        children_axis_size = children_axis_size
817            + (AxisSize::new(total_run_spacing, 0.0) + current_run.axis_size.flipped());
818        (children_axis_size.flipped(), run_metrics)
819    }
820
821    /// Places each child of `run_metrics` within the container: `position_child` is told each
822    /// child's offset, and `get_child_size` gives each child's size.
823    fn position_children(
824        self: RenderHandle<Self>,
825        app: &mut App,
826        run_metrics: &[RunMetrics],
827        free_axis_size: AxisSize,
828        container_axis_size: AxisSize,
829        position_child: &mut dyn FnMut(&mut App, Offset, AnyRenderBox),
830        get_child_size: &mut dyn FnMut(&mut App, AnyRenderBox) -> Size,
831    ) {
832        debug_assert!(!run_metrics.is_empty());
833
834        let direction = self.direction(app);
835        let spacing = self.spacing(app);
836
837        let cross_axis_free_space = free_axis_size.cross_axis_extent().max(0.0);
838
839        let (flip_main_axis, flip_cross_axis) = self.are_axes_flipped(app);
840        let cross_axis_alignment = self.cross_axis_alignment(app);
841        let effective_cross_alignment = if flip_cross_axis {
842            cross_axis_alignment.flipped()
843        } else {
844            cross_axis_alignment
845        };
846        let (run_leading_space, run_between_space) = self.run_alignment(app).distribute_space(
847            cross_axis_free_space,
848            self.run_spacing(app),
849            run_metrics.len(),
850            flip_cross_axis,
851        );
852        let alignment = self.alignment(app);
853
854        let mut run_cross_axis_offset = run_leading_space;
855        let runs: Box<dyn Iterator<Item = &RunMetrics>> = if flip_cross_axis {
856            Box::new(run_metrics.iter().rev())
857        } else {
858            Box::new(run_metrics.iter())
859        };
860        for run in runs {
861            let run_cross_axis_extent = run.axis_size.cross_axis_extent();
862            let child_count = run.child_count;
863
864            let main_axis_free_space = (container_axis_size.main_axis_extent()
865                - run.axis_size.main_axis_extent())
866            .max(0.0);
867            let (child_leading_space, child_between_space) = alignment.distribute_space(
868                main_axis_free_space,
869                spacing,
870                child_count,
871                flip_main_axis,
872            );
873
874            let mut child_main_axis_offset = child_leading_space;
875
876            let mut remaining_child_count = run.child_count;
877            let mut child = Some(run.leading_child);
878            while let Some(current) = child
879                && remaining_child_count > 0
880            {
881                let child_axis_size = AxisSize::from_size(get_child_size(app, current), direction);
882                let child_cross_axis_offset = effective_cross_alignment.alignment()
883                    * (run_cross_axis_extent - child_axis_size.cross_axis_extent());
884                let offset = self.get_offset(
885                    app,
886                    child_main_axis_offset,
887                    run_cross_axis_offset + child_cross_axis_offset,
888                );
889                position_child(app, offset, current);
890                child_main_axis_offset += child_axis_size.main_axis_extent() + child_between_space;
891                child = if flip_main_axis {
892                    self.child_before(app, current)
893                } else {
894                    self.child_after(app, current)
895                };
896                remaining_child_count -= 1;
897            }
898            run_cross_axis_offset += run_cross_axis_extent + run_between_space;
899        }
900    }
901}
902
903impl ContainerRenderObjectMixin for RenderWrap {
904    type ChildType = AnyRenderBox;
905    type ParentDataType = WrapParentData;
906
907    fn container_data(
908        self: RenderHandle<Self>,
909        app: &App,
910    ) -> &ContainerRenderObjectData<AnyRenderBox> {
911        &self.get(app).container
912    }
913
914    fn container_data_mut(
915        self: RenderHandle<Self>,
916        app: &mut App,
917    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
918        &mut self.get_mut(app).container
919    }
920}
921
922impl RenderBoxContainerDefaultsMixin for RenderWrap {}
923
924impl RenderObject for RenderWrap {
925    crate::render_object_accessors!();
926
927    fn debug_fill_properties(
928        self: RenderHandle<Self>,
929        app: &App,
930        properties: &mut DiagnosticPropertiesBuilder,
931    ) {
932        let this = self.get(app);
933        properties.add(EnumProperty::<Axis>::new("direction", this.direction));
934        properties.add(EnumProperty::<WrapAlignment>::new(
935            "alignment",
936            this.alignment,
937        ));
938        properties.add(DoubleProperty::new("spacing", this.spacing));
939        properties.add(EnumProperty::<WrapAlignment>::new(
940            "runAlignment",
941            this.run_alignment,
942        ));
943        properties.add(DoubleProperty::new("runSpacing", this.run_spacing));
944        // Dart passes `runSpacing` here, not `crossAxisAlignment`.
945        properties.add(DoubleProperty::new("crossAxisAlignment", this.run_spacing));
946        properties.add(
947            EnumProperty::<TextDirection>::new("textDirection", this.text_direction)
948                .default_value(None),
949        );
950        properties.add(
951            EnumProperty::<VerticalDirection>::new(
952                "verticalDirection",
953                Some(this.vertical_direction),
954            )
955            .default_value(Some(VerticalDirection::Down)),
956        );
957    }
958
959    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
960        let constraints = self.constraints(app);
961        debug_assert!(self.debug_has_necessary_directions(app));
962        if self.first_child(app).is_none() {
963            self.set_size(app, constraints.smallest());
964            self.get_mut(app).has_visual_overflow = false;
965            return;
966        }
967
968        let direction = self.direction(app);
969        let (children_axis_size, run_metrics) =
970            self.compute_runs(app, constraints, ChildLayoutHelper::layout_child);
971        let container_axis_size = children_axis_size.apply_constraints(constraints, direction);
972        self.set_size(app, container_axis_size.to_size(direction));
973        let free_axis_size = container_axis_size - children_axis_size;
974        self.get_mut(app).has_visual_overflow =
975            free_axis_size.main_axis_extent() < 0.0 || free_axis_size.cross_axis_extent() < 0.0;
976        self.position_children(
977            app,
978            &run_metrics,
979            free_axis_size,
980            container_axis_size,
981            &mut |app, offset, child| {
982                child
983                    .parent_data_of_mut::<WrapParentData>(app)
984                    .set_offset(offset);
985            },
986            &mut |app, child| child.size(app),
987        );
988    }
989
990    fn visit_children(
991        self: RenderHandle<Self>,
992        app: &App,
993        visitor: &mut dyn FnMut(AnyRenderObject),
994    ) {
995        ContainerRenderObjectMixin::visit_children(self, app, visitor)
996    }
997
998    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
999        ContainerRenderObjectMixin::did_attach(self, app, owner)
1000    }
1001
1002    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1003        ContainerRenderObjectMixin::did_detach(self, app)
1004    }
1005
1006    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1007        ContainerRenderObjectMixin::redepth_children(self, app)
1008    }
1009
1010    /// Paints the children, clipping them to this wrap when they overflow it and
1011    /// [`clip_behavior`](RenderWrap::clip_behavior) asks for it.
1012    fn paint(
1013        self: RenderHandle<Self>,
1014        app: &mut App,
1015        context: &mut PaintingContext,
1016        offset: Offset,
1017    ) {
1018        // TODO(ianh): move the debug flex overflow paint logic somewhere common so it can be
1019        // reused here
1020        let clip_behavior = self.clip_behavior(app);
1021        if self.get(app).has_visual_overflow && clip_behavior != Clip::None {
1022            let size = self.size(app);
1023            let old = self.get(app).clip_rect_layer.layer();
1024            let layer = context.push_clip_rect(
1025                app,
1026                self.as_object().needs_compositing(app),
1027                offset,
1028                Offset::ZERO & size,
1029                |app, context, offset| self.default_paint(app, context, offset),
1030                clip_behavior,
1031                old,
1032            );
1033            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
1034        } else {
1035            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
1036            self.default_paint(app, context, offset);
1037        }
1038    }
1039
1040    /// Flutter's `dispose`: drop the clip layer handle, then `super.dispose()`.
1041    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1042        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
1043        crate::object::RenderObjectBase::dispose(self, app);
1044    }
1045}
1046
1047impl RenderBox for RenderWrap {
1048    crate::render_box_accessors!();
1049
1050    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1051        if !child.parent_data_is::<WrapParentData>(app) {
1052            child.set_parent_data(app, WrapParentData::new());
1053        }
1054    }
1055
1056    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1057        match self.direction(app) {
1058            Axis::Horizontal => {
1059                let mut width: f64 = 0.0;
1060                let mut child = self.first_child(app);
1061                while let Some(current) = child {
1062                    width = width.max(current.get_min_intrinsic_width(app, f64::INFINITY));
1063                    child = self.child_after(app, current);
1064                }
1065                width
1066            }
1067            Axis::Vertical => self
1068                .get_dry_layout(app, BoxConstraints::new().max_height(height))
1069                .width(),
1070        }
1071    }
1072
1073    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1074        match self.direction(app) {
1075            Axis::Horizontal => {
1076                let mut width = 0.0;
1077                let mut child = self.first_child(app);
1078                while let Some(current) = child {
1079                    width += current.get_max_intrinsic_width(app, f64::INFINITY);
1080                    child = self.child_after(app, current);
1081                }
1082                width
1083            }
1084            Axis::Vertical => self
1085                .get_dry_layout(app, BoxConstraints::new().max_height(height))
1086                .width(),
1087        }
1088    }
1089
1090    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1091        match self.direction(app) {
1092            Axis::Horizontal => self
1093                .get_dry_layout(app, BoxConstraints::new().max_width(width))
1094                .height(),
1095            Axis::Vertical => {
1096                let mut height: f64 = 0.0;
1097                let mut child = self.first_child(app);
1098                while let Some(current) = child {
1099                    height = height.max(current.get_min_intrinsic_height(app, f64::INFINITY));
1100                    child = self.child_after(app, current);
1101                }
1102                height
1103            }
1104        }
1105    }
1106
1107    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1108        match self.direction(app) {
1109            Axis::Horizontal => self
1110                .get_dry_layout(app, BoxConstraints::new().max_width(width))
1111                .height(),
1112            Axis::Vertical => {
1113                let mut height = 0.0;
1114                let mut child = self.first_child(app);
1115                while let Some(current) = child {
1116                    height += current.get_max_intrinsic_height(app, f64::INFINITY);
1117                    child = self.child_after(app, current);
1118                }
1119                height
1120            }
1121        }
1122    }
1123
1124    fn compute_distance_to_actual_baseline(
1125        self: RenderHandle<Self>,
1126        app: &mut App,
1127        baseline: TextBaseline,
1128    ) -> Option<f64> {
1129        self.default_compute_distance_to_highest_actual_baseline(app, baseline)
1130    }
1131
1132    fn compute_dry_baseline(
1133        self: RenderHandle<Self>,
1134        app: &mut App,
1135        constraints: BoxConstraints,
1136        baseline: TextBaseline,
1137    ) -> Option<f64> {
1138        self.first_child(app)?;
1139        let child_constraints = match self.direction(app) {
1140            Axis::Horizontal => BoxConstraints::new().max_width(constraints.max_width),
1141            Axis::Vertical => BoxConstraints::new().max_height(constraints.max_height),
1142        };
1143
1144        let (children_axis_size, run_metrics) =
1145            self.compute_runs(app, constraints, ChildLayoutHelper::dry_layout_child);
1146        let container_axis_size =
1147            children_axis_size.apply_constraints(constraints, self.direction(app));
1148
1149        let mut baseline_offset = BaselineOffset::NO_BASELINE;
1150        self.position_children(
1151            app,
1152            &run_metrics,
1153            children_axis_size,
1154            container_axis_size,
1155            &mut |app, offset, child| {
1156                baseline_offset = baseline_offset.min_of(
1157                    BaselineOffset(child.get_dry_baseline(app, child_constraints, baseline))
1158                        + offset.dy(),
1159                );
1160            },
1161            &mut |app, child| child.get_dry_layout(app, child_constraints),
1162        );
1163        baseline_offset.offset()
1164    }
1165
1166    fn compute_dry_layout(
1167        self: RenderHandle<Self>,
1168        app: &mut App,
1169        constraints: BoxConstraints,
1170    ) -> Size {
1171        self.compute_dry_layout_size(app, constraints)
1172    }
1173
1174    fn hit_test_children(
1175        self: RenderHandle<Self>,
1176        app: &mut App,
1177        result: &mut BoxHitTestResult<'_>,
1178        position: Offset,
1179    ) -> bool {
1180        self.default_hit_test_children(app, result, position)
1181    }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186    use waft_embedder::valo::Op;
1187    use waft_foundation::AppCell;
1188    use waft_painting::AlignmentGeometry;
1189
1190    use super::*;
1191    use crate::proxy_box::RenderConstrainedBox;
1192    use crate::testing::{EnginePhase, ignoring_hash_codes, layout_with, painted_ops};
1193
1194    /// `wrap_test.dart`: "Wrap test; toStringDeep".
1195    #[test]
1196    fn a_wrap_dump_shows_its_defaults() {
1197        let cell = AppCell::new();
1198        let mut app = cell.borrow_mut();
1199        let render_wrap = RenderWrap::new(&mut app);
1200        assert_eq!(
1201            ignoring_hash_codes(&render_wrap.as_object().to_string_deep(&app)),
1202            "RenderWrap#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n\
1203             \u{20}  parentData: MISSING\n\
1204             \u{20}  constraints: MISSING\n\
1205             \u{20}  size: MISSING\n\
1206             \u{20}  direction: horizontal\n\
1207             \u{20}  alignment: start\n\
1208             \u{20}  spacing: 0.0\n\
1209             \u{20}  runAlignment: start\n\
1210             \u{20}  runSpacing: 0.0\n\
1211             \u{20}  crossAxisAlignment: 0.0\n"
1212        );
1213    }
1214
1215    /// A box at least 80 square, as `wrap_test.dart`'s children are.
1216    fn box_80(app: &mut App) -> AnyRenderBox {
1217        let at_least = BoxConstraints::new().min_width(80.0).min_height(80.0);
1218        RenderConstrainedBox::new(app, at_least, None).as_box()
1219    }
1220
1221    /// A left-to-right wrap of three 80 square boxes, `spacing` apart in both axes.
1222    fn wrap_of_three(app: &mut App, direction: Axis, spacing: f64) -> RenderHandle<RenderWrap> {
1223        let wrap = RenderWrap::new(app);
1224        let children = vec![box_80(app), box_80(app), box_80(app)];
1225        wrap.add_all(app, Some(children));
1226        wrap.set_spacing(app, spacing);
1227        wrap.set_run_spacing(app, spacing);
1228        wrap.set_direction(app, direction);
1229        wrap
1230    }
1231
1232    /// `wrap_test.dart`: "Compute intrinsic height test".
1233    #[test]
1234    fn a_horizontal_wrap_is_as_tall_as_its_runs() {
1235        let cell = AppCell::new();
1236        let mut app = cell.borrow_mut();
1237        let wrap = wrap_of_three(&mut app, Axis::Horizontal, 5.0);
1238        for (width, height) in [(245.0, 165.0), (250.0, 80.0), (80.0, 250.0), (79.0, 250.0)] {
1239            assert_eq!(wrap.compute_max_intrinsic_height(&mut app, width), height);
1240            assert_eq!(wrap.compute_min_intrinsic_height(&mut app, width), height);
1241        }
1242    }
1243
1244    /// `wrap_test.dart`: "Compute intrinsic width test".
1245    #[test]
1246    fn a_vertical_wrap_is_as_wide_as_its_runs() {
1247        let cell = AppCell::new();
1248        let mut app = cell.borrow_mut();
1249        let wrap = wrap_of_three(&mut app, Axis::Vertical, 5.0);
1250        for (height, width) in [(245.0, 165.0), (250.0, 80.0), (80.0, 250.0), (79.0, 250.0)] {
1251            assert_eq!(wrap.compute_max_intrinsic_width(&mut app, height), width);
1252            assert_eq!(wrap.compute_min_intrinsic_width(&mut app, height), width);
1253        }
1254    }
1255
1256    /// `wrap_test.dart`: "Compute intrinsic height for only one run".
1257    #[test]
1258    fn one_child_makes_one_run_whatever_the_width() {
1259        let cell = AppCell::new();
1260        let mut app = cell.borrow_mut();
1261        let wrap = RenderWrap::new(&mut app);
1262        let child = box_80(&mut app);
1263        wrap.add(&mut app, child);
1264        wrap.set_spacing(&mut app, 5.0);
1265        wrap.set_run_spacing(&mut app, 5.0);
1266        for width in [100.0, 79.0, 80.0] {
1267            assert_eq!(wrap.compute_max_intrinsic_height(&mut app, width), 80.0);
1268            assert_eq!(wrap.compute_min_intrinsic_height(&mut app, width), 80.0);
1269        }
1270    }
1271
1272    fn offsets(app: &App, wrap: RenderHandle<RenderWrap>) -> Vec<Offset> {
1273        let mut offsets = Vec::new();
1274        let mut child = wrap.first_child(app);
1275        while let Some(current) = child {
1276            offsets.push(current.box_parent_data(app).offset);
1277            child = wrap.child_after(app, current);
1278        }
1279        offsets
1280    }
1281
1282    #[test]
1283    fn children_that_overflow_a_run_start_the_next_one() {
1284        let cell = AppCell::new();
1285        let mut app = cell.borrow_mut();
1286        let wrap = wrap_of_three(&mut app, Axis::Horizontal, 10.0);
1287        wrap.set_text_direction(&mut app, Some(TextDirection::Ltr));
1288        wrap.as_box()
1289            .layout(&mut app, BoxConstraints::new().max_width(200.0), true);
1290        assert_eq!(wrap.size(&app), Size::new(170.0, 170.0));
1291        assert_eq!(
1292            offsets(&app, wrap),
1293            [
1294                Offset::new(0.0, 0.0),
1295                Offset::new(90.0, 0.0),
1296                Offset::new(0.0, 90.0)
1297            ]
1298        );
1299    }
1300
1301    #[test]
1302    fn a_right_to_left_wrap_places_its_runs_from_the_right() {
1303        let cell = AppCell::new();
1304        let mut app = cell.borrow_mut();
1305        let wrap = wrap_of_three(&mut app, Axis::Horizontal, 10.0);
1306        wrap.set_text_direction(&mut app, Some(TextDirection::Rtl));
1307        wrap.set_alignment(&mut app, WrapAlignment::Start);
1308        wrap.as_box().layout(
1309            &mut app,
1310            BoxConstraints::tight(Size::new(200.0, 200.0)),
1311            true,
1312        );
1313        // The first run's 170 sit against the right edge, 30 from the left.
1314        assert_eq!(
1315            offsets(&app, wrap),
1316            [
1317                Offset::new(120.0, 0.0),
1318                Offset::new(30.0, 0.0),
1319                Offset::new(120.0, 90.0)
1320            ]
1321        );
1322    }
1323
1324    #[test]
1325    fn alignments_spread_the_free_space() {
1326        let cell = AppCell::new();
1327        let mut app = cell.borrow_mut();
1328        let wrap = wrap_of_three(&mut app, Axis::Horizontal, 0.0);
1329        wrap.set_text_direction(&mut app, Some(TextDirection::Ltr));
1330        wrap.set_alignment(&mut app, WrapAlignment::SpaceBetween);
1331        wrap.set_run_alignment(&mut app, WrapAlignment::End);
1332        wrap.set_cross_axis_alignment(&mut app, WrapCrossAlignment::Center);
1333        wrap.as_box().layout(
1334            &mut app,
1335            BoxConstraints::tight(Size::new(300.0, 100.0)),
1336            true,
1337        );
1338        assert_eq!(
1339            offsets(&app, wrap),
1340            [
1341                Offset::new(0.0, 20.0),
1342                Offset::new(110.0, 20.0),
1343                Offset::new(220.0, 20.0)
1344            ]
1345        );
1346        assert_eq!(
1347            WrapAlignment::SpaceEvenly.distribute_space(40.0, 0.0, 3, false),
1348            (10.0, 10.0)
1349        );
1350        assert_eq!(
1351            WrapAlignment::SpaceAround.distribute_space(60.0, 5.0, 3, false),
1352            (10.0, 25.0)
1353        );
1354    }
1355
1356    #[test]
1357    fn a_wrap_measures_dry_as_it_lays_out() {
1358        let cell = AppCell::new();
1359        let mut app = cell.borrow_mut();
1360        let wrap = wrap_of_three(&mut app, Axis::Horizontal, 10.0);
1361        wrap.set_text_direction(&mut app, Some(TextDirection::Ltr));
1362        let constraints = BoxConstraints::new().max_width(200.0);
1363        let dry = wrap.get_dry_layout(&mut app, constraints);
1364        wrap.as_box().layout(&mut app, constraints, true);
1365        assert_eq!(dry, wrap.size(&app));
1366    }
1367
1368    /// Whether `render`, painted on its own, clips.
1369    fn picture_has_clip(app: &mut App, render: AnyRenderObject) -> bool {
1370        painted_ops(app, render)
1371            .iter()
1372            .any(|op| matches!(op, Op::ClipPath { .. }))
1373    }
1374
1375    /// `wrap_test.dart`: "Wrap respects clipBehavior", which defaults to no clip.
1376    #[test]
1377    fn an_overflowing_wrap_clips_only_when_asked() {
1378        for (clip_behavior, clips) in [(None, false), (Some(Clip::HardEdge), true)] {
1379            let cell = AppCell::new();
1380            let mut app = cell.borrow_mut();
1381            let child = RenderConstrainedBox::new(
1382                &mut app,
1383                BoxConstraints::tight(Size::square(200.0)),
1384                None,
1385            );
1386            let wrap = RenderWrap::new(&mut app);
1387            wrap.set_text_direction(&mut app, Some(TextDirection::Ltr));
1388            if let Some(clip_behavior) = clip_behavior {
1389                wrap.set_clip_behavior(&mut app, clip_behavior);
1390            }
1391            wrap.add(&mut app, child.as_box());
1392            layout_with(
1393                &mut app,
1394                wrap.as_box(),
1395                Some(BoxConstraints::new().max_width(100.0).max_height(100.0)),
1396                AlignmentGeometry::CENTER,
1397                EnginePhase::Paint,
1398            );
1399
1400            assert_eq!(
1401                picture_has_clip(&mut app, wrap.as_object()),
1402                clips,
1403                "{clip_behavior:?}"
1404            );
1405        }
1406    }
1407}