Skip to main content

waft_rendering/
shifted_box.rs

1//! Flutter counterpart: `rendering/shifted_box.dart` (`BoxConstraintsTransform`,
2//! `RenderShiftedBox`, `RenderPadding`, `RenderAligningShiftedBox`, `RenderPositionedBox`,
3//! `OverflowBoxFit`, `RenderConstrainedOverflowBox`, `RenderConstraintsTransformBox`,
4//! `RenderSizedOverflowBox`, `RenderFractionallySizedOverflowBox`,
5//! `RenderCustomSingleChildLayoutBox`, `SingleChildLayoutDelegate`, `RenderBaseline`).
6
7use std::any::Any;
8use std::fmt::Debug;
9use std::rc::Rc;
10
11use waft_embedder::{Clip, Offset, Rect, Size, TextBaseline};
12use waft_foundation::{
13    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty, Handle,
14    Listenable, Listener,
15};
16use waft_painting::{Alignment, AlignmentGeometry, EdgeInsets, EdgeInsetsGeometry, TextDirection};
17
18use crate::box_::{
19    AnyRenderBox, BoxConstraints, BoxHitTestResult, BoxParentData, RenderBox, RenderBoxData,
20};
21use crate::layer::{ClipRectLayer, LayerHandle};
22use crate::layout_helper::{ChildBaselineGetter, ChildLayoutHelper, ChildLayouter};
23use crate::object::{
24    AnyRenderObject, Constraints, RenderHandle, RenderObject, RenderObjectData,
25    RenderObjectWithChildData, RenderObjectWithChildMixin,
26};
27use crate::painting_context::PaintingContext;
28use crate::pipeline_owner::PipelineOwner;
29use crate::stack::RelativeRect;
30
31/// Signature for a function that transforms a [`BoxConstraints`] to another [`BoxConstraints`].
32///
33/// Used by [`RenderConstraintsTransformBox`]. Typically the caller requires the returned
34/// [`BoxConstraints`] to be [`Constraints::is_normalized`].
35pub type BoxConstraintsTransform = fn(BoxConstraints) -> BoxConstraints;
36
37/// Abstract class for one-child-layout render boxes that provide control over
38/// the child's position.
39///
40/// Flutter's `RenderShiftedBox`: the shared bodies. A leaf implements the marker and calls
41/// these where Dart would run the inherited method: `RenderShiftedBox::paint(self, …)`.
42pub trait RenderShiftedBox:
43    RenderObjectWithChildMixin<ChildType = AnyRenderBox> + RenderBox
44{
45    /// The child's minimum intrinsic width, or 0 without a child.
46    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
47        match self.child(app) {
48            Some(child) => child.get_min_intrinsic_width(app, height),
49            None => 0.0,
50        }
51    }
52
53    /// The child's maximum intrinsic width, or 0 without a child.
54    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
55        match self.child(app) {
56            Some(child) => child.get_max_intrinsic_width(app, height),
57            None => 0.0,
58        }
59    }
60
61    /// The child's minimum intrinsic height, or 0 without a child.
62    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
63        match self.child(app) {
64            Some(child) => child.get_min_intrinsic_height(app, width),
65            None => 0.0,
66        }
67    }
68
69    /// The child's maximum intrinsic height, or 0 without a child.
70    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
71        match self.child(app) {
72            Some(child) => child.get_max_intrinsic_height(app, width),
73            None => 0.0,
74        }
75    }
76
77    /// The child's baseline shifted by the child's paint offset, or none without a child.
78    fn compute_distance_to_actual_baseline(
79        self: RenderHandle<Self>,
80        app: &mut App,
81        baseline: TextBaseline,
82    ) -> Option<f64> {
83        debug_assert!(!self.as_object().debug_needs_layout(app));
84        let child = self.child(app)?;
85        debug_assert!(!child.as_object().debug_needs_layout(app));
86        let result = child.get_distance_to_actual_baseline(app, baseline)?;
87        let offset = child
88            .as_object()
89            .parent_data_of::<BoxParentData>(app)
90            .offset;
91        Some(result + offset.dy())
92    }
93
94    /// The child's dry baseline at this box's constraints. The base applies no transform;
95    /// subclasses override to add their offset.
96    fn compute_dry_baseline(
97        self: RenderHandle<Self>,
98        app: &mut App,
99        constraints: BoxConstraints,
100        baseline: TextBaseline,
101    ) -> Option<f64> {
102        self.child(app)
103            .and_then(|child| child.get_dry_baseline(app, constraints, baseline))
104    }
105
106    /// Hit tests the child at its parent-data offset.
107    fn hit_test_children(
108        self: RenderHandle<Self>,
109        app: &mut App,
110        result: &mut BoxHitTestResult<'_>,
111        position: Offset,
112    ) -> bool {
113        let Some(child) = self.child(app) else {
114            return false;
115        };
116        let child_offset = child
117            .as_object()
118            .parent_data_of::<BoxParentData>(app)
119            .offset;
120        result.add_with_paint_offset(Some(child_offset), position, |result, transformed| {
121            debug_assert_eq!(transformed, position - child_offset);
122            child.hit_test(app, result, transformed)
123        })
124    }
125
126    /// Paints the child at its parent-data offset.
127    fn paint(
128        self: RenderHandle<Self>,
129        app: &mut App,
130        context: &mut PaintingContext,
131        offset: Offset,
132    ) {
133        if let Some(child) = self.child(app) {
134            let child_offset = child
135                .as_object()
136                .parent_data_of::<BoxParentData>(app)
137                .offset;
138            context.paint_child(app, child.as_object(), child_offset + offset);
139        }
140    }
141}
142
143/// Insets its child by the given padding.
144pub struct RenderPadding {
145    render_object: RenderObjectData,
146    render_box: RenderBoxData,
147    child: RenderObjectWithChildData<AnyRenderBox>,
148    resolved_padding_cache: Option<EdgeInsets>,
149    padding: EdgeInsetsGeometry,
150    text_direction: Option<TextDirection>,
151}
152
153impl RenderPadding {
154    /// Creates a render object that insets its child.
155    ///
156    /// `padding` must have non-negative insets.
157    pub fn new(
158        app: &mut App,
159        padding: EdgeInsetsGeometry,
160        text_direction: Option<TextDirection>,
161        child: Option<AnyRenderBox>,
162    ) -> RenderHandle<RenderPadding> {
163        debug_assert!(padding.is_non_negative());
164        let this = RenderHandle::new_box(
165            app,
166            RenderPadding {
167                render_object: RenderObjectData::new(),
168                render_box: RenderBoxData::new(),
169                child: RenderObjectWithChildData::new(),
170                resolved_padding_cache: None,
171                padding,
172                text_direction,
173            },
174        );
175        this.set_child(app, child);
176        this
177    }
178
179    /// The amount to pad the child in each dimension.
180    pub fn padding(self: RenderHandle<Self>, app: &App) -> EdgeInsetsGeometry {
181        self.get(app).padding
182    }
183
184    /// Sets [`padding`](Self::padding).
185    pub fn set_padding(self: RenderHandle<Self>, app: &mut App, value: EdgeInsetsGeometry) {
186        debug_assert!(value.is_non_negative());
187        if self.get(app).padding == value {
188            return;
189        }
190        self.get_mut(app).padding = value;
191        self.mark_need_resolution(app);
192    }
193
194    /// The text direction with which to resolve [`padding`](Self::padding).
195    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
196        self.get(app).text_direction
197    }
198
199    /// Sets [`text_direction`](Self::text_direction).
200    pub fn set_text_direction(
201        self: RenderHandle<Self>,
202        app: &mut App,
203        value: Option<TextDirection>,
204    ) {
205        if self.get(app).text_direction == value {
206            return;
207        }
208        self.get_mut(app).text_direction = value;
209        self.mark_need_resolution(app);
210    }
211
212    fn resolved_padding(&mut self) -> EdgeInsets {
213        if let Some(cached) = self.resolved_padding_cache {
214            return cached;
215        }
216        let resolved = self.padding.resolve(self.text_direction);
217        debug_assert!(resolved.is_non_negative());
218        self.resolved_padding_cache = Some(resolved);
219        resolved
220    }
221
222    fn mark_need_resolution(self: RenderHandle<Self>, app: &mut App) {
223        self.get_mut(app).resolved_padding_cache = None;
224        self.mark_needs_layout(app);
225    }
226}
227
228impl RenderObjectWithChildMixin for RenderPadding {
229    type ChildType = AnyRenderBox;
230
231    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
232        &self.get(app).child
233    }
234
235    fn child_data_mut(
236        self: RenderHandle<Self>,
237        app: &mut App,
238    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
239        &mut self.get_mut(app).child
240    }
241}
242
243impl RenderShiftedBox for RenderPadding {}
244
245impl RenderObject for RenderPadding {
246    crate::render_object_accessors!();
247
248    fn debug_fill_properties(
249        self: RenderHandle<Self>,
250        app: &App,
251        properties: &mut DiagnosticPropertiesBuilder,
252    ) {
253        let this = self.get(app);
254        properties.add(DiagnosticsProperty::new("padding", this.padding));
255        properties.add(
256            EnumProperty::<TextDirection>::new("textDirection", this.text_direction)
257                .default_value(None),
258        );
259    }
260
261    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
262        let constraints = self.constraints(app);
263        let padding = self.get_mut(app).resolved_padding();
264        let child = self.child(app);
265        if child.is_none() {
266            self.set_size(
267                app,
268                constraints.constrain(Size::new(padding.horizontal(), padding.vertical())),
269            );
270            return;
271        }
272        let child = child.expect("checked");
273        let inner_constraints = constraints.deflate(EdgeInsetsGeometry::Insets(padding));
274        child.layout(app, inner_constraints, true);
275        child.parent_data_of_mut::<BoxParentData>(app).offset =
276            Offset::new(padding.left, padding.top);
277        self.set_size(
278            app,
279            constraints.constrain(Size::new(
280                padding.horizontal() + child.size(app).width(),
281                padding.vertical() + child.size(app).height(),
282            )),
283        );
284    }
285
286    fn paint(
287        self: RenderHandle<Self>,
288        app: &mut App,
289        context: &mut PaintingContext,
290        offset: Offset,
291    ) {
292        RenderShiftedBox::paint(self, app, context, offset);
293    }
294
295    fn visit_children(
296        self: RenderHandle<Self>,
297        app: &App,
298        visitor: &mut dyn FnMut(AnyRenderObject),
299    ) {
300        if let Some(child) = self.child(app) {
301            visitor(child.as_object());
302        }
303    }
304}
305
306impl RenderBox for RenderPadding {
307    crate::render_box_accessors!();
308
309    fn hit_test_children(
310        self: RenderHandle<Self>,
311        app: &mut App,
312        result: &mut BoxHitTestResult<'_>,
313        position: Offset,
314    ) -> bool {
315        RenderShiftedBox::hit_test_children(self, app, result, position)
316    }
317
318    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
319        let padding = self.get_mut(app).resolved_padding();
320        match self.child(app) {
321            // Relies on f64::INFINITY absorption.
322            Some(child) => {
323                child.get_min_intrinsic_width(app, (height - padding.vertical()).max(0.0))
324                    + padding.horizontal()
325            }
326            None => padding.horizontal(),
327        }
328    }
329
330    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
331        let padding = self.get_mut(app).resolved_padding();
332        match self.child(app) {
333            Some(child) => {
334                child.get_max_intrinsic_width(app, (height - padding.vertical()).max(0.0))
335                    + padding.horizontal()
336            }
337            None => padding.horizontal(),
338        }
339    }
340
341    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
342        let padding = self.get_mut(app).resolved_padding();
343        match self.child(app) {
344            Some(child) => {
345                child.get_min_intrinsic_height(app, (width - padding.horizontal()).max(0.0))
346                    + padding.vertical()
347            }
348            None => padding.vertical(),
349        }
350    }
351
352    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
353        let padding = self.get_mut(app).resolved_padding();
354        match self.child(app) {
355            Some(child) => {
356                child.get_max_intrinsic_height(app, (width - padding.horizontal()).max(0.0))
357                    + padding.vertical()
358            }
359            None => padding.vertical(),
360        }
361    }
362
363    fn compute_distance_to_actual_baseline(
364        self: RenderHandle<Self>,
365        app: &mut App,
366        baseline: TextBaseline,
367    ) -> Option<f64> {
368        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
369    }
370
371    fn compute_dry_baseline(
372        self: RenderHandle<Self>,
373        app: &mut App,
374        constraints: BoxConstraints,
375        baseline: TextBaseline,
376    ) -> Option<f64> {
377        let child = self.child(app)?;
378        let padding = self.get_mut(app).resolved_padding();
379        let inner_constraints = constraints.deflate(EdgeInsetsGeometry::Insets(padding));
380        let child_baseline = child.get_dry_baseline(app, inner_constraints, baseline)?;
381        Some(child_baseline + padding.top)
382    }
383
384    fn compute_dry_layout(
385        self: RenderHandle<Self>,
386        app: &mut App,
387        constraints: BoxConstraints,
388    ) -> Size {
389        let padding = self.get_mut(app).resolved_padding();
390        let Some(child) = self.child(app) else {
391            return constraints.constrain(Size::new(padding.horizontal(), padding.vertical()));
392        };
393        let inner_constraints = constraints.deflate(EdgeInsetsGeometry::Insets(padding));
394        let child_size = child.get_dry_layout(app, inner_constraints);
395        constraints.constrain(Size::new(
396            padding.horizontal() + child_size.width(),
397            padding.vertical() + child_size.height(),
398        ))
399    }
400}
401
402/// The mixin fields of [`RenderAligningShiftedBox`].
403pub struct RenderAligningShiftedBoxData {
404    resolved_alignment: Option<Alignment>,
405    alignment: AlignmentGeometry,
406    text_direction: Option<TextDirection>,
407}
408
409impl RenderAligningShiftedBoxData {
410    /// Flutter's constructor arguments; `alignment` defaults to center.
411    pub const fn new(
412        alignment: AlignmentGeometry,
413        text_direction: Option<TextDirection>,
414    ) -> RenderAligningShiftedBoxData {
415        RenderAligningShiftedBoxData {
416            resolved_alignment: None,
417            alignment,
418            text_direction,
419        }
420    }
421}
422
423/// Abstract class for one-child-layout render boxes that use a
424/// [`AlignmentGeometry`] to align their children.
425pub trait RenderAligningShiftedBox: RenderShiftedBox {
426    /// Mixin field access.
427    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData;
428
429    /// See [`aligning_data`](Self::aligning_data).
430    fn aligning_data_mut(
431        self: RenderHandle<Self>,
432        app: &mut App,
433    ) -> &mut RenderAligningShiftedBoxData;
434
435    /// The [`alignment`](Self::alignment) resolved against [`text_direction`](Self::text_direction).
436    fn resolved_alignment(self: RenderHandle<Self>, app: &mut App) -> Alignment {
437        let data = self.aligning_data(app);
438        if let Some(resolved) = data.resolved_alignment {
439            return resolved;
440        }
441        let resolved = data.alignment.resolve(data.text_direction);
442        self.aligning_data_mut(app).resolved_alignment = Some(resolved);
443        resolved
444    }
445
446    fn mark_need_resolution(self: RenderHandle<Self>, app: &mut App) {
447        self.aligning_data_mut(app).resolved_alignment = None;
448        self.mark_needs_layout(app);
449    }
450
451    /// How to align the child.
452    ///
453    /// The x and y values of the alignment control the horizontal and vertical
454    /// alignment, respectively. An x value of -1.0 means that the left edge of
455    /// the child is aligned with the left edge of the parent whereas an x value
456    /// of 1.0 means that the right edge of the child is aligned with the right
457    /// edge of the parent. Other values interpolate (and extrapolate) linearly.
458    fn alignment(self: RenderHandle<Self>, app: &App) -> AlignmentGeometry {
459        self.aligning_data(app).alignment
460    }
461
462    /// Sets [`alignment`](Self::alignment).
463    fn set_alignment(self: RenderHandle<Self>, app: &mut App, value: AlignmentGeometry) {
464        if self.aligning_data(app).alignment == value {
465            return;
466        }
467        self.aligning_data_mut(app).alignment = value;
468        self.mark_need_resolution(app);
469    }
470
471    /// The text direction with which to resolve [`alignment`](Self::alignment).
472    fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
473        self.aligning_data(app).text_direction
474    }
475
476    /// Sets [`text_direction`](Self::text_direction).
477    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: Option<TextDirection>) {
478        if self.aligning_data(app).text_direction == value {
479            return;
480        }
481        self.aligning_data_mut(app).text_direction = value;
482        self.mark_need_resolution(app);
483    }
484
485    /// Apply the current [`alignment`](Self::alignment) to the child.
486    ///
487    /// Subclasses should call this method if they have a child, to have this
488    /// class perform the actual alignment. If they don't have a child, they
489    /// should not call this method.
490    fn align_child(self: RenderHandle<Self>, app: &mut App) {
491        let child = self.child(app).expect("align_child requires a child");
492        debug_assert!(!child.as_object().debug_needs_layout(app));
493        let offset = self
494            .resolved_alignment(app)
495            .along_offset(self.size(app) - child.size(app));
496        child
497            .as_object()
498            .parent_data_of_mut::<BoxParentData>(app)
499            .offset = offset;
500    }
501
502    /// Dart's `RenderAligningShiftedBox.debugFillProperties`: what a subclass's own override
503    /// adds before its properties.
504    fn debug_fill_properties(
505        self: RenderHandle<Self>,
506        app: &App,
507        properties: &mut DiagnosticPropertiesBuilder,
508    ) {
509        let data = self.aligning_data(app);
510        properties.add(DiagnosticsProperty::new("alignment", data.alignment));
511        properties.add(
512            EnumProperty::<TextDirection>::new("textDirection", data.text_direction)
513                .default_value(None),
514        );
515    }
516}
517
518/// Positions its child using an [`AlignmentGeometry`].
519///
520/// For example, to align a box at the bottom right, you would pass this box a
521/// tight constraint that is bigger than the child's natural size, with an
522/// alignment of `Alignment::BOTTOM_RIGHT`.
523///
524/// By default, sizes to be as big as possible in both axes. If either axis is
525/// unconstrained, then in that direction it will be sized to fit the child's
526/// dimensions. Using `width_factor` and `height_factor` you can force this
527/// latter behavior in all cases.
528pub struct RenderPositionedBox {
529    render_object: RenderObjectData,
530    render_box: RenderBoxData,
531    child: RenderObjectWithChildData<AnyRenderBox>,
532    aligning: RenderAligningShiftedBoxData,
533    width_factor: Option<f64>,
534    height_factor: Option<f64>,
535}
536
537impl RenderPositionedBox {
538    /// Creates a render object that positions its child.
539    ///
540    /// `width_factor` and `height_factor` must be non-negative when given.
541    pub fn new(
542        app: &mut App,
543        alignment: AlignmentGeometry,
544        text_direction: Option<TextDirection>,
545        width_factor: Option<f64>,
546        height_factor: Option<f64>,
547        child: Option<AnyRenderBox>,
548    ) -> RenderHandle<Self> {
549        debug_assert!(width_factor.is_none_or(|factor| factor >= 0.0));
550        debug_assert!(height_factor.is_none_or(|factor| factor >= 0.0));
551        let this = RenderHandle::new_box(
552            app,
553            RenderPositionedBox {
554                render_object: RenderObjectData::new(),
555                render_box: RenderBoxData::new(),
556                child: RenderObjectWithChildData::new(),
557                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
558                width_factor,
559                height_factor,
560            },
561        );
562        this.set_child(app, child);
563        this
564    }
565
566    /// If non-null, sets its width to the child's width multiplied by this factor.
567    ///
568    /// Can be both greater and less than 1.0 but must be positive.
569    pub fn width_factor(self: RenderHandle<Self>, app: &App) -> Option<f64> {
570        self.get(app).width_factor
571    }
572
573    /// Sets [`width_factor`](Self::width_factor).
574    pub fn set_width_factor(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
575        debug_assert!(value.is_none_or(|factor| factor >= 0.0));
576        if self.get(app).width_factor == value {
577            return;
578        }
579        self.get_mut(app).width_factor = value;
580        self.mark_needs_layout(app);
581    }
582
583    /// If non-null, sets its height to the child's height multiplied by this factor.
584    ///
585    /// Can be both greater and less than 1.0 but must be positive.
586    pub fn height_factor(self: RenderHandle<Self>, app: &App) -> Option<f64> {
587        self.get(app).height_factor
588    }
589
590    /// Sets [`height_factor`](Self::height_factor).
591    pub fn set_height_factor(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
592        debug_assert!(value.is_none_or(|factor| factor >= 0.0));
593        if self.get(app).height_factor == value {
594            return;
595        }
596        self.get_mut(app).height_factor = value;
597        self.mark_needs_layout(app);
598    }
599}
600
601impl RenderObjectWithChildMixin for RenderPositionedBox {
602    type ChildType = AnyRenderBox;
603
604    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
605        &self.get(app).child
606    }
607
608    fn child_data_mut(
609        self: RenderHandle<Self>,
610        app: &mut App,
611    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
612        &mut self.get_mut(app).child
613    }
614}
615
616impl RenderShiftedBox for RenderPositionedBox {}
617
618impl RenderAligningShiftedBox for RenderPositionedBox {
619    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
620        &self.get(app).aligning
621    }
622
623    fn aligning_data_mut(
624        self: RenderHandle<Self>,
625        app: &mut App,
626    ) -> &mut RenderAligningShiftedBoxData {
627        &mut self.get_mut(app).aligning
628    }
629}
630
631impl RenderPositionedBox {
632    /// Dart's sizing line of `performLayout` / `computeDryLayout`: shrink-wrap an axis when it
633    /// has a factor or is unbounded, and `child_size` is zero without a child.
634    fn size_for_child(
635        self: RenderHandle<Self>,
636        app: &App,
637        constraints: BoxConstraints,
638        child_size: Size,
639    ) -> Size {
640        let (width_factor, height_factor) = {
641            let this = self.get(app);
642            (this.width_factor, this.height_factor)
643        };
644        let shrink_wrap_width = width_factor.is_some() || constraints.max_width == f64::INFINITY;
645        let shrink_wrap_height = height_factor.is_some() || constraints.max_height == f64::INFINITY;
646        constraints.constrain(Size::new(
647            if shrink_wrap_width {
648                child_size.width() * width_factor.unwrap_or(1.0)
649            } else {
650                f64::INFINITY
651            },
652            if shrink_wrap_height {
653                child_size.height() * height_factor.unwrap_or(1.0)
654            } else {
655                f64::INFINITY
656            },
657        ))
658    }
659}
660
661impl RenderObject for RenderPositionedBox {
662    crate::render_object_accessors!();
663
664    fn debug_fill_properties(
665        self: RenderHandle<Self>,
666        app: &App,
667        properties: &mut DiagnosticPropertiesBuilder,
668    ) {
669        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
670        let this = self.get(app);
671        properties.add(DoubleProperty::new("widthFactor", this.width_factor).if_null("expand"));
672        properties.add(DoubleProperty::new("heightFactor", this.height_factor).if_null("expand"));
673    }
674
675    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
676        let constraints = self.constraints(app);
677        match self.child(app) {
678            Some(child) => {
679                child.layout(app, constraints.loosen(), true);
680                let child_size = child.size(app);
681                let size = self.size_for_child(app, constraints, child_size);
682                self.set_size(app, size);
683                self.align_child(app);
684            }
685            None => {
686                let size = self.size_for_child(app, constraints, Size::ZERO);
687                self.set_size(app, size);
688            }
689        }
690    }
691
692    fn paint(
693        self: RenderHandle<Self>,
694        app: &mut App,
695        context: &mut PaintingContext,
696        offset: Offset,
697    ) {
698        RenderShiftedBox::paint(self, app, context, offset);
699    }
700
701    fn visit_children(
702        self: RenderHandle<Self>,
703        app: &App,
704        visitor: &mut dyn FnMut(AnyRenderObject),
705    ) {
706        if let Some(child) = self.child(app) {
707            visitor(child.as_object());
708        }
709    }
710}
711
712impl RenderBox for RenderPositionedBox {
713    crate::render_box_accessors!();
714
715    fn hit_test_children(
716        self: RenderHandle<Self>,
717        app: &mut App,
718        result: &mut BoxHitTestResult<'_>,
719        position: Offset,
720    ) -> bool {
721        RenderShiftedBox::hit_test_children(self, app, result, position)
722    }
723
724    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
725        let factor = self.get(app).width_factor.unwrap_or(1.0);
726        RenderShiftedBox::compute_min_intrinsic_width(self, app, height) * factor
727    }
728
729    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
730        let factor = self.get(app).width_factor.unwrap_or(1.0);
731        RenderShiftedBox::compute_max_intrinsic_width(self, app, height) * factor
732    }
733
734    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
735        let factor = self.get(app).height_factor.unwrap_or(1.0);
736        RenderShiftedBox::compute_min_intrinsic_height(self, app, width) * factor
737    }
738
739    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
740        let factor = self.get(app).height_factor.unwrap_or(1.0);
741        RenderShiftedBox::compute_max_intrinsic_height(self, app, width) * factor
742    }
743
744    fn compute_distance_to_actual_baseline(
745        self: RenderHandle<Self>,
746        app: &mut App,
747        baseline: TextBaseline,
748    ) -> Option<f64> {
749        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
750    }
751
752    fn compute_dry_baseline(
753        self: RenderHandle<Self>,
754        app: &mut App,
755        constraints: BoxConstraints,
756        baseline: TextBaseline,
757    ) -> Option<f64> {
758        let child = self.child(app)?;
759        let child_constraints = constraints.loosen();
760        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
761        let child_size = child.get_dry_layout(app, child_constraints);
762        let size = self.size_for_child(app, constraints, child_size);
763        let child_offset = self.resolved_alignment(app).along_offset(size - child_size);
764        Some(result + child_offset.dy())
765    }
766
767    fn compute_dry_layout(
768        self: RenderHandle<Self>,
769        app: &mut App,
770        constraints: BoxConstraints,
771    ) -> Size {
772        match self.child(app) {
773            Some(child) => {
774                let child_size = child.get_dry_layout(app, constraints.loosen());
775                self.size_for_child(app, constraints, child_size)
776            }
777            None => self.size_for_child(app, constraints, Size::ZERO),
778        }
779    }
780}
781
782/// How much space should be occupied by the [`RenderConstrainedOverflowBox`] when it is not
783/// overflowing.
784#[derive(Clone, Copy, Debug, PartialEq, Eq)]
785pub enum OverflowBoxFit {
786    /// The widget will size itself to be as large as the parent allows.
787    Max,
788
789    /// The widget will follow the child's size.
790    ///
791    /// More specifically, the render object will size itself to match the size of its child
792    /// within the constraints of its parent, or as small as the parent allows if no child is
793    /// set.
794    DeferToChild,
795}
796
797/// A render object that imposes different constraints on its child than it gets from its parent,
798/// possibly allowing the child to overflow the parent.
799///
800/// A render overflow box proxies most functions in the render box protocol to its child, except
801/// that when laying out its child, it passes constraints based on the `min_width`, `max_width`,
802/// `min_height`, and `max_height` fields instead of just passing the parent's constraints in.
803/// Specifically, it overrides any of the equivalent fields on the constraints given by the parent
804/// with the constraints given by these fields, as long as those values are not null. If a value is
805/// null, then the original constraint is used.
806///
807/// Additionally, this render object allows the child to overflow the bounds of this box. If the
808/// child overflows, this box will not clip the overflowing part.
809pub struct RenderConstrainedOverflowBox {
810    render_object: RenderObjectData,
811    render_box: RenderBoxData,
812    child: RenderObjectWithChildData<AnyRenderBox>,
813    aligning: RenderAligningShiftedBoxData,
814    min_width: Option<f64>,
815    max_width: Option<f64>,
816    min_height: Option<f64>,
817    max_height: Option<f64>,
818    fit: OverflowBoxFit,
819}
820
821impl RenderConstrainedOverflowBox {
822    /// Creates a render object that lets its child overflow itself; `None` constraints use the
823    /// parent's, and Dart's default `fit` is [`OverflowBoxFit::Max`].
824    #[allow(clippy::too_many_arguments)]
825    pub fn new(
826        app: &mut App,
827        min_width: Option<f64>,
828        max_width: Option<f64>,
829        min_height: Option<f64>,
830        max_height: Option<f64>,
831        fit: OverflowBoxFit,
832        alignment: AlignmentGeometry,
833        text_direction: Option<TextDirection>,
834        child: Option<AnyRenderBox>,
835    ) -> RenderHandle<Self> {
836        let this = RenderHandle::new_box(
837            app,
838            RenderConstrainedOverflowBox {
839                render_object: RenderObjectData::new(),
840                render_box: RenderBoxData::new(),
841                child: RenderObjectWithChildData::new(),
842                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
843                min_width,
844                max_width,
845                min_height,
846                max_height,
847                fit,
848            },
849        );
850        this.set_child(app, child);
851        this
852    }
853
854    /// The minimum width constraint to give the child. `None` (the default) uses the constraint
855    /// from the parent instead.
856    pub fn min_width(self: RenderHandle<Self>, app: &App) -> Option<f64> {
857        self.get(app).min_width
858    }
859
860    /// Sets [`min_width`](Self::min_width).
861    pub fn set_min_width(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
862        if self.get(app).min_width == value {
863            return;
864        }
865        self.get_mut(app).min_width = value;
866        self.mark_needs_layout(app);
867    }
868
869    /// The maximum width constraint to give the child. `None` (the default) uses the constraint
870    /// from the parent instead.
871    pub fn max_width(self: RenderHandle<Self>, app: &App) -> Option<f64> {
872        self.get(app).max_width
873    }
874
875    /// Sets [`max_width`](Self::max_width).
876    pub fn set_max_width(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
877        if self.get(app).max_width == value {
878            return;
879        }
880        self.get_mut(app).max_width = value;
881        self.mark_needs_layout(app);
882    }
883
884    /// The minimum height constraint to give the child. `None` (the default) uses the constraint
885    /// from the parent instead.
886    pub fn min_height(self: RenderHandle<Self>, app: &App) -> Option<f64> {
887        self.get(app).min_height
888    }
889
890    /// Sets [`min_height`](Self::min_height).
891    pub fn set_min_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
892        if self.get(app).min_height == value {
893            return;
894        }
895        self.get_mut(app).min_height = value;
896        self.mark_needs_layout(app);
897    }
898
899    /// The maximum height constraint to give the child. `None` (the default) uses the constraint
900    /// from the parent instead.
901    pub fn max_height(self: RenderHandle<Self>, app: &App) -> Option<f64> {
902        self.get(app).max_height
903    }
904
905    /// Sets [`max_height`](Self::max_height).
906    pub fn set_max_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
907        if self.get(app).max_height == value {
908            return;
909        }
910        self.get_mut(app).max_height = value;
911        self.mark_needs_layout(app);
912    }
913
914    /// The way to size the render object.
915    ///
916    /// This only affects the scenario where the child does not indeed overflow. If set to
917    /// [`OverflowBoxFit::DeferToChild`], the render object will size itself to match the size of
918    /// its child within the constraints of its parent, or as small as the parent allows if no
919    /// child is set. If set to [`OverflowBoxFit::Max`] (the default), the render object will size
920    /// itself to be as large as the parent allows.
921    pub fn fit(self: RenderHandle<Self>, app: &App) -> OverflowBoxFit {
922        self.get(app).fit
923    }
924
925    /// Sets [`fit`](Self::fit).
926    pub fn set_fit(self: RenderHandle<Self>, app: &mut App, value: OverflowBoxFit) {
927        if self.get(app).fit == value {
928            return;
929        }
930        self.get_mut(app).fit = value;
931        self.as_object()
932            .mark_needs_layout_for_sized_by_parent_change(app);
933    }
934
935    fn get_inner_constraints(
936        self: RenderHandle<Self>,
937        app: &App,
938        constraints: BoxConstraints,
939    ) -> BoxConstraints {
940        let this = self.get(app);
941        BoxConstraints {
942            min_width: this.min_width.unwrap_or(constraints.min_width),
943            max_width: this.max_width.unwrap_or(constraints.max_width),
944            min_height: this.min_height.unwrap_or(constraints.min_height),
945            max_height: this.max_height.unwrap_or(constraints.max_height),
946        }
947    }
948}
949
950impl RenderObjectWithChildMixin for RenderConstrainedOverflowBox {
951    type ChildType = AnyRenderBox;
952
953    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
954        &self.get(app).child
955    }
956
957    fn child_data_mut(
958        self: RenderHandle<Self>,
959        app: &mut App,
960    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
961        &mut self.get_mut(app).child
962    }
963}
964
965impl RenderShiftedBox for RenderConstrainedOverflowBox {}
966
967impl RenderAligningShiftedBox for RenderConstrainedOverflowBox {
968    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
969        &self.get(app).aligning
970    }
971
972    fn aligning_data_mut(
973        self: RenderHandle<Self>,
974        app: &mut App,
975    ) -> &mut RenderAligningShiftedBoxData {
976        &mut self.get_mut(app).aligning
977    }
978}
979
980impl RenderObject for RenderConstrainedOverflowBox {
981    crate::render_object_accessors!();
982
983    fn debug_fill_properties(
984        self: RenderHandle<Self>,
985        app: &App,
986        properties: &mut DiagnosticPropertiesBuilder,
987    ) {
988        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
989        let this = self.get(app);
990        properties.add(
991            DoubleProperty::new("minWidth", this.min_width)
992                .if_null("use parent minWidth constraint"),
993        );
994        properties.add(
995            DoubleProperty::new("maxWidth", this.max_width)
996                .if_null("use parent maxWidth constraint"),
997        );
998        properties.add(
999            DoubleProperty::new("minHeight", this.min_height)
1000                .if_null("use parent minHeight constraint"),
1001        );
1002        properties.add(
1003            DoubleProperty::new("maxHeight", this.max_height)
1004                .if_null("use parent maxHeight constraint"),
1005        );
1006        properties.add(EnumProperty::<OverflowBoxFit>::new("fit", this.fit));
1007    }
1008
1009    fn sized_by_parent(self: RenderHandle<Self>, app: &App) -> bool {
1010        match self.fit(app) {
1011            OverflowBoxFit::Max => true,
1012            // If defer_to_child, the size will be as small as its child when non-overflowing,
1013            // thus it cannot be sized_by_parent.
1014            OverflowBoxFit::DeferToChild => false,
1015        }
1016    }
1017
1018    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1019        let constraints = self.constraints(app);
1020        match self.child(app) {
1021            Some(child) => {
1022                let inner = self.get_inner_constraints(app, constraints);
1023                child.layout(app, inner, true);
1024                match self.fit(app) {
1025                    OverflowBoxFit::Max => debug_assert!(self.sized_by_parent(app)),
1026                    OverflowBoxFit::DeferToChild => {
1027                        let size = constraints.constrain(child.size(app));
1028                        self.set_size(app, size);
1029                    }
1030                }
1031                self.align_child(app);
1032            }
1033            None => match self.fit(app) {
1034                OverflowBoxFit::Max => debug_assert!(self.sized_by_parent(app)),
1035                OverflowBoxFit::DeferToChild => self.set_size(app, constraints.smallest()),
1036            },
1037        }
1038    }
1039
1040    fn paint(
1041        self: RenderHandle<Self>,
1042        app: &mut App,
1043        context: &mut PaintingContext,
1044        offset: Offset,
1045    ) {
1046        RenderShiftedBox::paint(self, app, context, offset);
1047    }
1048
1049    fn visit_children(
1050        self: RenderHandle<Self>,
1051        app: &App,
1052        visitor: &mut dyn FnMut(AnyRenderObject),
1053    ) {
1054        if let Some(child) = self.child(app) {
1055            visitor(child.as_object());
1056        }
1057    }
1058}
1059
1060impl RenderBox for RenderConstrainedOverflowBox {
1061    crate::render_box_accessors!();
1062
1063    fn hit_test_children(
1064        self: RenderHandle<Self>,
1065        app: &mut App,
1066        result: &mut BoxHitTestResult<'_>,
1067        position: Offset,
1068    ) -> bool {
1069        RenderShiftedBox::hit_test_children(self, app, result, position)
1070    }
1071
1072    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1073        RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
1074    }
1075
1076    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1077        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
1078    }
1079
1080    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1081        RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
1082    }
1083
1084    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1085        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
1086    }
1087
1088    fn compute_distance_to_actual_baseline(
1089        self: RenderHandle<Self>,
1090        app: &mut App,
1091        baseline: TextBaseline,
1092    ) -> Option<f64> {
1093        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1094    }
1095
1096    fn compute_dry_layout(
1097        self: RenderHandle<Self>,
1098        app: &mut App,
1099        constraints: BoxConstraints,
1100    ) -> Size {
1101        match self.fit(app) {
1102            OverflowBoxFit::Max => constraints.biggest(),
1103            OverflowBoxFit::DeferToChild => match self.child(app) {
1104                Some(child) => child.get_dry_layout(app, constraints),
1105                None => constraints.smallest(),
1106            },
1107        }
1108    }
1109
1110    fn compute_dry_baseline(
1111        self: RenderHandle<Self>,
1112        app: &mut App,
1113        constraints: BoxConstraints,
1114        baseline: TextBaseline,
1115    ) -> Option<f64> {
1116        let child = self.child(app)?;
1117        let child_constraints = self.get_inner_constraints(app, constraints);
1118        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
1119        let child_size = child.get_dry_layout(app, child_constraints);
1120        let size = self.get_dry_layout(app, constraints);
1121        Some(
1122            result
1123                + self
1124                    .resolved_alignment(app)
1125                    .along_offset(size - child_size)
1126                    .dy(),
1127        )
1128    }
1129}
1130
1131/// A [`RenderBox`] that applies an arbitrary transform to its constraints, and sizes its child
1132/// using the resulting [`BoxConstraints`], optionally clipping, or treating the overflow as an
1133/// error.
1134///
1135/// This [`RenderBox`] sizes its child using a [`BoxConstraints`] created by applying
1136/// [`constraints_transform`](Self::constraints_transform) to this [`RenderBox`]'s own constraints.
1137/// This box will then attempt to adopt the same size, within the limits of its own constraints. If
1138/// it ends up with a different size, it will align the child based on
1139/// [`RenderAligningShiftedBox::alignment`]. If the box cannot expand enough to accommodate the
1140/// entire child, the child will be clipped if
1141/// [`clip_behavior`](Self::clip_behavior) is not [`Clip::None`].
1142///
1143/// When the child is `None`, this [`RenderBox`] takes the smallest possible size and never
1144/// overflows.
1145pub struct RenderConstraintsTransformBox {
1146    render_object: RenderObjectData,
1147    render_box: RenderBoxData,
1148    child: RenderObjectWithChildData<AnyRenderBox>,
1149    aligning: RenderAligningShiftedBoxData,
1150    constraints_transform: BoxConstraintsTransform,
1151    clip_behavior: Clip,
1152    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
1153    overflow_container_rect: Rect,
1154    overflow_child_rect: Rect,
1155    is_overflowing: bool,
1156    child_constraints: Option<BoxConstraints>,
1157}
1158
1159impl RenderConstraintsTransformBox {
1160    /// Creates a [`RenderBox`] that sizes itself to the child and modifies the constraints before
1161    /// passing them down to that child.
1162    pub fn new(
1163        app: &mut App,
1164        alignment: AlignmentGeometry,
1165        text_direction: Option<TextDirection>,
1166        constraints_transform: BoxConstraintsTransform,
1167        child: Option<AnyRenderBox>,
1168    ) -> RenderHandle<Self> {
1169        let this = RenderHandle::new_box(
1170            app,
1171            RenderConstraintsTransformBox {
1172                render_object: RenderObjectData::new(),
1173                render_box: RenderBoxData::new(),
1174                child: RenderObjectWithChildData::new(),
1175                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
1176                constraints_transform,
1177                clip_behavior: Clip::None,
1178                clip_rect_layer: LayerHandle::new(),
1179                overflow_container_rect: Rect::ZERO,
1180                overflow_child_rect: Rect::ZERO,
1181                is_overflowing: false,
1182                child_constraints: None,
1183            },
1184        );
1185        this.set_child(app, child);
1186        this
1187    }
1188
1189    /// The transform this box applies to its own constraints before laying its child out.
1190    pub fn constraints_transform(self: RenderHandle<Self>, app: &App) -> BoxConstraintsTransform {
1191        self.get(app).constraints_transform
1192    }
1193
1194    /// Sets [`constraints_transform`](Self::constraints_transform).
1195    pub fn set_constraints_transform(
1196        self: RenderHandle<Self>,
1197        app: &mut App,
1198        value: BoxConstraintsTransform,
1199    ) {
1200        if std::ptr::fn_addr_eq(self.get(app).constraints_transform, value) {
1201            return;
1202        }
1203        self.get_mut(app).constraints_transform = value;
1204        // The render object only needs layout if the new transform maps the current constraints
1205        // to a different value, or the render object has never been laid out before.
1206        let needs_layout = match self.get(app).child_constraints {
1207            Some(child_constraints) => child_constraints != value(self.constraints(app)),
1208            None => true,
1209        };
1210        if needs_layout {
1211            self.mark_needs_layout(app);
1212        }
1213    }
1214
1215    /// How to clip a child that overflows this box. Defaults to [`Clip::None`].
1216    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
1217        self.get(app).clip_behavior
1218    }
1219
1220    /// Sets [`clip_behavior`](Self::clip_behavior).
1221    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
1222        if self.get(app).clip_behavior == value {
1223            return;
1224        }
1225        self.get_mut(app).clip_behavior = value;
1226        self.mark_needs_paint(app);
1227    }
1228}
1229
1230impl RenderObjectWithChildMixin for RenderConstraintsTransformBox {
1231    type ChildType = AnyRenderBox;
1232
1233    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1234        &self.get(app).child
1235    }
1236
1237    fn child_data_mut(
1238        self: RenderHandle<Self>,
1239        app: &mut App,
1240    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1241        &mut self.get_mut(app).child
1242    }
1243}
1244
1245impl RenderShiftedBox for RenderConstraintsTransformBox {}
1246
1247impl RenderAligningShiftedBox for RenderConstraintsTransformBox {
1248    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
1249        &self.get(app).aligning
1250    }
1251
1252    fn aligning_data_mut(
1253        self: RenderHandle<Self>,
1254        app: &mut App,
1255    ) -> &mut RenderAligningShiftedBoxData {
1256        &mut self.get_mut(app).aligning
1257    }
1258}
1259
1260impl RenderObject for RenderConstraintsTransformBox {
1261    crate::render_object_accessors!();
1262
1263    fn debug_fill_properties(
1264        self: RenderHandle<Self>,
1265        app: &App,
1266        properties: &mut DiagnosticPropertiesBuilder,
1267    ) {
1268        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
1269    }
1270
1271    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1272        let constraints = self.constraints(app);
1273        match self.child(app) {
1274            Some(child) => {
1275                let child_constraints = (self.constraints_transform(app))(constraints);
1276                debug_assert!(
1277                    child_constraints.is_normalized(),
1278                    "{child_constraints} is not normalized"
1279                );
1280                self.get_mut(app).child_constraints = Some(child_constraints);
1281                child.layout(app, child_constraints, true);
1282                let size = constraints.constrain(child.size(app));
1283                self.set_size(app, size);
1284                self.align_child(app);
1285                let child_offset = child
1286                    .as_object()
1287                    .parent_data_of::<BoxParentData>(app)
1288                    .offset;
1289                let child_rect = child_offset & child.size(app);
1290                let this = self.get_mut(app);
1291                this.overflow_container_rect = Offset::ZERO & size;
1292                this.overflow_child_rect = child_rect;
1293            }
1294            None => {
1295                self.set_size(app, constraints.smallest());
1296                let this = self.get_mut(app);
1297                this.overflow_container_rect = Rect::ZERO;
1298                this.overflow_child_rect = Rect::ZERO;
1299            }
1300        }
1301        let this = self.get_mut(app);
1302        this.is_overflowing =
1303            RelativeRect::from_rect(this.overflow_container_rect, this.overflow_child_rect)
1304                .has_insets();
1305    }
1306
1307    fn paint(
1308        self: RenderHandle<Self>,
1309        app: &mut App,
1310        context: &mut PaintingContext,
1311        offset: Offset,
1312    ) {
1313        if self.child(app).is_none() {
1314            return;
1315        }
1316        if !self.get(app).is_overflowing {
1317            RenderShiftedBox::paint(self, app, context, offset);
1318            return;
1319        }
1320        // We have overflow and the clipBehavior isn't none. Clip it.
1321        let clip_rect = Offset::ZERO & self.size(app);
1322        let clip_behavior = self.clip_behavior(app);
1323        let old = self.get(app).clip_rect_layer.layer();
1324        let layer = context.push_clip_rect(
1325            app,
1326            self.as_object().needs_compositing(app),
1327            offset,
1328            clip_rect,
1329            |app, context, offset| RenderShiftedBox::paint(self, app, context, offset),
1330            clip_behavior,
1331            old,
1332        );
1333        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
1334    }
1335
1336    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1337        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
1338        crate::object::RenderObjectBase::dispose(self, app);
1339    }
1340
1341    /// Dart's `describeApproximatePaintClip`: a child that overflowed is clipped to this box's
1342    /// bounds, and only when it overflowed.
1343    fn describe_approximate_paint_clip(
1344        self: RenderHandle<Self>,
1345        app: &App,
1346        _child: AnyRenderObject,
1347    ) -> Option<Rect> {
1348        match self.clip_behavior(app) {
1349            Clip::None => None,
1350            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => self
1351                .get(app)
1352                .is_overflowing
1353                .then(|| Offset::ZERO & self.size(app)),
1354        }
1355    }
1356
1357    fn visit_children(
1358        self: RenderHandle<Self>,
1359        app: &App,
1360        visitor: &mut dyn FnMut(AnyRenderObject),
1361    ) {
1362        if let Some(child) = self.child(app) {
1363            visitor(child.as_object());
1364        }
1365    }
1366}
1367
1368impl RenderBox for RenderConstraintsTransformBox {
1369    crate::render_box_accessors!();
1370
1371    fn hit_test_children(
1372        self: RenderHandle<Self>,
1373        app: &mut App,
1374        result: &mut BoxHitTestResult<'_>,
1375        position: Offset,
1376    ) -> bool {
1377        RenderShiftedBox::hit_test_children(self, app, result, position)
1378    }
1379
1380    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1381        let transformed =
1382            (self.constraints_transform(app))(BoxConstraints::new().max_height(height));
1383        RenderShiftedBox::compute_min_intrinsic_width(self, app, transformed.max_height)
1384    }
1385
1386    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1387        let transformed =
1388            (self.constraints_transform(app))(BoxConstraints::new().max_height(height));
1389        RenderShiftedBox::compute_max_intrinsic_width(self, app, transformed.max_height)
1390    }
1391
1392    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1393        let transformed = (self.constraints_transform(app))(BoxConstraints::new().max_width(width));
1394        RenderShiftedBox::compute_min_intrinsic_height(self, app, transformed.max_width)
1395    }
1396
1397    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1398        let transformed = (self.constraints_transform(app))(BoxConstraints::new().max_width(width));
1399        RenderShiftedBox::compute_max_intrinsic_height(self, app, transformed.max_width)
1400    }
1401
1402    fn compute_distance_to_actual_baseline(
1403        self: RenderHandle<Self>,
1404        app: &mut App,
1405        baseline: TextBaseline,
1406    ) -> Option<f64> {
1407        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1408    }
1409
1410    fn compute_dry_layout(
1411        self: RenderHandle<Self>,
1412        app: &mut App,
1413        constraints: BoxConstraints,
1414    ) -> Size {
1415        match self.child(app) {
1416            Some(child) => {
1417                let child_constraints = (self.constraints_transform(app))(constraints);
1418                let child_size = child.get_dry_layout(app, child_constraints);
1419                constraints.constrain(child_size)
1420            }
1421            None => constraints.smallest(),
1422        }
1423    }
1424
1425    fn compute_dry_baseline(
1426        self: RenderHandle<Self>,
1427        app: &mut App,
1428        constraints: BoxConstraints,
1429        baseline: TextBaseline,
1430    ) -> Option<f64> {
1431        let child = self.child(app)?;
1432        let child_constraints = (self.constraints_transform(app))(constraints);
1433        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
1434        let child_size = child.get_dry_layout(app, child_constraints);
1435        let size = constraints.constrain(child_size);
1436        Some(
1437            result
1438                + self
1439                    .resolved_alignment(app)
1440                    .along_offset(size - child_size)
1441                    .dy(),
1442        )
1443    }
1444}
1445
1446/// A render object that is a specific size but passes its original constraints through to its
1447/// child, which it allows to overflow.
1448///
1449/// If the child's resulting size differs from this render object's size, then the child is aligned
1450/// according to [`RenderAligningShiftedBox::alignment`].
1451pub struct RenderSizedOverflowBox {
1452    render_object: RenderObjectData,
1453    render_box: RenderBoxData,
1454    child: RenderObjectWithChildData<AnyRenderBox>,
1455    aligning: RenderAligningShiftedBoxData,
1456    requested_size: Size,
1457}
1458
1459impl RenderSizedOverflowBox {
1460    /// Creates a render box of a given size that lets its child overflow.
1461    pub fn new(
1462        app: &mut App,
1463        requested_size: Size,
1464        alignment: AlignmentGeometry,
1465        text_direction: Option<TextDirection>,
1466        child: Option<AnyRenderBox>,
1467    ) -> RenderHandle<Self> {
1468        let this = RenderHandle::new_box(
1469            app,
1470            RenderSizedOverflowBox {
1471                render_object: RenderObjectData::new(),
1472                render_box: RenderBoxData::new(),
1473                child: RenderObjectWithChildData::new(),
1474                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
1475                requested_size,
1476            },
1477        );
1478        this.set_child(app, child);
1479        this
1480    }
1481
1482    /// The size this render box should attempt to be.
1483    pub fn requested_size(self: RenderHandle<Self>, app: &App) -> Size {
1484        self.get(app).requested_size
1485    }
1486
1487    /// Sets [`requested_size`](Self::requested_size).
1488    pub fn set_requested_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
1489        if self.get(app).requested_size == value {
1490            return;
1491        }
1492        self.get_mut(app).requested_size = value;
1493        self.mark_needs_layout(app);
1494    }
1495}
1496
1497impl RenderObjectWithChildMixin for RenderSizedOverflowBox {
1498    type ChildType = AnyRenderBox;
1499
1500    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1501        &self.get(app).child
1502    }
1503
1504    fn child_data_mut(
1505        self: RenderHandle<Self>,
1506        app: &mut App,
1507    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1508        &mut self.get_mut(app).child
1509    }
1510}
1511
1512impl RenderShiftedBox for RenderSizedOverflowBox {}
1513
1514impl RenderAligningShiftedBox for RenderSizedOverflowBox {
1515    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
1516        &self.get(app).aligning
1517    }
1518
1519    fn aligning_data_mut(
1520        self: RenderHandle<Self>,
1521        app: &mut App,
1522    ) -> &mut RenderAligningShiftedBoxData {
1523        &mut self.get_mut(app).aligning
1524    }
1525}
1526
1527impl RenderObject for RenderSizedOverflowBox {
1528    crate::render_object_accessors!();
1529
1530    fn debug_fill_properties(
1531        self: RenderHandle<Self>,
1532        app: &App,
1533        properties: &mut DiagnosticPropertiesBuilder,
1534    ) {
1535        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
1536    }
1537
1538    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1539        let constraints = self.constraints(app);
1540        let size = constraints.constrain(self.requested_size(app));
1541        self.set_size(app, size);
1542        if let Some(child) = self.child(app) {
1543            child.layout(app, constraints, true);
1544            self.align_child(app);
1545        }
1546    }
1547
1548    fn paint(
1549        self: RenderHandle<Self>,
1550        app: &mut App,
1551        context: &mut PaintingContext,
1552        offset: Offset,
1553    ) {
1554        RenderShiftedBox::paint(self, app, context, offset);
1555    }
1556
1557    fn visit_children(
1558        self: RenderHandle<Self>,
1559        app: &App,
1560        visitor: &mut dyn FnMut(AnyRenderObject),
1561    ) {
1562        if let Some(child) = self.child(app) {
1563            visitor(child.as_object());
1564        }
1565    }
1566}
1567
1568impl RenderBox for RenderSizedOverflowBox {
1569    crate::render_box_accessors!();
1570
1571    fn hit_test_children(
1572        self: RenderHandle<Self>,
1573        app: &mut App,
1574        result: &mut BoxHitTestResult<'_>,
1575        position: Offset,
1576    ) -> bool {
1577        RenderShiftedBox::hit_test_children(self, app, result, position)
1578    }
1579
1580    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1581        self.requested_size(app).width()
1582    }
1583
1584    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1585        self.requested_size(app).width()
1586    }
1587
1588    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, _width: f64) -> f64 {
1589        self.requested_size(app).height()
1590    }
1591
1592    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, _width: f64) -> f64 {
1593        self.requested_size(app).height()
1594    }
1595
1596    fn compute_distance_to_actual_baseline(
1597        self: RenderHandle<Self>,
1598        app: &mut App,
1599        baseline: TextBaseline,
1600    ) -> Option<f64> {
1601        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1602    }
1603
1604    fn compute_dry_layout(
1605        self: RenderHandle<Self>,
1606        app: &mut App,
1607        constraints: BoxConstraints,
1608    ) -> Size {
1609        constraints.constrain(self.requested_size(app))
1610    }
1611
1612    fn compute_dry_baseline(
1613        self: RenderHandle<Self>,
1614        app: &mut App,
1615        constraints: BoxConstraints,
1616        baseline: TextBaseline,
1617    ) -> Option<f64> {
1618        let child = self.child(app)?;
1619        let result = child.get_dry_baseline(app, constraints, baseline)?;
1620        let child_size = child.get_dry_layout(app, constraints);
1621        let size = self.get_dry_layout(app, constraints);
1622        Some(
1623            result
1624                + self
1625                    .resolved_alignment(app)
1626                    .along_offset(size - child_size)
1627                    .dy(),
1628        )
1629    }
1630}
1631
1632/// Sizes its child to a fraction of the total available space.
1633///
1634/// For both its width and height, this render object imposes a tight constraint on its child that
1635/// is a multiple (typically less than 1.0) of the maximum constraint it received from its parent
1636/// on that axis. If the factor for a given axis is `None`, then the constraints from the parent
1637/// are just passed through instead.
1638///
1639/// It then tries to size itself to the size of its child. Where this is not possible (e.g. if the
1640/// constraints from the parent are themselves tight), the child is aligned according to
1641/// [`RenderAligningShiftedBox::alignment`].
1642pub struct RenderFractionallySizedOverflowBox {
1643    render_object: RenderObjectData,
1644    render_box: RenderBoxData,
1645    child: RenderObjectWithChildData<AnyRenderBox>,
1646    aligning: RenderAligningShiftedBoxData,
1647    width_factor: Option<f64>,
1648    height_factor: Option<f64>,
1649}
1650
1651impl RenderFractionallySizedOverflowBox {
1652    /// Creates a render box that sizes its child to a fraction of the total available space.
1653    pub fn new(
1654        app: &mut App,
1655        alignment: AlignmentGeometry,
1656        text_direction: Option<TextDirection>,
1657        child: Option<AnyRenderBox>,
1658    ) -> RenderHandle<Self> {
1659        let this = RenderHandle::new_box(
1660            app,
1661            RenderFractionallySizedOverflowBox {
1662                render_object: RenderObjectData::new(),
1663                render_box: RenderBoxData::new(),
1664                child: RenderObjectWithChildData::new(),
1665                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
1666                width_factor: None,
1667                height_factor: None,
1668            },
1669        );
1670        this.set_child(app, child);
1671        this
1672    }
1673
1674    /// If non-null, the factor of the incoming width to use.
1675    ///
1676    /// If non-null, the child is given a tight width constraint that is the max incoming width
1677    /// constraint multiplied by this factor. If null, the child is given the incoming width
1678    /// constraints.
1679    pub fn width_factor(self: RenderHandle<Self>, app: &App) -> Option<f64> {
1680        self.get(app).width_factor
1681    }
1682
1683    /// Sets [`width_factor`](Self::width_factor).
1684    pub fn set_width_factor(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
1685        debug_assert!(value.is_none_or(|factor| factor >= 0.0));
1686        if self.get(app).width_factor == value {
1687            return;
1688        }
1689        self.get_mut(app).width_factor = value;
1690        self.mark_needs_layout(app);
1691    }
1692
1693    /// If non-null, the factor of the incoming height to use.
1694    ///
1695    /// If non-null, the child is given a tight height constraint that is the max incoming height
1696    /// constraint multiplied by this factor. If null, the child is given the incoming height
1697    /// constraints.
1698    pub fn height_factor(self: RenderHandle<Self>, app: &App) -> Option<f64> {
1699        self.get(app).height_factor
1700    }
1701
1702    /// Sets [`height_factor`](Self::height_factor).
1703    pub fn set_height_factor(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
1704        debug_assert!(value.is_none_or(|factor| factor >= 0.0));
1705        if self.get(app).height_factor == value {
1706            return;
1707        }
1708        self.get_mut(app).height_factor = value;
1709        self.mark_needs_layout(app);
1710    }
1711
1712    fn get_inner_constraints(
1713        self: RenderHandle<Self>,
1714        app: &App,
1715        constraints: BoxConstraints,
1716    ) -> BoxConstraints {
1717        let (width_factor, height_factor) = {
1718            let this = self.get(app);
1719            (this.width_factor, this.height_factor)
1720        };
1721        let mut min_width = constraints.min_width;
1722        let mut max_width = constraints.max_width;
1723        if let Some(factor) = width_factor {
1724            let width = max_width * factor;
1725            min_width = width;
1726            max_width = width;
1727        }
1728        let mut min_height = constraints.min_height;
1729        let mut max_height = constraints.max_height;
1730        if let Some(factor) = height_factor {
1731            let height = max_height * factor;
1732            min_height = height;
1733            max_height = height;
1734        }
1735        BoxConstraints {
1736            min_width,
1737            max_width,
1738            min_height,
1739            max_height,
1740        }
1741    }
1742}
1743
1744impl RenderObjectWithChildMixin for RenderFractionallySizedOverflowBox {
1745    type ChildType = AnyRenderBox;
1746
1747    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1748        &self.get(app).child
1749    }
1750
1751    fn child_data_mut(
1752        self: RenderHandle<Self>,
1753        app: &mut App,
1754    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1755        &mut self.get_mut(app).child
1756    }
1757}
1758
1759impl RenderShiftedBox for RenderFractionallySizedOverflowBox {}
1760
1761impl RenderAligningShiftedBox for RenderFractionallySizedOverflowBox {
1762    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
1763        &self.get(app).aligning
1764    }
1765
1766    fn aligning_data_mut(
1767        self: RenderHandle<Self>,
1768        app: &mut App,
1769    ) -> &mut RenderAligningShiftedBoxData {
1770        &mut self.get_mut(app).aligning
1771    }
1772}
1773
1774impl RenderObject for RenderFractionallySizedOverflowBox {
1775    crate::render_object_accessors!();
1776
1777    fn debug_fill_properties(
1778        self: RenderHandle<Self>,
1779        app: &App,
1780        properties: &mut DiagnosticPropertiesBuilder,
1781    ) {
1782        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
1783        let this = self.get(app);
1784        properties
1785            .add(DoubleProperty::new("widthFactor", this.width_factor).if_null("pass-through"));
1786        properties
1787            .add(DoubleProperty::new("heightFactor", this.height_factor).if_null("pass-through"));
1788    }
1789
1790    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1791        let constraints = self.constraints(app);
1792        let inner = self.get_inner_constraints(app, constraints);
1793        match self.child(app) {
1794            Some(child) => {
1795                child.layout(app, inner, true);
1796                let size = constraints.constrain(child.size(app));
1797                self.set_size(app, size);
1798                self.align_child(app);
1799            }
1800            None => {
1801                let size = constraints.constrain(inner.constrain(Size::ZERO));
1802                self.set_size(app, size);
1803            }
1804        }
1805    }
1806
1807    fn paint(
1808        self: RenderHandle<Self>,
1809        app: &mut App,
1810        context: &mut PaintingContext,
1811        offset: Offset,
1812    ) {
1813        RenderShiftedBox::paint(self, app, context, offset);
1814    }
1815
1816    fn visit_children(
1817        self: RenderHandle<Self>,
1818        app: &App,
1819        visitor: &mut dyn FnMut(AnyRenderObject),
1820    ) {
1821        if let Some(child) = self.child(app) {
1822            visitor(child.as_object());
1823        }
1824    }
1825}
1826
1827impl RenderBox for RenderFractionallySizedOverflowBox {
1828    crate::render_box_accessors!();
1829
1830    fn hit_test_children(
1831        self: RenderHandle<Self>,
1832        app: &mut App,
1833        result: &mut BoxHitTestResult<'_>,
1834        position: Offset,
1835    ) -> bool {
1836        RenderShiftedBox::hit_test_children(self, app, result, position)
1837    }
1838
1839    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1840        let (width_factor, height_factor) = {
1841            let this = self.get(app);
1842            (this.width_factor, this.height_factor)
1843        };
1844        let result = match self.child(app) {
1845            // Relies on f64::INFINITY absorption.
1846            Some(child) => {
1847                child.get_min_intrinsic_width(app, height * height_factor.unwrap_or(1.0))
1848            }
1849            None => RenderShiftedBox::compute_min_intrinsic_width(self, app, height),
1850        };
1851        debug_assert!(result.is_finite());
1852        result / width_factor.unwrap_or(1.0)
1853    }
1854
1855    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1856        let (width_factor, height_factor) = {
1857            let this = self.get(app);
1858            (this.width_factor, this.height_factor)
1859        };
1860        let result = match self.child(app) {
1861            Some(child) => {
1862                child.get_max_intrinsic_width(app, height * height_factor.unwrap_or(1.0))
1863            }
1864            None => RenderShiftedBox::compute_max_intrinsic_width(self, app, height),
1865        };
1866        debug_assert!(result.is_finite());
1867        result / width_factor.unwrap_or(1.0)
1868    }
1869
1870    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1871        let (width_factor, height_factor) = {
1872            let this = self.get(app);
1873            (this.width_factor, this.height_factor)
1874        };
1875        let result = match self.child(app) {
1876            Some(child) => child.get_min_intrinsic_height(app, width * width_factor.unwrap_or(1.0)),
1877            None => RenderShiftedBox::compute_min_intrinsic_height(self, app, width),
1878        };
1879        debug_assert!(result.is_finite());
1880        result / height_factor.unwrap_or(1.0)
1881    }
1882
1883    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1884        let (width_factor, height_factor) = {
1885            let this = self.get(app);
1886            (this.width_factor, this.height_factor)
1887        };
1888        let result = match self.child(app) {
1889            Some(child) => child.get_max_intrinsic_height(app, width * width_factor.unwrap_or(1.0)),
1890            None => RenderShiftedBox::compute_max_intrinsic_height(self, app, width),
1891        };
1892        debug_assert!(result.is_finite());
1893        result / height_factor.unwrap_or(1.0)
1894    }
1895
1896    fn compute_distance_to_actual_baseline(
1897        self: RenderHandle<Self>,
1898        app: &mut App,
1899        baseline: TextBaseline,
1900    ) -> Option<f64> {
1901        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1902    }
1903
1904    fn compute_dry_layout(
1905        self: RenderHandle<Self>,
1906        app: &mut App,
1907        constraints: BoxConstraints,
1908    ) -> Size {
1909        let inner = self.get_inner_constraints(app, constraints);
1910        match self.child(app) {
1911            Some(child) => {
1912                let child_size = child.get_dry_layout(app, inner);
1913                constraints.constrain(child_size)
1914            }
1915            None => constraints.constrain(inner.constrain(Size::ZERO)),
1916        }
1917    }
1918
1919    fn compute_dry_baseline(
1920        self: RenderHandle<Self>,
1921        app: &mut App,
1922        constraints: BoxConstraints,
1923        baseline: TextBaseline,
1924    ) -> Option<f64> {
1925        let child = self.child(app)?;
1926        let child_constraints = self.get_inner_constraints(app, constraints);
1927        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
1928        let child_size = child.get_dry_layout(app, child_constraints);
1929        let size = self.get_dry_layout(app, constraints);
1930        Some(
1931            result
1932                + self
1933                    .resolved_alignment(app)
1934                    .along_offset(size - child_size)
1935                    .dy(),
1936        )
1937    }
1938}
1939
1940/// Shifts the child down such that the child's baseline (or the bottom of the child, if the child
1941/// has no baseline) is [`baseline`](Self::baseline) logical pixels below the top of this box, then
1942/// sizes this box to contain the child.
1943///
1944/// If [`baseline`](Self::baseline) is less than the distance from the top of the child to the
1945/// baseline of the child, then the child will overflow the top of the box. This is typically not
1946/// desirable, in particular, that part of the child will not be found when doing hit tests, so
1947/// the user cannot interact with that part of the child.
1948///
1949/// This box will be sized so that its bottom is coincident with the bottom of the child. This
1950/// means if this box shifts the child down, there will be space between the top of this box and
1951/// the top of the child, but there is never space between the bottom of the child and the bottom
1952/// of the box.
1953pub struct RenderBaseline {
1954    render_object: RenderObjectData,
1955    render_box: RenderBoxData,
1956    child: RenderObjectWithChildData<AnyRenderBox>,
1957    baseline: f64,
1958    baseline_type: TextBaseline,
1959}
1960
1961/// What [`RenderBaseline::compute_sizes`] worked out: Dart's `({Size size, double top})`.
1962struct BaselineSizes {
1963    size: Size,
1964    top: f64,
1965}
1966
1967impl RenderBaseline {
1968    /// Creates a [`RenderBaseline`] object.
1969    pub fn new(
1970        app: &mut App,
1971        baseline: f64,
1972        baseline_type: TextBaseline,
1973        child: Option<AnyRenderBox>,
1974    ) -> RenderHandle<Self> {
1975        let this = RenderHandle::new_box(
1976            app,
1977            RenderBaseline {
1978                render_object: RenderObjectData::new(),
1979                render_box: RenderBoxData::new(),
1980                child: RenderObjectWithChildData::new(),
1981                baseline,
1982                baseline_type,
1983            },
1984        );
1985        this.set_child(app, child);
1986        this
1987    }
1988
1989    /// The number of logical pixels from the top of this box at which to position the child's
1990    /// baseline.
1991    pub fn baseline(self: RenderHandle<Self>, app: &App) -> f64 {
1992        self.get(app).baseline
1993    }
1994
1995    /// Sets [`baseline`](Self::baseline).
1996    pub fn set_baseline(self: RenderHandle<Self>, app: &mut App, value: f64) {
1997        if self.get(app).baseline == value {
1998            return;
1999        }
2000        self.get_mut(app).baseline = value;
2001        self.mark_needs_layout(app);
2002    }
2003
2004    /// The type of baseline to use for positioning the child.
2005    pub fn baseline_type(self: RenderHandle<Self>, app: &App) -> TextBaseline {
2006        self.get(app).baseline_type
2007    }
2008
2009    /// Sets [`baseline_type`](Self::baseline_type).
2010    pub fn set_baseline_type(self: RenderHandle<Self>, app: &mut App, value: TextBaseline) {
2011        if self.get(app).baseline_type == value {
2012            return;
2013        }
2014        self.get_mut(app).baseline_type = value;
2015        self.mark_needs_layout(app);
2016    }
2017
2018    /// Flutter's `_computeSizes`: this box's size and the offset the child is shifted down by.
2019    fn compute_sizes(
2020        self: RenderHandle<Self>,
2021        app: &mut App,
2022        constraints: BoxConstraints,
2023        layout_child: ChildLayouter,
2024        get_baseline: ChildBaselineGetter,
2025    ) -> BaselineSizes {
2026        let Some(child) = self.child(app) else {
2027            return BaselineSizes {
2028                size: constraints.smallest(),
2029                top: 0.0,
2030            };
2031        };
2032        let child_constraints = constraints.loosen();
2033        let child_size = layout_child(app, child, child_constraints);
2034        let baseline_type = self.baseline_type(app);
2035        let child_baseline = get_baseline(app, child, child_constraints, baseline_type)
2036            .unwrap_or(child_size.height());
2037        let top = self.baseline(app) - child_baseline;
2038        BaselineSizes {
2039            size: constraints.constrain(Size::new(child_size.width(), top + child_size.height())),
2040            top,
2041        }
2042    }
2043}
2044
2045impl RenderObjectWithChildMixin for RenderBaseline {
2046    type ChildType = AnyRenderBox;
2047
2048    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2049        &self.get(app).child
2050    }
2051
2052    fn child_data_mut(
2053        self: RenderHandle<Self>,
2054        app: &mut App,
2055    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2056        &mut self.get_mut(app).child
2057    }
2058}
2059
2060impl RenderShiftedBox for RenderBaseline {}
2061
2062impl RenderObject for RenderBaseline {
2063    crate::render_object_accessors!();
2064
2065    fn debug_fill_properties(
2066        self: RenderHandle<Self>,
2067        app: &App,
2068        properties: &mut DiagnosticPropertiesBuilder,
2069    ) {
2070        let this = self.get(app);
2071        properties.add(DoubleProperty::new("baseline", this.baseline));
2072        properties.add(EnumProperty::<TextBaseline>::new(
2073            "baselineType",
2074            this.baseline_type,
2075        ));
2076    }
2077
2078    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2079        let constraints = self.constraints(app);
2080        let sizes = self.compute_sizes(
2081            app,
2082            constraints,
2083            ChildLayoutHelper::layout_child,
2084            ChildLayoutHelper::get_baseline,
2085        );
2086        self.set_size(app, sizes.size);
2087        if let Some(child) = self.child(app) {
2088            child.parent_data_of_mut::<BoxParentData>(app).offset = Offset::new(0.0, sizes.top);
2089        }
2090    }
2091
2092    fn paint(
2093        self: RenderHandle<Self>,
2094        app: &mut App,
2095        context: &mut PaintingContext,
2096        offset: Offset,
2097    ) {
2098        RenderShiftedBox::paint(self, app, context, offset);
2099    }
2100
2101    fn visit_children(
2102        self: RenderHandle<Self>,
2103        app: &App,
2104        visitor: &mut dyn FnMut(AnyRenderObject),
2105    ) {
2106        if let Some(child) = self.child(app) {
2107            visitor(child.as_object());
2108        }
2109    }
2110}
2111
2112impl RenderBox for RenderBaseline {
2113    crate::render_box_accessors!();
2114
2115    fn hit_test_children(
2116        self: RenderHandle<Self>,
2117        app: &mut App,
2118        result: &mut BoxHitTestResult<'_>,
2119        position: Offset,
2120    ) -> bool {
2121        RenderShiftedBox::hit_test_children(self, app, result, position)
2122    }
2123
2124    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2125        RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
2126    }
2127
2128    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2129        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
2130    }
2131
2132    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2133        RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
2134    }
2135
2136    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2137        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
2138    }
2139
2140    fn compute_distance_to_actual_baseline(
2141        self: RenderHandle<Self>,
2142        app: &mut App,
2143        baseline: TextBaseline,
2144    ) -> Option<f64> {
2145        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
2146    }
2147
2148    fn compute_dry_layout(
2149        self: RenderHandle<Self>,
2150        app: &mut App,
2151        constraints: BoxConstraints,
2152    ) -> Size {
2153        self.compute_sizes(
2154            app,
2155            constraints,
2156            ChildLayoutHelper::dry_layout_child,
2157            ChildLayoutHelper::get_dry_baseline,
2158        )
2159        .size
2160    }
2161
2162    fn compute_dry_baseline(
2163        self: RenderHandle<Self>,
2164        app: &mut App,
2165        constraints: BoxConstraints,
2166        baseline: TextBaseline,
2167    ) -> Option<f64> {
2168        let child = self.child(app)?;
2169        let child_constraints = constraints.loosen();
2170        let baseline_type = self.baseline_type(app);
2171        let result1 = child.get_dry_baseline(app, child_constraints, baseline)?;
2172        let result2 = child.get_dry_baseline(app, child_constraints, baseline_type)?;
2173        Some(self.baseline(app) + result1 - result2)
2174    }
2175}
2176
2177/// A delegate for computing the layout of a render object with a single child.
2178///
2179/// Used by [`RenderCustomSingleChildLayoutBox`] and `CustomSingleChildLayout` (in the widgets
2180/// library).
2181///
2182/// When asked to layout, [`RenderCustomSingleChildLayoutBox`] first calls
2183/// [`get_size`](Self::get_size) with its incoming constraints to determine its size. It then
2184/// uses [`get_constraints_for_child`](Self::get_constraints_for_child) to determine the
2185/// constraints to apply to the child. After the child completes its layout,
2186/// [`RenderCustomSingleChildLayoutBox`] calls [`get_position_for_child`](Self::get_position_for_child)
2187/// to determine the child's position.
2188///
2189/// The [`relayout`](Self::relayout) listenable causes the layout to update whenever it
2190/// notifies its listeners.
2191pub trait SingleChildLayoutDelegate: Debug + 'static {
2192    /// The [`Listenable`] the layout will update on, Dart's `relayout` constructor argument.
2193    ///
2194    /// Defaults to `None`.
2195    fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
2196        None
2197    }
2198
2199    /// The size of this object given the incoming constraints.
2200    ///
2201    /// Defaults to the biggest size that satisfies the given constraints.
2202    fn get_size(&self, constraints: BoxConstraints) -> Size {
2203        constraints.biggest()
2204    }
2205
2206    /// The constraints for the child given the incoming constraints.
2207    ///
2208    /// During layout, the child is given the layout constraints returned by this function. The
2209    /// child is required to pick a size for itself that satisfies these constraints.
2210    ///
2211    /// Defaults to the given constraints.
2212    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
2213        constraints
2214    }
2215
2216    /// The position where the child should be placed.
2217    ///
2218    /// The `size` argument is the size of the parent, which might be different from the value
2219    /// returned by [`get_size`](Self::get_size) if that size doesn't satisfy the constraints
2220    /// passed to [`get_size`](Self::get_size). The `child_size` argument is the size of the
2221    /// child, which will satisfy the constraints returned by
2222    /// [`get_constraints_for_child`](Self::get_constraints_for_child).
2223    ///
2224    /// Defaults to positioning the child in the upper left corner of the parent.
2225    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
2226        let _ = (size, child_size);
2227        Offset::ZERO
2228    }
2229
2230    /// Called whenever a new instance of the custom layout delegate class is provided to the
2231    /// [`RenderCustomSingleChildLayoutBox`] object, or any time that a new `CustomSingleChildLayout`
2232    /// object is created with a new instance of the custom layout delegate class (which amounts
2233    /// to the same thing, because the latter is implemented in terms of the former).
2234    ///
2235    /// If the new instance represents different information than the old instance, then the
2236    /// method should return true, otherwise it should return false.
2237    ///
2238    /// If the method returns false, then the [`get_size`](Self::get_size),
2239    /// [`get_constraints_for_child`](Self::get_constraints_for_child), and
2240    /// [`get_position_for_child`](Self::get_position_for_child) calls might be optimized away.
2241    ///
2242    /// It's possible that the layout methods will get called even if [`should_relayout`](Self::should_relayout)
2243    /// returns false (e.g. if an ancestor changed its layout). It's also possible that the
2244    /// layout method will get called without [`should_relayout`](Self::should_relayout) being
2245    /// called at all (e.g. if the parent changes size).
2246    ///
2247    /// `old_delegate` is of the same concrete type, Dart's `covariant`: narrow it with
2248    /// [`as_any`](Self::as_any).
2249    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool;
2250
2251    /// The concrete delegate, for Dart's `runtimeType` comparison and its `covariant`
2252    /// narrowing of [`should_relayout`](Self::should_relayout)'s argument.
2253    fn as_any(&self) -> &dyn Any;
2254}
2255
2256/// Defers the layout of its single child to a delegate.
2257///
2258/// The delegate can determine the layout constraints for the child and can decide where to
2259/// position the child. The delegate can also determine the size of the parent, but the size of
2260/// the parent cannot depend on the size of the child.
2261pub struct RenderCustomSingleChildLayoutBox {
2262    render_object: RenderObjectData,
2263    render_box: RenderBoxData,
2264    child: RenderObjectWithChildData<AnyRenderBox>,
2265    delegate: Rc<dyn SingleChildLayoutDelegate>,
2266}
2267
2268impl RenderCustomSingleChildLayoutBox {
2269    /// Creates a render box that defers its layout to a delegate.
2270    pub fn new(
2271        app: &mut App,
2272        delegate: Rc<dyn SingleChildLayoutDelegate>,
2273        child: Option<AnyRenderBox>,
2274    ) -> RenderHandle<RenderCustomSingleChildLayoutBox> {
2275        let this = RenderHandle::new_box(
2276            app,
2277            RenderCustomSingleChildLayoutBox {
2278                render_object: RenderObjectData::new(),
2279                render_box: RenderBoxData::new(),
2280                child: RenderObjectWithChildData::new(),
2281                delegate,
2282            },
2283        );
2284        this.set_child(app, child);
2285        this
2286    }
2287
2288    /// A delegate that controls this object's layout.
2289    pub fn delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn SingleChildLayoutDelegate> {
2290        Rc::clone(&self.get(app).delegate)
2291    }
2292
2293    /// Sets [`delegate`](Self::delegate).
2294    pub fn set_delegate(
2295        self: RenderHandle<Self>,
2296        app: &mut App,
2297        new_delegate: Rc<dyn SingleChildLayoutDelegate>,
2298    ) {
2299        let old_delegate = Rc::clone(&self.get(app).delegate);
2300        if Rc::ptr_eq(&old_delegate, &new_delegate) {
2301            return;
2302        }
2303        if new_delegate.as_any().type_id() != old_delegate.as_any().type_id()
2304            || new_delegate.should_relayout(&*old_delegate)
2305        {
2306            self.mark_needs_layout(app);
2307        }
2308        self.get_mut(app).delegate = Rc::clone(&new_delegate);
2309        if self.attached(app) {
2310            if let Some(relayout) = old_delegate.relayout() {
2311                relayout.remove_listener(app, &self.relayout_listener());
2312            }
2313            if let Some(relayout) = new_delegate.relayout() {
2314                relayout.add_listener(app, self.relayout_listener());
2315            }
2316        }
2317    }
2318
2319    /// The `markNeedsLayout` tear-off, equal to itself across registrations.
2320    fn relayout_listener(self: RenderHandle<Self>) -> Listener {
2321        Listener::handle_method(self.handle(), mark_needs_layout_custom_single_child)
2322    }
2323
2324    /// Dart's `_getSize`.
2325    fn get_size(self: RenderHandle<Self>, app: &App, constraints: BoxConstraints) -> Size {
2326        constraints.constrain(self.get(app).delegate.get_size(constraints))
2327    }
2328}
2329
2330fn mark_needs_layout_custom_single_child(
2331    this: Handle<RenderCustomSingleChildLayoutBox>,
2332    app: &mut App,
2333) {
2334    RenderHandle::from_handle(this).mark_needs_layout(app);
2335}
2336
2337impl RenderObjectWithChildMixin for RenderCustomSingleChildLayoutBox {
2338    type ChildType = AnyRenderBox;
2339
2340    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2341        &self.get(app).child
2342    }
2343
2344    fn child_data_mut(
2345        self: RenderHandle<Self>,
2346        app: &mut App,
2347    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2348        &mut self.get_mut(app).child
2349    }
2350}
2351
2352impl RenderShiftedBox for RenderCustomSingleChildLayoutBox {}
2353
2354impl RenderObject for RenderCustomSingleChildLayoutBox {
2355    crate::render_object_accessors!();
2356
2357    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2358        let constraints = self.constraints(app);
2359        let size = self.get_size(app, constraints);
2360        self.set_size(app, size);
2361        if let Some(child) = self.child(app) {
2362            let child_constraints = self
2363                .get(app)
2364                .delegate
2365                .get_constraints_for_child(constraints);
2366            debug_assert!(child_constraints.debug_assert_is_valid(true));
2367            child.layout(app, child_constraints, !child_constraints.is_tight());
2368            let child_size = if child_constraints.is_tight() {
2369                child_constraints.smallest()
2370            } else {
2371                child.size(app)
2372            };
2373            child.parent_data_of_mut::<BoxParentData>(app).offset = self
2374                .get(app)
2375                .delegate
2376                .get_position_for_child(size, child_size);
2377        }
2378    }
2379
2380    fn paint(
2381        self: RenderHandle<Self>,
2382        app: &mut App,
2383        context: &mut PaintingContext,
2384        offset: Offset,
2385    ) {
2386        RenderShiftedBox::paint(self, app, context, offset);
2387    }
2388
2389    fn visit_children(
2390        self: RenderHandle<Self>,
2391        app: &App,
2392        visitor: &mut dyn FnMut(AnyRenderObject),
2393    ) {
2394        if let Some(child) = self.child(app) {
2395            visitor(child.as_object());
2396        }
2397    }
2398
2399    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
2400        if let Some(child) = self.child(app) {
2401            child.as_object().attach(app, owner);
2402        }
2403        if let Some(relayout) = self.delegate(app).relayout() {
2404            relayout.add_listener(app, self.relayout_listener());
2405        }
2406    }
2407
2408    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2409        if let Some(relayout) = self.delegate(app).relayout() {
2410            relayout.remove_listener(app, &self.relayout_listener());
2411        }
2412        if let Some(child) = self.child(app) {
2413            child.as_object().detach(app);
2414        }
2415    }
2416}
2417
2418impl RenderBox for RenderCustomSingleChildLayoutBox {
2419    crate::render_box_accessors!();
2420
2421    fn hit_test_children(
2422        self: RenderHandle<Self>,
2423        app: &mut App,
2424        result: &mut BoxHitTestResult<'_>,
2425        position: Offset,
2426    ) -> bool {
2427        RenderShiftedBox::hit_test_children(self, app, result, position)
2428    }
2429
2430    // TODO(ianh): It's a bit dubious to be using the getSize function from the delegate to
2431    // figure out the intrinsic dimensions. We really should either not support intrinsics,
2432    // or we should expose intrinsic delegate callbacks and throw if they're not implemented.
2433
2434    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2435        let width = self
2436            .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
2437            .width();
2438        if width.is_finite() { width } else { 0.0 }
2439    }
2440
2441    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2442        let width = self
2443            .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
2444            .width();
2445        if width.is_finite() { width } else { 0.0 }
2446    }
2447
2448    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2449        let height = self
2450            .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
2451            .height();
2452        if height.is_finite() { height } else { 0.0 }
2453    }
2454
2455    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2456        let height = self
2457            .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
2458            .height();
2459        if height.is_finite() { height } else { 0.0 }
2460    }
2461
2462    fn compute_dry_layout(
2463        self: RenderHandle<Self>,
2464        app: &mut App,
2465        constraints: BoxConstraints,
2466    ) -> Size {
2467        self.get_size(app, constraints)
2468    }
2469
2470    fn compute_dry_baseline(
2471        self: RenderHandle<Self>,
2472        app: &mut App,
2473        constraints: BoxConstraints,
2474        baseline: TextBaseline,
2475    ) -> Option<f64> {
2476        let child = self.child(app)?;
2477        let child_constraints = self
2478            .get(app)
2479            .delegate
2480            .get_constraints_for_child(constraints);
2481        let result = child.get_dry_baseline(app, child_constraints, baseline)?;
2482        let child_size = if child_constraints.is_tight() {
2483            child_constraints.smallest()
2484        } else {
2485            child.get_dry_layout(app, child_constraints)
2486        };
2487        Some(
2488            result
2489                + self
2490                    .get(app)
2491                    .delegate
2492                    .get_position_for_child(self.get_size(app, constraints), child_size)
2493                    .dy(),
2494        )
2495    }
2496}
2497
2498#[cfg(test)]
2499mod tests {
2500    use super::*;
2501    use waft_embedder::Size;
2502    use waft_foundation::AppCell;
2503
2504    use crate::box_::BoxConstraints;
2505    use crate::proxy_box::RenderConstrainedBox;
2506    use crate::testing::{EnginePhase, layout_with, painted_ops};
2507    use waft_embedder::valo::Op;
2508
2509    /// `padding_test.dart`: the padding is added to the child's intrinsics, and taken off the
2510    /// extent handed to the child.
2511    #[test]
2512    fn padding_intrinsics_add_the_insets() {
2513        let cell = AppCell::new();
2514        let mut app = cell.borrow_mut();
2515        let child =
2516            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(80.0, 40.0)), None);
2517        let padding = RenderPadding::new(
2518            &mut app,
2519            EdgeInsetsGeometry::all(8.0),
2520            None,
2521            Some(child.as_box()),
2522        );
2523        let padded = padding.as_box();
2524        assert_eq!(padded.get_min_intrinsic_width(&mut app, 100.0), 96.0);
2525        assert_eq!(padded.get_max_intrinsic_width(&mut app, 100.0), 96.0);
2526        assert_eq!(padded.get_min_intrinsic_height(&mut app, 100.0), 56.0);
2527        assert_eq!(padded.get_max_intrinsic_height(&mut app, 100.0), 56.0);
2528    }
2529
2530    /// Without a child, the padding is all there is.
2531    #[test]
2532    fn padding_intrinsics_without_a_child_are_the_insets() {
2533        let cell = AppCell::new();
2534        let mut app = cell.borrow_mut();
2535        let padding = RenderPadding::new(&mut app, EdgeInsetsGeometry::all(10.0), None, None);
2536        assert_eq!(
2537            padding.as_box().get_min_intrinsic_width(&mut app, 0.0),
2538            20.0
2539        );
2540        assert_eq!(
2541            padding.as_box().get_max_intrinsic_height(&mut app, 0.0),
2542            20.0
2543        );
2544    }
2545
2546    /// The dry layout of a padding is the size it lays out to.
2547    #[test]
2548    fn padding_dry_layout_matches_its_layout() {
2549        let cell = AppCell::new();
2550        let mut app = cell.borrow_mut();
2551        let child =
2552            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(80.0, 40.0)), None);
2553        let padding = RenderPadding::new(
2554            &mut app,
2555            EdgeInsetsGeometry::all(8.0),
2556            None,
2557            Some(child.as_box()),
2558        );
2559        let constraints = BoxConstraints::new().max_width(500.0).max_height(500.0);
2560        let dry = padding.as_box().get_dry_layout(&mut app, constraints);
2561        padding.layout(&mut app, constraints, false);
2562        assert_eq!(dry, padding.size(&app));
2563    }
2564
2565    /// `unconstrained_box_test.dart`: an `UnconstrainedBox` is a
2566    /// `RenderConstraintsTransformBox` whose transform drops every constraint, so the child takes
2567    /// its natural size and is aligned within what the parent allows.
2568    #[test]
2569    fn constraints_transform_box_leaves_the_child_unconstrained_and_aligns_it() {
2570        let cell = AppCell::new();
2571        let mut app = cell.borrow_mut();
2572        let child =
2573            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(50.0, 20.0)), None);
2574        let unconstrained = RenderConstraintsTransformBox::new(
2575            &mut app,
2576            AlignmentGeometry::CENTER,
2577            None,
2578            |_| BoxConstraints::new(),
2579            Some(child.as_box()),
2580        );
2581        unconstrained.layout(
2582            &mut app,
2583            BoxConstraints::tight(Size::new(100.0, 100.0)),
2584            false,
2585        );
2586        assert_eq!(child.size(&app), Size::new(50.0, 20.0));
2587        assert_eq!(unconstrained.size(&app), Size::new(100.0, 100.0));
2588        assert_eq!(
2589            child.as_box().box_parent_data(&app).offset,
2590            Offset::new(25.0, 40.0)
2591        );
2592    }
2593
2594    /// A child that does not fit is clipped when the clip behavior asks for it.
2595    #[test]
2596    fn constraints_transform_box_clips_an_overflowing_child() {
2597        let cell = AppCell::new();
2598        let mut app = cell.borrow_mut();
2599        let child = RenderConstrainedBox::new(
2600            &mut app,
2601            BoxConstraints::tight(Size::new(200.0, 200.0)),
2602            None,
2603        );
2604        let unconstrained = RenderConstraintsTransformBox::new(
2605            &mut app,
2606            AlignmentGeometry::CENTER,
2607            None,
2608            |_| BoxConstraints::new(),
2609            Some(child.as_box()),
2610        );
2611        unconstrained.set_clip_behavior(&mut app, Clip::HardEdge);
2612        layout_with(
2613            &mut app,
2614            unconstrained.as_box(),
2615            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
2616            AlignmentGeometry::CENTER,
2617            EnginePhase::Layout,
2618        );
2619
2620        assert_eq!(unconstrained.size(&app), Size::new(100.0, 100.0));
2621        let clipped = painted_ops(&mut app, unconstrained.as_object())
2622            .iter()
2623            .any(|op| matches!(op, Op::ClipPath { .. }));
2624        assert!(clipped, "the overflowing child is clipped");
2625    }
2626
2627    /// `RenderConstraintsTransformBox.describeApproximatePaintClip`: an overflowing child is
2628    /// clipped to the box's bounds, and only when the clip behavior asks for a clip.
2629    #[test]
2630    fn constraints_transform_box_describes_its_clip_only_when_overflowing() {
2631        for (clip_behavior, child_extent, expected) in [
2632            (Clip::None, 200.0, None),
2633            (
2634                Clip::HardEdge,
2635                200.0,
2636                Some(Rect::from_ltrb(0.0, 0.0, 100.0, 100.0)),
2637            ),
2638            (Clip::HardEdge, 50.0, None),
2639        ] {
2640            let cell = AppCell::new();
2641            let mut app = cell.borrow_mut();
2642            let child = RenderConstrainedBox::new(
2643                &mut app,
2644                BoxConstraints::tight(Size::new(child_extent, child_extent)),
2645                None,
2646            );
2647            let unconstrained = RenderConstraintsTransformBox::new(
2648                &mut app,
2649                AlignmentGeometry::CENTER,
2650                None,
2651                |_| BoxConstraints::new(),
2652                Some(child.as_box()),
2653            );
2654            unconstrained.set_clip_behavior(&mut app, clip_behavior);
2655            layout_with(
2656                &mut app,
2657                unconstrained.as_box(),
2658                Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
2659                AlignmentGeometry::CENTER,
2660                EnginePhase::Paint,
2661            );
2662
2663            assert_eq!(
2664                unconstrained
2665                    .as_object()
2666                    .describe_approximate_paint_clip(&app, child.as_object()),
2667                expected,
2668                "{clip_behavior:?}, child {child_extent}"
2669            );
2670        }
2671    }
2672
2673    /// A `RenderConstrainedOverflowBox` lets its child overflow and keeps the parent's size.
2674    #[test]
2675    fn constrained_overflow_box_sizes_itself_to_the_parent() {
2676        let cell = AppCell::new();
2677        let mut app = cell.borrow_mut();
2678        let child = RenderConstrainedBox::new(&mut app, BoxConstraints::new(), None);
2679        let overflow = RenderConstrainedOverflowBox::new(
2680            &mut app,
2681            Some(200.0),
2682            Some(200.0),
2683            None,
2684            None,
2685            OverflowBoxFit::Max,
2686            AlignmentGeometry::CENTER,
2687            None,
2688            Some(child.as_box()),
2689        );
2690        overflow.layout(
2691            &mut app,
2692            BoxConstraints::tight(Size::new(100.0, 100.0)),
2693            false,
2694        );
2695        assert_eq!(overflow.size(&app), Size::new(100.0, 100.0));
2696        assert_eq!(child.size(&app).width(), 200.0);
2697        assert_eq!(
2698            child.as_box().box_parent_data(&app).offset.dx(),
2699            -50.0,
2700            "the child is centered, so it overflows both sides"
2701        );
2702    }
2703
2704    /// A `RenderSizedOverflowBox` takes its requested size and passes the original constraints
2705    /// through, and reports the requested size as its intrinsics.
2706    #[test]
2707    fn sized_overflow_box_takes_its_requested_size() {
2708        let cell = AppCell::new();
2709        let mut app = cell.borrow_mut();
2710        let child =
2711            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 30.0)), None);
2712        let sized = RenderSizedOverflowBox::new(
2713            &mut app,
2714            Size::new(50.0, 50.0),
2715            AlignmentGeometry::CENTER,
2716            None,
2717            Some(child.as_box()),
2718        );
2719        sized.layout(&mut app, BoxConstraints::new().max_width(100.0), false);
2720        assert_eq!(sized.size(&app), Size::new(50.0, 50.0));
2721        assert_eq!(sized.as_box().get_min_intrinsic_width(&mut app, 0.0), 50.0);
2722        assert_eq!(sized.as_box().get_max_intrinsic_height(&mut app, 0.0), 50.0);
2723    }
2724
2725    /// A `RenderFractionallySizedOverflowBox` tightens the child to a fraction of the incoming
2726    /// maximum, and divides its intrinsics by the factor.
2727    #[test]
2728    fn fractionally_sized_box_tightens_the_child_to_a_fraction() {
2729        let cell = AppCell::new();
2730        let mut app = cell.borrow_mut();
2731        let child = RenderConstrainedBox::new(&mut app, BoxConstraints::new(), None);
2732        let fraction = RenderFractionallySizedOverflowBox::new(
2733            &mut app,
2734            AlignmentGeometry::CENTER,
2735            None,
2736            Some(child.as_box()),
2737        );
2738        fraction.set_width_factor(&mut app, Some(0.5));
2739        fraction.layout(
2740            &mut app,
2741            BoxConstraints::new().max_width(200.0).max_height(80.0),
2742            false,
2743        );
2744        assert_eq!(child.size(&app).width(), 100.0);
2745        assert_eq!(fraction.size(&app).width(), 100.0);
2746    }
2747
2748    /// `baseline_test.dart`: the child is shifted down so that its baseline sits at the given
2749    /// distance from the top.
2750    #[test]
2751    fn baseline_shifts_the_child_down_to_its_baseline() {
2752        let cell = AppCell::new();
2753        let mut app = cell.borrow_mut();
2754        let child =
2755            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(20.0, 20.0)), None);
2756        let baseline = RenderBaseline::new(
2757            &mut app,
2758            30.0,
2759            TextBaseline::Alphabetic,
2760            Some(child.as_box()),
2761        );
2762        baseline.layout(&mut app, BoxConstraints::new(), false);
2763        // The child has no baseline, so its bottom is used: the shift is 30 - 20.
2764        assert_eq!(
2765            child.as_box().box_parent_data(&app).offset,
2766            Offset::new(0.0, 10.0)
2767        );
2768        assert_eq!(baseline.size(&app), Size::new(20.0, 30.0));
2769    }
2770
2771    #[test]
2772    fn padding_around_tight_child() {
2773        let cell = AppCell::new();
2774        let mut app = cell.borrow_mut();
2775        let child =
2776            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(80.0, 40.0)), None);
2777        let padding = RenderPadding::new(
2778            &mut app,
2779            EdgeInsetsGeometry::all(8.0),
2780            None,
2781            Some(child.as_box()),
2782        );
2783        padding.layout(&mut app, BoxConstraints::new(), false);
2784        assert_eq!(child.size(&app), Size::new(80.0, 40.0));
2785        assert_eq!(padding.size(&app), Size::new(96.0, 56.0));
2786        assert_eq!(
2787            child.as_box().box_parent_data(&app).offset,
2788            Offset::new(8.0, 8.0)
2789        );
2790    }
2791
2792    #[test]
2793    fn positioned_box_centers_its_child() {
2794        let cell = AppCell::new();
2795        let mut app = cell.borrow_mut();
2796        let child =
2797            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(20.0, 20.0)), None);
2798        let positioned = RenderPositionedBox::new(
2799            &mut app,
2800            AlignmentGeometry::CENTER,
2801            None,
2802            None,
2803            None,
2804            Some(child.as_box()),
2805        );
2806        positioned.layout(
2807            &mut app,
2808            BoxConstraints::tight(Size::new(100.0, 100.0)),
2809            false,
2810        );
2811        assert_eq!(positioned.size(&app), Size::new(100.0, 100.0));
2812        assert_eq!(
2813            child.as_box().box_parent_data(&app).offset,
2814            Offset::new(40.0, 40.0)
2815        );
2816    }
2817
2818    #[test]
2819    fn positioned_box_shrink_wraps_with_a_factor() {
2820        let cell = AppCell::new();
2821        let mut app = cell.borrow_mut();
2822        let child =
2823            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(20.0, 20.0)), None);
2824        let positioned = RenderPositionedBox::new(
2825            &mut app,
2826            AlignmentGeometry::CENTER,
2827            None,
2828            Some(2.0),
2829            None,
2830            Some(child.as_box()),
2831        );
2832        positioned.layout(
2833            &mut app,
2834            BoxConstraints::new().max_width(100.0).max_height(100.0),
2835            false,
2836        );
2837        assert_eq!(positioned.size(&app), Size::new(40.0, 100.0));
2838        assert_eq!(
2839            child.as_box().box_parent_data(&app).offset,
2840            Offset::new(10.0, 40.0)
2841        );
2842    }
2843
2844    #[test]
2845    fn padding_without_child() {
2846        let cell = AppCell::new();
2847        let mut app = cell.borrow_mut();
2848        let padding = RenderPadding::new(&mut app, EdgeInsetsGeometry::all(10.0), None, None);
2849        padding.layout(
2850            &mut app,
2851            BoxConstraints::tight(Size::new(100.0, 100.0)),
2852            false,
2853        );
2854        assert_eq!(padding.size(&app), Size::new(100.0, 100.0));
2855    }
2856
2857    #[derive(Debug)]
2858    struct OffsetDelegate {
2859        offset: Offset,
2860    }
2861
2862    impl SingleChildLayoutDelegate for OffsetDelegate {
2863        fn get_size(&self, constraints: BoxConstraints) -> Size {
2864            constraints.biggest()
2865        }
2866
2867        fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
2868            constraints.loosen()
2869        }
2870
2871        fn get_position_for_child(&self, _size: Size, _child_size: Size) -> Offset {
2872            self.offset
2873        }
2874
2875        fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
2876            old_delegate
2877                .as_any()
2878                .downcast_ref::<OffsetDelegate>()
2879                .is_none_or(|old| old.offset != self.offset)
2880        }
2881
2882        fn as_any(&self) -> &dyn Any {
2883            self
2884        }
2885    }
2886
2887    #[test]
2888    fn custom_single_child_layout_positions_the_child() {
2889        let cell = AppCell::new();
2890        let mut app = cell.borrow_mut();
2891        let child =
2892            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(20.0, 10.0)), None);
2893        let parent = RenderCustomSingleChildLayoutBox::new(
2894            &mut app,
2895            Rc::new(OffsetDelegate {
2896                offset: Offset::new(8.0, 4.0),
2897            }),
2898            Some(child.as_box()),
2899        );
2900        parent.layout(
2901            &mut app,
2902            BoxConstraints::tight(Size::new(100.0, 50.0)),
2903            false,
2904        );
2905        assert_eq!(parent.size(&app), Size::new(100.0, 50.0));
2906        assert_eq!(
2907            child.as_box().box_parent_data(&app).offset,
2908            Offset::new(8.0, 4.0)
2909        );
2910    }
2911}