Skip to main content

waft_rendering/
box.rs

1//! Flutter counterpart: `rendering/box.dart` (`BoxConstraints`, `RenderBox`
2//! layout wrapper, intrinsics, dry layout and baselines), with the `BoxConstraints` subclass
3//! mechanism ([`AnyBoxConstraints`]) that a box's stored constraints travel in.
4//!
5//! `_DebugSize` and `debugAssertDoesMeetConstraints` wait.
6
7use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::fmt::{self, Debug, Display};
10use std::hash::{Hash, Hasher};
11
12use std::cell::Cell;
13use std::ops::{Add, Deref, DerefMut};
14use std::rc::Rc;
15
16use waft_embedder::{
17    Matrix4, Offset, Rect, Size, TextBaseline, ViewConstraints, clamp_double, lerp_double,
18};
19use waft_foundation::{App, Handle, HandleId, debug_format_double};
20use waft_gestures::{
21    HitTestEntry, HitTestResult, HitTestTarget, PointerEvent, remove_perspective_transform,
22};
23use waft_painting::EdgeInsetsGeometry;
24use waft_painting::transform_point;
25
26use crate::object::{
27    AnyRenderObject, Constraints, ContainerParentDataMixin, ContainerRenderObjectMixin, ParentData,
28    RenderHandle, RenderObject, RenderObjectVTable, create, debug_checking_intrinsics, resolve,
29};
30use crate::painting_context::PaintingContext;
31use crate::pipeline_owner::PipelineOwner;
32
33thread_local! {
34    static DEBUG_DOING_BASELINE: Cell<bool> = const { Cell::new(false) };
35}
36
37/// Immutable layout constraints for `RenderBox` layout.
38///
39/// A [`Size`] respects a [`BoxConstraints`] if, and only if, all of the following
40/// relations hold:
41///
42/// * [`min_width`](Self::min_width) <= [`Size::width`] <= [`max_width`](Self::max_width)
43/// * [`min_height`](Self::min_height) <= [`Size::height`] <= [`max_height`](Self::max_height)
44#[derive(Clone, Copy)]
45pub struct BoxConstraints {
46    /// The minimum width that satisfies the constraints.
47    pub min_width: f64,
48    /// The maximum width that satisfies the constraints.
49    ///
50    /// Might be [`f64::INFINITY`].
51    pub max_width: f64,
52    /// The minimum height that satisfies the constraints.
53    pub min_height: f64,
54    /// The maximum height that satisfies the constraints.
55    ///
56    /// Might be [`f64::INFINITY`].
57    pub max_height: f64,
58}
59
60impl BoxConstraints {
61    /// Creates box constraints with the given constraints.
62    pub const fn new() -> BoxConstraints {
63        BoxConstraints {
64            min_width: 0.0,
65            max_width: f64::INFINITY,
66            min_height: 0.0,
67            max_height: f64::INFINITY,
68        }
69    }
70
71    /// Sets [`min_width`](Self::min_width).
72    pub const fn min_width(mut self, value: f64) -> BoxConstraints {
73        self.min_width = value;
74        self
75    }
76
77    /// Sets [`max_width`](Self::max_width).
78    pub const fn max_width(mut self, value: f64) -> BoxConstraints {
79        self.max_width = value;
80        self
81    }
82
83    /// Sets [`min_height`](Self::min_height).
84    pub const fn min_height(mut self, value: f64) -> BoxConstraints {
85        self.min_height = value;
86        self
87    }
88
89    /// Sets [`max_height`](Self::max_height).
90    pub const fn max_height(mut self, value: f64) -> BoxConstraints {
91        self.max_height = value;
92        self
93    }
94
95    /// Creates box constraints that is respected only by the given size.
96    pub fn tight(size: Size) -> BoxConstraints {
97        BoxConstraints {
98            min_width: size.width(),
99            max_width: size.width(),
100            min_height: size.height(),
101            max_height: size.height(),
102        }
103    }
104
105    /// Creates box constraints that require the given width or height.
106    pub const fn tight_for(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
107        BoxConstraints {
108            min_width: match width {
109                Some(width) => width,
110                None => 0.0,
111            },
112            max_width: match width {
113                Some(width) => width,
114                None => f64::INFINITY,
115            },
116            min_height: match height {
117                Some(height) => height,
118                None => 0.0,
119            },
120            max_height: match height {
121                Some(height) => height,
122                None => f64::INFINITY,
123            },
124        }
125    }
126
127    /// Creates box constraints that require the given width or height, except if
128    /// they are infinite.
129    pub const fn tight_for_finite(width: f64, height: f64) -> BoxConstraints {
130        BoxConstraints {
131            min_width: if width != f64::INFINITY { width } else { 0.0 },
132            max_width: if width != f64::INFINITY {
133                width
134            } else {
135                f64::INFINITY
136            },
137            min_height: if height != f64::INFINITY { height } else { 0.0 },
138            max_height: if height != f64::INFINITY {
139                height
140            } else {
141                f64::INFINITY
142            },
143        }
144    }
145
146    /// Creates box constraints that forbid sizes larger than the given size.
147    pub fn loose(size: Size) -> BoxConstraints {
148        BoxConstraints {
149            min_width: 0.0,
150            max_width: size.width(),
151            min_height: 0.0,
152            max_height: size.height(),
153        }
154    }
155
156    /// Creates box constraints that expand to fill another box constraints.
157    pub const fn expand(width: Option<f64>, height: Option<f64>) -> BoxConstraints {
158        BoxConstraints {
159            min_width: match width {
160                Some(width) => width,
161                None => f64::INFINITY,
162            },
163            max_width: match width {
164                Some(width) => width,
165                None => f64::INFINITY,
166            },
167            min_height: match height {
168                Some(height) => height,
169                None => f64::INFINITY,
170            },
171            max_height: match height {
172                Some(height) => height,
173                None => f64::INFINITY,
174            },
175        }
176    }
177
178    /// Creates box constraints that match the given view constraints.
179    pub const fn from_view_constraints(constraints: ViewConstraints) -> BoxConstraints {
180        BoxConstraints {
181            min_width: constraints.min_width,
182            max_width: constraints.max_width,
183            min_height: constraints.min_height,
184            max_height: constraints.max_height,
185        }
186    }
187
188    /// Creates a copy of this box constraints. Chain field replacements.
189    pub const fn copy_with(self) -> BoxConstraints {
190        self
191    }
192
193    /// Returns new box constraints that are smaller by the given edge dimensions.
194    pub fn deflate(self, edges: EdgeInsetsGeometry) -> BoxConstraints {
195        debug_assert!(self.debug_assert_is_valid(false));
196        let horizontal = edges.horizontal();
197        let vertical = edges.vertical();
198        let deflated_min_width = (self.min_width - horizontal).max(0.0);
199        let deflated_min_height = (self.min_height - vertical).max(0.0);
200        BoxConstraints {
201            min_width: deflated_min_width,
202            max_width: (self.max_width - horizontal).max(deflated_min_width),
203            min_height: deflated_min_height,
204            max_height: (self.max_height - vertical).max(deflated_min_height),
205        }
206    }
207
208    /// Returns new box constraints that remove the minimum width and height requirements.
209    pub fn loosen(self) -> BoxConstraints {
210        debug_assert!(self.debug_assert_is_valid(false));
211        BoxConstraints {
212            min_width: 0.0,
213            max_width: self.max_width,
214            min_height: 0.0,
215            max_height: self.max_height,
216        }
217    }
218
219    /// Returns new box constraints that respect the given constraints while being
220    /// as close as possible to the original constraints.
221    pub fn enforce(self, constraints: BoxConstraints) -> BoxConstraints {
222        BoxConstraints {
223            min_width: clamp_double(self.min_width, constraints.min_width, constraints.max_width),
224            max_width: clamp_double(self.max_width, constraints.min_width, constraints.max_width),
225            min_height: clamp_double(
226                self.min_height,
227                constraints.min_height,
228                constraints.max_height,
229            ),
230            max_height: clamp_double(
231                self.max_height,
232                constraints.min_height,
233                constraints.max_height,
234            ),
235        }
236    }
237
238    /// Returns new box constraints with a tight width and/or height as close to
239    /// the given width and height as possible while still respecting the original
240    /// box constraints.
241    pub fn tighten(self, width: Option<f64>, height: Option<f64>) -> BoxConstraints {
242        BoxConstraints {
243            min_width: match width {
244                Some(width) => clamp_double(width, self.min_width, self.max_width),
245                None => self.min_width,
246            },
247            max_width: match width {
248                Some(width) => clamp_double(width, self.min_width, self.max_width),
249                None => self.max_width,
250            },
251            min_height: match height {
252                Some(height) => clamp_double(height, self.min_height, self.max_height),
253                None => self.min_height,
254            },
255            max_height: match height {
256                Some(height) => clamp_double(height, self.min_height, self.max_height),
257                None => self.max_height,
258            },
259        }
260    }
261
262    /// A box constraints with the width and height constraints flipped.
263    pub const fn flipped(self) -> BoxConstraints {
264        BoxConstraints {
265            min_width: self.min_height,
266            max_width: self.max_height,
267            min_height: self.min_width,
268            max_height: self.max_width,
269        }
270    }
271
272    /// Returns box constraints with the same width constraints but with
273    /// unconstrained height.
274    pub const fn width_constraints(self) -> BoxConstraints {
275        BoxConstraints {
276            min_width: self.min_width,
277            max_width: self.max_width,
278            min_height: 0.0,
279            max_height: f64::INFINITY,
280        }
281    }
282
283    /// Returns box constraints with the same height constraints but with
284    /// unconstrained width.
285    pub const fn height_constraints(self) -> BoxConstraints {
286        BoxConstraints {
287            min_width: 0.0,
288            max_width: f64::INFINITY,
289            min_height: self.min_height,
290            max_height: self.max_height,
291        }
292    }
293
294    /// Returns the width that both satisfies the constraints and is as close as
295    /// possible to the given width.
296    pub fn constrain_width(self, width: f64) -> f64 {
297        debug_assert!(self.debug_assert_is_valid(false));
298        clamp_double(width, self.min_width, self.max_width)
299    }
300
301    /// Returns the height that both satisfies the constraints and is as close as
302    /// possible to the given height.
303    pub fn constrain_height(self, height: f64) -> f64 {
304        debug_assert!(self.debug_assert_is_valid(false));
305        clamp_double(height, self.min_height, self.max_height)
306    }
307
308    /// Returns the size that both satisfies the constraints and is as close as
309    /// possible to the given size.
310    pub fn constrain(self, size: Size) -> Size {
311        Size::new(
312            self.constrain_width(size.width()),
313            self.constrain_height(size.height()),
314        )
315    }
316
317    /// Returns the size that both satisfies the constraints and is as close as
318    /// possible to the given width and height.
319    pub fn constrain_dimensions(self, width: f64, height: f64) -> Size {
320        Size::new(self.constrain_width(width), self.constrain_height(height))
321    }
322
323    /// Returns a size that attempts to meet the following conditions, in order:
324    ///
325    ///  * The size must satisfy these constraints.
326    ///  * The aspect ratio of the returned size matches the aspect ratio of the
327    ///    given size.
328    ///  * The returned size is as big as possible while still being equal to or
329    ///    smaller than the given size.
330    pub fn constrain_size_and_attempt_to_preserve_aspect_ratio(self, size: Size) -> Size {
331        if self.is_tight() {
332            return self.smallest();
333        }
334        if size.is_empty() {
335            return self.constrain(size);
336        }
337        let mut width = size.width();
338        let mut height = size.height();
339        let aspect_ratio = width / height;
340        if width > self.max_width {
341            width = self.max_width;
342            height = width / aspect_ratio;
343        }
344        if height > self.max_height {
345            height = self.max_height;
346            width = height * aspect_ratio;
347        }
348        if width < self.min_width {
349            width = self.min_width;
350            height = width / aspect_ratio;
351        }
352        if height < self.min_height {
353            height = self.min_height;
354            width = height * aspect_ratio;
355        }
356        Size::new(self.constrain_width(width), self.constrain_height(height))
357    }
358
359    /// The biggest size that satisfies the constraints.
360    pub fn biggest(self) -> Size {
361        Size::new(
362            self.constrain_width(f64::INFINITY),
363            self.constrain_height(f64::INFINITY),
364        )
365    }
366
367    /// The smallest size that satisfies the constraints.
368    pub fn smallest(self) -> Size {
369        Size::new(self.constrain_width(0.0), self.constrain_height(0.0))
370    }
371
372    /// Whether there is exactly one width value that satisfies the constraints.
373    pub fn has_tight_width(self) -> bool {
374        self.min_width >= self.max_width
375    }
376
377    /// Whether there is exactly one height value that satisfies the constraints.
378    pub fn has_tight_height(self) -> bool {
379        self.min_height >= self.max_height
380    }
381
382    /// Whether there is an upper bound on the maximum width.
383    pub fn has_bounded_width(self) -> bool {
384        self.max_width < f64::INFINITY
385    }
386
387    /// Whether there is an upper bound on the maximum height.
388    pub fn has_bounded_height(self) -> bool {
389        self.max_height < f64::INFINITY
390    }
391
392    /// Whether the width constraint is infinite.
393    pub fn has_infinite_width(self) -> bool {
394        self.min_width >= f64::INFINITY
395    }
396
397    /// Whether the height constraint is infinite.
398    pub fn has_infinite_height(self) -> bool {
399        self.min_height >= f64::INFINITY
400    }
401
402    /// Whether the given size satisfies the constraints.
403    pub fn is_satisfied_by(self, size: Size) -> bool {
404        debug_assert!(self.debug_assert_is_valid(false));
405        self.min_width <= size.width()
406            && size.width() <= self.max_width
407            && self.min_height <= size.height()
408            && size.height() <= self.max_height
409    }
410
411    /// Scales each constraint parameter by the inverse of the given factor,
412    /// rounded toward zero (Dart `~/`).
413    pub fn truncating_div(self, factor: f64) -> BoxConstraints {
414        BoxConstraints {
415            min_width: (self.min_width / factor).trunc(),
416            max_width: (self.max_width / factor).trunc(),
417            min_height: (self.min_height / factor).trunc(),
418            max_height: (self.max_height / factor).trunc(),
419        }
420    }
421
422    /// Linearly interpolate between two box constraints.
423    ///
424    /// If either is none, this function interpolates from a [`BoxConstraints`]
425    /// object whose fields are all set to 0.0.
426    pub fn lerp(
427        a: Option<BoxConstraints>,
428        b: Option<BoxConstraints>,
429        t: f64,
430    ) -> Option<BoxConstraints> {
431        if a == b {
432            return a;
433        }
434        let Some(a) = a else {
435            return Some((b.unwrap() * t).normalize());
436        };
437        let Some(b) = b else {
438            return Some((a * (1.0 - t)).normalize());
439        };
440        debug_assert!(a.debug_assert_is_valid(false));
441        debug_assert!(b.debug_assert_is_valid(false));
442        debug_assert!(
443            (a.min_width.is_finite() && b.min_width.is_finite())
444                || (a.min_width == f64::INFINITY && b.min_width == f64::INFINITY),
445            "Cannot interpolate between finite constraints and unbounded constraints."
446        );
447        debug_assert!(
448            (a.max_width.is_finite() && b.max_width.is_finite())
449                || (a.max_width == f64::INFINITY && b.max_width == f64::INFINITY),
450            "Cannot interpolate between finite constraints and unbounded constraints."
451        );
452        debug_assert!(
453            (a.min_height.is_finite() && b.min_height.is_finite())
454                || (a.min_height == f64::INFINITY && b.min_height == f64::INFINITY),
455            "Cannot interpolate between finite constraints and unbounded constraints."
456        );
457        debug_assert!(
458            (a.max_height.is_finite() && b.max_height.is_finite())
459                || (a.max_height == f64::INFINITY && b.max_height == f64::INFINITY),
460            "Cannot interpolate between finite constraints and unbounded constraints."
461        );
462        Some(
463            BoxConstraints {
464                min_width: if a.min_width.is_finite() {
465                    lerp_double(Some(a.min_width), Some(b.min_width), t).unwrap()
466                } else {
467                    f64::INFINITY
468                },
469                max_width: if a.max_width.is_finite() {
470                    lerp_double(Some(a.max_width), Some(b.max_width), t).unwrap()
471                } else {
472                    f64::INFINITY
473                },
474                min_height: if a.min_height.is_finite() {
475                    lerp_double(Some(a.min_height), Some(b.min_height), t).unwrap()
476                } else {
477                    f64::INFINITY
478                },
479                max_height: if a.max_height.is_finite() {
480                    lerp_double(Some(a.max_height), Some(b.max_height), t).unwrap()
481                } else {
482                    f64::INFINITY
483                },
484            }
485            .normalize(),
486        )
487    }
488
489    /// Returns a box constraints that [`is_normalized`](Self::is_normalized).
490    pub fn normalize(self) -> BoxConstraints {
491        if self.is_normalized() {
492            return self;
493        }
494        let min_width = if self.min_width >= 0.0 {
495            self.min_width
496        } else {
497            0.0
498        };
499        let min_height = if self.min_height >= 0.0 {
500            self.min_height
501        } else {
502            0.0
503        };
504        BoxConstraints {
505            min_width,
506            max_width: if min_width > self.max_width {
507                min_width
508            } else {
509                self.max_width
510            },
511            min_height,
512            max_height: if min_height > self.max_height {
513                min_height
514            } else {
515                self.max_height
516            },
517        }
518    }
519}
520
521impl Default for BoxConstraints {
522    fn default() -> BoxConstraints {
523        BoxConstraints::new()
524    }
525}
526
527impl Constraints for BoxConstraints {
528    fn is_tight(&self) -> bool {
529        self.has_tight_width() && self.has_tight_height()
530    }
531
532    fn is_normalized(&self) -> bool {
533        self.min_width >= 0.0
534            && self.min_width <= self.max_width
535            && self.min_height >= 0.0
536            && self.min_height <= self.max_height
537    }
538
539    fn debug_assert_is_valid(&self, is_applied_constraint: bool) -> bool {
540        if cfg!(debug_assertions) {
541            assert!(
542                !self.min_width.is_nan()
543                    && !self.max_width.is_nan()
544                    && !self.min_height.is_nan()
545                    && !self.max_height.is_nan(),
546                "BoxConstraints has a NaN value."
547            );
548            assert!(
549                self.min_width >= 0.0,
550                "BoxConstraints has a negative minimum width."
551            );
552            assert!(
553                self.min_height >= 0.0,
554                "BoxConstraints has a negative minimum height."
555            );
556            assert!(
557                self.max_width >= self.min_width,
558                "BoxConstraints has non-normalized width constraints."
559            );
560            assert!(
561                self.max_height >= self.min_height,
562                "BoxConstraints has non-normalized height constraints."
563            );
564            if is_applied_constraint {
565                assert!(
566                    self.min_width.is_finite(),
567                    "BoxConstraints forces an infinite width."
568                );
569                assert!(
570                    self.min_height.is_finite(),
571                    "BoxConstraints forces an infinite height."
572                );
573            }
574            debug_assert!(self.is_normalized());
575        }
576        self.is_normalized()
577    }
578}
579
580impl std::ops::Mul<f64> for BoxConstraints {
581    type Output = BoxConstraints;
582
583    fn mul(self, factor: f64) -> BoxConstraints {
584        BoxConstraints {
585            min_width: self.min_width * factor,
586            max_width: self.max_width * factor,
587            min_height: self.min_height * factor,
588            max_height: self.max_height * factor,
589        }
590    }
591}
592
593impl std::ops::Div<f64> for BoxConstraints {
594    type Output = BoxConstraints;
595
596    fn div(self, factor: f64) -> BoxConstraints {
597        BoxConstraints {
598            min_width: self.min_width / factor,
599            max_width: self.max_width / factor,
600            min_height: self.min_height / factor,
601            max_height: self.max_height / factor,
602        }
603    }
604}
605
606impl std::ops::Rem<f64> for BoxConstraints {
607    type Output = BoxConstraints;
608
609    fn rem(self, value: f64) -> BoxConstraints {
610        BoxConstraints {
611            min_width: self.min_width % value,
612            max_width: self.max_width % value,
613            min_height: self.min_height % value,
614            max_height: self.max_height % value,
615        }
616    }
617}
618
619impl PartialEq for BoxConstraints {
620    fn eq(&self, other: &BoxConstraints) -> bool {
621        debug_assert!(self.debug_assert_is_valid(false));
622        debug_assert!(other.debug_assert_is_valid(false));
623        self.min_width == other.min_width
624            && self.max_width == other.max_width
625            && self.min_height == other.min_height
626            && self.max_height == other.max_height
627    }
628}
629
630impl Eq for BoxConstraints {}
631
632impl Hash for BoxConstraints {
633    fn hash<H: Hasher>(&self, state: &mut H) {
634        debug_assert!(self.debug_assert_is_valid(false));
635        self.min_width.to_bits().hash(state);
636        self.max_width.to_bits().hash(state);
637        self.min_height.to_bits().hash(state);
638        self.max_height.to_bits().hash(state);
639    }
640}
641
642impl Display for BoxConstraints {
643    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644        let annotation = if self.is_normalized() {
645            ""
646        } else {
647            "; NOT NORMALIZED"
648        };
649        if self.min_width == f64::INFINITY && self.min_height == f64::INFINITY {
650            return write!(f, "BoxConstraints(biggest{annotation})");
651        }
652        if self.min_width == 0.0
653            && self.max_width == f64::INFINITY
654            && self.min_height == 0.0
655            && self.max_height == f64::INFINITY
656        {
657            return write!(f, "BoxConstraints(unconstrained{annotation})");
658        }
659        fn describe(min: f64, max: f64, dim: &str) -> String {
660            if min == max {
661                format!("{dim}={}", debug_format_double(Some(min)))
662            } else {
663                format!(
664                    "{}<={dim}<={}",
665                    debug_format_double(Some(min)),
666                    debug_format_double(Some(max))
667                )
668            }
669        }
670        write!(
671            f,
672            "BoxConstraints({}, {}{annotation})",
673            describe(self.min_width, self.max_width, "w"),
674            describe(self.min_height, self.max_height, "h")
675        )
676    }
677}
678
679impl Debug for BoxConstraints {
680    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681        Display::fmt(self, f)
682    }
683}
684
685/// What a subclass of `BoxConstraints` adds to its value.
686///
687/// Flutter's scaffold lays out its body and its bottom sheet with private subclasses
688/// (`_BodyBoxConstraints`, `_BottomSheetBoxConstraints`) that a `LayoutBuilder` below
689/// recognises with an `as` cast. Here [`BoxConstraints`] is a plain `Copy` value; a subclass
690/// is an extension that an [`AnyBoxConstraints`] carries beside the value the subclass
691/// constructor passed to `super`, as `AnyColor` carries a `Color` subclass.
692pub trait BoxConstraintsExtension: Any {
693    /// The extension as `Any`, for Dart's `is` checks ([`AnyBoxConstraints::extension`]).
694    fn as_any(&self) -> &dyn Any;
695
696    /// Dart's `==` override on the subclass, called once the values compared equal. `other`
697    /// is the same runtime type when it downcasts; any other type is unequal, as
698    /// `BoxConstraints.==`'s `runtimeType` check makes it.
699    fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool;
700}
701
702/// A `BoxConstraints` that may be an instance of a `BoxConstraints` subclass.
703///
704/// Rendering stores this where Flutter stores constraints that a later reader type-checks: a
705/// box's constraints from its last [`AnyRenderBox::layout`], read back with
706/// [`any_constraints`](AnyRenderBox::any_constraints), and what a `LayoutBuilder` hands its
707/// builder. The plain value is the one the subclass passed to `super`, reached by
708/// [`constraints`](Self::constraints) or by deref, so every `BoxConstraints` method is
709/// available and returns a plain [`BoxConstraints`], as an inherited method does in Dart. The
710/// subclass is recovered with [`extension`](Self::extension), Dart's `is` check.
711///
712/// Equality follows Dart's: two plain constraints compare by value, two extended ones by value
713/// and by the subclass's `==`, and a plain value never equals an extended one. So
714/// [`AnyRenderBox::layout`]'s early return lays out again when only the extension changed.
715///
716/// A box's [`constraints`](AnyRenderBox::constraints) is the plain value: a render object that
717/// hands its own constraints on to its child passes the value without the extension.
718#[derive(Clone)]
719pub struct AnyBoxConstraints {
720    constraints: BoxConstraints,
721    extension: Option<Rc<dyn BoxConstraintsExtension>>,
722}
723
724impl AnyBoxConstraints {
725    /// Plain constraints.
726    pub const fn new(constraints: BoxConstraints) -> AnyBoxConstraints {
727        AnyBoxConstraints {
728            constraints,
729            extension: None,
730        }
731    }
732
733    /// A subclass instance: `constraints` is what it passed to `super`.
734    pub fn with_shared(
735        constraints: BoxConstraints,
736        extension: Rc<dyn BoxConstraintsExtension>,
737    ) -> AnyBoxConstraints {
738        AnyBoxConstraints {
739            constraints,
740            extension: Some(extension),
741        }
742    }
743
744    /// The constraints as a layout reads them: the subclass's `super` value.
745    pub fn constraints(&self) -> BoxConstraints {
746        self.constraints
747    }
748
749    /// Dart's `constraints is T`: the subclass instance, if these constraints are one.
750    pub fn extension<T: BoxConstraintsExtension>(&self) -> Option<&T> {
751        self.extension
752            .as_ref()
753            .and_then(|extension| extension.as_any().downcast_ref::<T>())
754    }
755
756    /// Whether these constraints are a subclass instance.
757    pub fn has_extension(&self) -> bool {
758        self.extension.is_some()
759    }
760}
761
762impl Deref for AnyBoxConstraints {
763    type Target = BoxConstraints;
764
765    fn deref(&self) -> &BoxConstraints {
766        &self.constraints
767    }
768}
769
770impl From<BoxConstraints> for AnyBoxConstraints {
771    fn from(constraints: BoxConstraints) -> AnyBoxConstraints {
772        AnyBoxConstraints::new(constraints)
773    }
774}
775
776impl PartialEq for AnyBoxConstraints {
777    fn eq(&self, other: &AnyBoxConstraints) -> bool {
778        if self.constraints != other.constraints {
779            return false;
780        }
781        match (&self.extension, &other.extension) {
782            (None, None) => true,
783            (Some(mine), Some(theirs)) => mine.eq_extension(&**theirs),
784            _ => false,
785        }
786    }
787}
788
789impl PartialEq<BoxConstraints> for AnyBoxConstraints {
790    fn eq(&self, other: &BoxConstraints) -> bool {
791        self.extension.is_none() && self.constraints == *other
792    }
793}
794
795/// A subclass prints as its `BoxConstraints`: neither scaffold subclass overrides `toString`.
796impl Debug for AnyBoxConstraints {
797    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798        Debug::fmt(&self.constraints, f)
799    }
800}
801
802/// Method signature for hit testing a [`RenderBox`].
803///
804/// Used by [`BoxHitTestResult::add_with_paint_transform`] to hit test children of a
805/// [`RenderBox`].
806pub type BoxHitTest<'r> = dyn FnOnce(&mut BoxHitTestResult<'r>, Offset) -> bool;
807
808/// The result of performing a hit test on [`RenderBox`]es.
809///
810/// A view over a [`HitTestResult`]: Dart's `BoxHitTestResult.wrap`. Dart's bare
811/// `BoxHitTestResult()` constructor is `wrap` over a fresh `HitTestResult`.
812pub struct BoxHitTestResult<'a>(&'a mut HitTestResult);
813
814impl<'a> BoxHitTestResult<'a> {
815    /// Wraps `result` to create a [`BoxHitTestResult`] that shares its path.
816    pub fn wrap(result: &'a mut HitTestResult) -> BoxHitTestResult<'a> {
817        BoxHitTestResult(result)
818    }
819
820    /// Transforms `position` to the local coordinate system of a child for hit-testing the
821    /// child.
822    ///
823    /// The actual hit testing of the child needs to be implemented in the provided `hit_test`
824    /// callback, which is invoked with the transformed `position` as argument.
825    ///
826    /// The provided paint `transform` (which describes the transform from the child to the
827    /// parent in 3D) is processed by [`remove_perspective_transform`] to remove the
828    /// perspective component and inverted before it is used to transform `position` from the
829    /// coordinate system of the parent to the system of the child.
830    ///
831    /// If `transform` is `None` it will be treated as the identity transform and `position` is
832    /// provided to the `hit_test` callback as-is. If `transform` cannot be inverted, the
833    /// `hit_test` callback is not invoked and false is returned.
834    pub fn add_with_paint_transform(
835        &mut self,
836        transform: Option<Matrix4>,
837        position: Offset,
838        hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
839    ) -> bool {
840        let transform = match transform {
841            Some(transform) => match remove_perspective_transform(transform).invert() {
842                Some(inverted) => Some(inverted),
843                // Objects are not visible on screen and cannot be hit-tested.
844                None => return false,
845            },
846            None => None,
847        };
848        self.add_with_raw_transform(transform, position, hit_test)
849    }
850
851    /// Convenience method for hit testing children, that are translated by an [`Offset`].
852    ///
853    /// The actual hit testing of the child needs to be implemented in the provided `hit_test`
854    /// callback, which is invoked with the transformed `position` as argument.
855    pub fn add_with_paint_offset(
856        &mut self,
857        offset: Option<Offset>,
858        position: Offset,
859        hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
860    ) -> bool {
861        let transformed_position = match offset {
862            Some(offset) => position - offset,
863            None => position,
864        };
865        if let Some(offset) = offset {
866            self.0.push_offset(Offset::ZERO - offset);
867        }
868        let is_hit = hit_test(self, transformed_position);
869        if offset.is_some() {
870            self.0.pop_transform();
871        }
872        is_hit
873    }
874
875    /// Transforms `position` to the local coordinate system of a child for hit-testing the
876    /// child.
877    ///
878    /// Unlike [`add_with_paint_transform`](Self::add_with_paint_transform), the provided
879    /// `transform` is used as-is to transform `position`: it must describe the transform from
880    /// the parent to the child.
881    pub fn add_with_raw_transform(
882        &mut self,
883        transform: Option<Matrix4>,
884        position: Offset,
885        hit_test: impl FnOnce(&mut BoxHitTestResult<'_>, Offset) -> bool,
886    ) -> bool {
887        let transformed_position = match transform {
888            Some(transform) => transform_point(&transform, position),
889            None => position,
890        };
891        if let Some(transform) = transform {
892            self.0.push_transform(transform);
893        }
894        let is_hit = hit_test(self, transformed_position);
895        if transform.is_some() {
896            self.0.pop_transform();
897        }
898        is_hit
899    }
900
901    /// Pass-through method for adding a hit test while manually managing the position
902    /// transformation logic.
903    ///
904    /// Exactly one of `paint_offset`, `paint_transform`, or `raw_transform` must be given.
905    pub fn add_with_out_of_band_position(
906        &mut self,
907        paint_offset: Option<Offset>,
908        paint_transform: Option<Matrix4>,
909        raw_transform: Option<Matrix4>,
910        hit_test: impl FnOnce(&mut BoxHitTestResult<'_>) -> bool,
911    ) -> bool {
912        debug_assert_eq!(
913            [
914                paint_offset.is_some(),
915                paint_transform.is_some(),
916                raw_transform.is_some()
917            ]
918            .iter()
919            .filter(|given| **given)
920            .count(),
921            1,
922            "Exactly one transform or offset argument must be provided."
923        );
924        if let Some(paint_offset) = paint_offset {
925            self.0.push_offset(Offset::ZERO - paint_offset);
926        } else if let Some(raw_transform) = raw_transform {
927            self.0.push_transform(raw_transform);
928        } else {
929            let paint_transform = paint_transform
930                .expect("checked")
931                .invert()
932                .expect("paint_transform must be invertible.");
933            self.0.push_transform(paint_transform);
934        }
935        let is_hit = hit_test(self);
936        self.0.pop_transform();
937        is_hit
938    }
939}
940
941impl Deref for BoxHitTestResult<'_> {
942    type Target = HitTestResult;
943
944    fn deref(&self) -> &HitTestResult {
945        self.0
946    }
947}
948
949impl DerefMut for BoxHitTestResult<'_> {
950    fn deref_mut(&mut self) -> &mut HitTestResult {
951        self.0
952    }
953}
954
955/// A hit test entry used by [`RenderBox`].
956///
957/// Dart's `BoxHitTestEntry` subclasses `HitTestEntry`; here it is the entry's target, carrying
958/// the box and the position of the hit test in the local coordinates of the box. It becomes a
959/// [`HitTestEntry`] with [`From`].
960#[derive(Clone, Copy, Debug)]
961pub struct BoxHitTestEntry {
962    target: AnyRenderBox,
963    local_position: Offset,
964}
965
966impl BoxHitTestEntry {
967    /// Creates a box hit test entry.
968    pub fn new(target: AnyRenderBox, local_position: Offset) -> BoxHitTestEntry {
969        BoxHitTestEntry {
970            target,
971            local_position,
972        }
973    }
974
975    /// The [`RenderBox`] that was hit.
976    pub fn target(&self) -> AnyRenderBox {
977        self.target
978    }
979
980    /// The position of the hit test in the local coordinates of [`target`](Self::target).
981    pub fn local_position(&self) -> Offset {
982        self.local_position
983    }
984}
985
986impl HitTestTarget for BoxHitTestEntry {
987    fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
988        self.target.handle_event(app, event, self);
989    }
990
991    fn arena_id(&self) -> Option<HandleId> {
992        Some(self.target.id)
993    }
994}
995
996impl From<BoxHitTestEntry> for HitTestEntry {
997    fn from(entry: BoxHitTestEntry) -> HitTestEntry {
998        HitTestEntry::new(entry)
999    }
1000}
1001
1002/// Parent data used by [`RenderBox`] and its subclasses.
1003#[derive(Clone, Copy, Debug)]
1004pub struct BoxParentData {
1005    /// The offset at which to paint the child in the parent's coordinate system.
1006    pub offset: Offset,
1007}
1008
1009impl BoxParentData {
1010    /// Creates box parent data with a zero offset.
1011    pub const fn new() -> BoxParentData {
1012        BoxParentData {
1013            offset: Offset::ZERO,
1014        }
1015    }
1016}
1017
1018impl Default for BoxParentData {
1019    fn default() -> BoxParentData {
1020        BoxParentData::new()
1021    }
1022}
1023
1024impl ParentData for BoxParentData {
1025    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1026        (id == TypeId::of::<BoxParentData>()).then_some(self)
1027    }
1028
1029    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1030        (id == TypeId::of::<BoxParentData>()).then_some(self)
1031    }
1032}
1033
1034impl fmt::Display for BoxParentData {
1035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036        write!(f, "offset={}", self.offset)
1037    }
1038}
1039
1040/// Parent data for a [`RenderBox`] subclass that uses [`ContainerRenderObjectMixin`].
1041///
1042/// Flutter's `ContainerBoxParentData`: a convenience class that mixes
1043/// [`ContainerParentDataMixin`] into a [`BoxParentData`]. Here it is the pair of accessors a
1044/// container's parent data provides, one for each half.
1045pub trait ContainerBoxParentData: ContainerParentDataMixin<ChildType = AnyRenderBox> {
1046    /// Mixin field access: the [`BoxParentData`] half.
1047    ///
1048    /// [`ParentData::provide`](crate::ParentData::provide) must answer [`BoxParentData`] with
1049    /// the same value, or the box protocol cannot position this child.
1050    fn box_parent_data(&self) -> &BoxParentData;
1051
1052    /// See [`box_parent_data`](Self::box_parent_data).
1053    fn box_parent_data_mut(&mut self) -> &mut BoxParentData;
1054
1055    /// The offset at which to paint the child in the parent's coordinate system.
1056    fn offset(&self) -> Offset {
1057        self.box_parent_data().offset
1058    }
1059
1060    /// Sets [`offset`](Self::offset).
1061    fn set_offset(&mut self, value: Offset) {
1062        self.box_parent_data_mut().offset = value;
1063    }
1064}
1065
1066/// A wrapper that represents the baseline location of a [`RenderBox`].
1067#[derive(Clone, Copy, PartialEq, Debug)]
1068pub struct BaselineOffset(pub Option<f64>);
1069
1070impl BaselineOffset {
1071    /// A value that indicates that the associated [`RenderBox`] does not have any baselines.
1072    ///
1073    /// [`BaselineOffset::NO_BASELINE`] is an identity element in most binary operations
1074    /// involving two [`BaselineOffset`]s (such as [`min_of`](Self::min_of)), for render objects
1075    /// with no baselines typically do not contribute to the baseline offset of their parents.
1076    pub const NO_BASELINE: BaselineOffset = BaselineOffset(None);
1077
1078    /// The distance from the top of the box, or `None` for no baseline.
1079    pub fn offset(self) -> Option<f64> {
1080        self.0
1081    }
1082
1083    /// Compares this [`BaselineOffset`] and `other`, and returns whichever is closer to the
1084    /// origin.
1085    ///
1086    /// When both `self` and `other` are [`NO_BASELINE`](Self::NO_BASELINE), this method returns
1087    /// [`NO_BASELINE`](Self::NO_BASELINE). When one of them is
1088    /// [`NO_BASELINE`](Self::NO_BASELINE), this method returns the other operand.
1089    pub fn min_of(self, other: BaselineOffset) -> BaselineOffset {
1090        match (self.0, other.0) {
1091            (Some(lhs), Some(rhs)) => {
1092                if lhs >= rhs {
1093                    other
1094                } else {
1095                    self
1096                }
1097            }
1098            (Some(_), None) => self,
1099            (None, _) => other,
1100        }
1101    }
1102}
1103
1104impl Add<f64> for BaselineOffset {
1105    type Output = BaselineOffset;
1106
1107    /// Returns a new baseline location that is `offset` pixels further away from the origin than
1108    /// `self`, or unchanged if `self` is [`NO_BASELINE`](Self::NO_BASELINE).
1109    fn add(self, offset: f64) -> BaselineOffset {
1110        BaselineOffset(self.0.map(|value| value + offset))
1111    }
1112}
1113
1114/// Why a box cannot compute a dry layout, for
1115/// [`RenderBox::debug_cannot_compute_dry_layout`].
1116///
1117/// Flutter's `debugCannotComputeDryLayout` takes a `reason` or an `error`, exactly one of them.
1118#[derive(Clone, Copy, Debug)]
1119pub enum DryLayoutFailure<'a> {
1120    /// The box does not implement dry layout; the panic names the box and adds this reason.
1121    Reason(&'a str),
1122
1123    /// The box cannot lay out with the given constraints; the panic is this error.
1124    Error(&'a str),
1125}
1126
1127/// Intrinsic dimension calculation that computes the intrinsic width given the max height, or
1128/// the intrinsic height given the max width.
1129#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1130enum IntrinsicDimension {
1131    MinWidth,
1132    MaxWidth,
1133    MinHeight,
1134    MaxHeight,
1135}
1136
1137/// An `f64` used as a map key, as Dart uses a `double`.
1138#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1139struct DoubleKey(u64);
1140
1141impl DoubleKey {
1142    fn new(value: f64) -> DoubleKey {
1143        DoubleKey(value.to_bits())
1144    }
1145}
1146
1147/// Flutter's `_LayoutCacheStorage`: what one [`RenderBox`] has memoized.
1148///
1149/// The layout cache storage is typically cleared in
1150/// [`RenderBox::mark_needs_layout`], but is usually kept across
1151/// [`AnyRenderBox::layout`] calls because the incoming [`BoxConstraints`] is always an input of
1152/// every layout computation.
1153#[derive(Default)]
1154struct LayoutCacheStorage {
1155    cached_intrinsic_dimensions: HashMap<(IntrinsicDimension, DoubleKey), f64>,
1156    cached_dry_layout_sizes: HashMap<BoxConstraints, Size>,
1157    cached_alphabetic_baseline: HashMap<BoxConstraints, BaselineOffset>,
1158    cached_ideo_baseline: HashMap<BoxConstraints, BaselineOffset>,
1159}
1160
1161impl LayoutCacheStorage {
1162    /// Empties the storage, and returns whether it had anything cached.
1163    fn clear(&mut self) -> bool {
1164        let has_cache = !self.cached_dry_layout_sizes.is_empty()
1165            || !self.cached_intrinsic_dimensions.is_empty()
1166            || !self.cached_alphabetic_baseline.is_empty()
1167            || !self.cached_ideo_baseline.is_empty();
1168        if has_cache {
1169            self.cached_dry_layout_sizes.clear();
1170            self.cached_intrinsic_dimensions.clear();
1171            self.cached_alphabetic_baseline.clear();
1172            self.cached_ideo_baseline.clear();
1173        }
1174        has_cache
1175    }
1176
1177    fn baselines(
1178        &mut self,
1179        baseline: TextBaseline,
1180    ) -> &mut HashMap<BoxConstraints, BaselineOffset> {
1181        match baseline {
1182            TextBaseline::Alphabetic => &mut self.cached_alphabetic_baseline,
1183            TextBaseline::Ideographic => &mut self.cached_ideo_baseline,
1184        }
1185    }
1186}
1187
1188/// Flutter's `RenderBox` fields.
1189pub struct RenderBoxData {
1190    pub(crate) size: Option<Size>,
1191    pub(crate) constraints: Option<AnyBoxConstraints>,
1192    layout_cache: LayoutCacheStorage,
1193    debug_computing_this_dry_layout: bool,
1194    debug_computing_this_dry_baseline: bool,
1195}
1196
1197impl RenderBoxData {
1198    /// Unlaid-out box state.
1199    pub fn new() -> RenderBoxData {
1200        RenderBoxData {
1201            size: None,
1202            constraints: None,
1203            layout_cache: LayoutCacheStorage::default(),
1204            debug_computing_this_dry_layout: false,
1205            debug_computing_this_dry_baseline: false,
1206        }
1207    }
1208
1209    /// The constraints most recently supplied by the parent, or `None` before layout: Dart's
1210    /// `super.constraints` for a leaf that overrides [`RenderBox::constraints`].
1211    pub fn constraints(&self) -> Option<BoxConstraints> {
1212        self.constraints
1213            .as_ref()
1214            .map(AnyBoxConstraints::constraints)
1215    }
1216}
1217
1218impl Default for RenderBoxData {
1219    fn default() -> RenderBoxData {
1220        RenderBoxData::new()
1221    }
1222}
1223
1224/// Implements [`RenderBox`] field accessors for a `render_box` field.
1225#[macro_export]
1226macro_rules! render_box_accessors {
1227    () => {
1228        fn render_box_data(
1229            self: $crate::RenderHandle<Self>,
1230            app: &::waft_foundation::App,
1231        ) -> &$crate::RenderBoxData {
1232            &self.get(app).render_box
1233        }
1234        fn render_box_data_mut(
1235            self: $crate::RenderHandle<Self>,
1236            app: &mut ::waft_foundation::App,
1237        ) -> &mut $crate::RenderBoxData {
1238            &mut self.get_mut(app).render_box
1239        }
1240    };
1241}
1242
1243/// Dart's `child.parentData! as BoxParentData`.
1244///
1245/// # Panics
1246///
1247/// If the child has no parent data, or its parent data is not a box's.
1248fn box_parent_data_of(app: &App, child: AnyRenderObject) -> &BoxParentData {
1249    child
1250        .parent_data(app)
1251        .and_then(|parent_data| parent_data.part::<BoxParentData>())
1252        .expect("parent data is not a BoxParentData")
1253}
1254
1255/// A mixin that provides useful default behaviors for boxes with children managed by the
1256/// [`ContainerRenderObjectMixin`] mixin.
1257///
1258/// By convention, this trait doesn't override any members of the supertrait. Instead, it
1259/// provides helpful functions that render objects can call as appropriate.
1260///
1261/// Flutter's `RenderBoxContainerDefaultsMixin`.
1262pub trait RenderBoxContainerDefaultsMixin:
1263    ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType: ContainerBoxParentData>
1264    + RenderBox
1265{
1266    /// Returns the baseline of the first child with a baseline.
1267    ///
1268    /// Useful when the children are displayed vertically in the same order they appear in the
1269    /// child list.
1270    fn default_compute_distance_to_first_actual_baseline(
1271        self: RenderHandle<Self>,
1272        app: &mut App,
1273        baseline: TextBaseline,
1274    ) -> Option<f64> {
1275        debug_assert!(!self.as_object().debug_needs_layout(app));
1276        let mut child = self.first_child(app);
1277        while let Some(current) = child {
1278            let child_parent_data = current
1279                .as_object()
1280                .parent_data_of::<Self::ParentDataType>(app);
1281            let (offset, next_sibling) =
1282                (child_parent_data.offset(), child_parent_data.next_sibling());
1283            if let Some(result) = current.get_distance_to_actual_baseline(app, baseline) {
1284                return Some(result + offset.dy());
1285            }
1286            child = next_sibling;
1287        }
1288        None
1289    }
1290
1291    /// Returns the minimum baseline value among every child.
1292    ///
1293    /// Useful when the vertical position of the children isn't determined by the order in the
1294    /// child list.
1295    fn default_compute_distance_to_highest_actual_baseline(
1296        self: RenderHandle<Self>,
1297        app: &mut App,
1298        baseline: TextBaseline,
1299    ) -> Option<f64> {
1300        debug_assert!(!self.as_object().debug_needs_layout(app));
1301        let mut min_baseline = BaselineOffset::NO_BASELINE;
1302        let mut child = self.first_child(app);
1303        while let Some(current) = child {
1304            let child_parent_data = current
1305                .as_object()
1306                .parent_data_of::<Self::ParentDataType>(app);
1307            let (offset, next_sibling) =
1308                (child_parent_data.offset(), child_parent_data.next_sibling());
1309            let candidate = BaselineOffset(current.get_distance_to_actual_baseline(app, baseline))
1310                + offset.dy();
1311            min_baseline = min_baseline.min_of(candidate);
1312            child = next_sibling;
1313        }
1314        min_baseline.offset()
1315    }
1316
1317    /// Performs a hit test on each child by walking the child list backwards.
1318    ///
1319    /// Stops walking once after the first child reports that it contains the given point.
1320    /// Returns whether any children contain the given point.
1321    ///
1322    /// See also:
1323    ///
1324    ///  * [`default_paint`](Self::default_paint), which paints the children appropriate for
1325    ///    this hit-testing strategy.
1326    fn default_hit_test_children(
1327        self: RenderHandle<Self>,
1328        app: &mut App,
1329        result: &mut BoxHitTestResult<'_>,
1330        position: Offset,
1331    ) -> bool {
1332        let mut child = self.last_child(app);
1333        while let Some(current) = child {
1334            // The x, y parameters have the top left of the node's box as the origin.
1335            let child_parent_data = current
1336                .as_object()
1337                .parent_data_of::<Self::ParentDataType>(app);
1338            let (offset, previous_sibling) = (
1339                child_parent_data.offset(),
1340                child_parent_data.previous_sibling(),
1341            );
1342            let is_hit =
1343                result.add_with_paint_offset(Some(offset), position, |result, transformed| {
1344                    debug_assert_eq!(transformed, position - offset);
1345                    current.hit_test(app, result, transformed)
1346                });
1347            if is_hit {
1348                return true;
1349            }
1350            child = previous_sibling;
1351        }
1352        false
1353    }
1354
1355    /// Paints each child by walking the child list forwards.
1356    ///
1357    /// See also:
1358    ///
1359    ///  * [`default_hit_test_children`](Self::default_hit_test_children), which implements
1360    ///    hit-testing of the children in a manner appropriate for this painting strategy.
1361    fn default_paint(
1362        self: RenderHandle<Self>,
1363        app: &mut App,
1364        context: &mut PaintingContext,
1365        offset: Offset,
1366    ) {
1367        let mut child = self.first_child(app);
1368        while let Some(current) = child {
1369            let child_parent_data = current
1370                .as_object()
1371                .parent_data_of::<Self::ParentDataType>(app);
1372            let (child_offset, next_sibling) =
1373                (child_parent_data.offset(), child_parent_data.next_sibling());
1374            context.paint_child(app, current.as_object(), child_offset + offset);
1375            child = next_sibling;
1376        }
1377    }
1378}
1379
1380/// A render object in a 2D Cartesian coordinate system.
1381///
1382/// Flutter's counterpart is `RenderBox`. [`RenderObject::perform_layout`] is the leaf override;
1383/// [`AnyRenderBox::layout`] is the framework wrapper. `RenderObject`'s tree operations are
1384/// provided here and forward to [`as_object`](Self::as_object).
1385pub trait RenderBox: RenderObject {
1386    /// Mixin field access.
1387    fn render_box_data(self: RenderHandle<Self>, app: &App) -> &RenderBoxData;
1388
1389    /// See [`render_box_data`](Self::render_box_data).
1390    fn render_box_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderBoxData;
1391
1392    /// The box constraints most recently supplied by the parent.
1393    ///
1394    /// # Panics
1395    ///
1396    /// If layout has not yet happened.
1397    fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
1398        self.render_box_data(app)
1399            .constraints
1400            .as_ref()
1401            .map(AnyBoxConstraints::constraints)
1402            .unwrap_or_else(|| {
1403                panic!("A RenderObject does not have any constraints before it has been laid out.")
1404            })
1405    }
1406
1407    /// The box constraints most recently supplied by the parent, with the `BoxConstraints`
1408    /// subclass they may be an instance of: Dart's `constraints` getter, for a reader that
1409    /// type-checks it.
1410    ///
1411    /// # Panics
1412    ///
1413    /// If layout has not yet happened.
1414    fn any_constraints(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
1415        self.render_box_data(app)
1416            .constraints
1417            .clone()
1418            .unwrap_or_else(|| {
1419                panic!("A RenderObject does not have any constraints before it has been laid out.")
1420            })
1421    }
1422
1423    /// Installs [`BoxParentData`] unless the child already has it.
1424    ///
1425    /// The box default for [`RenderObject::setup_parent_data`]; override it here.
1426    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1427        if !child.parent_data_is::<BoxParentData>(app) {
1428            child.set_parent_data(app, BoxParentData::new());
1429        }
1430    }
1431
1432    /// See [`AnyRenderBox::get_min_intrinsic_width`].
1433    fn get_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1434        self.as_box().get_min_intrinsic_width(app, height)
1435    }
1436
1437    /// Computes the value returned by [`get_min_intrinsic_width`](Self::get_min_intrinsic_width).
1438    /// Do not call this function directly, instead, call
1439    /// [`get_min_intrinsic_width`](Self::get_min_intrinsic_width).
1440    ///
1441    /// Override in subclasses that implement [`RenderObject::perform_layout`]. This method
1442    /// should return the minimum width that this box could be without failing to correctly
1443    /// paint its contents within itself, without clipping.
1444    ///
1445    /// If the layout algorithm is independent of the context (e.g. it always tries to be a
1446    /// particular size), or if the layout algorithm is width-in-height-out, or if the layout
1447    /// algorithm uses both the incoming width and height constraints (e.g. it always sizes
1448    /// itself to [`BoxConstraints::biggest`]), then the `height` argument should be ignored.
1449    ///
1450    /// If the layout algorithm is strictly height-in-width-out, or is height-in-width-out when
1451    /// the width is unconstrained, then the height argument is the height to use.
1452    ///
1453    /// The `height` argument will never be negative. It may be infinite.
1454    ///
1455    /// If this algorithm depends on the intrinsic dimensions of a child, the intrinsic
1456    /// dimensions of that child should be obtained using the functions whose names start with
1457    /// `get_`, not `compute_`.
1458    ///
1459    /// This function should never return a negative or infinite value.
1460    ///
1461    /// # When the intrinsic dimensions cannot be known
1462    ///
1463    /// There are cases where render objects do not have an efficient way to compute their
1464    /// intrinsic dimensions. For example, it may be prohibitively expensive to reify and
1465    /// measure every child of a lazy viewport, or the dimensions may be computed by a callback
1466    /// about which the render object cannot reason.
1467    ///
1468    /// In such cases the intrinsic functions should panic when
1469    /// [`debug_checking_intrinsics`](crate::debug_checking_intrinsics) is false and debug
1470    /// assertions are enabled, and return 0.0 otherwise. See
1471    /// [`RenderViewportBase::debug_throw_if_not_checking_intrinsics`](crate::RenderViewportBase::debug_throw_if_not_checking_intrinsics).
1472    ///
1473    /// # Aspect-ratio-driven boxes
1474    ///
1475    /// Some boxes always return a fixed size based on the constraints. For these boxes, the
1476    /// intrinsic functions should return the appropriate size when the incoming `height` or
1477    /// `width` argument is finite, treating that as a tight constraint in the respective
1478    /// direction and treating the other direction's constraints as unbounded. When the incoming
1479    /// argument is not finite, then they should return the actual intrinsic dimensions based on
1480    /// the contents, as any other box would.
1481    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1482        let _ = (self, app, height);
1483        0.0
1484    }
1485
1486    /// See [`AnyRenderBox::get_max_intrinsic_width`].
1487    fn get_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1488        self.as_box().get_max_intrinsic_width(app, height)
1489    }
1490
1491    /// Computes the value returned by [`get_max_intrinsic_width`](Self::get_max_intrinsic_width).
1492    /// Do not call this function directly, instead, call
1493    /// [`get_max_intrinsic_width`](Self::get_max_intrinsic_width).
1494    ///
1495    /// Override in subclasses that implement [`RenderObject::perform_layout`]. This should
1496    /// return the smallest width beyond which increasing the width never decreases the preferred
1497    /// height. The preferred height is the value that would be returned by
1498    /// [`compute_min_intrinsic_height`](Self::compute_min_intrinsic_height) for that width.
1499    ///
1500    /// If the layout algorithm is strictly height-in-width-out, or is height-in-width-out when
1501    /// the width is unconstrained, then this should return the same value as
1502    /// [`compute_min_intrinsic_width`](Self::compute_min_intrinsic_width) for the same height.
1503    ///
1504    /// Otherwise, the height argument should be ignored, and the returned value should be equal
1505    /// to or bigger than the value returned by
1506    /// [`compute_min_intrinsic_width`](Self::compute_min_intrinsic_width).
1507    ///
1508    /// The value returned by this method might not match the size that the object would actually
1509    /// take. For example, a box that always exactly sizes itself using
1510    /// [`BoxConstraints::biggest`] might well size itself bigger than its max intrinsic size.
1511    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1512        let _ = (self, app, height);
1513        0.0
1514    }
1515
1516    /// See [`AnyRenderBox::get_min_intrinsic_height`].
1517    fn get_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1518        self.as_box().get_min_intrinsic_height(app, width)
1519    }
1520
1521    /// Computes the value returned by
1522    /// [`get_min_intrinsic_height`](Self::get_min_intrinsic_height). Do not call this function
1523    /// directly, instead, call [`get_min_intrinsic_height`](Self::get_min_intrinsic_height).
1524    ///
1525    /// Override in subclasses that implement [`RenderObject::perform_layout`]. Should return the
1526    /// minimum height that this box could be without failing to correctly paint its contents
1527    /// within itself, without clipping.
1528    ///
1529    /// If the layout algorithm is independent of the context, or if the layout algorithm is
1530    /// height-in-width-out, or if the layout algorithm uses both the incoming height and width
1531    /// constraints, then the `width` argument should be ignored.
1532    ///
1533    /// If the layout algorithm is strictly width-in-height-out, or is width-in-height-out when
1534    /// the height is unconstrained, then the width argument is the width to use.
1535    ///
1536    /// The `width` argument will never be negative. It may be infinite.
1537    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1538        let _ = (self, app, width);
1539        0.0
1540    }
1541
1542    /// See [`AnyRenderBox::get_max_intrinsic_height`].
1543    fn get_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1544        self.as_box().get_max_intrinsic_height(app, width)
1545    }
1546
1547    /// Computes the value returned by
1548    /// [`get_max_intrinsic_height`](Self::get_max_intrinsic_height). Do not call this function
1549    /// directly, instead, call [`get_max_intrinsic_height`](Self::get_max_intrinsic_height).
1550    ///
1551    /// Override in subclasses that implement [`RenderObject::perform_layout`]. Should return the
1552    /// smallest height beyond which increasing the height never decreases the preferred width.
1553    /// The preferred width is the value that would be returned by
1554    /// [`compute_min_intrinsic_width`](Self::compute_min_intrinsic_width) for that height.
1555    ///
1556    /// If the layout algorithm is strictly width-in-height-out, or is width-in-height-out when
1557    /// the height is unconstrained, then this should return the same value as
1558    /// [`compute_min_intrinsic_height`](Self::compute_min_intrinsic_height) for the same width.
1559    ///
1560    /// Otherwise, the width argument should be ignored, and the returned value should be equal
1561    /// to or bigger than the value returned by
1562    /// [`compute_min_intrinsic_height`](Self::compute_min_intrinsic_height).
1563    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1564        let _ = (self, app, width);
1565        0.0
1566    }
1567
1568    /// See [`AnyRenderBox::get_dry_layout`].
1569    fn get_dry_layout(
1570        self: RenderHandle<Self>,
1571        app: &mut App,
1572        constraints: BoxConstraints,
1573    ) -> Size {
1574        self.as_box().get_dry_layout(app, constraints)
1575    }
1576
1577    /// Computes the value returned by [`get_dry_layout`](Self::get_dry_layout). Do not call this
1578    /// function directly, instead, call [`get_dry_layout`](Self::get_dry_layout).
1579    ///
1580    /// Override in subclasses that implement [`RenderObject::perform_layout`] or
1581    /// [`perform_resize`](Self::perform_resize), or when setting
1582    /// [`RenderObject::sized_by_parent`] to true without overriding
1583    /// [`perform_resize`](Self::perform_resize). This method should return the [`Size`] that
1584    /// this box would like to be given the provided [`BoxConstraints`].
1585    ///
1586    /// The size returned by this method must match the [`size`](Self::size) that the box will
1587    /// compute for itself in [`RenderObject::perform_layout`] (or
1588    /// [`perform_resize`](Self::perform_resize), if
1589    /// [`RenderObject::sized_by_parent`] is true).
1590    ///
1591    /// If this algorithm depends on the size of a child, the size of that child should be
1592    /// obtained using its [`get_dry_layout`](Self::get_dry_layout) method.
1593    ///
1594    /// # When the size cannot be known
1595    ///
1596    /// There are cases where render objects do not have an efficient way to compute their size.
1597    /// For example, the size may be computed by a callback about which the render object cannot
1598    /// reason. In such cases, the function should call
1599    /// [`debug_cannot_compute_dry_layout`](Self::debug_cannot_compute_dry_layout) and return
1600    /// [`Size::ZERO`].
1601    fn compute_dry_layout(
1602        self: RenderHandle<Self>,
1603        app: &mut App,
1604        constraints: BoxConstraints,
1605    ) -> Size {
1606        let _ = (app, constraints);
1607        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1608            "It does not implement RenderBox::compute_dry_layout.",
1609        ));
1610        Size::ZERO
1611    }
1612
1613    /// See [`AnyRenderBox::get_dry_baseline`].
1614    fn get_dry_baseline(
1615        self: RenderHandle<Self>,
1616        app: &mut App,
1617        constraints: BoxConstraints,
1618        baseline: TextBaseline,
1619    ) -> Option<f64> {
1620        self.as_box().get_dry_baseline(app, constraints, baseline)
1621    }
1622
1623    /// Computes the value returned by [`get_dry_baseline`](Self::get_dry_baseline).
1624    ///
1625    /// This method is for overriding only and shouldn't be called directly. To get this box's
1626    /// speculative baseline location for the given `constraints`, call
1627    /// [`get_dry_baseline`](Self::get_dry_baseline) instead.
1628    ///
1629    /// The "dry" in the method name means the implementation must not produce observable side
1630    /// effects when called. For example, it must not change the [`size`](Self::size) of the box,
1631    /// or its children's paint offsets. Moreover, accessing the current layout of this box or a
1632    /// child box usually indicates a bug in the implementation, as the current layout is
1633    /// typically calculated using a set of [`BoxConstraints`] that's different from the
1634    /// `constraints` given as the first parameter. To get the size of this box or a child box in
1635    /// this method's implementation, use [`get_dry_layout`](Self::get_dry_layout) instead.
1636    ///
1637    /// The implementation must return a value that represents the distance from the top of the
1638    /// box to the first baseline of the box's contents, for the given `constraints`, or `None`
1639    /// if the box has no baselines. It's the same exact value
1640    /// [`compute_distance_to_actual_baseline`](Self::compute_distance_to_actual_baseline) would
1641    /// return, when this box was laid out at `constraints` in the same exact state.
1642    ///
1643    /// Not all boxes support dry baseline computation. In such cases the box must call
1644    /// [`debug_cannot_compute_dry_layout`](Self::debug_cannot_compute_dry_layout) and return a
1645    /// dummy baseline offset value (such as `None`).
1646    fn compute_dry_baseline(
1647        self: RenderHandle<Self>,
1648        app: &mut App,
1649        constraints: BoxConstraints,
1650        baseline: TextBaseline,
1651    ) -> Option<f64> {
1652        let _ = (app, constraints, baseline);
1653        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1654            "It does not implement RenderBox::compute_dry_baseline.",
1655        ));
1656        None
1657    }
1658
1659    /// Called from [`compute_dry_layout`](Self::compute_dry_layout) or
1660    /// [`compute_dry_baseline`](Self::compute_dry_baseline) if this box does not support
1661    /// calculating a dry layout.
1662    ///
1663    /// When debug assertions are enabled and
1664    /// [`debug_checking_intrinsics`](crate::debug_checking_intrinsics) is not true, this method
1665    /// panics with the given [`DryLayoutFailure`].
1666    fn debug_cannot_compute_dry_layout(self: RenderHandle<Self>, failure: DryLayoutFailure<'_>) {
1667        let _ = self;
1668        if !cfg!(debug_assertions) || debug_checking_intrinsics() {
1669            return;
1670        }
1671        match failure {
1672            DryLayoutFailure::Reason(reason) => panic!(
1673                "The {} class does not support dry layout. {reason}",
1674                std::any::type_name::<Self>()
1675            ),
1676            DryLayoutFailure::Error(error) => panic!("{error}"),
1677        }
1678    }
1679
1680    /// See [`AnyRenderBox::get_distance_to_baseline`].
1681    fn get_distance_to_baseline(
1682        self: RenderHandle<Self>,
1683        app: &mut App,
1684        baseline: TextBaseline,
1685        only_real: bool,
1686    ) -> Option<f64> {
1687        self.as_box()
1688            .get_distance_to_baseline(app, baseline, only_real)
1689    }
1690
1691    /// See [`AnyRenderBox::get_distance_to_actual_baseline`].
1692    fn get_distance_to_actual_baseline(
1693        self: RenderHandle<Self>,
1694        app: &mut App,
1695        baseline: TextBaseline,
1696    ) -> Option<f64> {
1697        self.as_box().get_distance_to_actual_baseline(app, baseline)
1698    }
1699
1700    /// Returns the distance from the y-coordinate of the position of the box to the y-coordinate
1701    /// of the first given baseline in the box's contents, if any, or `None` otherwise.
1702    ///
1703    /// Do not call this function directly. If you need to know the baseline of a child from an
1704    /// invocation of [`RenderObject::perform_layout`] or [`RenderObject::paint`], call
1705    /// [`get_distance_to_baseline`](Self::get_distance_to_baseline).
1706    ///
1707    /// Subclasses should override this method to supply the distances to their baselines. When
1708    /// implementing this method, there are generally three strategies:
1709    ///
1710    ///  * For classes that use the [`ContainerRenderObjectMixin`] child model, consider
1711    ///    implementing [`RenderBoxContainerDefaultsMixin`] and using
1712    ///    [`RenderBoxContainerDefaultsMixin::default_compute_distance_to_first_actual_baseline`].
1713    ///
1714    ///  * For classes that define a particular baseline themselves, return that value directly.
1715    ///
1716    ///  * For classes that have a child to which they wish to defer the computation, call
1717    ///    [`get_distance_to_actual_baseline`](Self::get_distance_to_actual_baseline) on the
1718    ///    child.
1719    fn compute_distance_to_actual_baseline(
1720        self: RenderHandle<Self>,
1721        app: &mut App,
1722        baseline: TextBaseline,
1723    ) -> Option<f64> {
1724        let _ = (self, app, baseline);
1725        debug_assert!(
1726            DEBUG_DOING_BASELINE.get(),
1727            "Please see the documentation for compute_distance_to_actual_baseline for the \
1728             required calling conventions of this method."
1729        );
1730        None
1731    }
1732
1733    /// Mark this render object's layout information as dirty.
1734    ///
1735    /// Flutter's `RenderBox.markNeedsLayout`: it also clears the intrinsics, dry layout and
1736    /// baseline caches, and defers to the parent when they held anything. An override calls
1737    /// [`RenderBoxBase::mark_needs_layout`] where Dart writes `super.markNeedsLayout()`.
1738    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1739        RenderBoxBase::mark_needs_layout(self, app);
1740    }
1741
1742    /// Updates the box's size using only the constraints.
1743    ///
1744    /// By default this method sets [`size`](Self::size) to the result of
1745    /// [`compute_dry_layout`](Self::compute_dry_layout) called with the current
1746    /// [`constraints`](Self::constraints). Instead of overriding this method, consider
1747    /// overriding [`compute_dry_layout`](Self::compute_dry_layout).
1748    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1749        RenderBoxBase::perform_resize(self, app);
1750    }
1751
1752    /// The size of this box.
1753    fn size(self: RenderHandle<Self>, app: &App) -> Size {
1754        self.as_box().size(app)
1755    }
1756
1757    /// Multiply the transform from the parent's coordinate system to this box's coordinate
1758    /// system into the given transform.
1759    ///
1760    /// This function is used to convert coordinate systems between boxes. Subclasses that
1761    /// apply transforms during painting should override this function to factor those
1762    /// transforms into the calculation.
1763    ///
1764    /// The [`RenderBox`] implementation takes care of adjusting the matrix for the position
1765    /// of the given child as determined during layout and stored on the child's parent data.
1766    fn apply_paint_transform(
1767        self: RenderHandle<Self>,
1768        app: &App,
1769        child: AnyRenderObject,
1770        transform: &mut Matrix4,
1771    ) {
1772        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
1773        // Dart asserts the child's parent data is a `BoxParentData` with a message naming
1774        // this type; `box_parent_data` panics the same way.
1775        let offset = box_parent_data_of(app, child).offset;
1776        crate::object::translate(transform, offset.dx(), offset.dy());
1777    }
1778
1779    /// An estimate of the bounds within which this render object will paint: the box's own size.
1780    fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
1781        Offset::ZERO & self.size(app)
1782    }
1783
1784    /// Whether this render object has undergone layout and has a [`size`](Self::size).
1785    fn has_size(self: RenderHandle<Self>, app: &App) -> bool {
1786        self.render_box_data(app).size.is_some()
1787    }
1788
1789    /// Override this method to handle pointer events that hit this render object.
1790    ///
1791    /// For [`RenderBox`] objects, the `entry` argument is a [`BoxHitTestEntry`]. From this
1792    /// object you can determine the position of the hit test in the local coordinates of the
1793    /// render object (via `entry.local_position()`).
1794    fn handle_event(
1795        self: RenderHandle<Self>,
1796        app: &mut App,
1797        event: &PointerEvent,
1798        entry: &BoxHitTestEntry,
1799    ) {
1800        let _ = (self, app, event, entry);
1801    }
1802
1803    /// Determines the set of render objects located at the given position.
1804    ///
1805    /// Returns true, and adds any render objects that contain the point to the given hit test
1806    /// result, if this render object or one of its descendants absorbs the hit (preventing
1807    /// objects below this one from being hit). Returns false if the hit can continue to other
1808    /// objects below this one.
1809    ///
1810    /// The caller is responsible for transforming `position` from global coordinates to its
1811    /// location relative to the origin of this [`RenderBox`]. This [`RenderBox`] is responsible
1812    /// for checking whether the given position is within its bounds.
1813    ///
1814    /// # Panics
1815    ///
1816    /// In debug builds, if this box has not been laid out.
1817    fn hit_test(
1818        self: RenderHandle<Self>,
1819        app: &mut App,
1820        result: &mut BoxHitTestResult<'_>,
1821        position: Offset,
1822    ) -> bool {
1823        RenderBoxBase::hit_test(self, app, result, position)
1824    }
1825
1826    /// Override this method if this render object can be hit even if its children were not hit.
1827    ///
1828    /// Returns true if the specified `position` should be considered a hit on this render
1829    /// object.
1830    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1831        let _ = self;
1832        false
1833    }
1834
1835    /// Override this method to check whether any children are located at the given position.
1836    ///
1837    /// Subclasses should return true if at least one child reported a hit at the specified
1838    /// position.
1839    fn hit_test_children(
1840        self: RenderHandle<Self>,
1841        app: &mut App,
1842        result: &mut BoxHitTestResult<'_>,
1843        position: Offset,
1844    ) -> bool {
1845        let _ = (self, app, result, position);
1846        false
1847    }
1848
1849    /// Sets the size of this box. Call from [`RenderObject::perform_layout`] or
1850    /// [`RenderObject::perform_resize`].
1851    fn set_size(self: RenderHandle<Self>, app: &mut App, size: Size) {
1852        self.as_box().set_size(app, size)
1853    }
1854
1855    /// See [`AnyRenderBox::layout`].
1856    fn layout(
1857        self: RenderHandle<Self>,
1858        app: &mut App,
1859        constraints: impl Into<AnyBoxConstraints>,
1860        parent_uses_size: bool,
1861    ) {
1862        self.as_box().layout(app, constraints, parent_uses_size)
1863    }
1864
1865    /// The type-erased `RenderBox` handle. Free: the vtable is a `const`, and the id is copied.
1866    fn as_box(self: RenderHandle<Self>) -> AnyRenderBox {
1867        AnyRenderBox {
1868            id: self.id(),
1869            vtable: const { &RenderBoxVTable::of::<Self>() },
1870        }
1871    }
1872
1873    /// The type-erased `RenderObject` handle, through [`as_box`](Self::as_box).
1874    fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
1875        self.as_box().as_object()
1876    }
1877
1878    /// See [`AnyRenderObject::adopt_child`].
1879    fn adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1880        self.as_object().adopt_child(app, child)
1881    }
1882
1883    /// See [`AnyRenderObject::drop_child`].
1884    fn drop_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1885        self.as_object().drop_child(app, child)
1886    }
1887
1888    /// See [`AnyRenderObject::mark_needs_paint`].
1889    fn mark_needs_paint(self: RenderHandle<Self>, app: &mut App) {
1890        self.as_object().mark_needs_paint(app)
1891    }
1892
1893    /// See [`AnyRenderObject::mark_needs_composited_layer_update`].
1894    fn mark_needs_composited_layer_update(self: RenderHandle<Self>, app: &mut App) {
1895        self.as_object().mark_needs_composited_layer_update(app)
1896    }
1897
1898    /// See [`AnyRenderObject::mark_needs_compositing_bits_update`].
1899    fn mark_needs_compositing_bits_update(self: RenderHandle<Self>, app: &mut App) {
1900        self.as_object().mark_needs_compositing_bits_update(app)
1901    }
1902
1903    /// See [`AnyRenderObject::schedule_initial_layout`].
1904    fn schedule_initial_layout(self: RenderHandle<Self>, app: &mut App) {
1905        self.as_object().schedule_initial_layout(app)
1906    }
1907
1908    /// See [`AnyRenderObject::parent`].
1909    fn parent(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderObject> {
1910        self.as_object().parent(app)
1911    }
1912
1913    /// See [`AnyRenderObject::owner`].
1914    fn owner(self: RenderHandle<Self>, app: &App) -> Option<Handle<PipelineOwner>> {
1915        self.as_object().owner(app)
1916    }
1917
1918    /// See [`AnyRenderObject::attached`].
1919    fn attached(self: RenderHandle<Self>, app: &App) -> bool {
1920        self.as_object().attached(app)
1921    }
1922
1923    /// See [`AnyRenderObject::debug_needs_layout`].
1924    fn debug_needs_layout(self: RenderHandle<Self>, app: &App) -> bool {
1925        self.as_object().debug_needs_layout(app)
1926    }
1927}
1928
1929/// Flutter's `RenderBox` bodies that an override calls through `super`.
1930///
1931/// A trait default cannot call `super`, and a leaf's [`RenderBox::hit_test`] shadows the default
1932/// it would call; this sibling trait, blanket-implemented for every box, carries that body (the
1933/// shape `ElementBase` has for `Element`). A leaf in any crate calls it at Dart's `super` call:
1934/// `RenderBoxBase::hit_test(self, app, result, position)`.
1935pub trait RenderBoxBase: RenderBox {
1936    /// Flutter's `RenderBox.markNeedsLayout`.
1937    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1938        // If the cache was not empty, then this box's layout is used by the parent's layout
1939        // algorithm (it's possible that the parent only used the intrinsics for paint, but
1940        // there's no good way to detect that so we conservatively assume it's a layout
1941        // dependency).
1942        //
1943        // A render object's perform_layout implementation may depend on the baseline location or
1944        // the intrinsic dimensions of a descendant, even when there are relayout boundaries
1945        // between them.
1946        //
1947        // Some calculations may fail (dry baseline, for example). The layout dependency is still
1948        // established, but only from the box that failed to compute the dry baseline to the
1949        // ancestor that queried the dry baseline.
1950        if self.render_box_data_mut(app).layout_cache.clear() && self.parent(app).is_some() {
1951            self.as_object().mark_parent_needs_layout(app);
1952            return;
1953        }
1954        crate::object::RenderObjectBase::mark_needs_layout(self, app);
1955    }
1956
1957    /// Flutter's `RenderBox.performResize`.
1958    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
1959        // Default behavior for subclasses that have sized_by_parent = true.
1960        let constraints = RenderBox::constraints(self, app);
1961        let size = RenderBox::compute_dry_layout(self, app, constraints);
1962        debug_assert!(size.width().is_finite() && size.height().is_finite());
1963        self.set_size(app, size);
1964    }
1965
1966    /// Flutter's `RenderBox.hitTest`.
1967    fn hit_test(
1968        self: RenderHandle<Self>,
1969        app: &mut App,
1970        result: &mut BoxHitTestResult<'_>,
1971        position: Offset,
1972    ) -> bool {
1973        debug_assert!(
1974            self.has_size(app),
1975            "Cannot hit test a render box that has never been laid out: {self:?}"
1976        );
1977        if self.size(app).contains(position)
1978            && (RenderBox::hit_test_children(self, app, result, position)
1979                || RenderBox::hit_test_self(self, app, position))
1980        {
1981            result.add(BoxHitTestEntry::new(self.as_box(), position).into());
1982            return true;
1983        }
1984        false
1985    }
1986}
1987
1988impl<T: RenderBox> RenderBoxBase for T {}
1989
1990/// The vtable of an [`AnyRenderBox`]: the object vtable plus the box accessors.
1991pub(crate) struct RenderBoxVTable {
1992    pub object: RenderObjectVTable,
1993    pub box_data: fn(&App, HandleId) -> &RenderBoxData,
1994    pub box_data_mut: fn(&mut App, HandleId) -> &mut RenderBoxData,
1995    pub hit_test: fn(&mut App, HandleId, &mut BoxHitTestResult<'_>, Offset) -> bool,
1996    pub handle_event: fn(&mut App, HandleId, &PointerEvent, &BoxHitTestEntry),
1997    pub compute_min_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1998    pub compute_max_intrinsic_width: fn(&mut App, HandleId, f64) -> f64,
1999    pub compute_min_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
2000    pub compute_max_intrinsic_height: fn(&mut App, HandleId, f64) -> f64,
2001    pub compute_dry_layout: fn(&mut App, HandleId, BoxConstraints) -> Size,
2002    pub compute_dry_baseline: fn(&mut App, HandleId, BoxConstraints, TextBaseline) -> Option<f64>,
2003    pub compute_distance_to_actual_baseline: fn(&mut App, HandleId, TextBaseline) -> Option<f64>,
2004}
2005
2006impl RenderBoxVTable {
2007    const fn of<T: RenderBox>() -> RenderBoxVTable {
2008        RenderBoxVTable {
2009            object: RenderObjectVTable::of::<T>(
2010                |app, id, child| <T as RenderBox>::setup_parent_data(resolve(id), app, child),
2011                |app, id| T::paint_bounds(resolve(id), app),
2012                |app, id, child, transform| {
2013                    <T as RenderBox>::apply_paint_transform(resolve(id), app, child, transform)
2014                },
2015                |app, id| <T as RenderBox>::perform_resize(resolve(id), app),
2016                |app, id| <T as RenderBox>::mark_needs_layout(resolve(id), app),
2017                Some(|| const { &RenderBoxVTable::of::<T>() }),
2018                None,
2019            ),
2020            box_data: |app, id| T::render_box_data(resolve(id), app),
2021            box_data_mut: |app, id| T::render_box_data_mut(resolve(id), app),
2022            hit_test: |app, id, result, position| T::hit_test(resolve(id), app, result, position),
2023            handle_event: |app, id, event, entry| T::handle_event(resolve(id), app, event, entry),
2024            compute_min_intrinsic_width: |app, id, height| {
2025                T::compute_min_intrinsic_width(resolve(id), app, height)
2026            },
2027            compute_max_intrinsic_width: |app, id, height| {
2028                T::compute_max_intrinsic_width(resolve(id), app, height)
2029            },
2030            compute_min_intrinsic_height: |app, id, width| {
2031                T::compute_min_intrinsic_height(resolve(id), app, width)
2032            },
2033            compute_max_intrinsic_height: |app, id, width| {
2034                T::compute_max_intrinsic_height(resolve(id), app, width)
2035            },
2036            compute_dry_layout: |app, id, constraints| {
2037                T::compute_dry_layout(resolve(id), app, constraints)
2038            },
2039            compute_dry_baseline: |app, id, constraints, baseline| {
2040                T::compute_dry_baseline(resolve(id), app, constraints, baseline)
2041            },
2042            compute_distance_to_actual_baseline: |app, id, baseline| {
2043                T::compute_distance_to_actual_baseline(resolve(id), app, baseline)
2044            },
2045        }
2046    }
2047}
2048
2049impl<T: RenderBox> RenderHandle<T> {
2050    /// Creates a box-protocol render object in `app`.
2051    pub fn new_box(app: &mut App, object: T) -> RenderHandle<T> {
2052        let this = create(app, object);
2053        let data = this.render_object_data_mut(app);
2054        data.object_vtable = Some(&const { RenderBoxVTable::of::<T>() }.object);
2055        // Flutter's `RenderObject()` constructor:
2056        // `_needsCompositing = isRepaintBoundary || alwaysNeedsCompositing` and
2057        // `_wasRepaintBoundary = isRepaintBoundary`.
2058        let is_repaint_boundary = this.is_repaint_boundary(app);
2059        let always_needs_compositing = this.always_needs_compositing(app);
2060        let data = this.render_object_data_mut(app);
2061        data.was_repaint_boundary = is_repaint_boundary;
2062        data.needs_compositing = is_repaint_boundary || always_needs_compositing;
2063        this
2064    }
2065}
2066
2067/// Flutter's `RenderBox._debugSetDoingBaseline(true)` and the `finally` that clears it.
2068struct DebugDoingBaseline;
2069
2070impl DebugDoingBaseline {
2071    fn enter() -> DebugDoingBaseline {
2072        DEBUG_DOING_BASELINE.set(cfg!(debug_assertions));
2073        DebugDoingBaseline
2074    }
2075}
2076
2077impl Drop for DebugDoingBaseline {
2078    fn drop(&mut self) {
2079        DEBUG_DOING_BASELINE.set(false);
2080    }
2081}
2082
2083/// Flutter's `RenderBox._computeIntrinsics` preamble: whether the result may be memoized.
2084fn should_cache_intrinsics(this: AnyRenderBox, app: &App) -> bool {
2085    // perform_resize should not depend on anything except the incoming constraints.
2086    debug_assert!(debug_checking_intrinsics() || !this.as_object().debug_doing_this_resize(app));
2087    // We don't want the debug-mode intrinsic tests to affect who gets marked dirty, etc.
2088    !cfg!(debug_assertions) || !debug_checking_intrinsics()
2089}
2090
2091/// Flutter's `_IntrinsicDimension.memoize`.
2092fn memoize_intrinsic(
2093    this: AnyRenderBox,
2094    app: &mut App,
2095    dimension: IntrinsicDimension,
2096    input: f64,
2097    computer: fn(&mut App, HandleId, f64) -> f64,
2098) -> f64 {
2099    if !should_cache_intrinsics(this, app) {
2100        return computer(app, this.id, input);
2101    }
2102    let key = (dimension, DoubleKey::new(input));
2103    if let Some(cached) = this.layout_cache(app).cached_intrinsic_dimensions.get(&key) {
2104        return *cached;
2105    }
2106    let result = computer(app, this.id, input);
2107    this.layout_cache_mut(app)
2108        .cached_intrinsic_dimensions
2109        .insert(key, result);
2110    result
2111}
2112
2113/// Flutter's `_Baseline.memoize`.
2114fn memoize_baseline(
2115    this: AnyRenderBox,
2116    app: &mut App,
2117    constraints: BoxConstraints,
2118    baseline: TextBaseline,
2119    computer: impl FnOnce(AnyRenderBox, &mut App) -> BaselineOffset,
2120) -> BaselineOffset {
2121    if !should_cache_intrinsics(this, app) {
2122        return computer(this, app);
2123    }
2124    if let Some(cached) = this
2125        .layout_cache_mut(app)
2126        .baselines(baseline)
2127        .get(&constraints)
2128    {
2129        return *cached;
2130    }
2131    let result = computer(this, app);
2132    this.layout_cache_mut(app)
2133        .baselines(baseline)
2134        .insert(constraints, result);
2135    result
2136}
2137
2138/// Erased `RenderBox`.
2139#[derive(Clone, Copy)]
2140pub struct AnyRenderBox {
2141    id: HandleId,
2142    vtable: &'static RenderBoxVTable,
2143}
2144
2145impl PartialEq for AnyRenderBox {
2146    fn eq(&self, other: &AnyRenderBox) -> bool {
2147        self.id == other.id
2148    }
2149}
2150
2151impl Eq for AnyRenderBox {}
2152
2153impl std::hash::Hash for AnyRenderBox {
2154    fn hash<H: Hasher>(&self, state: &mut H) {
2155        self.id.hash(state);
2156    }
2157}
2158
2159impl Debug for AnyRenderBox {
2160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2161        write!(f, "AnyRenderBox({:?})", self.id)
2162    }
2163}
2164
2165impl AnyRenderBox {
2166    pub(crate) fn from_vtable(id: HandleId, vtable: &'static RenderBoxVTable) -> AnyRenderBox {
2167        AnyRenderBox { id, vtable }
2168    }
2169
2170    /// The `RenderObject` view of this box. Free: points into the nested table.
2171    /// Whether this render object has undergone layout and has a size.
2172    pub fn has_size(self, app: &App) -> bool {
2173        self.box_data(app).size.is_some()
2174    }
2175
2176    pub fn as_object(self) -> AnyRenderObject {
2177        AnyRenderObject::from_vtable(self.id, &self.vtable.object)
2178    }
2179
2180    /// See [`RenderBox::hit_test`].
2181    pub fn hit_test(
2182        self,
2183        app: &mut App,
2184        result: &mut BoxHitTestResult<'_>,
2185        position: Offset,
2186    ) -> bool {
2187        (self.vtable.hit_test)(app, self.id, result, position)
2188    }
2189
2190    /// See [`RenderBox::handle_event`].
2191    pub fn handle_event(self, app: &mut App, event: &PointerEvent, entry: &BoxHitTestEntry) {
2192        (self.vtable.handle_event)(app, self.id, event, entry)
2193    }
2194
2195    pub(crate) fn box_data(self, app: &App) -> &RenderBoxData {
2196        (self.vtable.box_data)(app, self.id)
2197    }
2198
2199    fn box_data_mut(self, app: &mut App) -> &mut RenderBoxData {
2200        (self.vtable.box_data_mut)(app, self.id)
2201    }
2202
2203    /// Compute the layout for this box.
2204    ///
2205    /// A `BoxConstraints` subclass instance ([`AnyBoxConstraints`]) is stored as it is given,
2206    /// and its `==` decides the early return: constraints equal in value but not in extension
2207    /// lay the box out again.
2208    pub fn layout(
2209        self,
2210        app: &mut App,
2211        constraints: impl Into<AnyBoxConstraints>,
2212        parent_uses_size: bool,
2213    ) {
2214        let constraints: AnyBoxConstraints = constraints.into();
2215        debug_assert!(
2216            !app.is_disposed(self.id),
2217            "layout on a disposed render object"
2218        );
2219        debug_assert!(constraints.debug_assert_is_valid(true));
2220        let same = self.box_data(app).constraints.as_ref() == Some(&constraints);
2221        let tight = constraints.is_tight();
2222        self.as_object()
2223            .run_layout(app, parent_uses_size, tight, same, |app| {
2224                self.box_data_mut(app).constraints = Some(constraints)
2225            });
2226    }
2227
2228    /// The size of this box.
2229    ///
2230    /// # Panics
2231    ///
2232    /// If this box has not been laid out.
2233    pub fn size(self, app: &App) -> Size {
2234        self.box_data(app)
2235            .size
2236            .unwrap_or_else(|| panic!("RenderBox was not laid out: {self:?}"))
2237    }
2238
2239    /// Sets the size of this box.
2240    pub fn set_size(self, app: &mut App, size: Size) {
2241        self.box_data_mut(app).size = Some(size);
2242    }
2243
2244    /// The box constraints most recently supplied by the parent.
2245    ///
2246    /// # Panics
2247    ///
2248    /// If layout has not yet happened.
2249    pub fn constraints(self, app: &App) -> BoxConstraints {
2250        self.box_data(app)
2251            .constraints
2252            .as_ref()
2253            .map(AnyBoxConstraints::constraints)
2254            .unwrap_or_else(|| {
2255                panic!("A RenderObject does not have any constraints before it has been laid out.")
2256            })
2257    }
2258
2259    /// See [`RenderBox::any_constraints`].
2260    pub fn any_constraints(self, app: &App) -> AnyBoxConstraints {
2261        self.box_data(app).constraints.clone().unwrap_or_else(|| {
2262            panic!("A RenderObject does not have any constraints before it has been laid out.")
2263        })
2264    }
2265
2266    /// Returns the minimum width that this box could be without failing to correctly paint its
2267    /// contents within itself, without clipping.
2268    ///
2269    /// The height argument may give a specific height to assume. The given height can be
2270    /// infinite, meaning that the intrinsic width in an unconstrained environment is being
2271    /// requested. The given height should never be negative.
2272    ///
2273    /// This function should only be called on one's children. Calling this function couples the
2274    /// child with the parent so that when the child's layout changes, the parent is notified
2275    /// (via [`RenderBox::mark_needs_layout`]).
2276    ///
2277    /// Calling this function is expensive as it can result in O(N^2) behavior.
2278    ///
2279    /// Do not override this method. Instead, implement
2280    /// [`RenderBox::compute_min_intrinsic_width`].
2281    pub fn get_min_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2282        debug_assert!(
2283            height >= 0.0,
2284            "The height argument to get_min_intrinsic_width was negative. If you perform \
2285             computations on another height before passing it to get_min_intrinsic_width, \
2286             consider using f64::max or clamp_double to force the value into the valid range."
2287        );
2288        memoize_intrinsic(
2289            self,
2290            app,
2291            IntrinsicDimension::MinWidth,
2292            height,
2293            self.vtable.compute_min_intrinsic_width,
2294        )
2295    }
2296
2297    /// Returns the smallest width beyond which increasing the width never decreases the
2298    /// preferred height. The preferred height is the value that would be returned by
2299    /// [`get_min_intrinsic_height`](Self::get_min_intrinsic_height) for that width.
2300    ///
2301    /// Do not override this method. Instead, implement
2302    /// [`RenderBox::compute_max_intrinsic_width`].
2303    pub fn get_max_intrinsic_width(self, app: &mut App, height: f64) -> f64 {
2304        debug_assert!(
2305            height >= 0.0,
2306            "The height argument to get_max_intrinsic_width was negative."
2307        );
2308        memoize_intrinsic(
2309            self,
2310            app,
2311            IntrinsicDimension::MaxWidth,
2312            height,
2313            self.vtable.compute_max_intrinsic_width,
2314        )
2315    }
2316
2317    /// Returns the minimum height that this box could be without failing to correctly paint its
2318    /// contents within itself, without clipping.
2319    ///
2320    /// Do not override this method. Instead, implement
2321    /// [`RenderBox::compute_min_intrinsic_height`].
2322    pub fn get_min_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2323        debug_assert!(
2324            width >= 0.0,
2325            "The width argument to get_min_intrinsic_height was negative."
2326        );
2327        memoize_intrinsic(
2328            self,
2329            app,
2330            IntrinsicDimension::MinHeight,
2331            width,
2332            self.vtable.compute_min_intrinsic_height,
2333        )
2334    }
2335
2336    /// Returns the smallest height beyond which increasing the height never decreases the
2337    /// preferred width. The preferred width is the value that would be returned by
2338    /// [`get_min_intrinsic_width`](Self::get_min_intrinsic_width) for that height.
2339    ///
2340    /// Do not override this method. Instead, implement
2341    /// [`RenderBox::compute_max_intrinsic_height`].
2342    pub fn get_max_intrinsic_height(self, app: &mut App, width: f64) -> f64 {
2343        debug_assert!(
2344            width >= 0.0,
2345            "The width argument to get_max_intrinsic_height was negative."
2346        );
2347        memoize_intrinsic(
2348            self,
2349            app,
2350            IntrinsicDimension::MaxHeight,
2351            width,
2352            self.vtable.compute_max_intrinsic_height,
2353        )
2354    }
2355
2356    /// Returns the [`Size`] that this box would like to be given the provided
2357    /// [`BoxConstraints`].
2358    ///
2359    /// The size returned by this method is guaranteed to be the same size that this box computes
2360    /// for itself during layout given the same constraints.
2361    ///
2362    /// This function should only be called on one's children. Calling this function couples the
2363    /// child with the parent so that when the child's layout changes, the parent is notified
2364    /// (via [`RenderBox::mark_needs_layout`]).
2365    ///
2366    /// This layout is called "dry" layout as opposed to the regular "wet" layout run performed
2367    /// by [`RenderObject::perform_layout`] because it computes the desired size for the given
2368    /// constraints without changing any internal state.
2369    ///
2370    /// Calling this function is expensive as it can result in O(N^2) behavior.
2371    ///
2372    /// Do not override this method. Instead, implement [`RenderBox::compute_dry_layout`].
2373    pub fn get_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2374        if !should_cache_intrinsics(self, app) {
2375            return self.compute_dry_layout(app, constraints);
2376        }
2377        if let Some(cached) = self
2378            .layout_cache(app)
2379            .cached_dry_layout_sizes
2380            .get(&constraints)
2381        {
2382            return *cached;
2383        }
2384        let result = self.compute_dry_layout(app, constraints);
2385        self.layout_cache_mut(app)
2386            .cached_dry_layout_sizes
2387            .insert(constraints, result);
2388        result
2389    }
2390
2391    /// Flutter's `RenderBox._computeDryLayout`: the re-entrancy guard around the virtual.
2392    fn compute_dry_layout(self, app: &mut App, constraints: BoxConstraints) -> Size {
2393        if cfg!(debug_assertions) {
2394            assert!(!self.box_data(app).debug_computing_this_dry_layout);
2395            self.box_data_mut(app).debug_computing_this_dry_layout = true;
2396        }
2397        let result = (self.vtable.compute_dry_layout)(app, self.id, constraints);
2398        if cfg!(debug_assertions) {
2399            self.box_data_mut(app).debug_computing_this_dry_layout = false;
2400        }
2401        result
2402    }
2403
2404    /// Returns the distance from the top of the box to the first baseline of the box's contents
2405    /// for the given `constraints`, or `None` if this box does not have any baselines.
2406    ///
2407    /// This method calls [`RenderBox::compute_dry_baseline`] under the hood and caches the
2408    /// result. Boxes typically don't override
2409    /// [`get_dry_baseline`](Self::get_dry_baseline). Instead, consider overriding
2410    /// [`RenderBox::compute_dry_baseline`] such that it returns a baseline location that is
2411    /// consistent with [`get_distance_to_actual_baseline`](Self::get_distance_to_actual_baseline).
2412    ///
2413    /// This method is usually called by the [`RenderBox::compute_dry_baseline`] or the
2414    /// [`RenderBox::compute_dry_layout`] implementation of a parent box to get the baseline
2415    /// location of a box child. Unlike
2416    /// [`get_distance_to_baseline`](Self::get_distance_to_baseline), this method takes a
2417    /// [`BoxConstraints`] as an argument and computes the baseline location as if the box was
2418    /// laid out by the parent using that [`BoxConstraints`].
2419    pub fn get_dry_baseline(
2420        self,
2421        app: &mut App,
2422        constraints: BoxConstraints,
2423        baseline: TextBaseline,
2424    ) -> Option<f64> {
2425        let baseline_offset = memoize_baseline(self, app, constraints, baseline, |this, app| {
2426            this.compute_dry_baseline(app, constraints, baseline)
2427        })
2428        .offset();
2429        // This assert makes sure compute_dry_baseline always gets called in debug mode, in case
2430        // the compute_dry_baseline implementation invokes debug_cannot_compute_dry_layout. The
2431        // check is skipped when debug_checking_intrinsics is true to avoid slowing down the app
2432        // significantly.
2433        if cfg!(debug_assertions) && !debug_checking_intrinsics() {
2434            assert_eq!(
2435                baseline_offset,
2436                (self.vtable.compute_dry_baseline)(app, self.id, constraints, baseline)
2437            );
2438        }
2439        baseline_offset
2440    }
2441
2442    /// Flutter's `RenderBox._computeDryBaseline`: the re-entrancy guard around the virtual.
2443    fn compute_dry_baseline(
2444        self,
2445        app: &mut App,
2446        constraints: BoxConstraints,
2447        baseline: TextBaseline,
2448    ) -> BaselineOffset {
2449        if cfg!(debug_assertions) {
2450            assert!(!self.box_data(app).debug_computing_this_dry_baseline);
2451            self.box_data_mut(app).debug_computing_this_dry_baseline = true;
2452        }
2453        let result = BaselineOffset((self.vtable.compute_dry_baseline)(
2454            app,
2455            self.id,
2456            constraints,
2457            baseline,
2458        ));
2459        if cfg!(debug_assertions) {
2460            self.box_data_mut(app).debug_computing_this_dry_baseline = false;
2461        }
2462        result
2463    }
2464
2465    /// Returns the distance from the y-coordinate of the position of the box to the y-coordinate
2466    /// of the first given baseline in the box's contents.
2467    ///
2468    /// Used by certain layout models to align adjacent boxes on a common baseline, regardless of
2469    /// padding, font size differences, etc. If there is no baseline, this function returns the
2470    /// distance from the y-coordinate of the position of the box to the y-coordinate of the
2471    /// bottom of the box (i.e., the height of the box) unless the caller passes true for
2472    /// `only_real`, in which case the function returns `None`.
2473    ///
2474    /// Only call this function after calling [`layout`](Self::layout) on this box. You are only
2475    /// allowed to call this from the parent of this box during that parent's
2476    /// [`RenderObject::perform_layout`] or [`RenderObject::paint`] functions.
2477    ///
2478    /// To override the baseline computation, override
2479    /// [`RenderBox::compute_distance_to_actual_baseline`].
2480    pub fn get_distance_to_baseline(
2481        self,
2482        app: &mut App,
2483        baseline: TextBaseline,
2484        only_real: bool,
2485    ) -> Option<f64> {
2486        debug_assert!(
2487            !DEBUG_DOING_BASELINE.get(),
2488            "Please see the documentation for compute_distance_to_actual_baseline for the \
2489             required calling conventions of this method."
2490        );
2491        debug_assert!(!self.as_object().debug_needs_layout(app) || debug_checking_intrinsics());
2492        let result = {
2493            let _doing_baseline = DebugDoingBaseline::enter();
2494            self.get_distance_to_actual_baseline(app, baseline)
2495        };
2496        match result {
2497            None if !only_real => Some(self.size(app).height()),
2498            result => result,
2499        }
2500    }
2501
2502    /// Calls [`RenderBox::compute_distance_to_actual_baseline`] and caches the result.
2503    ///
2504    /// This function must only be called from
2505    /// [`get_distance_to_baseline`](Self::get_distance_to_baseline) and
2506    /// [`RenderBox::compute_distance_to_actual_baseline`].
2507    pub fn get_distance_to_actual_baseline(
2508        self,
2509        app: &mut App,
2510        baseline: TextBaseline,
2511    ) -> Option<f64> {
2512        debug_assert!(
2513            DEBUG_DOING_BASELINE.get() || !cfg!(debug_assertions),
2514            "Please see the documentation for compute_distance_to_actual_baseline for the \
2515             required calling conventions of this method."
2516        );
2517        let constraints = self
2518            .box_data(app)
2519            .constraints
2520            .as_ref()
2521            .map(AnyBoxConstraints::constraints)
2522            .expect("a RenderBox has constraints once it has been laid out");
2523        memoize_baseline(self, app, constraints, baseline, |this, app| {
2524            BaselineOffset((this.vtable.compute_distance_to_actual_baseline)(
2525                app, this.id, baseline,
2526            ))
2527        })
2528        .offset()
2529    }
2530
2531    fn layout_cache(self, app: &App) -> &LayoutCacheStorage {
2532        &self.box_data(app).layout_cache
2533    }
2534
2535    fn layout_cache_mut(self, app: &mut App) -> &mut LayoutCacheStorage {
2536        &mut self.box_data_mut(app).layout_cache
2537    }
2538
2539    /// [`BoxParentData`] stored on this child by its box parent.
2540    ///
2541    /// Dart's `child.parentData! as BoxParentData`: a subclass answers with its own
2542    /// [`BoxParentData`] half through [`ParentData::provide`].
2543    pub fn box_parent_data(self, app: &App) -> &BoxParentData {
2544        box_parent_data_of(app, self.as_object())
2545    }
2546
2547    /// Convert the given point from the global coordinate system in logical pixels to the
2548    /// local coordinate system for this box.
2549    ///
2550    /// This method will un-project the point from the screen onto the widget, which makes it
2551    /// different from `MatrixUtils.transformPoint`.
2552    ///
2553    /// If the transform from global coordinates to local coordinates is degenerate, this
2554    /// function returns `Offset::ZERO`.
2555    ///
2556    /// If `ancestor` is non-null, this function converts the given point from the coordinate
2557    /// system of `ancestor` (which must be an ancestor of this render object) instead of from
2558    /// the global coordinate system.
2559    ///
2560    /// This method is implemented in terms of [`AnyRenderObject::get_transform_to`].
2561    pub fn global_to_local(
2562        self,
2563        app: &App,
2564        point: Offset,
2565        ancestor: Option<AnyRenderObject>,
2566    ) -> Offset {
2567        // We want to find the local point that corresponds to the given point on
2568        // the screen, but that also physically resides on this RenderBox's local
2569        // render plane, so that it is useful for visually accurate gesture
2570        // processing in the local space. For that, we cannot simply transform the
2571        // 2D screen point to the 3D local space since the screen space lacks the
2572        // depth component |z|, and so there are many 3D points that correspond to
2573        // the screen point. We must first unproject the screen point onto the local
2574        // render plane to find the true 3D point that corresponds to the screen
2575        // point.
2576        //
2577        // We do orthogonal unprojection after undoing perspective, in local space.
2578        // The local render plane is the XY plane with normal vector <0, 0, 1>.
2579        // Unprojection is done by finding the intersection of the view vector with
2580        // the local XY plane at z = 0.
2581        let transform = self.as_object().get_transform_to(app, ancestor);
2582        let Some(transform) = transform.invert() else {
2583            return Offset::ZERO;
2584        };
2585
2586        // Two points with the same screen x and y but different depths define the
2587        // view direction in local coordinates.
2588        let n = [0.0, 0.0, 1.0];
2589        let i = crate::object::perspective_transform(&transform, [0.0, 0.0, 0.0]);
2590        let d = subtract(
2591            crate::object::perspective_transform(&transform, [0.0, 0.0, 1.0]),
2592            i,
2593        );
2594        let s = crate::object::perspective_transform(&transform, [point.dx(), point.dy(), 0.0]);
2595        // Project the screen point onto the local render plane.
2596        let p = subtract(s, scale(d, dot(n, s) / dot(n, d)));
2597        Offset::new(p[0], p[1])
2598    }
2599
2600    /// Convert the given point from the local coordinate system for this box to the global
2601    /// coordinate system in logical pixels.
2602    ///
2603    /// If `ancestor` is non-null, this function converts the given point to the coordinate
2604    /// system of `ancestor` (which must be an ancestor of this render object) instead of to
2605    /// the global coordinate system.
2606    ///
2607    /// This method is implemented in terms of [`AnyRenderObject::get_transform_to`]. If the
2608    /// transform matrix puts the given `point` on the line at infinity (for instance, when
2609    /// the transform matrix is the zero matrix), this method returns (NaN, NaN).
2610    pub fn local_to_global(
2611        self,
2612        app: &App,
2613        point: Offset,
2614        ancestor: Option<AnyRenderObject>,
2615    ) -> Offset {
2616        waft_painting::transform_point(&self.as_object().get_transform_to(app, ancestor), point)
2617    }
2618
2619    /// See [`AnyRenderObject::parent_data_of_mut`].
2620    pub fn parent_data_of_mut<P: crate::object::ParentData + 'static>(
2621        self,
2622        app: &mut App,
2623    ) -> &mut P {
2624        self.as_object().parent_data_of_mut(app)
2625    }
2626
2627    /// See [`AnyRenderObject::parent_data_is`].
2628    pub fn parent_data_is<P: crate::object::ParentData + 'static>(self, app: &App) -> bool {
2629        self.as_object().parent_data_is::<P>(app)
2630    }
2631}
2632
2633impl crate::object::ErasedRenderObject for AnyRenderBox {
2634    fn as_object(self) -> AnyRenderObject {
2635        AnyRenderBox::as_object(self)
2636    }
2637
2638    fn from_object(object: AnyRenderObject) -> AnyRenderBox {
2639        object
2640            .as_box()
2641            .expect("the render object is not a RenderBox")
2642    }
2643}
2644
2645impl From<AnyRenderBox> for AnyRenderObject {
2646    fn from(box_: AnyRenderBox) -> AnyRenderObject {
2647        box_.as_object()
2648    }
2649}
2650
2651fn subtract(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
2652    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
2653}
2654
2655fn scale(a: [f64; 3], factor: f64) -> [f64; 3] {
2656    [a[0] * factor, a[1] * factor, a[2] * factor]
2657}
2658
2659fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
2660    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
2661}
2662
2663#[cfg(test)]
2664mod tests {
2665    use super::*;
2666
2667    #[test]
2668    fn to_string_marks_biggest_unconstrained_and_tight() {
2669        assert!(
2670            BoxConstraints::expand(None, None)
2671                .to_string()
2672                .contains("biggest")
2673        );
2674        assert!(BoxConstraints::new().to_string().contains("unconstrained"));
2675        assert!(
2676            BoxConstraints::tight_for(Some(50.0), None)
2677                .to_string()
2678                .contains("w=50")
2679        );
2680    }
2681
2682    #[test]
2683    fn copy_with_replaces_fields() {
2684        let constraints = BoxConstraints::new()
2685            .min_width(3.0)
2686            .max_width(7.0)
2687            .min_height(11.0)
2688            .max_height(17.0);
2689        let copy = constraints.copy_with();
2690        assert_eq!(copy, constraints);
2691        let copy = constraints
2692            .copy_with()
2693            .min_width(13.0)
2694            .max_width(17.0)
2695            .min_height(111.0)
2696            .max_height(117.0);
2697        assert_eq!(copy.min_width, 13.0);
2698        assert_eq!(copy.max_width, 17.0);
2699        assert_eq!(copy.min_height, 111.0);
2700        assert_eq!(copy.max_height, 117.0);
2701        assert_ne!(copy, constraints);
2702        let mut copy_hasher = std::collections::hash_map::DefaultHasher::new();
2703        let mut original_hasher = std::collections::hash_map::DefaultHasher::new();
2704        copy.hash(&mut copy_hasher);
2705        constraints.hash(&mut original_hasher);
2706        assert_ne!(copy_hasher.finish(), original_hasher.finish());
2707    }
2708
2709    #[test]
2710    fn operators() {
2711        let constraints = BoxConstraints::new()
2712            .min_width(3.0)
2713            .max_width(7.0)
2714            .min_height(11.0)
2715            .max_height(17.0);
2716        let copy = constraints * 2.0;
2717        assert_eq!(copy.min_width, 6.0);
2718        assert_eq!(copy.max_width, 14.0);
2719        assert_eq!(copy.min_height, 22.0);
2720        assert_eq!(copy.max_height, 34.0);
2721        assert_eq!(copy / 2.0, constraints);
2722        let copy = constraints.truncating_div(2.0);
2723        assert_eq!(copy.min_width, 1.0);
2724        assert_eq!(copy.max_width, 3.0);
2725        assert_eq!(copy.min_height, 5.0);
2726        assert_eq!(copy.max_height, 8.0);
2727        let copy = constraints % 3.0;
2728        assert_eq!(copy.min_width, 0.0);
2729        assert_eq!(copy.max_width, 1.0);
2730        assert_eq!(copy.min_height, 2.0);
2731        assert_eq!(copy.max_height, 2.0);
2732    }
2733
2734    #[test]
2735    fn lerp_from_null_and_between() {
2736        assert!(BoxConstraints::lerp(None, None, 0.5).is_none());
2737        let constraints = BoxConstraints::new()
2738            .min_width(3.0)
2739            .max_width(7.0)
2740            .min_height(11.0)
2741            .max_height(17.0);
2742        let copy = BoxConstraints::lerp(None, Some(constraints), 0.5).unwrap();
2743        assert!((copy.min_width - 1.5).abs() < 1e-9);
2744        assert!((copy.max_width - 3.5).abs() < 1e-9);
2745        assert!((copy.min_height - 5.5).abs() < 1e-9);
2746        assert!((copy.max_height - 8.5).abs() < 1e-9);
2747        let copy = BoxConstraints::lerp(Some(constraints), None, 0.5).unwrap();
2748        assert!((copy.min_width - 1.5).abs() < 1e-9);
2749        let copy = BoxConstraints::lerp(
2750            Some(
2751                BoxConstraints::new()
2752                    .min_width(13.0)
2753                    .max_width(17.0)
2754                    .min_height(111.0)
2755                    .max_height(117.0),
2756            ),
2757            Some(constraints),
2758            0.2,
2759        )
2760        .unwrap();
2761        assert!((copy.min_width - 11.0).abs() < 1e-9);
2762        assert!((copy.max_width - 15.0).abs() < 1e-9);
2763        assert!((copy.min_height - 91.0).abs() < 1e-9);
2764        assert!((copy.max_height - 97.0).abs() < 1e-9);
2765    }
2766
2767    #[test]
2768    fn lerp_unbounded_axes() {
2769        let constraints1 = BoxConstraints::new()
2770            .min_width(f64::INFINITY)
2771            .min_height(10.0)
2772            .max_height(20.0);
2773        let constraints2 = BoxConstraints::new()
2774            .min_width(f64::INFINITY)
2775            .min_height(20.0)
2776            .max_height(30.0);
2777        let constraints3 = BoxConstraints::new()
2778            .min_width(f64::INFINITY)
2779            .min_height(15.0)
2780            .max_height(25.0);
2781        assert_eq!(
2782            BoxConstraints::lerp(Some(constraints1), Some(constraints2), 0.5),
2783            Some(constraints3)
2784        );
2785    }
2786
2787    #[test]
2788    fn lerp_overshoot_is_normalized() {
2789        assert_eq!(
2790            BoxConstraints::lerp(
2791                Some(BoxConstraints::tight_for(None, Some(25.0))),
2792                Some(BoxConstraints::tight_for(None, Some(0.0))),
2793                1.2,
2794            ),
2795            Some(BoxConstraints::tight_for(None, Some(0.0)))
2796        );
2797        let lerped = BoxConstraints::lerp(
2798            Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
2799            Some(BoxConstraints::new().max_width(100.0).max_height(100.0)),
2800            -0.1,
2801        )
2802        .unwrap();
2803        assert!(lerped.is_normalized());
2804        assert_eq!(lerped, BoxConstraints::tight(Size::new(11.0, 11.0)));
2805    }
2806
2807    #[test]
2808    fn normalize_raises_inverted_max() {
2809        let constraints = BoxConstraints::new()
2810            .min_width(3.0)
2811            .max_width(2.0)
2812            .min_height(11.0)
2813            .max_height(18.0);
2814        let copy = constraints.normalize();
2815        assert_eq!(copy.min_width, 3.0);
2816        assert_eq!(copy.max_width, 3.0);
2817        assert_eq!(copy.min_height, 11.0);
2818        assert_eq!(copy.max_height, 18.0);
2819    }
2820
2821    #[test]
2822    fn from_view_constraints() {
2823        let unconstrained = BoxConstraints::from_view_constraints(ViewConstraints::default());
2824        assert_eq!(unconstrained, BoxConstraints::new());
2825        let constraints =
2826            BoxConstraints::from_view_constraints(ViewConstraints::new(1.0, 2.0, 3.0, 4.0));
2827        assert_eq!(
2828            constraints,
2829            BoxConstraints::new()
2830                .min_width(1.0)
2831                .max_width(2.0)
2832                .min_height(3.0)
2833                .max_height(4.0)
2834        );
2835    }
2836
2837    #[test]
2838    fn constrain_size_and_attempt_to_preserve_aspect_ratio_empty_size() {
2839        let constraints = BoxConstraints::new()
2840            .min_width(10.0)
2841            .max_width(20.0)
2842            .min_height(10.0)
2843            .max_height(20.0);
2844        let constrained =
2845            constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(Size::new(15.0, 0.0));
2846        assert_eq!(constrained, Size::new(15.0, 10.0));
2847    }
2848}
2849
2850#[cfg(test)]
2851mod hit_test_tests {
2852    use waft_painting::force_to_point;
2853
2854    use super::*;
2855
2856    #[derive(Debug)]
2857    struct DummyHitTestTarget;
2858
2859    impl HitTestTarget for DummyHitTestTarget {
2860        fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
2861    }
2862
2863    /// `box_test.dart`: `BoxHitTestResult wrapping HitTestResult`.
2864    #[test]
2865    fn wrapping_shares_the_path() {
2866        let transform = Matrix4::translation(40.0, 150.0);
2867        let mut wrapped = HitTestResult::new();
2868        wrapped.push_transform(transform);
2869        wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2870        assert_eq!(wrapped.path().len(), 1);
2871        assert_eq!(wrapped.path()[0].transform(), Some(transform));
2872
2873        let mut wrapping = BoxHitTestResult::wrap(&mut wrapped);
2874        wrapping.add(HitTestEntry::new(DummyHitTestTarget));
2875        assert_eq!(wrapping.path().len(), 2);
2876        assert_eq!(wrapping.path()[1].transform(), Some(transform));
2877
2878        wrapped.add(HitTestEntry::new(DummyHitTestTarget));
2879        assert_eq!(wrapped.path().len(), 3);
2880        assert_eq!(wrapped.path()[2].transform(), Some(transform));
2881    }
2882
2883    /// `box_test.dart`: `addWithPaintTransform`.
2884    #[test]
2885    fn add_with_paint_transform() {
2886        let mut base = HitTestResult::new();
2887        let mut result = BoxHitTestResult::wrap(&mut base);
2888        let mut positions = Vec::new();
2889
2890        let is_hit = result.add_with_paint_transform(None, Offset::ZERO, |_, position| {
2891            positions.push(position);
2892            true
2893        });
2894        assert!(is_hit);
2895        assert_eq!(positions, [Offset::ZERO]);
2896        positions.clear();
2897
2898        let is_hit = result.add_with_paint_transform(
2899            Some(Matrix4::translation(20.0, 30.0)),
2900            Offset::ZERO,
2901            |_, position| {
2902                positions.push(position);
2903                true
2904            },
2905        );
2906        assert!(is_hit);
2907        assert_eq!(positions, [Offset::new(-20.0, -30.0)]);
2908        positions.clear();
2909
2910        let position = Offset::new(3.0, 4.0);
2911        let is_hit = result.add_with_paint_transform(None, position, |_, position| {
2912            positions.push(position);
2913            false
2914        });
2915        assert!(!is_hit);
2916        assert_eq!(positions, [position]);
2917        positions.clear();
2918
2919        let is_hit =
2920            result.add_with_paint_transform(Some(Matrix4::IDENTITY), position, |_, position| {
2921                positions.push(position);
2922                true
2923            });
2924        assert!(is_hit);
2925        assert_eq!(positions, [position]);
2926        positions.clear();
2927
2928        let is_hit = result.add_with_paint_transform(
2929            Some(Matrix4::translation(20.0, 30.0)),
2930            position,
2931            |_, position| {
2932                positions.push(position);
2933                true
2934            },
2935        );
2936        assert!(is_hit);
2937        assert_eq!(positions, [position - Offset::new(20.0, 30.0)]);
2938        positions.clear();
2939
2940        let is_hit = result.add_with_paint_transform(
2941            Some(force_to_point(position)), // cannot be inverted
2942            position,
2943            |_, position| {
2944                positions.push(position);
2945                true
2946            },
2947        );
2948        assert!(!is_hit);
2949        assert!(positions.is_empty());
2950    }
2951
2952    /// A child under a perspective transform, as Flutter's docs build one:
2953    /// `Matrix4.identity()..setEntry(3, 2, 0.001)..rotateY(0.5)`. Inverting it whole left
2954    /// its third row and column away from `(0, 0, 1, 0)`, and `push_transform`'s check
2955    /// panicked; with the perspective removed first the pointer lands where Flutter's does.
2956    #[test]
2957    fn a_hit_test_through_a_perspective_transform_lands_where_flutters_does() {
2958        let angle = 0.5_f64;
2959        let (cos, sin) = (angle.cos(), angle.sin());
2960        let perspective = 0.001;
2961        let mut storage = Matrix4::IDENTITY.to_flutter_array();
2962        storage[0] = cos as f32;
2963        storage[2] = -sin as f32;
2964        storage[8] = sin as f32;
2965        storage[10] = cos as f32;
2966        // Row 3 of `setEntry(3, 2, p)` times the rotation: (-p sin, 0, p cos, 1).
2967        storage[3] = (-perspective * sin) as f32;
2968        storage[11] = (perspective * cos) as f32;
2969        let transform = Matrix4::from_flutter_array(&storage);
2970
2971        let mut base = HitTestResult::new();
2972        let mut result = BoxHitTestResult::wrap(&mut base);
2973        let position = Offset::new(100.0, 50.0);
2974        let mut landed = None;
2975        let is_hit = result.add_with_paint_transform(Some(transform), position, |result, local| {
2976            result.add(HitTestEntry::new(DummyHitTestTarget));
2977            landed = Some(local);
2978            true
2979        });
2980        assert!(is_hit);
2981
2982        // Flutter's arithmetic in f64: without its third row and column the transform is
2983        // x' = x cos, y' = y, w' = 1 - p sin x, and its inverse divides the other way.
2984        let w = 1.0 + perspective * sin * position.dx() / cos;
2985        let expected = Offset::new(position.dx() / cos / w, position.dy() / w);
2986        let landed = landed.expect("the child was hit-tested");
2987        assert!(
2988            (landed.dx() - expected.dx()).abs() < 1e-3
2989                && (landed.dy() - expected.dy()).abs() < 1e-3,
2990            "{landed:?} != {expected:?}"
2991        );
2992    }
2993
2994    /// `box_test.dart`: `addWithPaintOffset`.
2995    #[test]
2996    fn add_with_paint_offset() {
2997        let mut base = HitTestResult::new();
2998        let mut result = BoxHitTestResult::wrap(&mut base);
2999        let mut positions = Vec::new();
3000
3001        let is_hit = result.add_with_paint_offset(None, Offset::ZERO, |_, position| {
3002            positions.push(position);
3003            true
3004        });
3005        assert!(is_hit);
3006        assert_eq!(positions, [Offset::ZERO]);
3007        positions.clear();
3008
3009        let is_hit = result.add_with_paint_offset(
3010            Some(Offset::new(55.0, 32.0)),
3011            Offset::ZERO,
3012            |_, position| {
3013                positions.push(position);
3014                true
3015            },
3016        );
3017        assert!(is_hit);
3018        assert_eq!(positions, [Offset::new(-55.0, -32.0)]);
3019        positions.clear();
3020
3021        let position = Offset::new(3.0, 4.0);
3022        let is_hit = result.add_with_paint_offset(
3023            Some(Offset::new(55.0, 32.0)),
3024            position,
3025            |result, position| {
3026                result.add(HitTestEntry::new(DummyHitTestTarget));
3027                positions.push(position);
3028                true
3029            },
3030        );
3031        assert!(is_hit);
3032        assert_eq!(positions, [position - Offset::new(55.0, 32.0)]);
3033        assert_eq!(
3034            result.path()[0].transform(),
3035            Some(Matrix4::translation(-55.0, -32.0)),
3036            "the entry records the transform to the child"
3037        );
3038    }
3039
3040    /// `box_test.dart`: `addWithRawTransform`.
3041    #[test]
3042    fn add_with_raw_transform() {
3043        let mut base = HitTestResult::new();
3044        let mut result = BoxHitTestResult::wrap(&mut base);
3045        let mut positions = Vec::new();
3046
3047        let is_hit = result.add_with_raw_transform(
3048            Some(Matrix4::translation(20.0, 30.0)),
3049            Offset::ZERO,
3050            |_, position| {
3051                positions.push(position);
3052                true
3053            },
3054        );
3055        assert!(is_hit);
3056        assert_eq!(positions, [Offset::new(20.0, 30.0)]);
3057        positions.clear();
3058
3059        let position = Offset::new(3.0, 4.0);
3060        let is_hit =
3061            result.add_with_raw_transform(Some(Matrix4::IDENTITY), position, |_, position| {
3062                positions.push(position);
3063                true
3064            });
3065        assert!(is_hit);
3066        assert_eq!(positions, [position]);
3067    }
3068}
3069
3070#[cfg(test)]
3071mod intrinsics_tests {
3072    use std::cell::Cell;
3073    use std::rc::Rc;
3074    use waft_foundation::AppCell;
3075
3076    use super::*;
3077    use crate::object::RenderObjectData;
3078
3079    /// A leaf whose minimum intrinsic width is `100.0 + height`, counting how often it is
3080    /// actually computed.
3081    struct CountingBox {
3082        render_object: RenderObjectData,
3083        render_box: RenderBoxData,
3084        computations: Rc<Cell<u32>>,
3085    }
3086
3087    impl RenderObject for CountingBox {
3088        crate::render_object_accessors!();
3089
3090        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3091            let size = self.constraints(app).smallest();
3092            self.set_size(app, size);
3093        }
3094    }
3095
3096    impl RenderBox for CountingBox {
3097        crate::render_box_accessors!();
3098
3099        fn compute_min_intrinsic_width(
3100            self: RenderHandle<Self>,
3101            app: &mut App,
3102            height: f64,
3103        ) -> f64 {
3104            let computations = self.get(app).computations.clone();
3105            computations.set(computations.get() + 1);
3106            100.0 + height
3107        }
3108    }
3109
3110    /// `box_test.dart`: `Intrinsics cache' and `Intrinsics cache is cleared when the render
3111    /// object is marked as needing layout`.
3112    #[test]
3113    fn the_intrinsic_cache_is_reused_and_cleared_by_mark_needs_layout() {
3114        let cell = AppCell::new();
3115        let mut app = cell.borrow_mut();
3116        let computations = Rc::new(Cell::new(0));
3117        let box_ = RenderHandle::new_box(
3118            &mut app,
3119            CountingBox {
3120                render_object: RenderObjectData::new(),
3121                render_box: RenderBoxData::new(),
3122                computations: computations.clone(),
3123            },
3124        );
3125
3126        assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3127        assert_eq!(computations.get(), 1);
3128
3129        assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3130        assert_eq!(computations.get(), 1, "the memoized value is reused");
3131
3132        assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 10.0), 110.0);
3133        assert_eq!(computations.get(), 2, "another height is another entry");
3134
3135        RenderBox::mark_needs_layout(box_, &mut app);
3136        assert_eq!(box_.as_box().get_min_intrinsic_width(&mut app, 0.0), 100.0);
3137        assert_eq!(computations.get(), 3, "mark_needs_layout cleared the cache");
3138    }
3139
3140    /// Flutter's `RenderBox.markNeedsLayout`: a box whose intrinsics the parent read defers to
3141    /// the parent, because the parent's layout depends on them.
3142    #[test]
3143    fn clearing_a_cached_intrinsic_marks_the_parent() {
3144        let cell = AppCell::new();
3145        let mut app = cell.borrow_mut();
3146        let computations = Rc::new(Cell::new(0));
3147        let child = RenderHandle::new_box(
3148            &mut app,
3149            CountingBox {
3150                render_object: RenderObjectData::new(),
3151                render_box: RenderBoxData::new(),
3152                computations,
3153            },
3154        );
3155        let parent = crate::proxy_box::RenderConstrainedBox::new(
3156            &mut app,
3157            BoxConstraints::new(),
3158            Some(child.as_box()),
3159        );
3160        parent.layout(&mut app, BoxConstraints::new().max_width(50.0), false);
3161        assert!(!parent.debug_needs_layout(&app));
3162
3163        child.as_box().get_min_intrinsic_width(&mut app, 0.0);
3164        RenderBox::mark_needs_layout(child, &mut app);
3165        assert!(
3166            parent.debug_needs_layout(&app),
3167            "the parent read an intrinsic, so it has to lay out again"
3168        );
3169    }
3170}
3171
3172#[cfg(test)]
3173mod any_box_constraints_tests {
3174    use std::cell::Cell;
3175    use std::rc::Rc;
3176    use waft_foundation::{AppCell, ValueKey};
3177
3178    use super::*;
3179    use crate::custom_layout::{
3180        ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
3181        MultiChildLayoutParentData, RenderCustomMultiChildLayoutBox,
3182    };
3183    use crate::object::RenderObjectData;
3184    use crate::proxy_box::RenderOpacity;
3185
3186    /// A `BoxConstraints` subclass with one field, as `_BottomSheetBoxConstraints` is.
3187    #[derive(Debug)]
3188    struct Inset(f64);
3189
3190    impl BoxConstraintsExtension for Inset {
3191        fn as_any(&self) -> &dyn Any {
3192            self
3193        }
3194
3195        fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3196            other
3197                .as_any()
3198                .downcast_ref::<Inset>()
3199                .is_some_and(|other| other.0 == self.0)
3200        }
3201    }
3202
3203    /// Another subclass with the same field, to tell the runtime types apart.
3204    #[derive(Debug)]
3205    struct Other(f64);
3206
3207    impl BoxConstraintsExtension for Other {
3208        fn as_any(&self) -> &dyn Any {
3209            self
3210        }
3211
3212        fn eq_extension(&self, other: &dyn BoxConstraintsExtension) -> bool {
3213            other
3214                .as_any()
3215                .downcast_ref::<Other>()
3216                .is_some_and(|other| other.0 == self.0)
3217        }
3218    }
3219
3220    fn inset(constraints: BoxConstraints, inset: f64) -> AnyBoxConstraints {
3221        AnyBoxConstraints::with_shared(constraints, Rc::new(Inset(inset)))
3222    }
3223
3224    fn inset_of(constraints: &AnyBoxConstraints) -> Option<f64> {
3225        constraints.extension::<Inset>().map(|inset| inset.0)
3226    }
3227
3228    /// A leaf that takes the smallest size its constraints allow, counting its layouts.
3229    struct CountingLeaf {
3230        render_object: RenderObjectData,
3231        render_box: RenderBoxData,
3232        layouts: Rc<Cell<u32>>,
3233    }
3234
3235    impl RenderObject for CountingLeaf {
3236        crate::render_object_accessors!();
3237
3238        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3239            let layouts = Rc::clone(&self.get(app).layouts);
3240            layouts.set(layouts.get() + 1);
3241            let size = self.constraints(app).smallest();
3242            self.set_size(app, size);
3243        }
3244    }
3245
3246    impl RenderBox for CountingLeaf {
3247        crate::render_box_accessors!();
3248    }
3249
3250    fn counting_leaf(app: &mut App, layouts: &Rc<Cell<u32>>) -> RenderHandle<CountingLeaf> {
3251        RenderHandle::new_box(
3252            app,
3253            CountingLeaf {
3254                render_object: RenderObjectData::new(),
3255                render_box: RenderBoxData::new(),
3256                layouts: Rc::clone(layouts),
3257            },
3258        )
3259    }
3260
3261    fn child_id() -> ChildLayoutId {
3262        Rc::new(ValueKey::new("child"))
3263    }
3264
3265    /// Lays out its one child with an `Inset` subclass instance, as `_ScaffoldLayout` lays out
3266    /// the bottom sheet.
3267    #[derive(Debug)]
3268    struct InsetDelegate;
3269
3270    impl MultiChildLayoutDelegate for InsetDelegate {
3271        fn perform_layout(
3272            &self,
3273            app: &mut App,
3274            children: &mut MultiChildLayoutChildren,
3275            size: Size,
3276        ) {
3277            children.layout_child(app, &child_id(), inset(BoxConstraints::loose(size), 3.0));
3278        }
3279
3280        fn should_relayout(&self, _old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
3281            false
3282        }
3283
3284        fn as_any(&self) -> &dyn Any {
3285            self
3286        }
3287    }
3288
3289    #[test]
3290    fn equality_includes_the_subclass_and_its_fields() {
3291        let constraints = BoxConstraints::tight(Size::new(10.0, 20.0));
3292        let plain = AnyBoxConstraints::new(constraints);
3293        let converted: AnyBoxConstraints = constraints.into();
3294        assert!(plain == converted);
3295        assert!(plain == constraints);
3296
3297        assert!(
3298            inset(constraints, 1.0) != plain,
3299            "a plain value never equals a subclass instance, as Dart's runtimeType check"
3300        );
3301        assert!(inset(constraints, 1.0) != constraints);
3302        assert!(inset(constraints, 1.0) == inset(constraints, 1.0));
3303        assert!(inset(constraints, 1.0) != inset(constraints, 2.0));
3304        assert!(
3305            inset(constraints, 1.0)
3306                != AnyBoxConstraints::with_shared(constraints, Rc::new(Other(1.0)))
3307        );
3308        assert!(inset(constraints, 1.0) != inset(BoxConstraints::new(), 1.0));
3309    }
3310
3311    #[test]
3312    fn a_subclass_instance_derefs_to_its_value_and_answers_its_is_check() {
3313        let constraints = BoxConstraints::new().max_width(30.0).max_height(40.0);
3314        let extended = inset(constraints, 5.0);
3315        assert_eq!(extended.constraints(), constraints);
3316        assert_eq!(extended.max_width, 30.0);
3317        assert_eq!(extended.loosen(), constraints.loosen());
3318        assert!(extended.has_extension());
3319        assert_eq!(inset_of(&extended), Some(5.0));
3320        assert!(extended.extension::<Other>().is_none());
3321        assert!(!AnyBoxConstraints::new(constraints).has_extension());
3322        assert_eq!(format!("{extended:?}"), format!("{constraints:?}"));
3323    }
3324
3325    #[test]
3326    fn layout_lays_out_again_when_only_the_subclass_fields_change() {
3327        let cell = AppCell::new();
3328        let mut app = cell.borrow_mut();
3329        let layouts = Rc::new(Cell::new(0));
3330        let leaf = counting_leaf(&mut app, &layouts);
3331        let constraints = BoxConstraints::new().max_width(50.0).max_height(50.0);
3332
3333        leaf.layout(&mut app, inset(constraints, 1.0), false);
3334        assert_eq!(layouts.get(), 1);
3335        assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(1.0));
3336
3337        leaf.layout(&mut app, inset(constraints, 1.0), false);
3338        assert_eq!(layouts.get(), 1, "equal constraints return early");
3339
3340        leaf.layout(&mut app, inset(constraints, 2.0), false);
3341        assert_eq!(layouts.get(), 2, "only the inset changed");
3342        assert_eq!(inset_of(&leaf.any_constraints(&app)), Some(2.0));
3343
3344        leaf.layout(&mut app, constraints, false);
3345        assert_eq!(
3346            layouts.get(),
3347            3,
3348            "a plain value is not the subclass instance"
3349        );
3350        assert!(!leaf.any_constraints(&app).has_extension());
3351        assert_eq!(leaf.constraints(&app), constraints);
3352    }
3353
3354    #[test]
3355    fn a_subclass_instance_reaches_the_child_a_layout_delegate_lays_out() {
3356        let cell = AppCell::new();
3357        let mut app = cell.borrow_mut();
3358        let layouts = Rc::new(Cell::new(0));
3359        let leaf = counting_leaf(&mut app, &layouts);
3360        let parent = RenderCustomMultiChildLayoutBox::new(&mut app, Rc::new(InsetDelegate));
3361        parent.add(&mut app, leaf.as_box());
3362        leaf.as_object()
3363            .parent_data_of_mut::<MultiChildLayoutParentData>(&mut app)
3364            .id = Some(child_id());
3365
3366        parent.layout(
3367            &mut app,
3368            BoxConstraints::tight(Size::new(100.0, 80.0)),
3369            false,
3370        );
3371        assert_eq!(layouts.get(), 1);
3372        let child_constraints = leaf.as_box().any_constraints(&app);
3373        assert_eq!(inset_of(&child_constraints), Some(3.0));
3374        assert_eq!(
3375            leaf.as_box().constraints(&app),
3376            BoxConstraints::loose(Size::new(100.0, 80.0))
3377        );
3378    }
3379
3380    #[test]
3381    fn a_proxy_box_hands_its_child_the_plain_value() {
3382        let cell = AppCell::new();
3383        let mut app = cell.borrow_mut();
3384        let layouts = Rc::new(Cell::new(0));
3385        let leaf = counting_leaf(&mut app, &layouts);
3386        let proxy = RenderOpacity::new(&mut app, 1.0, Some(leaf.as_box()));
3387        let constraints = BoxConstraints::new().max_width(60.0).max_height(70.0);
3388
3389        proxy.layout(&mut app, inset(constraints, 4.0), false);
3390        assert_eq!(inset_of(&proxy.any_constraints(&app)), Some(4.0));
3391        assert!(
3392            !leaf.any_constraints(&app).has_extension(),
3393            "the subclass instance rides one hop: the proxy passes its `constraints()` on"
3394        );
3395        assert_eq!(leaf.constraints(&app), constraints);
3396    }
3397}