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