Skip to main content

waft_rendering/
proxy_box.rs

1//! Flutter counterpart: `rendering/proxy_box.dart` (`RenderProxyBoxMixin`,
2//! `HitTestBehavior`, `RenderConstrainedBox`, `RenderLimitedBox`, `RenderOpacity`,
3//! `RenderAnimatedOpacityMixin`, `RenderAnimatedOpacity`, `CustomClipper`,
4//! `RenderCustomClip`, `RenderClipRect`, `RenderClipRRect`, `RenderPhysicalModel`,
5//! `RenderPhysicalShape`, `RenderPointerListener`,
6//! `DecorationPosition`, `RenderDecoratedBox`, `RenderTransform`,
7//! `RenderFractionalTranslation`, `RenderRepaintBoundary`, `RenderMouseRegion`,
8//! `RenderIgnorePointer`, `RenderOffstage`, `RenderAbsorbPointer`, `RenderSemanticsAnnotations`,
9//! `RenderBlockSemantics`, `RenderMergeSemantics`, `RenderExcludeSemantics`,
10//! `RenderIndexedSemantics`, `RenderAnnotatedRegion`),
11//! plus
12//! `widgets/basic.dart`'s `_RenderColoredBox`.
13//!
14//! Intrinsics wait.
15
16use std::any::Any;
17use std::rc::Rc;
18
19use waft_animation::{AnimationRef, AnyAnimation};
20use waft_embedder::Locale;
21use waft_embedder::{
22    BlendMode, Clip, Color, FillRule, FilterQuality, ImageFilter, Matrix4, Offset, Paint, Path,
23    PathBuilder, RRect, RSuperellipse, Rect, Size, TextBaseline, rrect_radii_elliptical,
24    rsuperellipse_radii_elliptical, valo,
25};
26use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained};
27use waft_gestures::{
28    PointerCancelEventListener, PointerDownEventListener, PointerEnterEventListener, PointerEvent,
29    PointerExitEventListener, PointerHoverEventListener, PointerMoveEventListener,
30    PointerPanZoomEndEventListener, PointerPanZoomStartEventListener,
31    PointerPanZoomUpdateEventListener, PointerSignalEventListener, PointerUpEventListener,
32};
33use waft_painting::{
34    Alignment, AlignmentGeometry, BorderRadius, BorderRadiusGeometry, BoxFit, BoxPainter, BoxShape,
35    ClipContext, DecorationRef, ImageConfiguration, ShapeBorderRef, TextDirection, apply_box_fit,
36    draw_rrect, get_as_translation,
37};
38use waft_services::{MouseCursor, MouseCursorRef, MouseTrackerAnnotation};
39
40use crate::box_::{
41    AnyRenderBox, BoxConstraints, BoxHitTestEntry, BoxHitTestResult, RenderBox, RenderBoxBase,
42    RenderBoxData,
43};
44use crate::image_filter_config::{ImageFilterConfig, ImageFilterContext};
45use crate::layer::{
46    AnnotatedRegionLayer, BackdropFilterLayer, BackdropKey, ClipPathLayer, ClipRRectLayer,
47    ClipRectLayer, ContainerLayer, FollowerLayer, ImageFilterLayer, LayerHandle, LayerLink,
48    LeaderLayer, OffsetLayerMixin, OpacityLayer, TransformLayer,
49};
50use crate::layout_helper::{ChildLayoutHelper, ChildLayouter};
51use crate::object::{
52    AnyRenderObject, Constraints, EmptyParentData, RenderHandle, RenderObject, RenderObjectData,
53    RenderObjectWithChildData, RenderObjectWithChildMixin,
54};
55use crate::painting_context::PaintingContext;
56use crate::pipeline_owner::PipelineOwner;
57use crate::semantics::SemanticsProperties;
58use crate::semantics_annotations::{SemanticsAnnotationsData, SemanticsAnnotationsMixin};
59use crate::view::RenderView;
60use waft_foundation::Ref;
61
62/// A base class for render boxes that resemble their children.
63///
64/// Flutter's `RenderProxyBoxMixin`: the shared bodies of a proxy box. A leaf implements the
65/// marker and calls these where Dart would run the inherited method:
66/// `RenderProxyBoxMixin::perform_layout(self, app)`.
67pub trait RenderProxyBoxMixin:
68    RenderObjectWithChildMixin<ChildType = AnyRenderBox> + RenderBox
69{
70    /// A proxy child gets plain parent data, not [`crate::BoxParentData`].
71    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
72        if child.parent_data(app).is_none() {
73            child.set_parent_data(app, EmptyParentData);
74        }
75    }
76
77    /// A proxy paints its child at its own offset: no transform to apply.
78    fn apply_paint_transform(
79        self: RenderHandle<Self>,
80        app: &App,
81        child: AnyRenderObject,
82        transform: &mut Matrix4,
83    ) {
84        let _ = (app, child, transform);
85    }
86
87    /// The child's minimum intrinsic width, or 0 without a child.
88    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
89        match self.child(app) {
90            Some(child) => child.get_min_intrinsic_width(app, height),
91            None => 0.0,
92        }
93    }
94
95    /// The child's maximum intrinsic width, or 0 without a child.
96    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
97        match self.child(app) {
98            Some(child) => child.get_max_intrinsic_width(app, height),
99            None => 0.0,
100        }
101    }
102
103    /// The child's minimum intrinsic height, or 0 without a child.
104    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
105        match self.child(app) {
106            Some(child) => child.get_min_intrinsic_height(app, width),
107            None => 0.0,
108        }
109    }
110
111    /// The child's maximum intrinsic height, or 0 without a child.
112    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
113        match self.child(app) {
114            Some(child) => child.get_max_intrinsic_height(app, width),
115            None => 0.0,
116        }
117    }
118
119    /// The child's baseline, or none without a child.
120    fn compute_distance_to_actual_baseline(
121        self: RenderHandle<Self>,
122        app: &mut App,
123        baseline: TextBaseline,
124    ) -> Option<f64> {
125        self.child(app)
126            .and_then(|child| child.get_distance_to_actual_baseline(app, baseline))
127    }
128
129    /// The child's dry baseline, or none without a child.
130    fn compute_dry_baseline(
131        self: RenderHandle<Self>,
132        app: &mut App,
133        constraints: BoxConstraints,
134        baseline: TextBaseline,
135    ) -> Option<f64> {
136        self.child(app)
137            .and_then(|child| child.get_dry_baseline(app, constraints, baseline))
138    }
139
140    /// The child's dry layout at this box's constraints, or
141    /// [`compute_size_for_no_child`](Self::compute_size_for_no_child).
142    fn compute_dry_layout(
143        self: RenderHandle<Self>,
144        app: &mut App,
145        constraints: BoxConstraints,
146    ) -> Size {
147        match self.child(app) {
148            Some(child) => child.get_dry_layout(app, constraints),
149            None => self.compute_size_for_no_child(app, constraints),
150        }
151    }
152
153    /// Lays the child out with this box's constraints and takes its size.
154    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
155        let constraints = self.constraints(app);
156        let size = match self.child(app) {
157            Some(child) => {
158                child.layout(app, constraints, true);
159                child.size(app)
160            }
161            None => self.compute_size_for_no_child(app, constraints),
162        };
163        self.set_size(app, size);
164    }
165
166    /// Calculate the size the proxy box would have when it has no child.
167    fn compute_size_for_no_child(
168        self: RenderHandle<Self>,
169        _app: &App,
170        constraints: BoxConstraints,
171    ) -> Size {
172        constraints.smallest()
173    }
174
175    /// Hit tests the child at this box's position.
176    fn hit_test_children(
177        self: RenderHandle<Self>,
178        app: &mut App,
179        result: &mut BoxHitTestResult<'_>,
180        position: Offset,
181    ) -> bool {
182        match self.child(app) {
183            Some(child) => child.hit_test(app, result, position),
184            None => false,
185        }
186    }
187
188    /// Paints the child at this box's offset.
189    fn paint(
190        self: RenderHandle<Self>,
191        app: &mut App,
192        context: &mut PaintingContext,
193        offset: Offset,
194    ) {
195        let Some(child) = self.child(app) else {
196            return;
197        };
198        context.paint_child(app, child.as_object(), offset);
199    }
200}
201
202/// A [`RenderProxyBoxMixin`] that allows customizing its hit-test behavior.
203///
204/// Flutter's `RenderProxyBoxWithHitTestBehavior`. A leaf stores the [`HitTestBehavior`] and
205/// wires `hit_test` / `hit_test_self` to these.
206pub trait RenderProxyBoxWithHitTestBehavior: RenderProxyBoxMixin {
207    /// How to behave during hit testing when deciding how the hit test propagates to children
208    /// and whether to consider targets behind this one.
209    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior;
210
211    /// Flutter's `hitTest`: a translucent box is added even when nothing was hit.
212    fn hit_test(
213        self: RenderHandle<Self>,
214        app: &mut App,
215        result: &mut BoxHitTestResult<'_>,
216        position: Offset,
217    ) -> bool {
218        let mut hit_target = false;
219        if self.size(app).contains(position) {
220            hit_target = RenderBox::hit_test_children(self, app, result, position)
221                || RenderBox::hit_test_self(self, app, position);
222            if hit_target || self.behavior(app) == HitTestBehavior::Translucent {
223                result.add(BoxHitTestEntry::new(self.as_box(), position).into());
224            }
225        }
226        hit_target
227    }
228
229    /// Flutter's `hitTestSelf`: an opaque box is hit by itself.
230    fn hit_test_self(self: RenderHandle<Self>, app: &App, _position: Offset) -> bool {
231        self.behavior(app) == HitTestBehavior::Opaque
232    }
233}
234
235/// How to behave during hit tests.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub enum HitTestBehavior {
238    /// Targets that defer to their children receive events within their bounds
239    /// only if one of their children is hit by the hit test.
240    DeferToChild,
241
242    /// Opaque targets can be hit by hit tests, causing them to both receive
243    /// events within their bounds and prevent targets visually behind them from
244    /// also receiving events.
245    Opaque,
246
247    /// Translucent targets both receive events within their bounds and permit
248    /// targets visually behind them to also receive events.
249    Translucent,
250}
251
252/// Flutter's `RenderConstrainedBox` fields.
253pub struct RenderConstrainedBoxData {
254    additional_constraints: BoxConstraints,
255}
256
257impl RenderConstrainedBoxData {
258    /// Dart's constructor: `additional_constraints` must be valid.
259    pub fn new(additional_constraints: BoxConstraints) -> RenderConstrainedBoxData {
260        debug_assert!(additional_constraints.debug_assert_is_valid(false));
261        RenderConstrainedBoxData {
262            additional_constraints,
263        }
264    }
265}
266
267/// Flutter's `RenderConstrainedBox` bodies. [`RenderConstrainedBox`] is the plain leaf; a Dart
268/// subclass (`cupertino_ui`'s `_RenderCupertinoSlider`) is a leaf that implements this trait too
269/// and overrides what Dart's subclass overrides.
270///
271/// A leaf calls [`perform_layout`](Self::perform_layout), the intrinsics,
272/// [`compute_dry_baseline`](Self::compute_dry_baseline) and
273/// [`compute_dry_layout`](Self::compute_dry_layout) from its [`RenderObject`] and [`RenderBox`]
274/// impls, where Dart inherits them.
275pub trait RenderConstrainedBoxBase: RenderProxyBoxMixin {
276    /// Base class field access.
277    fn constrained_box_data(self: RenderHandle<Self>, app: &App) -> &RenderConstrainedBoxData;
278
279    /// See [`constrained_box_data`](Self::constrained_box_data).
280    fn constrained_box_data_mut(
281        self: RenderHandle<Self>,
282        app: &mut App,
283    ) -> &mut RenderConstrainedBoxData;
284
285    /// Additional constraints to apply to the child during layout.
286    fn additional_constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
287        self.constrained_box_data(app).additional_constraints
288    }
289
290    /// Sets [`additional_constraints`](Self::additional_constraints).
291    fn set_additional_constraints(self: RenderHandle<Self>, app: &mut App, value: BoxConstraints) {
292        debug_assert!(value.debug_assert_is_valid(false));
293        if self.constrained_box_data(app).additional_constraints == value {
294            return;
295        }
296        self.constrained_box_data_mut(app).additional_constraints = value;
297        self.mark_needs_layout(app);
298    }
299
300    /// Flutter's `computeMinIntrinsicWidth` override.
301    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
302        let additional = self.additional_constraints(app);
303        if additional.has_bounded_width() && additional.has_tight_width() {
304            return additional.min_width;
305        }
306        let width = RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height);
307        debug_assert!(width.is_finite());
308        if !additional.has_infinite_width() {
309            return additional.constrain_width(width);
310        }
311        width
312    }
313
314    /// Flutter's `computeMaxIntrinsicWidth` override.
315    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
316        let additional = self.additional_constraints(app);
317        if additional.has_bounded_width() && additional.has_tight_width() {
318            return additional.min_width;
319        }
320        let width = RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height);
321        debug_assert!(width.is_finite());
322        if !additional.has_infinite_width() {
323            return additional.constrain_width(width);
324        }
325        width
326    }
327
328    /// Flutter's `computeMinIntrinsicHeight` override.
329    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
330        let additional = self.additional_constraints(app);
331        if additional.has_bounded_height() && additional.has_tight_height() {
332            return additional.min_height;
333        }
334        let height = RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width);
335        debug_assert!(height.is_finite());
336        if !additional.has_infinite_height() {
337            return additional.constrain_height(height);
338        }
339        height
340    }
341
342    /// Flutter's `computeMaxIntrinsicHeight` override.
343    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
344        let additional = self.additional_constraints(app);
345        if additional.has_bounded_height() && additional.has_tight_height() {
346            return additional.min_height;
347        }
348        let height = RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width);
349        debug_assert!(height.is_finite());
350        if !additional.has_infinite_height() {
351            return additional.constrain_height(height);
352        }
353        height
354    }
355
356    /// Flutter's `computeDryBaseline` override.
357    fn compute_dry_baseline(
358        self: RenderHandle<Self>,
359        app: &mut App,
360        constraints: BoxConstraints,
361        baseline: TextBaseline,
362    ) -> Option<f64> {
363        let additional = self.additional_constraints(app);
364        self.child(app).and_then(|child| {
365            child.get_dry_baseline(app, additional.enforce(constraints), baseline)
366        })
367    }
368
369    /// Flutter's `performLayout` override.
370    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
371        let constraints = self.constraints(app);
372        let additional = self.additional_constraints(app);
373        if let Some(child) = self.child(app) {
374            child.layout(app, additional.enforce(constraints), true);
375            self.set_size(app, child.size(app));
376        } else {
377            self.set_size(app, additional.enforce(constraints).constrain(Size::ZERO));
378        }
379    }
380
381    /// Flutter's `computeDryLayout` override.
382    fn compute_dry_layout(
383        self: RenderHandle<Self>,
384        app: &mut App,
385        constraints: BoxConstraints,
386    ) -> Size {
387        let additional = self.additional_constraints(app);
388        match self.child(app) {
389            Some(child) => child.get_dry_layout(app, additional.enforce(constraints)),
390            None => additional.enforce(constraints).constrain(Size::ZERO),
391        }
392    }
393}
394
395/// Imposes additional constraints on its child.
396///
397/// Its members are [`RenderConstrainedBoxBase`]'s.
398pub struct RenderConstrainedBox {
399    render_object: RenderObjectData,
400    render_box: RenderBoxData,
401    child: RenderObjectWithChildData<AnyRenderBox>,
402    constrained_box: RenderConstrainedBoxData,
403}
404
405impl RenderConstrainedBox {
406    /// Creates a render box that constrains its child.
407    ///
408    /// `additional_constraints` must be valid.
409    pub fn new(
410        app: &mut App,
411        additional_constraints: BoxConstraints,
412        child: Option<AnyRenderBox>,
413    ) -> RenderHandle<RenderConstrainedBox> {
414        let this = RenderHandle::new_box(
415            app,
416            RenderConstrainedBox {
417                render_object: RenderObjectData::new(),
418                render_box: RenderBoxData::new(),
419                child: RenderObjectWithChildData::new(),
420                constrained_box: RenderConstrainedBoxData::new(additional_constraints),
421            },
422        );
423        this.set_child(app, child);
424        this
425    }
426}
427
428impl RenderConstrainedBoxBase for RenderConstrainedBox {
429    fn constrained_box_data(self: RenderHandle<Self>, app: &App) -> &RenderConstrainedBoxData {
430        &self.get(app).constrained_box
431    }
432
433    fn constrained_box_data_mut(
434        self: RenderHandle<Self>,
435        app: &mut App,
436    ) -> &mut RenderConstrainedBoxData {
437        &mut self.get_mut(app).constrained_box
438    }
439}
440
441impl RenderObjectWithChildMixin for RenderConstrainedBox {
442    type ChildType = AnyRenderBox;
443
444    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
445        &self.get(app).child
446    }
447
448    fn child_data_mut(
449        self: RenderHandle<Self>,
450        app: &mut App,
451    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
452        &mut self.get_mut(app).child
453    }
454}
455
456impl RenderProxyBoxMixin for RenderConstrainedBox {}
457
458impl RenderObject for RenderConstrainedBox {
459    crate::render_object_accessors!();
460
461    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
462        RenderConstrainedBoxBase::perform_layout(self, app);
463    }
464
465    fn paint(
466        self: RenderHandle<Self>,
467        app: &mut App,
468        context: &mut PaintingContext,
469        offset: Offset,
470    ) {
471        RenderProxyBoxMixin::paint(self, app, context, offset);
472    }
473
474    fn visit_children(
475        self: RenderHandle<Self>,
476        app: &App,
477        visitor: &mut dyn FnMut(AnyRenderObject),
478    ) {
479        if let Some(child) = self.child(app) {
480            visitor(child.as_object());
481        }
482    }
483}
484
485impl RenderBox for RenderConstrainedBox {
486    crate::render_box_accessors!();
487
488    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
489        RenderProxyBoxMixin::setup_parent_data(self, app, child);
490    }
491
492    fn apply_paint_transform(
493        self: RenderHandle<Self>,
494        app: &App,
495        child: AnyRenderObject,
496        transform: &mut Matrix4,
497    ) {
498        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
499    }
500
501    fn hit_test_children(
502        self: RenderHandle<Self>,
503        app: &mut App,
504        result: &mut BoxHitTestResult<'_>,
505        position: Offset,
506    ) -> bool {
507        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
508    }
509
510    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
511        RenderConstrainedBoxBase::compute_min_intrinsic_width(self, app, height)
512    }
513
514    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
515        RenderConstrainedBoxBase::compute_max_intrinsic_width(self, app, height)
516    }
517
518    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
519        RenderConstrainedBoxBase::compute_min_intrinsic_height(self, app, width)
520    }
521
522    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
523        RenderConstrainedBoxBase::compute_max_intrinsic_height(self, app, width)
524    }
525
526    fn compute_distance_to_actual_baseline(
527        self: RenderHandle<Self>,
528        app: &mut App,
529        baseline: TextBaseline,
530    ) -> Option<f64> {
531        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
532    }
533
534    fn compute_dry_baseline(
535        self: RenderHandle<Self>,
536        app: &mut App,
537        constraints: BoxConstraints,
538        baseline: TextBaseline,
539    ) -> Option<f64> {
540        RenderConstrainedBoxBase::compute_dry_baseline(self, app, constraints, baseline)
541    }
542
543    fn compute_dry_layout(
544        self: RenderHandle<Self>,
545        app: &mut App,
546        constraints: BoxConstraints,
547    ) -> Size {
548        RenderConstrainedBoxBase::compute_dry_layout(self, app, constraints)
549    }
550}
551
552/// Makes its child partially transparent.
553///
554/// This class paints its child into an intermediate buffer and then blends the
555/// child back into the scene partially transparent.
556///
557/// For values of opacity other than 0.0 and 1.0, this class is relatively
558/// expensive because it requires painting the child into an intermediate
559/// buffer. For the value 0.0, the child is not painted at all. For the
560/// value 1.0, the child is painted immediately without an intermediate buffer.
561pub struct RenderOpacity {
562    render_object: RenderObjectData,
563    render_box: RenderBoxData,
564    child: RenderObjectWithChildData<AnyRenderBox>,
565    alpha: i32,
566    opacity: f64,
567}
568
569impl RenderOpacity {
570    /// Creates a partially transparent render object.
571    ///
572    /// The `opacity` argument must be between 0.0 and 1.0, inclusive.
573    pub fn new(app: &mut App, opacity: f64, child: Option<AnyRenderBox>) -> RenderHandle<Self> {
574        debug_assert!((0.0..=1.0).contains(&opacity));
575        let this = RenderHandle::new_box(
576            app,
577            RenderOpacity {
578                render_object: RenderObjectData::new(),
579                render_box: RenderBoxData::new(),
580                child: RenderObjectWithChildData::new(),
581                alpha: Color::get_alpha_from_opacity(opacity),
582                opacity,
583            },
584        );
585        this.set_child(app, child);
586        this
587    }
588
589    /// The fraction to scale the child's alpha value.
590    ///
591    /// An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent
592    /// (i.e., invisible).
593    ///
594    /// Values 1.0 and 0.0 are painted with a fast path. Other values
595    /// require painting the child into an intermediate buffer, which is
596    /// expensive.
597    pub fn opacity(self: RenderHandle<Self>, app: &App) -> f64 {
598        self.get(app).opacity
599    }
600
601    /// Sets [`opacity`](Self::opacity).
602    pub fn set_opacity(self: RenderHandle<Self>, app: &mut App, value: f64) {
603        debug_assert!((0.0..=1.0).contains(&value));
604        if self.get(app).opacity == value {
605            return;
606        }
607        let did_need_compositing = self.always_needs_compositing(app);
608        let this = self.get_mut(app);
609        this.opacity = value;
610        this.alpha = Color::get_alpha_from_opacity(value);
611        if did_need_compositing != self.always_needs_compositing(app) {
612            self.mark_needs_compositing_bits_update(app);
613        }
614        self.mark_needs_composited_layer_update(app);
615    }
616}
617
618impl RenderObjectWithChildMixin for RenderOpacity {
619    type ChildType = AnyRenderBox;
620
621    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
622        &self.get(app).child
623    }
624
625    fn child_data_mut(
626        self: RenderHandle<Self>,
627        app: &mut App,
628    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
629        &mut self.get_mut(app).child
630    }
631}
632
633impl RenderProxyBoxMixin for RenderOpacity {}
634
635impl RenderObject for RenderOpacity {
636    crate::render_object_accessors!();
637
638    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
639        self.child(app).is_some() && self.get(app).alpha > 0
640    }
641
642    fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
643        self.always_needs_compositing(app)
644    }
645
646    fn update_composited_layer(
647        self: RenderHandle<Self>,
648        app: &mut App,
649        old_layer: Option<crate::AnyOffsetLayer>,
650    ) -> crate::AnyOffsetLayer {
651        let layer = match old_layer {
652            Some(old) => app
653                .handle::<OpacityLayer>(old.id())
654                .expect("RenderOpacity reuses an OpacityLayer"),
655            None => OpacityLayer::new(app),
656        };
657        layer.set_alpha(app, self.get(app).alpha);
658        layer.as_offset_layer()
659    }
660
661    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
662        debug_assert!(child.parent(app) == Some(self.as_object()));
663        self.get(app).alpha > 0
664    }
665
666    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
667        RenderProxyBoxMixin::perform_layout(self, app);
668    }
669
670    fn paint(
671        self: RenderHandle<Self>,
672        app: &mut App,
673        context: &mut PaintingContext,
674        offset: Offset,
675    ) {
676        if self.child(app).is_none() || self.get(app).alpha == 0 {
677            return;
678        }
679        RenderProxyBoxMixin::paint(self, app, context, offset);
680    }
681
682    fn visit_children(
683        self: RenderHandle<Self>,
684        app: &App,
685        visitor: &mut dyn FnMut(AnyRenderObject),
686    ) {
687        if let Some(child) = self.child(app) {
688            visitor(child.as_object());
689        }
690    }
691}
692
693impl RenderBox for RenderOpacity {
694    crate::render_box_accessors!();
695
696    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
697        RenderProxyBoxMixin::setup_parent_data(self, app, child);
698    }
699
700    fn apply_paint_transform(
701        self: RenderHandle<Self>,
702        app: &App,
703        child: AnyRenderObject,
704        transform: &mut Matrix4,
705    ) {
706        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
707    }
708
709    fn hit_test_children(
710        self: RenderHandle<Self>,
711        app: &mut App,
712        result: &mut BoxHitTestResult<'_>,
713        position: Offset,
714    ) -> bool {
715        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
716    }
717
718    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
719        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
720    }
721
722    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
723        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
724    }
725
726    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
727        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
728    }
729
730    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
731        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
732    }
733
734    fn compute_distance_to_actual_baseline(
735        self: RenderHandle<Self>,
736        app: &mut App,
737        baseline: TextBaseline,
738    ) -> Option<f64> {
739        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
740    }
741
742    fn compute_dry_baseline(
743        self: RenderHandle<Self>,
744        app: &mut App,
745        constraints: BoxConstraints,
746        baseline: TextBaseline,
747    ) -> Option<f64> {
748        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
749    }
750
751    fn compute_dry_layout(
752        self: RenderHandle<Self>,
753        app: &mut App,
754        constraints: BoxConstraints,
755    ) -> Size {
756        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
757    }
758}
759
760/// Provides an anchor for a [`RenderFollowerLayer`].
761///
762/// Flutter's `RenderLeaderLayer`: paints its child through a leader item that records where the
763/// child lands for the link's followers.
764pub struct RenderLeaderLayer {
765    render_object: RenderObjectData,
766    render_box: RenderBoxData,
767    child: RenderObjectWithChildData<AnyRenderBox>,
768    link: Ref<LayerLink>,
769    /// The size of the last layout, which `link.leader_size` reports.
770    previous_layout_size: Option<Size>,
771}
772
773impl RenderLeaderLayer {
774    pub fn new(
775        app: &mut App,
776        link: Ref<LayerLink>,
777        child: Option<AnyRenderBox>,
778    ) -> RenderHandle<Self> {
779        let this = RenderHandle::new_box(
780            app,
781            RenderLeaderLayer {
782                render_object: RenderObjectData::new(),
783                render_box: RenderBoxData::new(),
784                child: RenderObjectWithChildData::new(),
785                link,
786                previous_layout_size: None,
787            },
788        );
789        this.set_child(app, child);
790        this
791    }
792
793    /// The link object that connects this [`RenderLeaderLayer`] with one or more
794    /// [`RenderFollowerLayer`]s.
795    pub fn link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
796        self.get(app).link.handle()
797    }
798
799    /// Sets [`link`](Self::link).
800    pub fn set_link(self: RenderHandle<Self>, app: &mut App, value: Ref<LayerLink>) {
801        let link = self.link(app);
802        if link == value {
803            return;
804        }
805        let old = app.get_mut(link);
806        old.leader_size = None;
807        let new = value.handle();
808        self.get_mut(app).link = value;
809        if let Some(size) = self.get(app).previous_layout_size {
810            app.get_mut(new).leader_size = Some(size);
811        }
812        self.mark_needs_paint(app);
813    }
814}
815
816impl RenderObjectWithChildMixin for RenderLeaderLayer {
817    type ChildType = AnyRenderBox;
818
819    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
820        &self.get(app).child
821    }
822
823    fn child_data_mut(
824        self: RenderHandle<Self>,
825        app: &mut App,
826    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
827        &mut self.get_mut(app).child
828    }
829}
830
831impl RenderProxyBoxMixin for RenderLeaderLayer {}
832
833impl RenderObject for RenderLeaderLayer {
834    crate::render_object_accessors!();
835
836    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
837        true
838    }
839
840    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
841        RenderProxyBoxMixin::perform_layout(self, app);
842        let size = self.size(app);
843        self.get_mut(app).previous_layout_size = Some(size);
844        let link = self.link(app);
845        app.get_mut(link).leader_size = Some(size);
846    }
847
848    fn paint(
849        self: RenderHandle<Self>,
850        app: &mut App,
851        context: &mut PaintingContext,
852        offset: Offset,
853    ) {
854        let link = self.get(app).link.clone();
855        let layer = match self.as_object().layer_as::<LeaderLayer>(app) {
856            None => {
857                let layer = LeaderLayer::new(app, link);
858                layer.set_offset(app, offset);
859                self.as_object()
860                    .set_layer(app, Some(layer.as_container_layer()));
861                layer
862            }
863            Some(layer) => {
864                layer.set_link(app, link);
865                layer.set_offset(app, offset);
866                layer
867            }
868        };
869        context.push_layer(
870            app,
871            layer.as_container_layer(),
872            |app, context, offset| {
873                RenderProxyBoxMixin::paint(self, app, context, offset);
874            },
875            Offset::ZERO,
876            None,
877        );
878    }
879
880    fn visit_children(
881        self: RenderHandle<Self>,
882        app: &App,
883        visitor: &mut dyn FnMut(AnyRenderObject),
884    ) {
885        if let Some(child) = self.child(app) {
886            visitor(child.as_object());
887        }
888    }
889}
890
891impl RenderBox for RenderLeaderLayer {
892    crate::render_box_accessors!();
893
894    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
895        RenderProxyBoxMixin::setup_parent_data(self, app, child);
896    }
897
898    fn apply_paint_transform(
899        self: RenderHandle<Self>,
900        app: &App,
901        child: AnyRenderObject,
902        transform: &mut Matrix4,
903    ) {
904        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
905    }
906
907    fn hit_test_children(
908        self: RenderHandle<Self>,
909        app: &mut App,
910        result: &mut BoxHitTestResult<'_>,
911        position: Offset,
912    ) -> bool {
913        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
914    }
915
916    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
917        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
918    }
919
920    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
921        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
922    }
923
924    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
925        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
926    }
927
928    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
929        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
930    }
931
932    fn compute_distance_to_actual_baseline(
933        self: RenderHandle<Self>,
934        app: &mut App,
935        baseline: TextBaseline,
936    ) -> Option<f64> {
937        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
938    }
939
940    fn compute_dry_baseline(
941        self: RenderHandle<Self>,
942        app: &mut App,
943        constraints: BoxConstraints,
944        baseline: TextBaseline,
945    ) -> Option<f64> {
946        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
947    }
948
949    fn compute_dry_layout(
950        self: RenderHandle<Self>,
951        app: &mut App,
952        constraints: BoxConstraints,
953    ) -> Size {
954        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
955    }
956}
957
958/// Transforms its child using a transform matrix computed at composite time from the link's
959/// [`RenderLeaderLayer`]: the child paints where the leader is, whatever lies between them.
960///
961/// Flutter's `RenderFollowerLayer`.
962pub struct RenderFollowerLayer {
963    render_object: RenderObjectData,
964    render_box: RenderBoxData,
965    child: RenderObjectWithChildData<AnyRenderBox>,
966    link: Ref<LayerLink>,
967    show_when_unlinked: bool,
968    offset: Offset,
969    leader_anchor: Alignment,
970    follower_anchor: Alignment,
971}
972
973impl RenderFollowerLayer {
974    pub fn new(
975        app: &mut App,
976        link: Ref<LayerLink>,
977        show_when_unlinked: bool,
978        offset: Offset,
979        leader_anchor: Alignment,
980        follower_anchor: Alignment,
981        child: Option<AnyRenderBox>,
982    ) -> RenderHandle<Self> {
983        let this = RenderHandle::new_box(
984            app,
985            RenderFollowerLayer {
986                render_object: RenderObjectData::new(),
987                render_box: RenderBoxData::new(),
988                child: RenderObjectWithChildData::new(),
989                link,
990                show_when_unlinked,
991                offset,
992                leader_anchor,
993                follower_anchor,
994            },
995        );
996        this.set_child(app, child);
997        this
998    }
999
1000    /// The link object that connects this [`RenderFollowerLayer`] with a [`RenderLeaderLayer`].
1001    pub fn link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
1002        self.get(app).link.handle()
1003    }
1004
1005    /// Sets [`link`](Self::link).
1006    pub fn set_link(self: RenderHandle<Self>, app: &mut App, value: Ref<LayerLink>) {
1007        if self.get(app).link == value {
1008            return;
1009        }
1010        self.get_mut(app).link = value;
1011        self.mark_needs_paint(app);
1012    }
1013
1014    /// Whether to show the render object's contents when there is no corresponding
1015    /// [`RenderLeaderLayer`].
1016    pub fn show_when_unlinked(self: RenderHandle<Self>, app: &App) -> bool {
1017        self.get(app).show_when_unlinked
1018    }
1019
1020    /// Sets [`show_when_unlinked`](Self::show_when_unlinked).
1021    pub fn set_show_when_unlinked(self: RenderHandle<Self>, app: &mut App, value: bool) {
1022        if self.get(app).show_when_unlinked == value {
1023            return;
1024        }
1025        self.get_mut(app).show_when_unlinked = value;
1026        self.mark_needs_paint(app);
1027    }
1028
1029    /// The offset to apply to the origin of the linked [`RenderLeaderLayer`] to obtain this
1030    /// render object's origin.
1031    pub fn offset(self: RenderHandle<Self>, app: &App) -> Offset {
1032        self.get(app).offset
1033    }
1034
1035    /// Sets [`offset`](Self::offset).
1036    pub fn set_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
1037        if self.get(app).offset == value {
1038            return;
1039        }
1040        self.get_mut(app).offset = value;
1041        self.mark_needs_paint(app);
1042    }
1043
1044    /// The anchor point on the linked [`RenderLeaderLayer`] that [`follower_anchor`] lines up
1045    /// with.
1046    ///
1047    /// [`follower_anchor`]: Self::follower_anchor
1048    pub fn leader_anchor(self: RenderHandle<Self>, app: &App) -> Alignment {
1049        self.get(app).leader_anchor
1050    }
1051
1052    /// Sets [`leader_anchor`](Self::leader_anchor).
1053    pub fn set_leader_anchor(self: RenderHandle<Self>, app: &mut App, value: Alignment) {
1054        if self.get(app).leader_anchor == value {
1055            return;
1056        }
1057        self.get_mut(app).leader_anchor = value;
1058        self.mark_needs_paint(app);
1059    }
1060
1061    /// The anchor point on this render object that lines up with [`leader_anchor`].
1062    ///
1063    /// [`leader_anchor`]: Self::leader_anchor
1064    pub fn follower_anchor(self: RenderHandle<Self>, app: &App) -> Alignment {
1065        self.get(app).follower_anchor
1066    }
1067
1068    /// Sets [`follower_anchor`](Self::follower_anchor).
1069    pub fn set_follower_anchor(self: RenderHandle<Self>, app: &mut App, value: Alignment) {
1070        if self.get(app).follower_anchor == value {
1071            return;
1072        }
1073        self.get_mut(app).follower_anchor = value;
1074        self.mark_needs_paint(app);
1075    }
1076
1077    /// The transform that was used during the last composite, from this render object's
1078    /// children to its own coordinates, or the identity when there was none.
1079    ///
1080    /// Flutter's `getCurrentTransform`.
1081    pub fn current_transform(self: RenderHandle<Self>, app: &App) -> Matrix4 {
1082        self.as_object()
1083            .layer_as::<FollowerLayer>(app)
1084            .and_then(|layer| layer.get_last_transform(app))
1085            .unwrap_or(Matrix4::IDENTITY)
1086    }
1087}
1088
1089impl RenderObjectWithChildMixin for RenderFollowerLayer {
1090    type ChildType = AnyRenderBox;
1091
1092    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1093        &self.get(app).child
1094    }
1095
1096    fn child_data_mut(
1097        self: RenderHandle<Self>,
1098        app: &mut App,
1099    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1100        &mut self.get_mut(app).child
1101    }
1102}
1103
1104impl RenderProxyBoxMixin for RenderFollowerLayer {}
1105
1106impl RenderObject for RenderFollowerLayer {
1107    crate::render_object_accessors!();
1108
1109    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
1110        true
1111    }
1112
1113    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1114        RenderProxyBoxMixin::perform_layout(self, app);
1115    }
1116
1117    /// Flutter's `detach`: `layer = null`.
1118    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1119        self.as_object().set_layer(app, None);
1120        if let Some(child) = self.child(app) {
1121            child.as_object().detach(app);
1122        }
1123    }
1124
1125    fn paint(
1126        self: RenderHandle<Self>,
1127        app: &mut App,
1128        context: &mut PaintingContext,
1129        offset: Offset,
1130    ) {
1131        let link = self.get(app).link.clone();
1132        let leader_size = app.get(&link).leader_size;
1133        debug_assert!(
1134            leader_size.is_some()
1135                || link.leader(app).is_none()
1136                || self.get(app).leader_anchor == Alignment::TOP_LEFT,
1137            "a leader size is required when leader_anchor is not Alignment::TOP_LEFT"
1138        );
1139        let this = self.get(app);
1140        let effective_linked_offset = match leader_size {
1141            None => this.offset,
1142            Some(leader_size) => {
1143                this.leader_anchor.along_size(leader_size)
1144                    - this.follower_anchor.along_size(self.size(app))
1145                    + this.offset
1146            }
1147        };
1148        let show_when_unlinked = this.show_when_unlinked;
1149        let layer = match self.as_object().layer_as::<FollowerLayer>(app) {
1150            None => {
1151                let layer = FollowerLayer::new(app, link);
1152                layer.set_show_when_unlinked(app, show_when_unlinked);
1153                layer.set_linked_offset(app, effective_linked_offset);
1154                layer.set_unlinked_offset(app, offset);
1155                self.as_object()
1156                    .set_layer(app, Some(layer.as_container_layer()));
1157                layer
1158            }
1159            Some(layer) => {
1160                layer.set_link(app, link);
1161                layer.set_show_when_unlinked(app, show_when_unlinked);
1162                layer.set_linked_offset(app, effective_linked_offset);
1163                layer.set_unlinked_offset(app, offset);
1164                layer
1165            }
1166        };
1167        context.push_layer(
1168            app,
1169            layer.as_container_layer(),
1170            |app, context, offset| {
1171                RenderProxyBoxMixin::paint(self, app, context, offset);
1172            },
1173            Offset::ZERO,
1174            Some(Rect::from_ltrb(
1175                f64::NEG_INFINITY,
1176                f64::NEG_INFINITY,
1177                f64::INFINITY,
1178                f64::INFINITY,
1179            )),
1180        );
1181    }
1182
1183    fn visit_children(
1184        self: RenderHandle<Self>,
1185        app: &App,
1186        visitor: &mut dyn FnMut(AnyRenderObject),
1187    ) {
1188        if let Some(child) = self.child(app) {
1189            visitor(child.as_object());
1190        }
1191    }
1192}
1193
1194impl RenderBox for RenderFollowerLayer {
1195    crate::render_box_accessors!();
1196
1197    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1198        RenderProxyBoxMixin::setup_parent_data(self, app, child);
1199    }
1200
1201    fn apply_paint_transform(
1202        self: RenderHandle<Self>,
1203        app: &App,
1204        _child: AnyRenderObject,
1205        transform: &mut Matrix4,
1206    ) {
1207        *transform = transform.then(&self.current_transform(app));
1208    }
1209
1210    /// Disables the hit testing if this render object is hidden. A follower does not check
1211    /// whether it is itself hit: the untransformed size and the child's transformed position
1212    /// do not relate.
1213    fn hit_test(
1214        self: RenderHandle<Self>,
1215        app: &mut App,
1216        result: &mut BoxHitTestResult<'_>,
1217        position: Offset,
1218    ) -> bool {
1219        let link = self.get(app).link.handle();
1220        if link.leader(app).is_none() && !self.get(app).show_when_unlinked {
1221            return false;
1222        }
1223        RenderBox::hit_test_children(self, app, result, position)
1224    }
1225
1226    fn hit_test_children(
1227        self: RenderHandle<Self>,
1228        app: &mut App,
1229        result: &mut BoxHitTestResult<'_>,
1230        position: Offset,
1231    ) -> bool {
1232        let transform = self.current_transform(app);
1233        result.add_with_paint_transform(Some(transform), position, |result, position| {
1234            RenderProxyBoxMixin::hit_test_children(self, app, result, position)
1235        })
1236    }
1237
1238    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1239        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
1240    }
1241
1242    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1243        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
1244    }
1245
1246    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1247        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
1248    }
1249
1250    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1251        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
1252    }
1253
1254    fn compute_distance_to_actual_baseline(
1255        self: RenderHandle<Self>,
1256        app: &mut App,
1257        baseline: TextBaseline,
1258    ) -> Option<f64> {
1259        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
1260    }
1261
1262    fn compute_dry_baseline(
1263        self: RenderHandle<Self>,
1264        app: &mut App,
1265        constraints: BoxConstraints,
1266        baseline: TextBaseline,
1267    ) -> Option<f64> {
1268        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
1269    }
1270
1271    fn compute_dry_layout(
1272        self: RenderHandle<Self>,
1273        app: &mut App,
1274        constraints: BoxConstraints,
1275    ) -> Size {
1276        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
1277    }
1278}
1279
1280/// The mixin fields of [`RenderAnimatedOpacityMixin`].
1281pub struct RenderAnimatedOpacityData {
1282    alpha: Option<i32>,
1283    currently_is_repaint_boundary: Option<bool>,
1284    opacity: Option<AnimationRef<f64>>,
1285}
1286
1287impl RenderAnimatedOpacityData {
1288    /// No animation yet; the host sets one in its constructor.
1289    pub const fn new() -> RenderAnimatedOpacityData {
1290        RenderAnimatedOpacityData {
1291            alpha: None,
1292            currently_is_repaint_boundary: None,
1293            opacity: None,
1294        }
1295    }
1296}
1297
1298impl Default for RenderAnimatedOpacityData {
1299    fn default() -> RenderAnimatedOpacityData {
1300        RenderAnimatedOpacityData::new()
1301    }
1302}
1303
1304/// Implementation of [`RenderAnimatedOpacity`] and `RenderSliverAnimatedOpacity`.
1305///
1306/// This mixin allows the logic of animating opacity to be used with different
1307/// layout models, e.g. the way that [`RenderAnimatedOpacity`] uses it for
1308/// [`RenderBox`] and `RenderSliverAnimatedOpacity` uses it for `RenderSliver`.
1309///
1310/// The host wires the virtuals: `is_repaint_boundary`, `update_composited_layer`,
1311/// `paints_child`, `did_attach`, `did_detach`, and `paint` call the same-named functions here.
1312pub trait RenderAnimatedOpacityMixin:
1313    RenderObjectWithChildMixin<ChildType = AnyRenderBox> + RenderBox
1314{
1315    /// Mixin field access.
1316    fn animated_opacity_data(self: RenderHandle<Self>, app: &App) -> &RenderAnimatedOpacityData;
1317
1318    /// See [`animated_opacity_data`](Self::animated_opacity_data).
1319    fn animated_opacity_data_mut(
1320        self: RenderHandle<Self>,
1321        app: &mut App,
1322    ) -> &mut RenderAnimatedOpacityData;
1323
1324    /// Flutter's `isRepaintBoundary`.
1325    fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
1326        self.child(app).is_some()
1327            && self
1328                .animated_opacity_data(app)
1329                .currently_is_repaint_boundary
1330                .expect("set by the opacity setter")
1331    }
1332
1333    /// Flutter's `updateCompositedLayer`.
1334    fn update_composited_layer(
1335        self: RenderHandle<Self>,
1336        app: &mut App,
1337        old_layer: Option<crate::AnyOffsetLayer>,
1338    ) -> crate::AnyOffsetLayer {
1339        let alpha = self
1340            .animated_opacity_data(app)
1341            .alpha
1342            .expect("set by the opacity setter");
1343        let layer = match old_layer {
1344            Some(old) => app
1345                .handle::<OpacityLayer>(old.id())
1346                .expect("RenderAnimatedOpacity reuses an OpacityLayer"),
1347            None => OpacityLayer::new(app),
1348        };
1349        layer.set_alpha(app, alpha);
1350        layer.as_offset_layer()
1351    }
1352
1353    /// The animation that drives this render object's opacity.
1354    ///
1355    /// An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent
1356    /// (i.e., invisible).
1357    fn opacity(self: RenderHandle<Self>, app: &App) -> AnyAnimation<f64> {
1358        self.animated_opacity_data(app)
1359            .opacity
1360            .handle()
1361            .expect("set by the constructor")
1362    }
1363
1364    /// Sets [`opacity`](Self::opacity).
1365    fn set_opacity(self: RenderHandle<Self>, app: &mut App, value: AnimationRef<f64>) {
1366        if self.animated_opacity_data(app).opacity.as_ref() == Some(&value) {
1367            return;
1368        }
1369        if self.attached(app)
1370            && let Some(opacity) = self.animated_opacity_data(app).opacity.handle()
1371        {
1372            opacity.remove_listener(app, &self.opacity_listener());
1373        }
1374        let new = value.handle();
1375        // The old animation goes when this local does, after the listener moved off it.
1376        let _old = self.animated_opacity_data_mut(app).opacity.replace(value);
1377        if self.attached(app) {
1378            new.add_listener(app, self.opacity_listener());
1379        }
1380        self.update_opacity(app);
1381    }
1382
1383    /// Flutter's `attach` after `super.attach(owner)`.
1384    fn did_attach(self: RenderHandle<Self>, app: &mut App) {
1385        self.opacity(app).add_listener(app, self.opacity_listener());
1386        self.update_opacity(app); // in case it changed while we weren't listening
1387    }
1388
1389    /// Flutter's `detach` before `super.detach()`.
1390    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1391        self.opacity(app)
1392            .remove_listener(app, &self.opacity_listener());
1393    }
1394
1395    /// The `_updateOpacity` tear-off, equal to itself across registrations.
1396    fn opacity_listener(self: RenderHandle<Self>) -> Listener {
1397        Listener::handle_method(self.handle(), update_opacity::<Self>)
1398    }
1399
1400    /// Flutter's `_updateOpacity`.
1401    fn update_opacity(self: RenderHandle<Self>, app: &mut App) {
1402        let old_alpha = self.animated_opacity_data(app).alpha;
1403        let alpha = Color::get_alpha_from_opacity(self.opacity(app).value(app));
1404        self.animated_opacity_data_mut(app).alpha = Some(alpha);
1405        if old_alpha != Some(alpha) {
1406            let was_repaint_boundary = self
1407                .animated_opacity_data(app)
1408                .currently_is_repaint_boundary;
1409            self.animated_opacity_data_mut(app)
1410                .currently_is_repaint_boundary = Some(alpha > 0);
1411            // Flutter: `markNeedsCompositingBitsUpdate`, whose effect on a boundary change is a repaint.
1412            if self.child(app).is_some() && was_repaint_boundary != Some(alpha > 0) {
1413                self.mark_needs_compositing_bits_update(app);
1414            }
1415            self.mark_needs_composited_layer_update(app);
1416        }
1417    }
1418
1419    /// Flutter's `paintsChild`: the child is painted while the opacity is above zero.
1420    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
1421        debug_assert!(child.parent(app) == Some(self.as_object()));
1422        self.opacity(app).value(app) > 0.0
1423    }
1424
1425    /// Flutter's `paint`: nothing when fully transparent, else the proxy paint.
1426    fn paint(self: RenderHandle<Self>, app: &mut App, context: &mut PaintingContext, offset: Offset)
1427    where
1428        Self: RenderProxyBoxMixin,
1429    {
1430        if self.animated_opacity_data(app).alpha == Some(0) {
1431            return;
1432        }
1433        RenderProxyBoxMixin::paint(self, app, context, offset);
1434    }
1435}
1436
1437fn update_opacity<T: RenderAnimatedOpacityMixin>(this: Handle<T>, app: &mut App) {
1438    RenderAnimatedOpacityMixin::update_opacity(RenderHandle::from_handle(this), app);
1439}
1440
1441/// Makes its child partially transparent, driven from an [`AnyAnimation`].
1442///
1443/// This is a variant of [`RenderOpacity`] that uses an [`AnyAnimation<f64>`]
1444/// rather than a `f64` to control the opacity.
1445pub struct RenderAnimatedOpacity {
1446    render_object: RenderObjectData,
1447    render_box: RenderBoxData,
1448    child: RenderObjectWithChildData<AnyRenderBox>,
1449    animated_opacity: RenderAnimatedOpacityData,
1450}
1451
1452impl RenderAnimatedOpacity {
1453    /// Creates a partially transparent render object.
1454    pub fn new(
1455        app: &mut App,
1456        opacity: AnimationRef<f64>,
1457        child: Option<AnyRenderBox>,
1458    ) -> RenderHandle<Self> {
1459        let this = RenderHandle::new_box(
1460            app,
1461            RenderAnimatedOpacity {
1462                render_object: RenderObjectData::new(),
1463                render_box: RenderBoxData::new(),
1464                child: RenderObjectWithChildData::new(),
1465                animated_opacity: RenderAnimatedOpacityData::new(),
1466            },
1467        );
1468        this.set_child(app, child);
1469        this.set_opacity(app, opacity);
1470        this
1471    }
1472}
1473
1474impl RenderObjectWithChildMixin for RenderAnimatedOpacity {
1475    type ChildType = AnyRenderBox;
1476
1477    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1478        &self.get(app).child
1479    }
1480
1481    fn child_data_mut(
1482        self: RenderHandle<Self>,
1483        app: &mut App,
1484    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1485        &mut self.get_mut(app).child
1486    }
1487}
1488
1489impl RenderProxyBoxMixin for RenderAnimatedOpacity {}
1490
1491impl RenderAnimatedOpacityMixin for RenderAnimatedOpacity {
1492    fn animated_opacity_data(self: RenderHandle<Self>, app: &App) -> &RenderAnimatedOpacityData {
1493        &self.get(app).animated_opacity
1494    }
1495
1496    fn animated_opacity_data_mut(
1497        self: RenderHandle<Self>,
1498        app: &mut App,
1499    ) -> &mut RenderAnimatedOpacityData {
1500        &mut self.get_mut(app).animated_opacity
1501    }
1502}
1503
1504impl RenderObject for RenderAnimatedOpacity {
1505    crate::render_object_accessors!();
1506
1507    fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
1508        RenderAnimatedOpacityMixin::is_repaint_boundary(self, app)
1509    }
1510
1511    fn update_composited_layer(
1512        self: RenderHandle<Self>,
1513        app: &mut App,
1514        old_layer: Option<crate::AnyOffsetLayer>,
1515    ) -> crate::AnyOffsetLayer {
1516        RenderAnimatedOpacityMixin::update_composited_layer(self, app, old_layer)
1517    }
1518
1519    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
1520        RenderAnimatedOpacityMixin::paints_child(self, app, child)
1521    }
1522
1523    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<crate::PipelineOwner>) {
1524        if let Some(child) = self.child(app) {
1525            child.as_object().attach(app, owner);
1526        }
1527        RenderAnimatedOpacityMixin::did_attach(self, app);
1528    }
1529
1530    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1531        RenderAnimatedOpacityMixin::did_detach(self, app);
1532        if let Some(child) = self.child(app) {
1533            child.as_object().detach(app);
1534        }
1535    }
1536
1537    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1538        RenderProxyBoxMixin::perform_layout(self, app);
1539    }
1540
1541    fn paint(
1542        self: RenderHandle<Self>,
1543        app: &mut App,
1544        context: &mut PaintingContext,
1545        offset: Offset,
1546    ) {
1547        RenderAnimatedOpacityMixin::paint(self, app, context, offset);
1548    }
1549
1550    fn visit_children(
1551        self: RenderHandle<Self>,
1552        app: &App,
1553        visitor: &mut dyn FnMut(AnyRenderObject),
1554    ) {
1555        if let Some(child) = self.child(app) {
1556            visitor(child.as_object());
1557        }
1558    }
1559}
1560
1561impl RenderBox for RenderAnimatedOpacity {
1562    crate::render_box_accessors!();
1563
1564    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1565        RenderProxyBoxMixin::setup_parent_data(self, app, child);
1566    }
1567
1568    fn apply_paint_transform(
1569        self: RenderHandle<Self>,
1570        app: &App,
1571        child: AnyRenderObject,
1572        transform: &mut Matrix4,
1573    ) {
1574        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
1575    }
1576
1577    fn hit_test_children(
1578        self: RenderHandle<Self>,
1579        app: &mut App,
1580        result: &mut BoxHitTestResult<'_>,
1581        position: Offset,
1582    ) -> bool {
1583        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
1584    }
1585
1586    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1587        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
1588    }
1589
1590    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1591        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
1592    }
1593
1594    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1595        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
1596    }
1597
1598    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1599        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
1600    }
1601
1602    fn compute_distance_to_actual_baseline(
1603        self: RenderHandle<Self>,
1604        app: &mut App,
1605        baseline: TextBaseline,
1606    ) -> Option<f64> {
1607        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
1608    }
1609
1610    fn compute_dry_baseline(
1611        self: RenderHandle<Self>,
1612        app: &mut App,
1613        constraints: BoxConstraints,
1614        baseline: TextBaseline,
1615    ) -> Option<f64> {
1616        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
1617    }
1618
1619    fn compute_dry_layout(
1620        self: RenderHandle<Self>,
1621        app: &mut App,
1622        constraints: BoxConstraints,
1623    ) -> Size {
1624        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
1625    }
1626}
1627
1628/// Calls callbacks in response to common pointer events.
1629///
1630/// It responds to events that can indicate the location of a pointer, such as when the pointer
1631/// presses down, moves, releases, or is cancelled.
1632///
1633/// It does not respond to events that are exclusive to mouse, such as when the mouse enters and
1634/// exits a region without pressing any buttons. For these events, use `RenderMouseRegion`.
1635///
1636/// If it has a child, defers to the child for sizing behavior.
1637///
1638/// If it does not have a child, grows to fit the parent-provided constraints.
1639pub struct RenderPointerListener {
1640    render_object: RenderObjectData,
1641    render_box: RenderBoxData,
1642    child: RenderObjectWithChildData<AnyRenderBox>,
1643    on_pointer_down: Option<PointerDownEventListener>,
1644    on_pointer_move: Option<PointerMoveEventListener>,
1645    on_pointer_up: Option<PointerUpEventListener>,
1646    on_pointer_hover: Option<PointerHoverEventListener>,
1647    on_pointer_cancel: Option<PointerCancelEventListener>,
1648    on_pointer_pan_zoom_start: Option<PointerPanZoomStartEventListener>,
1649    on_pointer_pan_zoom_update: Option<PointerPanZoomUpdateEventListener>,
1650    on_pointer_pan_zoom_end: Option<PointerPanZoomEndEventListener>,
1651    on_pointer_signal: Option<PointerSignalEventListener>,
1652    behavior: HitTestBehavior,
1653}
1654
1655macro_rules! pointer_listener_field {
1656    ($get:ident, $set:ident, $ty:ty, $doc:expr) => {
1657        #[doc = $doc]
1658        pub fn $get(self: RenderHandle<Self>, app: &App) -> Option<$ty> {
1659            self.get(app).$get.clone()
1660        }
1661
1662        #[doc = concat!("Sets [`", stringify!($get), "`](Self::", stringify!($get), ").")]
1663        pub fn $set(self: RenderHandle<Self>, app: &mut App, value: Option<$ty>) {
1664            self.get_mut(app).$get = value;
1665        }
1666    };
1667}
1668
1669impl RenderPointerListener {
1670    /// Creates a render object that forwards pointer events to callbacks.
1671    ///
1672    /// The callbacks are set afterwards; Flutter's constructor takes them as optional named
1673    /// arguments, all `null` by default.
1674    pub fn new(
1675        app: &mut App,
1676        behavior: HitTestBehavior,
1677        child: Option<AnyRenderBox>,
1678    ) -> RenderHandle<Self> {
1679        let this = RenderHandle::new_box(
1680            app,
1681            RenderPointerListener {
1682                render_object: RenderObjectData::new(),
1683                render_box: RenderBoxData::new(),
1684                child: RenderObjectWithChildData::new(),
1685                on_pointer_down: None,
1686                on_pointer_move: None,
1687                on_pointer_up: None,
1688                on_pointer_hover: None,
1689                on_pointer_cancel: None,
1690                on_pointer_pan_zoom_start: None,
1691                on_pointer_pan_zoom_update: None,
1692                on_pointer_pan_zoom_end: None,
1693                on_pointer_signal: None,
1694                behavior,
1695            },
1696        );
1697        this.set_child(app, child);
1698        this
1699    }
1700
1701    pointer_listener_field!(
1702        on_pointer_down,
1703        set_on_pointer_down,
1704        PointerDownEventListener,
1705        "Called when a pointer comes into contact with the screen (for touch pointers), or has its button pressed (for mouse pointers) at this widget's location."
1706    );
1707    pointer_listener_field!(
1708        on_pointer_move,
1709        set_on_pointer_move,
1710        PointerMoveEventListener,
1711        "Called when a pointer that triggered an `on_pointer_down` changes position."
1712    );
1713    pointer_listener_field!(
1714        on_pointer_up,
1715        set_on_pointer_up,
1716        PointerUpEventListener,
1717        "Called when a pointer that triggered an `on_pointer_down` is no longer in contact with the screen."
1718    );
1719    pointer_listener_field!(
1720        on_pointer_hover,
1721        set_on_pointer_hover,
1722        PointerHoverEventListener,
1723        "Called when a pointer that has not an `on_pointer_down` changes position."
1724    );
1725    pointer_listener_field!(
1726        on_pointer_cancel,
1727        set_on_pointer_cancel,
1728        PointerCancelEventListener,
1729        "Called when the input from a pointer that triggered an `on_pointer_down` is no longer directed towards this receiver."
1730    );
1731    pointer_listener_field!(
1732        on_pointer_pan_zoom_start,
1733        set_on_pointer_pan_zoom_start,
1734        PointerPanZoomStartEventListener,
1735        "Called when a pan/zoom begins such as from a trackpad gesture."
1736    );
1737    pointer_listener_field!(
1738        on_pointer_pan_zoom_update,
1739        set_on_pointer_pan_zoom_update,
1740        PointerPanZoomUpdateEventListener,
1741        "Called when a pan/zoom is updated."
1742    );
1743    pointer_listener_field!(
1744        on_pointer_pan_zoom_end,
1745        set_on_pointer_pan_zoom_end,
1746        PointerPanZoomEndEventListener,
1747        "Called when a pan/zoom finishes."
1748    );
1749    pointer_listener_field!(
1750        on_pointer_signal,
1751        set_on_pointer_signal,
1752        PointerSignalEventListener,
1753        "Called when a pointer signal occurs over this object."
1754    );
1755
1756    /// Sets [`behavior`](RenderProxyBoxWithHitTestBehavior::behavior).
1757    pub fn set_behavior(self: RenderHandle<Self>, app: &mut App, value: HitTestBehavior) {
1758        self.get_mut(app).behavior = value;
1759    }
1760}
1761
1762impl RenderObjectWithChildMixin for RenderPointerListener {
1763    type ChildType = AnyRenderBox;
1764
1765    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1766        &self.get(app).child
1767    }
1768
1769    fn child_data_mut(
1770        self: RenderHandle<Self>,
1771        app: &mut App,
1772    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1773        &mut self.get_mut(app).child
1774    }
1775}
1776
1777impl RenderProxyBoxMixin for RenderPointerListener {
1778    fn compute_size_for_no_child(
1779        self: RenderHandle<Self>,
1780        _app: &App,
1781        constraints: BoxConstraints,
1782    ) -> Size {
1783        constraints.biggest()
1784    }
1785}
1786
1787impl RenderProxyBoxWithHitTestBehavior for RenderPointerListener {
1788    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
1789        self.get(app).behavior
1790    }
1791}
1792
1793impl RenderObject for RenderPointerListener {
1794    crate::render_object_accessors!();
1795
1796    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1797        RenderProxyBoxMixin::perform_layout(self, app);
1798    }
1799
1800    fn paint(
1801        self: RenderHandle<Self>,
1802        app: &mut App,
1803        context: &mut PaintingContext,
1804        offset: Offset,
1805    ) {
1806        RenderProxyBoxMixin::paint(self, app, context, offset);
1807    }
1808
1809    fn visit_children(
1810        self: RenderHandle<Self>,
1811        app: &App,
1812        visitor: &mut dyn FnMut(AnyRenderObject),
1813    ) {
1814        if let Some(child) = self.child(app) {
1815            visitor(child.as_object());
1816        }
1817    }
1818}
1819
1820impl RenderBox for RenderPointerListener {
1821    crate::render_box_accessors!();
1822
1823    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1824        RenderProxyBoxMixin::setup_parent_data(self, app, child);
1825    }
1826
1827    fn apply_paint_transform(
1828        self: RenderHandle<Self>,
1829        app: &App,
1830        child: AnyRenderObject,
1831        transform: &mut Matrix4,
1832    ) {
1833        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
1834    }
1835
1836    fn handle_event(
1837        self: RenderHandle<Self>,
1838        app: &mut App,
1839        event: &PointerEvent,
1840        _entry: &BoxHitTestEntry,
1841    ) {
1842        match event {
1843            PointerEvent::Down(event) => {
1844                if let Some(callback) = self.get(app).on_pointer_down.clone() {
1845                    callback(app, event.clone());
1846                }
1847            }
1848            PointerEvent::Move(event) => {
1849                if let Some(callback) = self.get(app).on_pointer_move.clone() {
1850                    callback(app, event.clone());
1851                }
1852            }
1853            PointerEvent::Up(event) => {
1854                if let Some(callback) = self.get(app).on_pointer_up.clone() {
1855                    callback(app, event.clone());
1856                }
1857            }
1858            PointerEvent::Hover(event) => {
1859                if let Some(callback) = self.get(app).on_pointer_hover.clone() {
1860                    callback(app, event.clone());
1861                }
1862            }
1863            PointerEvent::Cancel(event) => {
1864                if let Some(callback) = self.get(app).on_pointer_cancel.clone() {
1865                    callback(app, event.clone());
1866                }
1867            }
1868            PointerEvent::PanZoomStart(event) => {
1869                if let Some(callback) = self.get(app).on_pointer_pan_zoom_start.clone() {
1870                    callback(app, event.clone());
1871                }
1872            }
1873            PointerEvent::PanZoomUpdate(event) => {
1874                if let Some(callback) = self.get(app).on_pointer_pan_zoom_update.clone() {
1875                    callback(app, event.clone());
1876                }
1877            }
1878            PointerEvent::PanZoomEnd(event) => {
1879                if let Some(callback) = self.get(app).on_pointer_pan_zoom_end.clone() {
1880                    callback(app, event.clone());
1881                }
1882            }
1883            PointerEvent::Scroll(_)
1884            | PointerEvent::ScrollInertiaCancel(_)
1885            | PointerEvent::Scale(_) => {
1886                if let Some(callback) = self.get(app).on_pointer_signal.clone() {
1887                    callback(app, event.clone());
1888                }
1889            }
1890            PointerEvent::Added(_)
1891            | PointerEvent::Removed(_)
1892            | PointerEvent::Enter(_)
1893            | PointerEvent::Exit(_) => {}
1894        }
1895    }
1896
1897    fn hit_test(
1898        self: RenderHandle<Self>,
1899        app: &mut App,
1900        result: &mut BoxHitTestResult<'_>,
1901        position: Offset,
1902    ) -> bool {
1903        RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
1904    }
1905
1906    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
1907        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
1908    }
1909
1910    fn hit_test_children(
1911        self: RenderHandle<Self>,
1912        app: &mut App,
1913        result: &mut BoxHitTestResult<'_>,
1914        position: Offset,
1915    ) -> bool {
1916        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
1917    }
1918
1919    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1920        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
1921    }
1922
1923    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1924        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
1925    }
1926
1927    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1928        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
1929    }
1930
1931    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1932        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
1933    }
1934
1935    fn compute_distance_to_actual_baseline(
1936        self: RenderHandle<Self>,
1937        app: &mut App,
1938        baseline: TextBaseline,
1939    ) -> Option<f64> {
1940        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
1941    }
1942
1943    fn compute_dry_baseline(
1944        self: RenderHandle<Self>,
1945        app: &mut App,
1946        constraints: BoxConstraints,
1947        baseline: TextBaseline,
1948    ) -> Option<f64> {
1949        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
1950    }
1951
1952    fn compute_dry_layout(
1953        self: RenderHandle<Self>,
1954        app: &mut App,
1955        constraints: BoxConstraints,
1956    ) -> Size {
1957        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
1958    }
1959}
1960
1961/// Where to paint a box decoration.
1962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1963pub enum DecorationPosition {
1964    /// Paint the box decoration behind the children.
1965    Background,
1966
1967    /// Paint the box decoration in front of the children.
1968    Foreground,
1969}
1970
1971/// Paints a [`Decoration`] either before or after its child paints.
1972pub struct RenderDecoratedBox {
1973    render_object: RenderObjectData,
1974    render_box: RenderBoxData,
1975    child: RenderObjectWithChildData<AnyRenderBox>,
1976    painter: Option<Box<dyn BoxPainter>>,
1977    decoration: DecorationRef,
1978    position: DecorationPosition,
1979    configuration: ImageConfiguration,
1980}
1981
1982impl RenderDecoratedBox {
1983    /// Creates a decorated box.
1984    ///
1985    /// The `configuration` is normally obtained from `createLocalImageConfiguration`.
1986    pub fn new(
1987        app: &mut App,
1988        decoration: DecorationRef,
1989        position: DecorationPosition,
1990        configuration: ImageConfiguration,
1991        child: Option<AnyRenderBox>,
1992    ) -> RenderHandle<Self> {
1993        let this = RenderHandle::new_box(
1994            app,
1995            RenderDecoratedBox {
1996                render_object: RenderObjectData::new(),
1997                render_box: RenderBoxData::new(),
1998                child: RenderObjectWithChildData::new(),
1999                painter: None,
2000                decoration,
2001                position,
2002                configuration,
2003            },
2004        );
2005        this.set_child(app, child);
2006        this
2007    }
2008
2009    /// What decoration to paint.
2010    pub fn decoration(self: RenderHandle<Self>, app: &App) -> &DecorationRef {
2011        &self.get(app).decoration
2012    }
2013
2014    /// Sets [`decoration`](Self::decoration).
2015    pub fn set_decoration(self: RenderHandle<Self>, app: &mut App, value: DecorationRef) {
2016        if value == self.get(app).decoration {
2017            return;
2018        }
2019        let this = self.get_mut(app);
2020        if let Some(mut painter) = this.painter.take() {
2021            painter.dispose();
2022        }
2023        this.decoration = value;
2024        self.mark_needs_paint(app);
2025    }
2026
2027    /// Whether to paint the box decoration behind or in front of the child.
2028    pub fn position(self: RenderHandle<Self>, app: &App) -> DecorationPosition {
2029        self.get(app).position
2030    }
2031
2032    /// Sets [`position`](Self::position).
2033    pub fn set_position(self: RenderHandle<Self>, app: &mut App, value: DecorationPosition) {
2034        if self.get(app).position == value {
2035            return;
2036        }
2037        self.get_mut(app).position = value;
2038        self.mark_needs_paint(app);
2039    }
2040
2041    /// The settings to pass to the decoration when painting, so that it can
2042    /// resolve images appropriately. See [`ImageConfiguration`].
2043    pub fn configuration(self: RenderHandle<Self>, app: &App) -> &ImageConfiguration {
2044        &self.get(app).configuration
2045    }
2046
2047    /// Sets [`configuration`](Self::configuration).
2048    pub fn set_configuration(self: RenderHandle<Self>, app: &mut App, value: ImageConfiguration) {
2049        if self.get(app).configuration == value {
2050            return;
2051        }
2052        self.get_mut(app).configuration = value;
2053        self.mark_needs_paint(app);
2054    }
2055
2056    fn paint_decoration(
2057        self: RenderHandle<Self>,
2058        app: &mut App,
2059        context: &mut PaintingContext,
2060        offset: Offset,
2061        configuration: &ImageConfiguration,
2062    ) {
2063        let debug_save_count = context.canvas().save_count();
2064        let is_complex = {
2065            let this = self.get_mut(app);
2066            let painter = this.painter.get_or_insert_with(|| {
2067                this.decoration
2068                    .create_box_painter(Some(Rc::new(move |app| self.mark_needs_paint(app))))
2069            });
2070            painter.paint(context.canvas(), offset, configuration);
2071            this.decoration.is_complex()
2072        };
2073        debug_assert_eq!(
2074            debug_save_count,
2075            context.canvas().save_count(),
2076            "the decoration's painter had mismatching save and restore calls"
2077        );
2078        if is_complex {
2079            context.set_is_complex_hint();
2080        }
2081    }
2082}
2083
2084impl RenderObjectWithChildMixin for RenderDecoratedBox {
2085    type ChildType = AnyRenderBox;
2086
2087    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2088        &self.get(app).child
2089    }
2090
2091    fn child_data_mut(
2092        self: RenderHandle<Self>,
2093        app: &mut App,
2094    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2095        &mut self.get_mut(app).child
2096    }
2097}
2098
2099impl RenderProxyBoxMixin for RenderDecoratedBox {}
2100
2101impl RenderObject for RenderDecoratedBox {
2102    crate::render_object_accessors!();
2103
2104    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2105        if let Some(mut painter) = self.get_mut(app).painter.take() {
2106            painter.dispose();
2107        }
2108        if let Some(child) = self.child(app) {
2109            child.as_object().detach(app);
2110        }
2111        self.mark_needs_paint(app);
2112    }
2113
2114    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2115        RenderProxyBoxMixin::perform_layout(self, app);
2116    }
2117
2118    fn paint(
2119        self: RenderHandle<Self>,
2120        app: &mut App,
2121        context: &mut PaintingContext,
2122        offset: Offset,
2123    ) {
2124        let size = self.size(app);
2125        let filled_configuration =
2126            self.get(app)
2127                .configuration
2128                .copy_with(None, None, None, None, Some(size), None);
2129        if self.get(app).position == DecorationPosition::Background {
2130            self.paint_decoration(app, context, offset, &filled_configuration);
2131        }
2132        RenderProxyBoxMixin::paint(self, app, context, offset);
2133        if self.get(app).position == DecorationPosition::Foreground {
2134            self.paint_decoration(app, context, offset, &filled_configuration);
2135        }
2136    }
2137
2138    fn visit_children(
2139        self: RenderHandle<Self>,
2140        app: &App,
2141        visitor: &mut dyn FnMut(AnyRenderObject),
2142    ) {
2143        if let Some(child) = self.child(app) {
2144            visitor(child.as_object());
2145        }
2146    }
2147}
2148
2149impl RenderBox for RenderDecoratedBox {
2150    crate::render_box_accessors!();
2151
2152    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
2153        let this = self.get(app);
2154        this.decoration
2155            .hit_test(self.size(app), position, this.configuration.text_direction)
2156    }
2157
2158    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2159        RenderProxyBoxMixin::setup_parent_data(self, app, child);
2160    }
2161
2162    fn apply_paint_transform(
2163        self: RenderHandle<Self>,
2164        app: &App,
2165        child: AnyRenderObject,
2166        transform: &mut Matrix4,
2167    ) {
2168        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
2169    }
2170
2171    fn hit_test_children(
2172        self: RenderHandle<Self>,
2173        app: &mut App,
2174        result: &mut BoxHitTestResult<'_>,
2175        position: Offset,
2176    ) -> bool {
2177        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
2178    }
2179
2180    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2181        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
2182    }
2183
2184    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2185        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
2186    }
2187
2188    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2189        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
2190    }
2191
2192    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2193        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
2194    }
2195
2196    fn compute_distance_to_actual_baseline(
2197        self: RenderHandle<Self>,
2198        app: &mut App,
2199        baseline: TextBaseline,
2200    ) -> Option<f64> {
2201        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
2202    }
2203
2204    fn compute_dry_baseline(
2205        self: RenderHandle<Self>,
2206        app: &mut App,
2207        constraints: BoxConstraints,
2208        baseline: TextBaseline,
2209    ) -> Option<f64> {
2210        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
2211    }
2212
2213    fn compute_dry_layout(
2214        self: RenderHandle<Self>,
2215        app: &mut App,
2216        constraints: BoxConstraints,
2217    ) -> Size {
2218        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
2219    }
2220}
2221
2222/// Creates a separate display list for its child.
2223///
2224/// This render object creates a separate display list for its child, which
2225/// can improve performance if the subtree repaints at different times than
2226/// the surrounding parts of the tree.
2227pub struct RenderRepaintBoundary {
2228    render_object: RenderObjectData,
2229    render_box: RenderBoxData,
2230    child: RenderObjectWithChildData<AnyRenderBox>,
2231}
2232
2233impl RenderRepaintBoundary {
2234    /// Creates a repaint boundary around `child`.
2235    pub fn new(app: &mut App, child: Option<AnyRenderBox>) -> RenderHandle<Self> {
2236        let this = RenderHandle::new_box(
2237            app,
2238            RenderRepaintBoundary {
2239                render_object: RenderObjectData::new(),
2240                render_box: RenderBoxData::new(),
2241                child: RenderObjectWithChildData::new(),
2242            },
2243        );
2244        this.set_child(app, child);
2245        this
2246    }
2247}
2248
2249impl RenderObjectWithChildMixin for RenderRepaintBoundary {
2250    type ChildType = AnyRenderBox;
2251
2252    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2253        &self.get(app).child
2254    }
2255
2256    fn child_data_mut(
2257        self: RenderHandle<Self>,
2258        app: &mut App,
2259    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2260        &mut self.get_mut(app).child
2261    }
2262}
2263
2264impl RenderProxyBoxMixin for RenderRepaintBoundary {}
2265
2266impl RenderObject for RenderRepaintBoundary {
2267    crate::render_object_accessors!();
2268
2269    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
2270        true
2271    }
2272
2273    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2274        RenderProxyBoxMixin::perform_layout(self, app);
2275    }
2276
2277    fn paint(
2278        self: RenderHandle<Self>,
2279        app: &mut App,
2280        context: &mut PaintingContext,
2281        offset: Offset,
2282    ) {
2283        RenderProxyBoxMixin::paint(self, app, context, offset);
2284    }
2285
2286    fn visit_children(
2287        self: RenderHandle<Self>,
2288        app: &App,
2289        visitor: &mut dyn FnMut(AnyRenderObject),
2290    ) {
2291        if let Some(child) = self.child(app) {
2292            visitor(child.as_object());
2293        }
2294    }
2295}
2296
2297impl RenderBox for RenderRepaintBoundary {
2298    crate::render_box_accessors!();
2299
2300    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2301        RenderProxyBoxMixin::setup_parent_data(self, app, child);
2302    }
2303
2304    fn apply_paint_transform(
2305        self: RenderHandle<Self>,
2306        app: &App,
2307        child: AnyRenderObject,
2308        transform: &mut Matrix4,
2309    ) {
2310        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
2311    }
2312
2313    fn hit_test_children(
2314        self: RenderHandle<Self>,
2315        app: &mut App,
2316        result: &mut BoxHitTestResult<'_>,
2317        position: Offset,
2318    ) -> bool {
2319        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
2320    }
2321
2322    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2323        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
2324    }
2325
2326    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2327        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
2328    }
2329
2330    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2331        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
2332    }
2333
2334    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2335        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
2336    }
2337
2338    fn compute_distance_to_actual_baseline(
2339        self: RenderHandle<Self>,
2340        app: &mut App,
2341        baseline: TextBaseline,
2342    ) -> Option<f64> {
2343        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
2344    }
2345
2346    fn compute_dry_baseline(
2347        self: RenderHandle<Self>,
2348        app: &mut App,
2349        constraints: BoxConstraints,
2350        baseline: TextBaseline,
2351    ) -> Option<f64> {
2352        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
2353    }
2354
2355    fn compute_dry_layout(
2356        self: RenderHandle<Self>,
2357        app: &mut App,
2358        constraints: BoxConstraints,
2359    ) -> Size {
2360        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
2361    }
2362}
2363
2364/// Flutter's `RenderMouseRegion` fields.
2365pub struct RenderMouseRegionData {
2366    on_enter: Option<PointerEnterEventListener>,
2367    on_hover: Option<PointerHoverEventListener>,
2368    on_exit: Option<PointerExitEventListener>,
2369    cursor: MouseCursorRef,
2370    valid_for_mouse_tracker: bool,
2371    opaque: bool,
2372    behavior: HitTestBehavior,
2373}
2374
2375impl RenderMouseRegionData {
2376    /// Dart's constructor defaults: no callbacks, `MouseCursor.defer`, `opaque` true and
2377    /// `hit_test_behavior` opaque. `valid_for_mouse_tracker` has no setter, so it is a
2378    /// parameter (Dart's default is true).
2379    pub fn new(valid_for_mouse_tracker: bool) -> RenderMouseRegionData {
2380        RenderMouseRegionData {
2381            on_enter: None,
2382            on_hover: None,
2383            on_exit: None,
2384            cursor: <dyn MouseCursor>::defer(),
2385            valid_for_mouse_tracker,
2386            opaque: true,
2387            behavior: HitTestBehavior::Opaque,
2388        }
2389    }
2390
2391    /// The hit test behavior a leaf answers from
2392    /// [`RenderProxyBoxWithHitTestBehavior::behavior`].
2393    pub fn behavior(&self) -> HitTestBehavior {
2394        self.behavior
2395    }
2396}
2397
2398/// Flutter's `RenderMouseRegion` bodies. [`RenderMouseRegion`] is the plain leaf; a Dart
2399/// subclass (`raw_tooltip.dart`'s `_RenderExclusiveMouseRegion`) is a leaf that implements this
2400/// trait too and overrides what Dart's subclass overrides.
2401///
2402/// A leaf calls [`did_attach`](Self::did_attach), [`did_detach`](Self::did_detach),
2403/// [`mouse_tracker_annotation`](Self::mouse_tracker_annotation),
2404/// [`hit_test`](Self::hit_test) and [`handle_event`](Self::handle_event) from its
2405/// [`RenderObject`] and [`RenderBox`] impls, where Dart inherits them.
2406pub trait RenderMouseRegionBase:
2407    RenderProxyBoxWithHitTestBehavior + RenderObjectWithChildMixin<ChildType = AnyRenderBox>
2408{
2409    /// Mixin field access.
2410    fn mouse_region_data(self: RenderHandle<Self>, app: &App) -> &RenderMouseRegionData;
2411
2412    /// See [`mouse_region_data`](Self::mouse_region_data).
2413    fn mouse_region_data_mut(self: RenderHandle<Self>, app: &mut App)
2414    -> &mut RenderMouseRegionData;
2415
2416    /// Whether this object should prevent [`RenderMouseRegion`]s visually behind it
2417    /// from detecting the pointer, thus affecting how their `on_hover`, `on_enter`,
2418    /// and `on_exit` behave.
2419    ///
2420    /// If `opaque` is true, this object will absorb the mouse pointer and
2421    /// prevent this object's siblings (or any other objects that are not
2422    /// ancestors or descendants of this object) from detecting the mouse
2423    /// pointer even when the pointer is within their areas.
2424    ///
2425    /// If `opaque` is false, this object will not affect how [`RenderMouseRegion`]s
2426    /// behind it behave, which will detect the mouse pointer as long as the
2427    /// pointer is within their areas.
2428    ///
2429    /// This defaults to true.
2430    fn opaque(self: RenderHandle<Self>, app: &App) -> bool {
2431        self.mouse_region_data(app).opaque
2432    }
2433
2434    /// Sets [`opaque`](Self::opaque).
2435    fn set_opaque(self: RenderHandle<Self>, app: &mut App, value: bool) {
2436        if self.mouse_region_data(app).opaque != value {
2437            self.mouse_region_data_mut(app).opaque = value;
2438            // Trigger [MouseTracker]'s device update to recalculate mouse states.
2439            self.mark_needs_paint(app);
2440        }
2441    }
2442
2443    /// How to behave during hit testing.
2444    ///
2445    /// This defaults to [`HitTestBehavior::Opaque`] if `None`.
2446    fn hit_test_behavior(self: RenderHandle<Self>, app: &App) -> Option<HitTestBehavior> {
2447        Some(self.mouse_region_data(app).behavior)
2448    }
2449
2450    /// Sets [`hit_test_behavior`](Self::hit_test_behavior).
2451    fn set_hit_test_behavior(
2452        self: RenderHandle<Self>,
2453        app: &mut App,
2454        value: Option<HitTestBehavior>,
2455    ) {
2456        let new_value = value.unwrap_or(HitTestBehavior::Opaque);
2457        if self.mouse_region_data(app).behavior != new_value {
2458            self.mouse_region_data_mut(app).behavior = new_value;
2459            // Trigger [MouseTracker]'s device update to recalculate mouse states.
2460            self.mark_needs_paint(app);
2461        }
2462    }
2463
2464    /// Triggered when a mouse pointer, with or without buttons pressed, has entered the region and `valid_for_mouse_tracker` is true.
2465    fn on_enter(self: RenderHandle<Self>, app: &App) -> Option<PointerEnterEventListener> {
2466        self.mouse_region_data(app).on_enter.clone()
2467    }
2468
2469    /// Sets [`on_enter`](Self::on_enter).
2470    fn set_on_enter(
2471        self: RenderHandle<Self>,
2472        app: &mut App,
2473        value: Option<PointerEnterEventListener>,
2474    ) {
2475        self.mouse_region_data_mut(app).on_enter = value;
2476    }
2477
2478    /// Triggered when a pointer has moved onto or within the region without buttons pressed.
2479    fn on_hover(self: RenderHandle<Self>, app: &App) -> Option<PointerHoverEventListener> {
2480        self.mouse_region_data(app).on_hover.clone()
2481    }
2482
2483    /// Sets [`on_hover`](Self::on_hover).
2484    fn set_on_hover(
2485        self: RenderHandle<Self>,
2486        app: &mut App,
2487        value: Option<PointerHoverEventListener>,
2488    ) {
2489        self.mouse_region_data_mut(app).on_hover = value;
2490    }
2491
2492    /// Triggered when a mouse pointer, with or without buttons pressed, has exited the region and `valid_for_mouse_tracker` is true.
2493    fn on_exit(self: RenderHandle<Self>, app: &App) -> Option<PointerExitEventListener> {
2494        self.mouse_region_data(app).on_exit.clone()
2495    }
2496
2497    /// Sets [`on_exit`](Self::on_exit).
2498    fn set_on_exit(
2499        self: RenderHandle<Self>,
2500        app: &mut App,
2501        value: Option<PointerExitEventListener>,
2502    ) {
2503        self.mouse_region_data_mut(app).on_exit = value;
2504    }
2505
2506    /// The mouse cursor for mouse pointers that are hovering over the region.
2507    ///
2508    /// When a mouse enters the region, its cursor will be changed to the `cursor`.
2509    /// When the mouse leaves the region, the cursor will be set by the region
2510    /// found at the new location.
2511    ///
2512    /// Defaults to `MouseCursor.defer`, deferring the choice of cursor to the next
2513    /// region behind it in hit-test order.
2514    fn cursor(self: RenderHandle<Self>, app: &App) -> MouseCursorRef {
2515        Rc::clone(&self.mouse_region_data(app).cursor)
2516    }
2517
2518    /// Sets [`cursor`](Self::cursor).
2519    fn set_cursor(self: RenderHandle<Self>, app: &mut App, value: MouseCursorRef) {
2520        if *self.mouse_region_data(app).cursor != *value {
2521            self.mouse_region_data_mut(app).cursor = value;
2522            // A repaint is needed in order to trigger a device update of
2523            // [MouseTracker] so that this new value can be found.
2524            self.mark_needs_paint(app);
2525        }
2526    }
2527
2528    /// Whether this is included when a `MouseTracker` collects the list of
2529    /// annotations: true while attached to a pipeline owner.
2530    fn valid_for_mouse_tracker(self: RenderHandle<Self>, app: &App) -> bool {
2531        self.mouse_region_data(app).valid_for_mouse_tracker
2532    }
2533
2534    /// Flutter's `attach` override; call it from [`RenderObject::did_attach`].
2535    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
2536        for child in [self.child(app)].into_iter().flatten() {
2537            child.as_object().attach(app, owner);
2538        }
2539        self.mouse_region_data_mut(app).valid_for_mouse_tracker = true;
2540    }
2541
2542    /// Flutter's `detach` override; call it from [`RenderObject::did_detach`].
2543    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2544        // Dart clears the flag before `super.detach()`; nothing in the base body reads it.
2545        self.mouse_region_data_mut(app).valid_for_mouse_tracker = false;
2546        for child in [self.child(app)].into_iter().flatten() {
2547            child.as_object().detach(app);
2548        }
2549    }
2550
2551    /// Flutter's `implements MouseTrackerAnnotation`; call it from
2552    /// [`RenderObject::mouse_tracker_annotation`].
2553    fn mouse_tracker_annotation(
2554        self: RenderHandle<Self>,
2555        app: &App,
2556    ) -> Option<MouseTrackerAnnotation> {
2557        let data = self.mouse_region_data(app);
2558        Some(MouseTrackerAnnotation {
2559            on_enter: data.on_enter.clone(),
2560            on_exit: data.on_exit.clone(),
2561            cursor: Rc::clone(&data.cursor),
2562            valid_for_mouse_tracker: data.valid_for_mouse_tracker,
2563        })
2564    }
2565
2566    /// Flutter's `hitTest` override: the proxy box's hit test, stopped by an opaque region.
2567    fn hit_test(
2568        self: RenderHandle<Self>,
2569        app: &mut App,
2570        result: &mut BoxHitTestResult<'_>,
2571        position: Offset,
2572    ) -> bool {
2573        RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
2574            && self.mouse_region_data(app).opaque
2575    }
2576
2577    /// Flutter's `handleEvent` override; call it from [`RenderBox::handle_event`].
2578    fn handle_event(self: RenderHandle<Self>, app: &mut App, event: &PointerEvent) {
2579        if let PointerEvent::Hover(event) = event
2580            && let Some(on_hover) = self.mouse_region_data(app).on_hover.clone()
2581        {
2582            on_hover(app, event.clone());
2583        }
2584    }
2585}
2586
2587/// Calls callbacks in response to pointer events that are exclusive to mice.
2588///
2589/// It responds to events that are related to hovering, i.e. when the mouse
2590/// enters, exits (with or without pressing buttons), or moves over a region
2591/// without pressing buttons.
2592///
2593/// It does not respond to common events that construct gestures, such as when
2594/// the pointer is pressed, moved, then released or canceled. For these events,
2595/// use [`RenderPointerListener`].
2596///
2597/// If it has a child, it defers to the child for sizing behavior.
2598///
2599/// If it does not have a child, it grows to fit the parent-provided constraints.
2600///
2601/// Flutter's `RenderMouseRegion implements MouseTrackerAnnotation`: here it answers
2602/// [`RenderObject::mouse_tracker_annotation`] with its current callbacks, cursor, and validity.
2603/// Its members are [`RenderMouseRegionBase`]'s.
2604///
2605/// See also:
2606///
2607///  * `MouseRegion`, a widget that listens to hover events using
2608///    [`RenderMouseRegion`].
2609pub struct RenderMouseRegion {
2610    render_object: RenderObjectData,
2611    render_box: RenderBoxData,
2612    child: RenderObjectWithChildData<AnyRenderBox>,
2613    mouse_region: RenderMouseRegionData,
2614}
2615
2616impl RenderMouseRegion {
2617    /// Creates a render object that forwards pointer events to callbacks.
2618    ///
2619    /// Dart's remaining constructor arguments have setters: the callbacks, `cursor`
2620    /// (`MouseCursor.defer`), `opaque` (true), and `hit_test_behavior` (opaque).
2621    /// `valid_for_mouse_tracker` has none, so it is a parameter (Dart's default is true).
2622    pub fn new(
2623        app: &mut App,
2624        valid_for_mouse_tracker: bool,
2625        child: Option<AnyRenderBox>,
2626    ) -> RenderHandle<Self> {
2627        let this = RenderHandle::new_box(
2628            app,
2629            RenderMouseRegion {
2630                render_object: RenderObjectData::new(),
2631                render_box: RenderBoxData::new(),
2632                child: RenderObjectWithChildData::new(),
2633                mouse_region: RenderMouseRegionData::new(valid_for_mouse_tracker),
2634            },
2635        );
2636        this.set_child(app, child);
2637        this
2638    }
2639}
2640
2641impl RenderMouseRegionBase for RenderMouseRegion {
2642    fn mouse_region_data(self: RenderHandle<Self>, app: &App) -> &RenderMouseRegionData {
2643        &self.get(app).mouse_region
2644    }
2645
2646    fn mouse_region_data_mut(
2647        self: RenderHandle<Self>,
2648        app: &mut App,
2649    ) -> &mut RenderMouseRegionData {
2650        &mut self.get_mut(app).mouse_region
2651    }
2652}
2653
2654impl RenderObjectWithChildMixin for RenderMouseRegion {
2655    type ChildType = AnyRenderBox;
2656
2657    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2658        &self.get(app).child
2659    }
2660
2661    fn child_data_mut(
2662        self: RenderHandle<Self>,
2663        app: &mut App,
2664    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2665        &mut self.get_mut(app).child
2666    }
2667}
2668
2669impl RenderProxyBoxMixin for RenderMouseRegion {
2670    fn compute_size_for_no_child(
2671        self: RenderHandle<Self>,
2672        _app: &App,
2673        constraints: BoxConstraints,
2674    ) -> Size {
2675        constraints.biggest()
2676    }
2677}
2678
2679impl RenderProxyBoxWithHitTestBehavior for RenderMouseRegion {
2680    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
2681        self.mouse_region_data(app).behavior
2682    }
2683}
2684
2685impl RenderObject for RenderMouseRegion {
2686    crate::render_object_accessors!();
2687
2688    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
2689        RenderMouseRegionBase::did_attach(self, app, owner);
2690    }
2691
2692    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2693        RenderMouseRegionBase::did_detach(self, app);
2694    }
2695
2696    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2697        RenderProxyBoxMixin::perform_layout(self, app);
2698    }
2699
2700    fn mouse_tracker_annotation(
2701        self: RenderHandle<Self>,
2702        app: &App,
2703    ) -> Option<MouseTrackerAnnotation> {
2704        RenderMouseRegionBase::mouse_tracker_annotation(self, app)
2705    }
2706
2707    fn paint(
2708        self: RenderHandle<Self>,
2709        app: &mut App,
2710        context: &mut PaintingContext,
2711        offset: Offset,
2712    ) {
2713        RenderProxyBoxMixin::paint(self, app, context, offset);
2714    }
2715
2716    fn visit_children(
2717        self: RenderHandle<Self>,
2718        app: &App,
2719        visitor: &mut dyn FnMut(AnyRenderObject),
2720    ) {
2721        if let Some(child) = self.child(app) {
2722            visitor(child.as_object());
2723        }
2724    }
2725}
2726
2727impl RenderBox for RenderMouseRegion {
2728    crate::render_box_accessors!();
2729
2730    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2731        RenderProxyBoxMixin::setup_parent_data(self, app, child);
2732    }
2733
2734    fn apply_paint_transform(
2735        self: RenderHandle<Self>,
2736        app: &App,
2737        child: AnyRenderObject,
2738        transform: &mut Matrix4,
2739    ) {
2740        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
2741    }
2742
2743    fn hit_test(
2744        self: RenderHandle<Self>,
2745        app: &mut App,
2746        result: &mut BoxHitTestResult<'_>,
2747        position: Offset,
2748    ) -> bool {
2749        RenderMouseRegionBase::hit_test(self, app, result, position)
2750    }
2751
2752    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
2753        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
2754    }
2755
2756    fn hit_test_children(
2757        self: RenderHandle<Self>,
2758        app: &mut App,
2759        result: &mut BoxHitTestResult<'_>,
2760        position: Offset,
2761    ) -> bool {
2762        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
2763    }
2764
2765    fn handle_event(
2766        self: RenderHandle<Self>,
2767        app: &mut App,
2768        event: &PointerEvent,
2769        _entry: &BoxHitTestEntry,
2770    ) {
2771        RenderMouseRegionBase::handle_event(self, app, event);
2772    }
2773
2774    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2775        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
2776    }
2777
2778    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2779        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
2780    }
2781
2782    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2783        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
2784    }
2785
2786    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2787        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
2788    }
2789
2790    fn compute_distance_to_actual_baseline(
2791        self: RenderHandle<Self>,
2792        app: &mut App,
2793        baseline: TextBaseline,
2794    ) -> Option<f64> {
2795        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
2796    }
2797
2798    fn compute_dry_baseline(
2799        self: RenderHandle<Self>,
2800        app: &mut App,
2801        constraints: BoxConstraints,
2802        baseline: TextBaseline,
2803    ) -> Option<f64> {
2804        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
2805    }
2806
2807    fn compute_dry_layout(
2808        self: RenderHandle<Self>,
2809        app: &mut App,
2810        constraints: BoxConstraints,
2811    ) -> Size {
2812        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
2813    }
2814}
2815
2816/// Dart's `a == b` for two objects that do not override `==`: the same instance.
2817pub(crate) fn same_instance<T: ?Sized>(a: Option<&Rc<T>>, b: Option<&Rc<T>>) -> bool {
2818    match (a, b) {
2819        (None, None) => true,
2820        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
2821        _ => false,
2822    }
2823}
2824
2825/// Constrains the child's [`BoxConstraints::max_width`] and [`BoxConstraints::max_height`] if
2826/// they're otherwise unconstrained.
2827///
2828/// This has the effect of giving the child a natural dimension in unbounded
2829/// environments. For example, by providing a [`max_height`](Self::max_height) to a widget that
2830/// normally tries to be as big as possible, the widget will normally size
2831/// itself to fit its parent, but when placed in a vertical list, it will take
2832/// on the given height.
2833///
2834/// This is useful when composing widgets that normally try to match their
2835/// parents' size, so that they behave reasonably in lists (which are
2836/// unbounded).
2837pub struct RenderLimitedBox {
2838    render_object: RenderObjectData,
2839    render_box: RenderBoxData,
2840    child: RenderObjectWithChildData<AnyRenderBox>,
2841    max_width: f64,
2842    max_height: f64,
2843}
2844
2845impl RenderLimitedBox {
2846    /// Creates a render box that imposes a maximum width or maximum height on its
2847    /// child if the child is otherwise unconstrained.
2848    ///
2849    /// The `max_width` and `max_height` arguments must be non-negative.
2850    pub fn new(
2851        app: &mut App,
2852        max_width: f64,
2853        max_height: f64,
2854        child: Option<AnyRenderBox>,
2855    ) -> RenderHandle<RenderLimitedBox> {
2856        debug_assert!(max_width >= 0.0);
2857        debug_assert!(max_height >= 0.0);
2858        let this = RenderHandle::new_box(
2859            app,
2860            RenderLimitedBox {
2861                render_object: RenderObjectData::new(),
2862                render_box: RenderBoxData::new(),
2863                child: RenderObjectWithChildData::new(),
2864                max_width,
2865                max_height,
2866            },
2867        );
2868        this.set_child(app, child);
2869        this
2870    }
2871
2872    /// The value to use for `max_width` if the incoming `max_width` constraint is infinite.
2873    pub fn max_width(self: RenderHandle<Self>, app: &App) -> f64 {
2874        self.get(app).max_width
2875    }
2876
2877    /// Sets [`max_width`](Self::max_width).
2878    pub fn set_max_width(self: RenderHandle<Self>, app: &mut App, value: f64) {
2879        debug_assert!(value >= 0.0);
2880        if self.get(app).max_width == value {
2881            return;
2882        }
2883        self.get_mut(app).max_width = value;
2884        RenderBox::mark_needs_layout(self, app);
2885    }
2886
2887    /// The value to use for `max_height` if the incoming `max_height` constraint is infinite.
2888    pub fn max_height(self: RenderHandle<Self>, app: &App) -> f64 {
2889        self.get(app).max_height
2890    }
2891
2892    /// Sets [`max_height`](Self::max_height).
2893    pub fn set_max_height(self: RenderHandle<Self>, app: &mut App, value: f64) {
2894        debug_assert!(value >= 0.0);
2895        if self.get(app).max_height == value {
2896            return;
2897        }
2898        self.get_mut(app).max_height = value;
2899        RenderBox::mark_needs_layout(self, app);
2900    }
2901
2902    /// Flutter's `_computeSize`.
2903    fn compute_size(
2904        self: RenderHandle<Self>,
2905        app: &mut App,
2906        constraints: BoxConstraints,
2907        layout_child: ChildLayouter,
2908    ) -> Size {
2909        let limited = self.limit_constraints(app, constraints);
2910        match self.child(app) {
2911            Some(child) => constraints.constrain(layout_child(app, child, limited)),
2912            None => limited.constrain(Size::ZERO),
2913        }
2914    }
2915
2916    fn limit_constraints(
2917        self: RenderHandle<Self>,
2918        app: &App,
2919        constraints: BoxConstraints,
2920    ) -> BoxConstraints {
2921        let this = self.get(app);
2922        BoxConstraints::new()
2923            .min_width(constraints.min_width)
2924            .max_width(if constraints.has_bounded_width() {
2925                constraints.max_width
2926            } else {
2927                constraints.constrain_width(this.max_width)
2928            })
2929            .min_height(constraints.min_height)
2930            .max_height(if constraints.has_bounded_height() {
2931                constraints.max_height
2932            } else {
2933                constraints.constrain_height(this.max_height)
2934            })
2935    }
2936}
2937
2938impl RenderObjectWithChildMixin for RenderLimitedBox {
2939    type ChildType = AnyRenderBox;
2940
2941    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2942        &self.get(app).child
2943    }
2944
2945    fn child_data_mut(
2946        self: RenderHandle<Self>,
2947        app: &mut App,
2948    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2949        &mut self.get_mut(app).child
2950    }
2951}
2952
2953impl RenderProxyBoxMixin for RenderLimitedBox {}
2954
2955impl RenderObject for RenderLimitedBox {
2956    crate::render_object_accessors!();
2957
2958    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2959        let constraints = self.constraints(app);
2960        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
2961        self.set_size(app, size);
2962    }
2963
2964    fn paint(
2965        self: RenderHandle<Self>,
2966        app: &mut App,
2967        context: &mut PaintingContext,
2968        offset: Offset,
2969    ) {
2970        RenderProxyBoxMixin::paint(self, app, context, offset);
2971    }
2972
2973    fn visit_children(
2974        self: RenderHandle<Self>,
2975        app: &App,
2976        visitor: &mut dyn FnMut(AnyRenderObject),
2977    ) {
2978        if let Some(child) = self.child(app) {
2979            visitor(child.as_object());
2980        }
2981    }
2982}
2983
2984impl RenderBox for RenderLimitedBox {
2985    crate::render_box_accessors!();
2986
2987    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2988        RenderProxyBoxMixin::setup_parent_data(self, app, child);
2989    }
2990
2991    fn apply_paint_transform(
2992        self: RenderHandle<Self>,
2993        app: &App,
2994        child: AnyRenderObject,
2995        transform: &mut Matrix4,
2996    ) {
2997        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
2998    }
2999
3000    fn hit_test_children(
3001        self: RenderHandle<Self>,
3002        app: &mut App,
3003        result: &mut BoxHitTestResult<'_>,
3004        position: Offset,
3005    ) -> bool {
3006        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
3007    }
3008
3009    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3010        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
3011    }
3012
3013    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3014        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
3015    }
3016
3017    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3018        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
3019    }
3020
3021    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3022        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
3023    }
3024
3025    fn compute_distance_to_actual_baseline(
3026        self: RenderHandle<Self>,
3027        app: &mut App,
3028        baseline: TextBaseline,
3029    ) -> Option<f64> {
3030        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
3031    }
3032
3033    fn compute_dry_baseline(
3034        self: RenderHandle<Self>,
3035        app: &mut App,
3036        constraints: BoxConstraints,
3037        baseline: TextBaseline,
3038    ) -> Option<f64> {
3039        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
3040    }
3041
3042    fn compute_dry_layout(
3043        self: RenderHandle<Self>,
3044        app: &mut App,
3045        constraints: BoxConstraints,
3046    ) -> Size {
3047        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
3048    }
3049}
3050
3051/// Attempts to size the child to a specific aspect ratio.
3052///
3053/// The render object first tries the largest width permitted by the layout constraints. The
3054/// height of the render object is determined by applying the given aspect ratio to the width,
3055/// expressed as a ratio of width to height.
3056///
3057/// For example, a 16:9 width:height aspect ratio would have a value of 16.0/9.0. If the maximum
3058/// width is infinite, the initial width is determined by applying the aspect ratio to the maximum
3059/// height.
3060///
3061/// Now consider a second example, this time with an aspect ratio of 2.0 and layout constraints
3062/// that require the width to be between 0.0 and 100.0 and the height to be between 0.0 and 100.0.
3063/// The largest width permitted is 100.0, and applying the ratio gives a height of 50.0.
3064pub struct RenderAspectRatio {
3065    render_object: RenderObjectData,
3066    render_box: RenderBoxData,
3067    child: RenderObjectWithChildData<AnyRenderBox>,
3068    aspect_ratio: f64,
3069}
3070
3071impl RenderAspectRatio {
3072    /// Creates a render object with a specific aspect ratio.
3073    ///
3074    /// The `aspect_ratio` argument must be a finite, positive value.
3075    pub fn new(
3076        app: &mut App,
3077        aspect_ratio: f64,
3078        child: Option<AnyRenderBox>,
3079    ) -> RenderHandle<RenderAspectRatio> {
3080        debug_assert!(aspect_ratio > 0.0);
3081        debug_assert!(aspect_ratio.is_finite());
3082        let this = RenderHandle::new_box(
3083            app,
3084            RenderAspectRatio {
3085                render_object: RenderObjectData::new(),
3086                render_box: RenderBoxData::new(),
3087                child: RenderObjectWithChildData::new(),
3088                aspect_ratio,
3089            },
3090        );
3091        this.set_child(app, child);
3092        this
3093    }
3094
3095    /// The aspect ratio to attempt to use.
3096    ///
3097    /// The aspect ratio is expressed as a ratio of width to height. For example, a 16:9
3098    /// width:height aspect ratio would have a value of 16.0/9.0.
3099    pub fn aspect_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
3100        self.get(app).aspect_ratio
3101    }
3102
3103    /// Sets [`aspect_ratio`](Self::aspect_ratio).
3104    pub fn set_aspect_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
3105        debug_assert!(value > 0.0);
3106        debug_assert!(value.is_finite());
3107        if self.get(app).aspect_ratio == value {
3108            return;
3109        }
3110        self.get_mut(app).aspect_ratio = value;
3111        RenderBox::mark_needs_layout(self, app);
3112    }
3113
3114    fn apply_aspect_ratio(
3115        self: RenderHandle<Self>,
3116        app: &App,
3117        constraints: BoxConstraints,
3118    ) -> Size {
3119        debug_assert!(constraints.debug_assert_is_valid(false));
3120        let aspect_ratio = self.get(app).aspect_ratio;
3121        debug_assert!(
3122            constraints.has_bounded_width() || constraints.has_bounded_height(),
3123            "{} has unbounded constraints.\n\
3124             This render object was given an aspect ratio of {aspect_ratio} but was given both \
3125             unbounded width and unbounded height constraints. Because both constraints were \
3126             unbounded, this render object doesn't know how much size to consume.",
3127            std::any::type_name::<Self>()
3128        );
3129
3130        if constraints.is_tight() {
3131            return constraints.smallest();
3132        }
3133
3134        let mut width = constraints.max_width;
3135        let mut height;
3136
3137        // We default to picking the height based on the width, but if the width would be
3138        // infinite, that's not sensible so we try to infer the height from the width.
3139        if width.is_finite() {
3140            height = width / aspect_ratio;
3141        } else {
3142            height = constraints.max_height;
3143            width = height * aspect_ratio;
3144        }
3145
3146        // We iteratively attempt to fit within the given constraints while maintaining the given
3147        // aspect ratio. The order of applying the constraints is also biased towards inferring
3148        // the height from the width.
3149
3150        if width > constraints.max_width {
3151            width = constraints.max_width;
3152            height = width / aspect_ratio;
3153        }
3154
3155        if height > constraints.max_height {
3156            height = constraints.max_height;
3157            width = height * aspect_ratio;
3158        }
3159
3160        if width < constraints.min_width {
3161            width = constraints.min_width;
3162            height = width / aspect_ratio;
3163        }
3164
3165        if height < constraints.min_height {
3166            height = constraints.min_height;
3167            width = height * aspect_ratio;
3168        }
3169
3170        constraints.constrain(Size::new(width, height))
3171    }
3172}
3173
3174impl RenderObjectWithChildMixin for RenderAspectRatio {
3175    type ChildType = AnyRenderBox;
3176
3177    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3178        &self.get(app).child
3179    }
3180
3181    fn child_data_mut(
3182        self: RenderHandle<Self>,
3183        app: &mut App,
3184    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3185        &mut self.get_mut(app).child
3186    }
3187}
3188
3189impl RenderProxyBoxMixin for RenderAspectRatio {}
3190
3191impl RenderObject for RenderAspectRatio {
3192    crate::render_object_accessors!();
3193
3194    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3195        let constraints = self.constraints(app);
3196        let size = self.get_dry_layout(app, constraints);
3197        self.set_size(app, size);
3198        if let Some(child) = self.child(app) {
3199            child.layout(app, BoxConstraints::tight(size), false);
3200        }
3201    }
3202
3203    fn paint(
3204        self: RenderHandle<Self>,
3205        app: &mut App,
3206        context: &mut PaintingContext,
3207        offset: Offset,
3208    ) {
3209        RenderProxyBoxMixin::paint(self, app, context, offset);
3210    }
3211
3212    fn visit_children(
3213        self: RenderHandle<Self>,
3214        app: &App,
3215        visitor: &mut dyn FnMut(AnyRenderObject),
3216    ) {
3217        if let Some(child) = self.child(app) {
3218            visitor(child.as_object());
3219        }
3220    }
3221}
3222
3223impl RenderBox for RenderAspectRatio {
3224    crate::render_box_accessors!();
3225
3226    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
3227        RenderProxyBoxMixin::setup_parent_data(self, app, child);
3228    }
3229
3230    fn apply_paint_transform(
3231        self: RenderHandle<Self>,
3232        app: &App,
3233        child: AnyRenderObject,
3234        transform: &mut Matrix4,
3235    ) {
3236        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
3237    }
3238
3239    fn hit_test_children(
3240        self: RenderHandle<Self>,
3241        app: &mut App,
3242        result: &mut BoxHitTestResult<'_>,
3243        position: Offset,
3244    ) -> bool {
3245        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
3246    }
3247
3248    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3249        if height.is_finite() {
3250            return height * self.get(app).aspect_ratio;
3251        }
3252        match self.child(app) {
3253            Some(child) => child.get_min_intrinsic_width(app, height),
3254            None => 0.0,
3255        }
3256    }
3257
3258    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3259        if height.is_finite() {
3260            return height * self.get(app).aspect_ratio;
3261        }
3262        match self.child(app) {
3263            Some(child) => child.get_max_intrinsic_width(app, height),
3264            None => 0.0,
3265        }
3266    }
3267
3268    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3269        if width.is_finite() {
3270            return width / self.get(app).aspect_ratio;
3271        }
3272        match self.child(app) {
3273            Some(child) => child.get_min_intrinsic_height(app, width),
3274            None => 0.0,
3275        }
3276    }
3277
3278    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3279        if width.is_finite() {
3280            return width / self.get(app).aspect_ratio;
3281        }
3282        match self.child(app) {
3283            Some(child) => child.get_max_intrinsic_height(app, width),
3284            None => 0.0,
3285        }
3286    }
3287
3288    fn compute_distance_to_actual_baseline(
3289        self: RenderHandle<Self>,
3290        app: &mut App,
3291        baseline: TextBaseline,
3292    ) -> Option<f64> {
3293        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
3294    }
3295
3296    fn compute_dry_layout(
3297        self: RenderHandle<Self>,
3298        app: &mut App,
3299        constraints: BoxConstraints,
3300    ) -> Size {
3301        self.apply_aspect_ratio(app, constraints)
3302    }
3303
3304    fn compute_dry_baseline(
3305        self: RenderHandle<Self>,
3306        app: &mut App,
3307        constraints: BoxConstraints,
3308        baseline: TextBaseline,
3309    ) -> Option<f64> {
3310        let size = self.get_dry_layout(app, constraints);
3311        RenderProxyBoxMixin::compute_dry_baseline(self, app, BoxConstraints::tight(size), baseline)
3312    }
3313}
3314
3315/// Sizes its child to the child's maximum intrinsic width.
3316///
3317/// This class is useful, for example, when unlimited width is available and you would like a
3318/// child that would otherwise attempt to expand infinitely to instead size itself to a more
3319/// reasonable width.
3320///
3321/// The constraints that this object passes to its child will adhere to the parent's constraints,
3322/// so if the constraints are not large enough to satisfy the child's maximum intrinsic width,
3323/// then the child will get less width than it otherwise would. Likewise, if the minimum width
3324/// constraint is larger than the child's maximum intrinsic width, the child will be given more
3325/// width than it otherwise would.
3326///
3327/// If [`step_width`](Self::step_width) is non-null, the child's width will be snapped to a
3328/// multiple of it. Similarly, if [`step_height`](Self::step_height) is non-null, the child's
3329/// height will be snapped to a multiple of it.
3330///
3331/// This class is relatively expensive, because it adds a speculative layout pass before the final
3332/// layout phase. Avoid using it where possible. In the worst case, this render object can result
3333/// in a layout that is O(N²) in the depth of the tree.
3334pub struct RenderIntrinsicWidth {
3335    render_object: RenderObjectData,
3336    render_box: RenderBoxData,
3337    child: RenderObjectWithChildData<AnyRenderBox>,
3338    step_width: Option<f64>,
3339    step_height: Option<f64>,
3340}
3341
3342/// Flutter's `RenderIntrinsicWidth._applyStep`.
3343fn apply_step(input: f64, step: Option<f64>) -> f64 {
3344    debug_assert!(input.is_finite());
3345    match step {
3346        Some(step) => (input / step).ceil() * step,
3347        None => input,
3348    }
3349}
3350
3351impl RenderIntrinsicWidth {
3352    /// Creates a render object that sizes itself to its child's intrinsic width.
3353    ///
3354    /// If `step_width` is given it must be > 0.0. Similarly if `step_height` is given it must be
3355    /// > 0.0.
3356    pub fn new(
3357        app: &mut App,
3358        step_width: Option<f64>,
3359        step_height: Option<f64>,
3360        child: Option<AnyRenderBox>,
3361    ) -> RenderHandle<RenderIntrinsicWidth> {
3362        debug_assert!(step_width.is_none_or(|step| step > 0.0));
3363        debug_assert!(step_height.is_none_or(|step| step > 0.0));
3364        let this = RenderHandle::new_box(
3365            app,
3366            RenderIntrinsicWidth {
3367                render_object: RenderObjectData::new(),
3368                render_box: RenderBoxData::new(),
3369                child: RenderObjectWithChildData::new(),
3370                step_width,
3371                step_height,
3372            },
3373        );
3374        this.set_child(app, child);
3375        this
3376    }
3377
3378    /// If non-null, force the child's width to be a multiple of this value.
3379    pub fn step_width(self: RenderHandle<Self>, app: &App) -> Option<f64> {
3380        self.get(app).step_width
3381    }
3382
3383    /// Sets [`step_width`](Self::step_width).
3384    pub fn set_step_width(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
3385        debug_assert!(value.is_none_or(|step| step > 0.0));
3386        if self.get(app).step_width == value {
3387            return;
3388        }
3389        self.get_mut(app).step_width = value;
3390        RenderBox::mark_needs_layout(self, app);
3391    }
3392
3393    /// If non-null, force the child's height to be a multiple of this value.
3394    pub fn step_height(self: RenderHandle<Self>, app: &App) -> Option<f64> {
3395        self.get(app).step_height
3396    }
3397
3398    /// Sets [`step_height`](Self::step_height).
3399    pub fn set_step_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
3400        debug_assert!(value.is_none_or(|step| step > 0.0));
3401        if self.get(app).step_height == value {
3402            return;
3403        }
3404        self.get_mut(app).step_height = value;
3405        RenderBox::mark_needs_layout(self, app);
3406    }
3407
3408    fn child_constraints(
3409        self: RenderHandle<Self>,
3410        app: &mut App,
3411        child: AnyRenderBox,
3412        constraints: BoxConstraints,
3413    ) -> BoxConstraints {
3414        let (step_width, step_height) = {
3415            let this = self.get(app);
3416            (this.step_width, this.step_height)
3417        };
3418        let width = if constraints.has_tight_width() {
3419            None
3420        } else {
3421            Some(apply_step(
3422                child.get_max_intrinsic_width(app, constraints.max_height),
3423                step_width,
3424            ))
3425        };
3426        let height = step_height.map(|_| {
3427            apply_step(
3428                child.get_max_intrinsic_height(app, constraints.max_width),
3429                step_height,
3430            )
3431        });
3432        constraints.tighten(width, height)
3433    }
3434
3435    /// Flutter's `_computeSize`.
3436    fn compute_size(
3437        self: RenderHandle<Self>,
3438        app: &mut App,
3439        constraints: BoxConstraints,
3440        layout_child: ChildLayouter,
3441    ) -> Size {
3442        match self.child(app) {
3443            Some(child) => {
3444                let child_constraints = self.child_constraints(app, child, constraints);
3445                layout_child(app, child, child_constraints)
3446            }
3447            None => constraints.smallest(),
3448        }
3449    }
3450}
3451
3452impl RenderObjectWithChildMixin for RenderIntrinsicWidth {
3453    type ChildType = AnyRenderBox;
3454
3455    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3456        &self.get(app).child
3457    }
3458
3459    fn child_data_mut(
3460        self: RenderHandle<Self>,
3461        app: &mut App,
3462    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3463        &mut self.get_mut(app).child
3464    }
3465}
3466
3467impl RenderProxyBoxMixin for RenderIntrinsicWidth {}
3468
3469impl RenderObject for RenderIntrinsicWidth {
3470    crate::render_object_accessors!();
3471
3472    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3473        let constraints = self.constraints(app);
3474        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
3475        self.set_size(app, size);
3476    }
3477
3478    fn paint(
3479        self: RenderHandle<Self>,
3480        app: &mut App,
3481        context: &mut PaintingContext,
3482        offset: Offset,
3483    ) {
3484        RenderProxyBoxMixin::paint(self, app, context, offset);
3485    }
3486
3487    fn visit_children(
3488        self: RenderHandle<Self>,
3489        app: &App,
3490        visitor: &mut dyn FnMut(AnyRenderObject),
3491    ) {
3492        if let Some(child) = self.child(app) {
3493            visitor(child.as_object());
3494        }
3495    }
3496}
3497
3498impl RenderBox for RenderIntrinsicWidth {
3499    crate::render_box_accessors!();
3500
3501    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
3502        RenderProxyBoxMixin::setup_parent_data(self, app, child);
3503    }
3504
3505    fn apply_paint_transform(
3506        self: RenderHandle<Self>,
3507        app: &App,
3508        child: AnyRenderObject,
3509        transform: &mut Matrix4,
3510    ) {
3511        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
3512    }
3513
3514    fn hit_test_children(
3515        self: RenderHandle<Self>,
3516        app: &mut App,
3517        result: &mut BoxHitTestResult<'_>,
3518        position: Offset,
3519    ) -> bool {
3520        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
3521    }
3522
3523    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3524        self.as_box().get_max_intrinsic_width(app, height)
3525    }
3526
3527    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3528        let Some(child) = self.child(app) else {
3529            return 0.0;
3530        };
3531        let width = child.get_max_intrinsic_width(app, height);
3532        apply_step(width, self.get(app).step_width)
3533    }
3534
3535    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3536        let Some(child) = self.child(app) else {
3537            return 0.0;
3538        };
3539        let width = if width.is_finite() {
3540            width
3541        } else {
3542            self.as_box().get_max_intrinsic_width(app, f64::INFINITY)
3543        };
3544        debug_assert!(width.is_finite());
3545        let height = child.get_min_intrinsic_height(app, width);
3546        apply_step(height, self.get(app).step_height)
3547    }
3548
3549    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3550        let Some(child) = self.child(app) else {
3551            return 0.0;
3552        };
3553        let width = if width.is_finite() {
3554            width
3555        } else {
3556            self.as_box().get_max_intrinsic_width(app, f64::INFINITY)
3557        };
3558        debug_assert!(width.is_finite());
3559        let height = child.get_max_intrinsic_height(app, width);
3560        apply_step(height, self.get(app).step_height)
3561    }
3562
3563    fn compute_distance_to_actual_baseline(
3564        self: RenderHandle<Self>,
3565        app: &mut App,
3566        baseline: TextBaseline,
3567    ) -> Option<f64> {
3568        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
3569    }
3570
3571    fn compute_dry_layout(
3572        self: RenderHandle<Self>,
3573        app: &mut App,
3574        constraints: BoxConstraints,
3575    ) -> Size {
3576        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
3577    }
3578
3579    fn compute_dry_baseline(
3580        self: RenderHandle<Self>,
3581        app: &mut App,
3582        constraints: BoxConstraints,
3583        baseline: TextBaseline,
3584    ) -> Option<f64> {
3585        let child = self.child(app)?;
3586        let child_constraints = self.child_constraints(app, child, constraints);
3587        child.get_dry_baseline(app, child_constraints, baseline)
3588    }
3589}
3590
3591/// Sizes its child to the child's intrinsic height.
3592///
3593/// This class is useful, for example, when unlimited height is available and you would like a
3594/// child that would otherwise attempt to expand infinitely to instead size itself to a more
3595/// reasonable height.
3596///
3597/// The constraints that this object passes to its child will adhere to the parent's constraints,
3598/// so if the constraints are not large enough to satisfy the child's maximum intrinsic height,
3599/// then the child will get less height than it otherwise would. Likewise, if the minimum height
3600/// constraint is larger than the child's maximum intrinsic height, the child will be given more
3601/// height than it otherwise would.
3602///
3603/// This class is relatively expensive, because it adds a speculative layout pass before the final
3604/// layout phase. Avoid using it where possible. In the worst case, this render object can result
3605/// in a layout that is O(N²) in the depth of the tree.
3606pub struct RenderIntrinsicHeight {
3607    render_object: RenderObjectData,
3608    render_box: RenderBoxData,
3609    child: RenderObjectWithChildData<AnyRenderBox>,
3610}
3611
3612impl RenderIntrinsicHeight {
3613    /// Creates a render object that sizes itself to its child's intrinsic height.
3614    pub fn new(app: &mut App, child: Option<AnyRenderBox>) -> RenderHandle<RenderIntrinsicHeight> {
3615        let this = RenderHandle::new_box(
3616            app,
3617            RenderIntrinsicHeight {
3618                render_object: RenderObjectData::new(),
3619                render_box: RenderBoxData::new(),
3620                child: RenderObjectWithChildData::new(),
3621            },
3622        );
3623        this.set_child(app, child);
3624        this
3625    }
3626
3627    fn child_constraints(
3628        self: RenderHandle<Self>,
3629        app: &mut App,
3630        child: AnyRenderBox,
3631        constraints: BoxConstraints,
3632    ) -> BoxConstraints {
3633        if constraints.has_tight_height() {
3634            return constraints;
3635        }
3636        let height = child.get_max_intrinsic_height(app, constraints.max_width);
3637        constraints.tighten(None, Some(height))
3638    }
3639
3640    /// Flutter's `_computeSize`.
3641    fn compute_size(
3642        self: RenderHandle<Self>,
3643        app: &mut App,
3644        constraints: BoxConstraints,
3645        layout_child: ChildLayouter,
3646    ) -> Size {
3647        match self.child(app) {
3648            Some(child) => {
3649                let child_constraints = self.child_constraints(app, child, constraints);
3650                layout_child(app, child, child_constraints)
3651            }
3652            None => constraints.smallest(),
3653        }
3654    }
3655}
3656
3657impl RenderObjectWithChildMixin for RenderIntrinsicHeight {
3658    type ChildType = AnyRenderBox;
3659
3660    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
3661        &self.get(app).child
3662    }
3663
3664    fn child_data_mut(
3665        self: RenderHandle<Self>,
3666        app: &mut App,
3667    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
3668        &mut self.get_mut(app).child
3669    }
3670}
3671
3672impl RenderProxyBoxMixin for RenderIntrinsicHeight {}
3673
3674impl RenderObject for RenderIntrinsicHeight {
3675    crate::render_object_accessors!();
3676
3677    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3678        let constraints = self.constraints(app);
3679        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
3680        self.set_size(app, size);
3681    }
3682
3683    fn paint(
3684        self: RenderHandle<Self>,
3685        app: &mut App,
3686        context: &mut PaintingContext,
3687        offset: Offset,
3688    ) {
3689        RenderProxyBoxMixin::paint(self, app, context, offset);
3690    }
3691
3692    fn visit_children(
3693        self: RenderHandle<Self>,
3694        app: &App,
3695        visitor: &mut dyn FnMut(AnyRenderObject),
3696    ) {
3697        if let Some(child) = self.child(app) {
3698            visitor(child.as_object());
3699        }
3700    }
3701}
3702
3703impl RenderBox for RenderIntrinsicHeight {
3704    crate::render_box_accessors!();
3705
3706    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
3707        RenderProxyBoxMixin::setup_parent_data(self, app, child);
3708    }
3709
3710    fn apply_paint_transform(
3711        self: RenderHandle<Self>,
3712        app: &App,
3713        child: AnyRenderObject,
3714        transform: &mut Matrix4,
3715    ) {
3716        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
3717    }
3718
3719    fn hit_test_children(
3720        self: RenderHandle<Self>,
3721        app: &mut App,
3722        result: &mut BoxHitTestResult<'_>,
3723        position: Offset,
3724    ) -> bool {
3725        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
3726    }
3727
3728    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3729        let Some(child) = self.child(app) else {
3730            return 0.0;
3731        };
3732        let height = if height.is_finite() {
3733            height
3734        } else {
3735            child.get_max_intrinsic_height(app, f64::INFINITY)
3736        };
3737        debug_assert!(height.is_finite());
3738        child.get_min_intrinsic_width(app, height)
3739    }
3740
3741    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
3742        let Some(child) = self.child(app) else {
3743            return 0.0;
3744        };
3745        let height = if height.is_finite() {
3746            height
3747        } else {
3748            child.get_max_intrinsic_height(app, f64::INFINITY)
3749        };
3750        debug_assert!(height.is_finite());
3751        child.get_max_intrinsic_width(app, height)
3752    }
3753
3754    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3755        self.as_box().get_max_intrinsic_height(app, width)
3756    }
3757
3758    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
3759        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
3760    }
3761
3762    fn compute_distance_to_actual_baseline(
3763        self: RenderHandle<Self>,
3764        app: &mut App,
3765        baseline: TextBaseline,
3766    ) -> Option<f64> {
3767        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
3768    }
3769
3770    fn compute_dry_layout(
3771        self: RenderHandle<Self>,
3772        app: &mut App,
3773        constraints: BoxConstraints,
3774    ) -> Size {
3775        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
3776    }
3777
3778    fn compute_dry_baseline(
3779        self: RenderHandle<Self>,
3780        app: &mut App,
3781        constraints: BoxConstraints,
3782        baseline: TextBaseline,
3783    ) -> Option<f64> {
3784        let child = self.child(app)?;
3785        let child_constraints = self.child_constraints(app, child, constraints);
3786        child.get_dry_baseline(app, child_constraints, baseline)
3787    }
3788}
3789
3790/// An interface for providing custom clips.
3791///
3792/// This trait is used by a number of clip widgets (e.g., `ClipRect` and `ClipPath`).
3793///
3794/// The [`get_clip`](Self::get_clip) method is called whenever the custom clip needs to be
3795/// updated.
3796///
3797/// The [`should_reclip`](Self::should_reclip) method is called when a new instance of the class
3798/// is provided, to check if the new instance actually represents different information.
3799///
3800/// The most efficient way to update the clip provided by this class is to
3801/// supply a [`reclip`](Self::reclip) listenable, which notifies its listeners when it is time to
3802/// reclip, avoiding both the build and layout phases of the pipeline.
3803pub trait CustomClipper<T>: 'static {
3804    /// The [`Listenable`] that notifies when it is time to reclip.
3805    ///
3806    /// Dart's `CustomClipper` takes it as a constructor argument and forwards `addListener` /
3807    /// `removeListener` to it; here the clipper answers with it and the same forwarding is the
3808    /// [`Listenable`] implementation of `dyn CustomClipper<T>`.
3809    fn reclip(&self) -> Option<&Rc<dyn Listenable>> {
3810        None
3811    }
3812
3813    /// Returns a description of the clip given that the render object being
3814    /// clipped is of the given size.
3815    ///
3816    /// `app` reaches what a Dart clipper reads directly: an animation's value.
3817    fn get_clip(&self, app: &App, size: Size) -> T;
3818
3819    /// Called whenever a new instance of the custom clipper delegate class is
3820    /// provided to the clip object, or any time that a new clip object is created
3821    /// with a new instance of the custom clipper delegate class (which amounts to
3822    /// the same thing, because the latter is implemented in terms of the former).
3823    ///
3824    /// If the new instance represents different information than the old
3825    /// instance, then the method should return true, otherwise it should return
3826    /// false.
3827    ///
3828    /// If the method returns false, then the [`get_clip`](Self::get_clip) call might be
3829    /// optimized away.
3830    ///
3831    /// It's possible that the [`get_clip`](Self::get_clip) method will get called even if
3832    /// [`should_reclip`](Self::should_reclip) returns false or if the
3833    /// [`should_reclip`](Self::should_reclip) method is never called at all (e.g. if the box
3834    /// changes size). It is only called with a clipper of this clipper's own type, as Dart's
3835    /// `covariant` parameter is.
3836    fn should_reclip(&self, app: &App, old_clipper: &dyn CustomClipper<T>) -> bool;
3837
3838    /// Downcast support for Dart's `runtimeType` comparison and `covariant` parameter.
3839    fn as_any(&self) -> &dyn Any;
3840}
3841
3842impl<T: 'static> Listenable for dyn CustomClipper<T> {
3843    /// Register a closure to be notified when it is time to reclip.
3844    ///
3845    /// Forwards to the [`reclip`](CustomClipper::reclip) listenable, if it is not `None`.
3846    fn add_listener(&self, app: &mut App, listener: Listener) {
3847        if let Some(reclip) = self.reclip() {
3848            reclip.add_listener(app, listener);
3849        }
3850    }
3851
3852    /// Remove a previously registered closure from the list of closures that the
3853    /// object notifies when it is time to reclip.
3854    fn remove_listener(&self, app: &mut App, listener: &Listener) {
3855        if let Some(reclip) = self.reclip() {
3856            reclip.remove_listener(app, listener);
3857        }
3858    }
3859}
3860
3861/// The fields of [`RenderCustomClip`].
3862pub struct RenderCustomClipData<T> {
3863    clipper: Option<Rc<dyn CustomClipper<T>>>,
3864    clip: Option<T>,
3865    clip_behavior: Clip,
3866}
3867
3868impl<T> RenderCustomClipData<T> {
3869    /// Creates the fields of a clip with no clip computed yet.
3870    pub fn new(
3871        clipper: Option<Rc<dyn CustomClipper<T>>>,
3872        clip_behavior: Clip,
3873    ) -> RenderCustomClipData<T> {
3874        RenderCustomClipData {
3875            clipper,
3876            clip: None,
3877            clip_behavior,
3878        }
3879    }
3880}
3881
3882/// A [`CustomClipper`] that clips to the outer path of a `ShapeBorder`.
3883pub struct ShapeBorderClipper {
3884    /// The shape border whose outer path defines the clip.
3885    pub shape: ShapeBorderRef,
3886    /// The text direction to use for getting the outer path for `shape`.
3887    ///
3888    /// `ShapeBorder`s can depend on the text direction (e.g having a "dent" on the left hand
3889    /// side in LTR and on the right hand side in RTL).
3890    pub text_direction: Option<TextDirection>,
3891}
3892
3893impl ShapeBorderClipper {
3894    /// Creates a [`ShapeBorder`] clipper.
3895    ///
3896    /// The `text_direction` argument must be provided non-`None` if `shape` has a text
3897    /// direction dependency (for example if it is expressed in terms of "start" and "end"
3898    /// instead of "left" and "right"). It may be `None` if the border will not need the text
3899    /// direction to paint itself.
3900    pub fn new(shape: ShapeBorderRef, text_direction: Option<TextDirection>) -> Self {
3901        ShapeBorderClipper {
3902            shape,
3903            text_direction,
3904        }
3905    }
3906}
3907
3908impl CustomClipper<Path> for ShapeBorderClipper {
3909    fn get_clip(&self, _app: &App, size: Size) -> Path {
3910        self.shape
3911            .get_outer_path(Offset::ZERO & size, self.text_direction)
3912    }
3913
3914    fn should_reclip(&self, _app: &App, old_clipper: &dyn CustomClipper<Path>) -> bool {
3915        let Some(old_clipper) = old_clipper.as_any().downcast_ref::<ShapeBorderClipper>() else {
3916            return true;
3917        };
3918        old_clipper.shape != self.shape || old_clipper.text_direction != self.text_direction
3919    }
3920
3921    fn as_any(&self) -> &dyn Any {
3922        self
3923    }
3924}
3925
3926/// A base class for render boxes that clip their child.
3927///
3928/// Flutter's private `_RenderCustomClip<T>`: the shared bodies of a clip. A leaf implements
3929/// [`default_clip`](Self::default_clip), holds a [`RenderCustomClipData<T>`], and calls these
3930/// where Dart would run the inherited method: `RenderCustomClip::perform_layout(self, app)`.
3931pub trait RenderCustomClip<T: Clone + 'static>: RenderProxyBoxMixin {
3932    /// Mixin field access.
3933    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<T>;
3934
3935    /// See [`custom_clip_data`](Self::custom_clip_data).
3936    fn custom_clip_data_mut(
3937        self: RenderHandle<Self>,
3938        app: &mut App,
3939    ) -> &mut RenderCustomClipData<T>;
3940
3941    /// The clip to use when [`clipper`](Self::clipper) is `None`.
3942    fn default_clip(self: RenderHandle<Self>, app: &App) -> T;
3943
3944    /// If non-`None`, determines which clip to use on the child.
3945    fn clipper(self: RenderHandle<Self>, app: &App) -> Option<Rc<dyn CustomClipper<T>>> {
3946        self.custom_clip_data(app).clipper.clone()
3947    }
3948
3949    /// Sets [`clipper`](Self::clipper).
3950    fn set_clipper(
3951        self: RenderHandle<Self>,
3952        app: &mut App,
3953        new_clipper: Option<Rc<dyn CustomClipper<T>>>,
3954    ) {
3955        let old_clipper = self.clipper(app);
3956        if same_instance(old_clipper.as_ref(), new_clipper.as_ref()) {
3957            return;
3958        }
3959        self.custom_clip_data_mut(app).clipper = new_clipper.clone();
3960        debug_assert!(new_clipper.is_some() || old_clipper.is_some());
3961        let reclip = match (&new_clipper, &old_clipper) {
3962            (Some(new_clipper), Some(old_clipper)) => {
3963                new_clipper.as_any().type_id() != old_clipper.as_any().type_id()
3964                    || new_clipper.should_reclip(app, &**old_clipper)
3965            }
3966            _ => true,
3967        };
3968        if reclip {
3969            self.mark_needs_clip(app);
3970        }
3971        if self.attached(app) {
3972            if let Some(old_clipper) = &old_clipper {
3973                old_clipper.remove_listener(app, &self.clip_listener());
3974            }
3975            if let Some(new_clipper) = &new_clipper {
3976                new_clipper.add_listener(app, self.clip_listener());
3977            }
3978        }
3979    }
3980
3981    /// Flutter's `attach` after `super.attach(owner)`.
3982    fn did_attach(self: RenderHandle<Self>, app: &mut App) {
3983        if let Some(clipper) = self.clipper(app) {
3984            clipper.add_listener(app, self.clip_listener());
3985        }
3986    }
3987
3988    /// Flutter's `detach` before `super.detach()`.
3989    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
3990        if let Some(clipper) = self.clipper(app) {
3991            clipper.remove_listener(app, &self.clip_listener());
3992        }
3993    }
3994
3995    /// Flutter's `_markNeedsClip`.
3996    fn mark_needs_clip(self: RenderHandle<Self>, app: &mut App) {
3997        self.custom_clip_data_mut(app).clip = None;
3998        self.mark_needs_paint(app);
3999    }
4000
4001    /// The `_markNeedsClip` tear-off, equal to itself across registrations.
4002    fn clip_listener(self: RenderHandle<Self>) -> Listener {
4003        Listener::handle_method(self.handle(), mark_needs_clip::<Self, T>)
4004    }
4005
4006    /// Whether and how to clip the child.
4007    fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
4008        self.custom_clip_data(app).clip_behavior
4009    }
4010
4011    /// Sets [`clip_behavior`](Self::clip_behavior).
4012    fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
4013        if value != self.clip_behavior(app) {
4014            self.custom_clip_data_mut(app).clip_behavior = value;
4015            self.mark_needs_paint(app);
4016        }
4017    }
4018
4019    /// Flutter's `performLayout`: a resize drops the cached clip.
4020    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4021        let old_size = self.has_size(app).then(|| self.size(app));
4022        RenderProxyBoxMixin::perform_layout(self, app);
4023        if old_size != Some(self.size(app)) {
4024            self.custom_clip_data_mut(app).clip = None;
4025        }
4026    }
4027
4028    /// Flutter's `_updateClip`: computes the clip if it is not cached.
4029    fn update_clip(self: RenderHandle<Self>, app: &mut App) {
4030        if self.custom_clip_data(app).clip.is_some() {
4031            return;
4032        }
4033        let clip = match self.clipper(app) {
4034            Some(clipper) => clipper.get_clip(app, self.size(app)),
4035            None => self.default_clip(app),
4036        };
4037        self.custom_clip_data_mut(app).clip = Some(clip);
4038    }
4039
4040    /// The cached clip. Call [`update_clip`](Self::update_clip) first; Dart's `_clip!`.
4041    fn clip(self: RenderHandle<Self>, app: &App) -> T {
4042        self.custom_clip_data(app)
4043            .clip
4044            .clone()
4045            .expect("update_clip computes the clip")
4046    }
4047}
4048
4049fn mark_needs_clip<C: RenderCustomClip<T>, T: Clone + 'static>(this: Handle<C>, app: &mut App) {
4050    RenderCustomClip::mark_needs_clip(RenderHandle::from_handle(this), app);
4051}
4052
4053/// Clips its child using a rectangle.
4054///
4055/// By default, [`RenderClipRect`] prevents its child from painting outside its
4056/// bounds, but the size and location of the clip rect can be customized using a
4057/// custom [`clipper`](RenderCustomClip::clipper).
4058pub struct RenderClipRect {
4059    render_object: RenderObjectData,
4060    render_box: RenderBoxData,
4061    child: RenderObjectWithChildData<AnyRenderBox>,
4062    custom_clip: RenderCustomClipData<Rect>,
4063}
4064
4065impl RenderClipRect {
4066    /// Creates a rectangular clip.
4067    ///
4068    /// If `clipper` is `None`, the clip will match the layout size and position of
4069    /// the child.
4070    ///
4071    /// If `clip_behavior` is [`Clip::None`], no clipping will be applied.
4072    pub fn new(
4073        app: &mut App,
4074        clipper: Option<Rc<dyn CustomClipper<Rect>>>,
4075        clip_behavior: Clip,
4076        child: Option<AnyRenderBox>,
4077    ) -> RenderHandle<RenderClipRect> {
4078        let this = RenderHandle::new_box(
4079            app,
4080            RenderClipRect {
4081                render_object: RenderObjectData::new(),
4082                render_box: RenderBoxData::new(),
4083                child: RenderObjectWithChildData::new(),
4084                custom_clip: RenderCustomClipData::new(clipper, clip_behavior),
4085            },
4086        );
4087        this.set_child(app, child);
4088        this
4089    }
4090}
4091
4092impl RenderObjectWithChildMixin for RenderClipRect {
4093    type ChildType = AnyRenderBox;
4094
4095    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
4096        &self.get(app).child
4097    }
4098
4099    fn child_data_mut(
4100        self: RenderHandle<Self>,
4101        app: &mut App,
4102    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
4103        &mut self.get_mut(app).child
4104    }
4105}
4106
4107impl RenderProxyBoxMixin for RenderClipRect {}
4108
4109impl RenderCustomClip<Rect> for RenderClipRect {
4110    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<Rect> {
4111        &self.get(app).custom_clip
4112    }
4113
4114    fn custom_clip_data_mut(
4115        self: RenderHandle<Self>,
4116        app: &mut App,
4117    ) -> &mut RenderCustomClipData<Rect> {
4118        &mut self.get_mut(app).custom_clip
4119    }
4120
4121    fn default_clip(self: RenderHandle<Self>, app: &App) -> Rect {
4122        Offset::ZERO & self.size(app)
4123    }
4124}
4125
4126impl RenderObject for RenderClipRect {
4127    crate::render_object_accessors!();
4128
4129    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
4130        if let Some(child) = self.child(app) {
4131            child.as_object().attach(app, owner);
4132        }
4133        RenderCustomClip::did_attach(self, app);
4134    }
4135
4136    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
4137        RenderCustomClip::did_detach(self, app);
4138        if let Some(child) = self.child(app) {
4139            child.as_object().detach(app);
4140        }
4141    }
4142
4143    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4144        RenderCustomClip::perform_layout(self, app);
4145    }
4146
4147    fn paint(
4148        self: RenderHandle<Self>,
4149        app: &mut App,
4150        context: &mut PaintingContext,
4151        offset: Offset,
4152    ) {
4153        if let Some(child) = self.child(app) {
4154            let clip_behavior = self.clip_behavior(app);
4155            if clip_behavior != Clip::None {
4156                self.update_clip(app);
4157                let clip = self.clip(app);
4158                let old = self.as_object().layer_as::<ClipRectLayer>(app);
4159                let layer = context.push_clip_rect(
4160                    app,
4161                    self.as_object().needs_compositing(app),
4162                    offset,
4163                    clip,
4164                    |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
4165                    clip_behavior,
4166                    old,
4167                );
4168                self.as_object()
4169                    .set_layer(app, layer.map(|layer| layer.as_container_layer()));
4170            } else {
4171                context.paint_child(app, child.as_object(), offset);
4172                self.as_object().set_layer(app, None);
4173            }
4174        } else {
4175            self.as_object().set_layer(app, None);
4176        }
4177    }
4178
4179    fn visit_children(
4180        self: RenderHandle<Self>,
4181        app: &App,
4182        visitor: &mut dyn FnMut(AnyRenderObject),
4183    ) {
4184        if let Some(child) = self.child(app) {
4185            visitor(child.as_object());
4186        }
4187    }
4188}
4189
4190impl RenderBox for RenderClipRect {
4191    crate::render_box_accessors!();
4192
4193    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
4194        RenderProxyBoxMixin::setup_parent_data(self, app, child);
4195    }
4196
4197    fn apply_paint_transform(
4198        self: RenderHandle<Self>,
4199        app: &App,
4200        child: AnyRenderObject,
4201        transform: &mut Matrix4,
4202    ) {
4203        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
4204    }
4205
4206    fn hit_test(
4207        self: RenderHandle<Self>,
4208        app: &mut App,
4209        result: &mut BoxHitTestResult<'_>,
4210        position: Offset,
4211    ) -> bool {
4212        if self.clipper(app).is_some() {
4213            self.update_clip(app);
4214            if !self.clip(app).contains(position) {
4215                return false;
4216            }
4217        }
4218        RenderBoxBase::hit_test(self, app, result, position)
4219    }
4220
4221    fn hit_test_children(
4222        self: RenderHandle<Self>,
4223        app: &mut App,
4224        result: &mut BoxHitTestResult<'_>,
4225        position: Offset,
4226    ) -> bool {
4227        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
4228    }
4229
4230    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4231        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
4232    }
4233
4234    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4235        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
4236    }
4237
4238    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4239        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
4240    }
4241
4242    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4243        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
4244    }
4245
4246    fn compute_distance_to_actual_baseline(
4247        self: RenderHandle<Self>,
4248        app: &mut App,
4249        baseline: TextBaseline,
4250    ) -> Option<f64> {
4251        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
4252    }
4253
4254    fn compute_dry_baseline(
4255        self: RenderHandle<Self>,
4256        app: &mut App,
4257        constraints: BoxConstraints,
4258        baseline: TextBaseline,
4259    ) -> Option<f64> {
4260        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
4261    }
4262
4263    fn compute_dry_layout(
4264        self: RenderHandle<Self>,
4265        app: &mut App,
4266        constraints: BoxConstraints,
4267    ) -> Size {
4268        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
4269    }
4270}
4271
4272/// Clips its child using a rounded rectangle.
4273///
4274/// By default, [`RenderClipRRect`] uses its own bounds as the base rectangle for
4275/// the clip, but the size and location of the clip can be customized using a
4276/// custom [`clipper`](RenderCustomClip::clipper).
4277pub struct RenderClipRRect {
4278    render_object: RenderObjectData,
4279    render_box: RenderBoxData,
4280    child: RenderObjectWithChildData<AnyRenderBox>,
4281    custom_clip: RenderCustomClipData<RRect>,
4282    border_radius: BorderRadiusGeometry,
4283    text_direction: Option<TextDirection>,
4284}
4285
4286impl RenderClipRRect {
4287    /// Creates a rounded-rectangular clip.
4288    ///
4289    /// The `border_radius` defaults to [`BorderRadiusGeometry::ZERO`], i.e. a rectangle with
4290    /// right-angled corners.
4291    ///
4292    /// If `clipper` is non-`None`, then `border_radius` is ignored.
4293    ///
4294    /// If `clip_behavior` is [`Clip::None`], no clipping will be applied.
4295    pub fn new(
4296        app: &mut App,
4297        border_radius: BorderRadiusGeometry,
4298        clipper: Option<Rc<dyn CustomClipper<RRect>>>,
4299        clip_behavior: Clip,
4300        text_direction: Option<TextDirection>,
4301        child: Option<AnyRenderBox>,
4302    ) -> RenderHandle<RenderClipRRect> {
4303        let this = RenderHandle::new_box(
4304            app,
4305            RenderClipRRect {
4306                render_object: RenderObjectData::new(),
4307                render_box: RenderBoxData::new(),
4308                child: RenderObjectWithChildData::new(),
4309                custom_clip: RenderCustomClipData::new(clipper, clip_behavior),
4310                border_radius,
4311                text_direction,
4312            },
4313        );
4314        this.set_child(app, child);
4315        this
4316    }
4317
4318    /// The border radius of the rounded corners.
4319    ///
4320    /// Values are clamped so that horizontal and vertical radii sums do not
4321    /// exceed width/height.
4322    ///
4323    /// This value is ignored if [`clipper`](RenderCustomClip::clipper) is non-`None`.
4324    pub fn border_radius(self: RenderHandle<Self>, app: &App) -> BorderRadiusGeometry {
4325        self.get(app).border_radius
4326    }
4327
4328    /// Sets [`border_radius`](Self::border_radius).
4329    pub fn set_border_radius(self: RenderHandle<Self>, app: &mut App, value: BorderRadiusGeometry) {
4330        if self.get(app).border_radius == value {
4331            return;
4332        }
4333        self.get_mut(app).border_radius = value;
4334        self.mark_needs_clip(app);
4335    }
4336
4337    /// The text direction with which to resolve [`border_radius`](Self::border_radius).
4338    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
4339        self.get(app).text_direction
4340    }
4341
4342    /// Sets [`text_direction`](Self::text_direction).
4343    pub fn set_text_direction(
4344        self: RenderHandle<Self>,
4345        app: &mut App,
4346        value: Option<TextDirection>,
4347    ) {
4348        if self.get(app).text_direction == value {
4349            return;
4350        }
4351        self.get_mut(app).text_direction = value;
4352        self.mark_needs_clip(app);
4353    }
4354}
4355
4356impl RenderObjectWithChildMixin for RenderClipRRect {
4357    type ChildType = AnyRenderBox;
4358
4359    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
4360        &self.get(app).child
4361    }
4362
4363    fn child_data_mut(
4364        self: RenderHandle<Self>,
4365        app: &mut App,
4366    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
4367        &mut self.get_mut(app).child
4368    }
4369}
4370
4371impl RenderProxyBoxMixin for RenderClipRRect {}
4372
4373impl RenderCustomClip<RRect> for RenderClipRRect {
4374    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<RRect> {
4375        &self.get(app).custom_clip
4376    }
4377
4378    fn custom_clip_data_mut(
4379        self: RenderHandle<Self>,
4380        app: &mut App,
4381    ) -> &mut RenderCustomClipData<RRect> {
4382        &mut self.get_mut(app).custom_clip
4383    }
4384
4385    fn default_clip(self: RenderHandle<Self>, app: &App) -> RRect {
4386        let this = self.get(app);
4387        this.border_radius
4388            .resolve(this.text_direction)
4389            .to_rrect(Offset::ZERO & self.size(app))
4390    }
4391}
4392
4393impl RenderObject for RenderClipRRect {
4394    crate::render_object_accessors!();
4395
4396    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
4397        if let Some(child) = self.child(app) {
4398            child.as_object().attach(app, owner);
4399        }
4400        RenderCustomClip::did_attach(self, app);
4401    }
4402
4403    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
4404        RenderCustomClip::did_detach(self, app);
4405        if let Some(child) = self.child(app) {
4406            child.as_object().detach(app);
4407        }
4408    }
4409
4410    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4411        RenderCustomClip::perform_layout(self, app);
4412    }
4413
4414    fn paint(
4415        self: RenderHandle<Self>,
4416        app: &mut App,
4417        context: &mut PaintingContext,
4418        offset: Offset,
4419    ) {
4420        if let Some(child) = self.child(app) {
4421            let clip_behavior = self.clip_behavior(app);
4422            if clip_behavior != Clip::None {
4423                self.update_clip(app);
4424                let clip = self.clip(app);
4425                let old = self.as_object().layer_as::<ClipRRectLayer>(app);
4426                let layer = context.push_clip_rrect(
4427                    app,
4428                    self.as_object().needs_compositing(app),
4429                    offset,
4430                    clip.outer_rect(),
4431                    clip,
4432                    |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
4433                    clip_behavior,
4434                    old,
4435                );
4436                self.as_object()
4437                    .set_layer(app, layer.map(|layer| layer.as_container_layer()));
4438            } else {
4439                context.paint_child(app, child.as_object(), offset);
4440                self.as_object().set_layer(app, None);
4441            }
4442        } else {
4443            self.as_object().set_layer(app, None);
4444        }
4445    }
4446
4447    fn visit_children(
4448        self: RenderHandle<Self>,
4449        app: &App,
4450        visitor: &mut dyn FnMut(AnyRenderObject),
4451    ) {
4452        if let Some(child) = self.child(app) {
4453            visitor(child.as_object());
4454        }
4455    }
4456}
4457
4458impl RenderBox for RenderClipRRect {
4459    crate::render_box_accessors!();
4460
4461    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
4462        RenderProxyBoxMixin::setup_parent_data(self, app, child);
4463    }
4464
4465    fn apply_paint_transform(
4466        self: RenderHandle<Self>,
4467        app: &App,
4468        child: AnyRenderObject,
4469        transform: &mut Matrix4,
4470    ) {
4471        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
4472    }
4473
4474    fn hit_test(
4475        self: RenderHandle<Self>,
4476        app: &mut App,
4477        result: &mut BoxHitTestResult<'_>,
4478        position: Offset,
4479    ) -> bool {
4480        if self.clipper(app).is_some() {
4481            self.update_clip(app);
4482            if !self.clip(app).contains(position) {
4483                return false;
4484            }
4485        }
4486        RenderBoxBase::hit_test(self, app, result, position)
4487    }
4488
4489    fn hit_test_children(
4490        self: RenderHandle<Self>,
4491        app: &mut App,
4492        result: &mut BoxHitTestResult<'_>,
4493        position: Offset,
4494    ) -> bool {
4495        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
4496    }
4497
4498    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4499        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
4500    }
4501
4502    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4503        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
4504    }
4505
4506    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4507        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
4508    }
4509
4510    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4511        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
4512    }
4513
4514    fn compute_distance_to_actual_baseline(
4515        self: RenderHandle<Self>,
4516        app: &mut App,
4517        baseline: TextBaseline,
4518    ) -> Option<f64> {
4519        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
4520    }
4521
4522    fn compute_dry_baseline(
4523        self: RenderHandle<Self>,
4524        app: &mut App,
4525        constraints: BoxConstraints,
4526        baseline: TextBaseline,
4527    ) -> Option<f64> {
4528        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
4529    }
4530
4531    fn compute_dry_layout(
4532        self: RenderHandle<Self>,
4533        app: &mut App,
4534        constraints: BoxConstraints,
4535    ) -> Size {
4536        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
4537    }
4538}
4539
4540/// Clips its child using an oval.
4541///
4542/// Inscribes an oval into its layout dimensions and prevents its child from
4543/// painting outside that oval.
4544pub struct RenderClipOval {
4545    render_object: RenderObjectData,
4546    render_box: RenderBoxData,
4547    child: RenderObjectWithChildData<AnyRenderBox>,
4548    custom_clip: RenderCustomClipData<Rect>,
4549    cached_rect: Option<Rect>,
4550    cached_path: Option<Path>,
4551}
4552
4553impl RenderClipOval {
4554    /// Creates an oval-shaped clip.
4555    ///
4556    /// If `clipper` is `None`, the oval will be inscribed into the layout size and
4557    /// position of the child.
4558    ///
4559    /// If `clip_behavior` is [`Clip::None`], no clipping will be applied.
4560    pub fn new(
4561        app: &mut App,
4562        clipper: Option<Rc<dyn CustomClipper<Rect>>>,
4563        clip_behavior: Clip,
4564        child: Option<AnyRenderBox>,
4565    ) -> RenderHandle<RenderClipOval> {
4566        let this = RenderHandle::new_box(
4567            app,
4568            RenderClipOval {
4569                render_object: RenderObjectData::new(),
4570                render_box: RenderBoxData::new(),
4571                child: RenderObjectWithChildData::new(),
4572                custom_clip: RenderCustomClipData::new(clipper, clip_behavior),
4573                cached_rect: None,
4574                cached_path: None,
4575            },
4576        );
4577        this.set_child(app, child);
4578        this
4579    }
4580
4581    fn get_clip_path(self: RenderHandle<Self>, app: &mut App, rect: Rect) -> Path {
4582        if self.get(app).cached_rect != Some(rect) {
4583            let radius = [(rect.width() / 2.0) as f32, (rect.height() / 2.0) as f32];
4584            let mut path = PathBuilder::new();
4585            path.rrect_radii_elliptical(rect, [radius; 4]);
4586            let this = self.get_mut(app);
4587            this.cached_rect = Some(rect);
4588            this.cached_path = Some(path.build().into());
4589        }
4590        self.get(app).cached_path.clone().expect("cached above")
4591    }
4592}
4593
4594impl RenderObjectWithChildMixin for RenderClipOval {
4595    type ChildType = AnyRenderBox;
4596
4597    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
4598        &self.get(app).child
4599    }
4600
4601    fn child_data_mut(
4602        self: RenderHandle<Self>,
4603        app: &mut App,
4604    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
4605        &mut self.get_mut(app).child
4606    }
4607}
4608
4609impl RenderProxyBoxMixin for RenderClipOval {}
4610
4611impl RenderCustomClip<Rect> for RenderClipOval {
4612    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<Rect> {
4613        &self.get(app).custom_clip
4614    }
4615
4616    fn custom_clip_data_mut(
4617        self: RenderHandle<Self>,
4618        app: &mut App,
4619    ) -> &mut RenderCustomClipData<Rect> {
4620        &mut self.get_mut(app).custom_clip
4621    }
4622
4623    fn default_clip(self: RenderHandle<Self>, app: &App) -> Rect {
4624        Offset::ZERO & self.size(app)
4625    }
4626}
4627
4628impl RenderObject for RenderClipOval {
4629    crate::render_object_accessors!();
4630
4631    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
4632        if let Some(child) = self.child(app) {
4633            child.as_object().attach(app, owner);
4634        }
4635        RenderCustomClip::did_attach(self, app);
4636    }
4637
4638    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
4639        RenderCustomClip::did_detach(self, app);
4640        if let Some(child) = self.child(app) {
4641            child.as_object().detach(app);
4642        }
4643    }
4644
4645    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4646        RenderCustomClip::perform_layout(self, app);
4647    }
4648
4649    fn paint(
4650        self: RenderHandle<Self>,
4651        app: &mut App,
4652        context: &mut PaintingContext,
4653        offset: Offset,
4654    ) {
4655        if let Some(child) = self.child(app) {
4656            let clip_behavior = self.clip_behavior(app);
4657            if clip_behavior != Clip::None {
4658                self.update_clip(app);
4659                let clip = self.clip(app);
4660                let clip_path = self.get_clip_path(app, clip);
4661                let old = self.as_object().layer_as::<ClipPathLayer>(app);
4662                let layer = context.push_clip_path(
4663                    app,
4664                    self.as_object().needs_compositing(app),
4665                    offset,
4666                    clip,
4667                    clip_path,
4668                    |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
4669                    clip_behavior,
4670                    old,
4671                );
4672                self.as_object()
4673                    .set_layer(app, layer.map(|layer| layer.as_container_layer()));
4674            } else {
4675                context.paint_child(app, child.as_object(), offset);
4676                self.as_object().set_layer(app, None);
4677            }
4678        } else {
4679            self.as_object().set_layer(app, None);
4680        }
4681    }
4682
4683    fn visit_children(
4684        self: RenderHandle<Self>,
4685        app: &App,
4686        visitor: &mut dyn FnMut(AnyRenderObject),
4687    ) {
4688        if let Some(child) = self.child(app) {
4689            visitor(child.as_object());
4690        }
4691    }
4692}
4693
4694impl RenderBox for RenderClipOval {
4695    crate::render_box_accessors!();
4696
4697    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
4698        RenderProxyBoxMixin::setup_parent_data(self, app, child);
4699    }
4700
4701    fn apply_paint_transform(
4702        self: RenderHandle<Self>,
4703        app: &App,
4704        child: AnyRenderObject,
4705        transform: &mut Matrix4,
4706    ) {
4707        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
4708    }
4709
4710    fn hit_test(
4711        self: RenderHandle<Self>,
4712        app: &mut App,
4713        result: &mut BoxHitTestResult<'_>,
4714        position: Offset,
4715    ) -> bool {
4716        self.update_clip(app);
4717        let clip = self.clip(app);
4718        let center = clip.center();
4719        // convert the position to an offset from the center of the unit circle
4720        let offset = Offset::new(
4721            (position.dx() - center.dx()) / clip.width(),
4722            (position.dy() - center.dy()) / clip.height(),
4723        );
4724        // check if the point is outside the unit circle
4725        if offset.distance_squared() > 0.25 {
4726            // x^2 + y^2 > r^2
4727            return false;
4728        }
4729        RenderBoxBase::hit_test(self, app, result, position)
4730    }
4731
4732    fn hit_test_children(
4733        self: RenderHandle<Self>,
4734        app: &mut App,
4735        result: &mut BoxHitTestResult<'_>,
4736        position: Offset,
4737    ) -> bool {
4738        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
4739    }
4740
4741    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4742        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
4743    }
4744
4745    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4746        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
4747    }
4748
4749    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4750        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
4751    }
4752
4753    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4754        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
4755    }
4756
4757    fn compute_distance_to_actual_baseline(
4758        self: RenderHandle<Self>,
4759        app: &mut App,
4760        baseline: TextBaseline,
4761    ) -> Option<f64> {
4762        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
4763    }
4764
4765    fn compute_dry_baseline(
4766        self: RenderHandle<Self>,
4767        app: &mut App,
4768        constraints: BoxConstraints,
4769        baseline: TextBaseline,
4770    ) -> Option<f64> {
4771        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
4772    }
4773
4774    fn compute_dry_layout(
4775        self: RenderHandle<Self>,
4776        app: &mut App,
4777        constraints: BoxConstraints,
4778    ) -> Size {
4779        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
4780    }
4781}
4782
4783/// Clips its child using a path.
4784///
4785/// Takes a delegate whose primary method returns a path that should
4786/// be used to prevent the child from painting outside the path.
4787///
4788/// Clipping to a path is expensive. Certain shapes have more
4789/// optimized render objects:
4790///
4791///  * To clip to a rectangle, consider [`RenderClipRect`].
4792///  * To clip to an oval or circle, consider [`RenderClipOval`].
4793///  * To clip to a rounded rectangle, consider [`RenderClipRRect`].
4794pub struct RenderClipPath {
4795    render_object: RenderObjectData,
4796    render_box: RenderBoxData,
4797    child: RenderObjectWithChildData<AnyRenderBox>,
4798    custom_clip: RenderCustomClipData<Path>,
4799}
4800
4801impl RenderClipPath {
4802    /// Creates a path clip.
4803    ///
4804    /// If `clipper` is `None`, the clip will be a rectangle that matches the layout
4805    /// size and location of the child. However, rather than use this default,
4806    /// consider using a [`RenderClipRect`], which can achieve the same effect more
4807    /// efficiently.
4808    ///
4809    /// If `clip_behavior` is [`Clip::None`], no clipping will be applied.
4810    pub fn new(
4811        app: &mut App,
4812        clipper: Option<Rc<dyn CustomClipper<Path>>>,
4813        clip_behavior: Clip,
4814        child: Option<AnyRenderBox>,
4815    ) -> RenderHandle<RenderClipPath> {
4816        let this = RenderHandle::new_box(
4817            app,
4818            RenderClipPath {
4819                render_object: RenderObjectData::new(),
4820                render_box: RenderBoxData::new(),
4821                child: RenderObjectWithChildData::new(),
4822                custom_clip: RenderCustomClipData::new(clipper, clip_behavior),
4823            },
4824        );
4825        this.set_child(app, child);
4826        this
4827    }
4828}
4829
4830impl RenderObjectWithChildMixin for RenderClipPath {
4831    type ChildType = AnyRenderBox;
4832
4833    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
4834        &self.get(app).child
4835    }
4836
4837    fn child_data_mut(
4838        self: RenderHandle<Self>,
4839        app: &mut App,
4840    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
4841        &mut self.get_mut(app).child
4842    }
4843}
4844
4845impl RenderProxyBoxMixin for RenderClipPath {}
4846
4847impl RenderCustomClip<Path> for RenderClipPath {
4848    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<Path> {
4849        &self.get(app).custom_clip
4850    }
4851
4852    fn custom_clip_data_mut(
4853        self: RenderHandle<Self>,
4854        app: &mut App,
4855    ) -> &mut RenderCustomClipData<Path> {
4856        &mut self.get_mut(app).custom_clip
4857    }
4858
4859    fn default_clip(self: RenderHandle<Self>, app: &App) -> Path {
4860        let mut path = PathBuilder::new();
4861        path.rect((Offset::ZERO & self.size(app)).into());
4862        path.build().into()
4863    }
4864}
4865
4866impl RenderObject for RenderClipPath {
4867    crate::render_object_accessors!();
4868
4869    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
4870        if let Some(child) = self.child(app) {
4871            child.as_object().attach(app, owner);
4872        }
4873        RenderCustomClip::did_attach(self, app);
4874    }
4875
4876    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
4877        RenderCustomClip::did_detach(self, app);
4878        if let Some(child) = self.child(app) {
4879            child.as_object().detach(app);
4880        }
4881    }
4882
4883    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
4884        RenderCustomClip::perform_layout(self, app);
4885    }
4886
4887    fn paint(
4888        self: RenderHandle<Self>,
4889        app: &mut App,
4890        context: &mut PaintingContext,
4891        offset: Offset,
4892    ) {
4893        if let Some(child) = self.child(app) {
4894            let clip_behavior = self.clip_behavior(app);
4895            if clip_behavior != Clip::None {
4896                self.update_clip(app);
4897                let clip = self.clip(app);
4898                let bounds = Offset::ZERO & self.size(app);
4899                let old = self.as_object().layer_as::<ClipPathLayer>(app);
4900                let layer = context.push_clip_path(
4901                    app,
4902                    self.as_object().needs_compositing(app),
4903                    offset,
4904                    bounds,
4905                    clip,
4906                    |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
4907                    clip_behavior,
4908                    old,
4909                );
4910                self.as_object()
4911                    .set_layer(app, layer.map(|layer| layer.as_container_layer()));
4912            } else {
4913                context.paint_child(app, child.as_object(), offset);
4914                self.as_object().set_layer(app, None);
4915            }
4916        } else {
4917            self.as_object().set_layer(app, None);
4918        }
4919    }
4920
4921    fn visit_children(
4922        self: RenderHandle<Self>,
4923        app: &App,
4924        visitor: &mut dyn FnMut(AnyRenderObject),
4925    ) {
4926        if let Some(child) = self.child(app) {
4927            visitor(child.as_object());
4928        }
4929    }
4930}
4931
4932impl RenderBox for RenderClipPath {
4933    crate::render_box_accessors!();
4934
4935    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
4936        RenderProxyBoxMixin::setup_parent_data(self, app, child);
4937    }
4938
4939    fn apply_paint_transform(
4940        self: RenderHandle<Self>,
4941        app: &App,
4942        child: AnyRenderObject,
4943        transform: &mut Matrix4,
4944    ) {
4945        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
4946    }
4947
4948    fn hit_test(
4949        self: RenderHandle<Self>,
4950        app: &mut App,
4951        result: &mut BoxHitTestResult<'_>,
4952        position: Offset,
4953    ) -> bool {
4954        if self.clipper(app).is_some() {
4955            self.update_clip(app);
4956            if !self.clip(app).contains(position) {
4957                return false;
4958            }
4959        }
4960        RenderBoxBase::hit_test(self, app, result, position)
4961    }
4962
4963    fn hit_test_children(
4964        self: RenderHandle<Self>,
4965        app: &mut App,
4966        result: &mut BoxHitTestResult<'_>,
4967        position: Offset,
4968    ) -> bool {
4969        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
4970    }
4971
4972    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4973        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
4974    }
4975
4976    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
4977        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
4978    }
4979
4980    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4981        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
4982    }
4983
4984    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
4985        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
4986    }
4987
4988    fn compute_distance_to_actual_baseline(
4989        self: RenderHandle<Self>,
4990        app: &mut App,
4991        baseline: TextBaseline,
4992    ) -> Option<f64> {
4993        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
4994    }
4995
4996    fn compute_dry_baseline(
4997        self: RenderHandle<Self>,
4998        app: &mut App,
4999        constraints: BoxConstraints,
5000        baseline: TextBaseline,
5001    ) -> Option<f64> {
5002        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
5003    }
5004
5005    fn compute_dry_layout(
5006        self: RenderHandle<Self>,
5007        app: &mut App,
5008        constraints: BoxConstraints,
5009    ) -> Size {
5010        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
5011    }
5012}
5013
5014/// Clips its child using a rounded superellipse.
5015///
5016/// By default, [`RenderClipRSuperellipse`] uses its own
5017/// [`border_radius`](Self::border_radius) to create the shape. A custom `clipper` can
5018/// define any rounded superellipse.
5019pub struct RenderClipRSuperellipse {
5020    render_object: RenderObjectData,
5021    render_box: RenderBoxData,
5022    child: RenderObjectWithChildData<AnyRenderBox>,
5023    custom_clip: RenderCustomClipData<RSuperellipse>,
5024    border_radius: BorderRadiusGeometry,
5025    text_direction: Option<TextDirection>,
5026}
5027
5028impl RenderClipRSuperellipse {
5029    /// Creates a rounded-superellipse clip.
5030    ///
5031    /// The `border_radius` defaults to [`BorderRadiusGeometry::ZERO`], i.e. a rectangle with
5032    /// right-angled corners.
5033    ///
5034    /// If `clipper` is non-`None`, then `border_radius` is ignored.
5035    ///
5036    /// If `clip_behavior` is [`Clip::None`], no clipping will be applied.
5037    pub fn new(
5038        app: &mut App,
5039        border_radius: BorderRadiusGeometry,
5040        clipper: Option<Rc<dyn CustomClipper<RSuperellipse>>>,
5041        clip_behavior: Clip,
5042        text_direction: Option<TextDirection>,
5043        child: Option<AnyRenderBox>,
5044    ) -> RenderHandle<RenderClipRSuperellipse> {
5045        let this = RenderHandle::new_box(
5046            app,
5047            RenderClipRSuperellipse {
5048                render_object: RenderObjectData::new(),
5049                render_box: RenderBoxData::new(),
5050                child: RenderObjectWithChildData::new(),
5051                custom_clip: RenderCustomClipData::new(clipper, clip_behavior),
5052                border_radius,
5053                text_direction,
5054            },
5055        );
5056        this.set_child(app, child);
5057        this
5058    }
5059
5060    /// The border radius of the rounded corners.
5061    ///
5062    /// Values are clamped so that horizontal and vertical radii sums do not exceed
5063    /// width/height.
5064    ///
5065    /// This value is ignored if `clipper` is non-`None`.
5066    pub fn border_radius(self: RenderHandle<Self>, app: &App) -> BorderRadiusGeometry {
5067        self.get(app).border_radius
5068    }
5069
5070    /// Sets [`border_radius`](Self::border_radius).
5071    pub fn set_border_radius(self: RenderHandle<Self>, app: &mut App, value: BorderRadiusGeometry) {
5072        if self.get(app).border_radius == value {
5073            return;
5074        }
5075        self.get_mut(app).border_radius = value;
5076        self.mark_needs_clip(app);
5077    }
5078
5079    /// The text direction with which to resolve [`border_radius`](Self::border_radius).
5080    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
5081        self.get(app).text_direction
5082    }
5083
5084    /// Sets [`text_direction`](Self::text_direction).
5085    pub fn set_text_direction(
5086        self: RenderHandle<Self>,
5087        app: &mut App,
5088        value: Option<TextDirection>,
5089    ) {
5090        if self.get(app).text_direction == value {
5091            return;
5092        }
5093        self.get_mut(app).text_direction = value;
5094        self.mark_needs_clip(app);
5095    }
5096}
5097
5098impl RenderObjectWithChildMixin for RenderClipRSuperellipse {
5099    type ChildType = AnyRenderBox;
5100
5101    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
5102        &self.get(app).child
5103    }
5104
5105    fn child_data_mut(
5106        self: RenderHandle<Self>,
5107        app: &mut App,
5108    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
5109        &mut self.get_mut(app).child
5110    }
5111}
5112
5113impl RenderProxyBoxMixin for RenderClipRSuperellipse {}
5114
5115impl RenderCustomClip<RSuperellipse> for RenderClipRSuperellipse {
5116    fn custom_clip_data(
5117        self: RenderHandle<Self>,
5118        app: &App,
5119    ) -> &RenderCustomClipData<RSuperellipse> {
5120        &self.get(app).custom_clip
5121    }
5122
5123    fn custom_clip_data_mut(
5124        self: RenderHandle<Self>,
5125        app: &mut App,
5126    ) -> &mut RenderCustomClipData<RSuperellipse> {
5127        &mut self.get_mut(app).custom_clip
5128    }
5129
5130    fn default_clip(self: RenderHandle<Self>, app: &App) -> RSuperellipse {
5131        let this = self.get(app);
5132        this.border_radius
5133            .resolve(this.text_direction)
5134            .to_r_superellipse(Offset::ZERO & self.size(app))
5135    }
5136}
5137
5138impl RenderObject for RenderClipRSuperellipse {
5139    crate::render_object_accessors!();
5140
5141    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
5142        if let Some(child) = self.child(app) {
5143            child.as_object().attach(app, owner);
5144        }
5145        RenderCustomClip::did_attach(self, app);
5146    }
5147
5148    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
5149        RenderCustomClip::did_detach(self, app);
5150        if let Some(child) = self.child(app) {
5151            child.as_object().detach(app);
5152        }
5153    }
5154
5155    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
5156        RenderCustomClip::perform_layout(self, app);
5157    }
5158
5159    fn paint(
5160        self: RenderHandle<Self>,
5161        app: &mut App,
5162        context: &mut PaintingContext,
5163        offset: Offset,
5164    ) {
5165        if let Some(child) = self.child(app) {
5166            let clip_behavior = self.clip_behavior(app);
5167            if clip_behavior != Clip::None {
5168                self.update_clip(app);
5169                let clip = self.clip(app);
5170                let mut clip_path = PathBuilder::new();
5171                clip_path.rsuperellipse_radii(
5172                    clip.outer_rect().into(),
5173                    rsuperellipse_radii_elliptical(clip),
5174                );
5175                let old = self.as_object().layer_as::<ClipPathLayer>(app);
5176                let layer = context.push_clip_path(
5177                    app,
5178                    self.as_object().needs_compositing(app),
5179                    offset,
5180                    clip.outer_rect(),
5181                    clip_path.build().into(),
5182                    |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
5183                    clip_behavior,
5184                    old,
5185                );
5186                self.as_object()
5187                    .set_layer(app, layer.map(|layer| layer.as_container_layer()));
5188            } else {
5189                context.paint_child(app, child.as_object(), offset);
5190                self.as_object().set_layer(app, None);
5191            }
5192        } else {
5193            self.as_object().set_layer(app, None);
5194        }
5195    }
5196
5197    fn visit_children(
5198        self: RenderHandle<Self>,
5199        app: &App,
5200        visitor: &mut dyn FnMut(AnyRenderObject),
5201    ) {
5202        if let Some(child) = self.child(app) {
5203            visitor(child.as_object());
5204        }
5205    }
5206}
5207
5208impl RenderBox for RenderClipRSuperellipse {
5209    crate::render_box_accessors!();
5210
5211    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
5212        RenderProxyBoxMixin::setup_parent_data(self, app, child);
5213    }
5214
5215    fn apply_paint_transform(
5216        self: RenderHandle<Self>,
5217        app: &App,
5218        child: AnyRenderObject,
5219        transform: &mut Matrix4,
5220    ) {
5221        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
5222    }
5223
5224    fn hit_test(
5225        self: RenderHandle<Self>,
5226        app: &mut App,
5227        result: &mut BoxHitTestResult<'_>,
5228        position: Offset,
5229    ) -> bool {
5230        if self.clipper(app).is_some() {
5231            self.update_clip(app);
5232            if !self.clip(app).outer_rect().contains(position) {
5233                return false;
5234            }
5235        }
5236        RenderBoxBase::hit_test(self, app, result, position)
5237    }
5238
5239    fn hit_test_children(
5240        self: RenderHandle<Self>,
5241        app: &mut App,
5242        result: &mut BoxHitTestResult<'_>,
5243        position: Offset,
5244    ) -> bool {
5245        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
5246    }
5247
5248    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5249        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
5250    }
5251
5252    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5253        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
5254    }
5255
5256    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5257        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
5258    }
5259
5260    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5261        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
5262    }
5263
5264    fn compute_distance_to_actual_baseline(
5265        self: RenderHandle<Self>,
5266        app: &mut App,
5267        baseline: TextBaseline,
5268    ) -> Option<f64> {
5269        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
5270    }
5271
5272    fn compute_dry_baseline(
5273        self: RenderHandle<Self>,
5274        app: &mut App,
5275        constraints: BoxConstraints,
5276        baseline: TextBaseline,
5277    ) -> Option<f64> {
5278        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
5279    }
5280
5281    fn compute_dry_layout(
5282        self: RenderHandle<Self>,
5283        app: &mut App,
5284        constraints: BoxConstraints,
5285    ) -> Size {
5286        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
5287    }
5288}
5289
5290/// The fields of [`RenderPhysicalModelBase`].
5291pub struct RenderPhysicalModelBaseData {
5292    elevation: f64,
5293    color: Color,
5294    shadow_color: Color,
5295}
5296
5297impl RenderPhysicalModelBaseData {
5298    /// The fields of a physical model; the `elevation` must be non-negative.
5299    pub fn new(elevation: f64, color: Color, shadow_color: Color) -> RenderPhysicalModelBaseData {
5300        debug_assert!(elevation >= 0.0);
5301        RenderPhysicalModelBaseData {
5302            elevation,
5303            color,
5304            shadow_color,
5305        }
5306    }
5307}
5308
5309/// The shared members of [`RenderPhysicalModel`] and [`RenderPhysicalShape`]; Flutter's private
5310/// `_RenderPhysicalModelBase<T>`.
5311pub trait RenderPhysicalModelBase<T: Clone + 'static>: RenderCustomClip<T> {
5312    /// Mixin field access.
5313    fn physical_model_data(self: RenderHandle<Self>, app: &App) -> &RenderPhysicalModelBaseData;
5314
5315    /// See [`physical_model_data`](Self::physical_model_data).
5316    fn physical_model_data_mut(
5317        self: RenderHandle<Self>,
5318        app: &mut App,
5319    ) -> &mut RenderPhysicalModelBaseData;
5320
5321    /// The z-coordinate relative to the parent at which to place this material.
5322    ///
5323    /// The value is non-negative.
5324    fn elevation(self: RenderHandle<Self>, app: &App) -> f64 {
5325        self.physical_model_data(app).elevation
5326    }
5327
5328    /// Sets [`elevation`](Self::elevation).
5329    fn set_elevation(self: RenderHandle<Self>, app: &mut App, value: f64) {
5330        debug_assert!(value >= 0.0);
5331        if self.elevation(app) == value {
5332            return;
5333        }
5334        let did_need_compositing = self.as_object().always_needs_compositing(app);
5335        self.physical_model_data_mut(app).elevation = value;
5336        if did_need_compositing != self.as_object().always_needs_compositing(app) {
5337            self.as_object().mark_needs_compositing_bits_update(app);
5338        }
5339        self.mark_needs_paint(app);
5340    }
5341
5342    /// The shadow color.
5343    fn shadow_color(self: RenderHandle<Self>, app: &App) -> Color {
5344        self.physical_model_data(app).shadow_color
5345    }
5346
5347    /// Sets [`shadow_color`](Self::shadow_color).
5348    fn set_shadow_color(self: RenderHandle<Self>, app: &mut App, value: Color) {
5349        if self.shadow_color(app) == value {
5350            return;
5351        }
5352        self.physical_model_data_mut(app).shadow_color = value;
5353        self.mark_needs_paint(app);
5354    }
5355
5356    /// The background color.
5357    fn color(self: RenderHandle<Self>, app: &App) -> Color {
5358        self.physical_model_data(app).color
5359    }
5360
5361    /// Sets [`color`](Self::color).
5362    fn set_color(self: RenderHandle<Self>, app: &mut App, value: Color) {
5363        if self.color(app) == value {
5364            return;
5365        }
5366        self.physical_model_data_mut(app).color = value;
5367        self.mark_needs_paint(app);
5368    }
5369}
5370
5371/// The device pixel ratio of the view `render_object` paints into, which the engine's
5372/// `Canvas.drawShadow` reads from the implicit view; 1 outside a view, as the engine's is
5373/// without metrics.
5374fn device_pixel_ratio_of_view(app: &App, render_object: AnyRenderObject) -> f64 {
5375    render_object
5376        .owner(app)
5377        .and_then(|owner| owner.root_node(app))
5378        .and_then(|root| root.downcast::<RenderView>(app))
5379        .map_or(1.0, |view| view.configuration(app).device_pixel_ratio)
5380}
5381
5382/// Creates a physical model layer that clips its child to a rounded
5383/// rectangle.
5384///
5385/// A physical model layer casts a shadow based on its [`elevation`](RenderPhysicalModelBase::elevation).
5386pub struct RenderPhysicalModel {
5387    render_object: RenderObjectData,
5388    render_box: RenderBoxData,
5389    child: RenderObjectWithChildData<AnyRenderBox>,
5390    custom_clip: RenderCustomClipData<RRect>,
5391    physical_model: RenderPhysicalModelBaseData,
5392    shape: BoxShape,
5393    border_radius: Option<BorderRadius>,
5394}
5395
5396impl RenderPhysicalModel {
5397    /// Creates a rounded-rectangular clip.
5398    ///
5399    /// The `color` is required.
5400    ///
5401    /// The `elevation` parameter must be non-negative. Dart's defaults: `shape`
5402    /// [`BoxShape::Rectangle`], `clip_behavior` [`Clip::None`], `elevation` 0, `shadow_color`
5403    /// opaque black.
5404    #[expect(
5405        clippy::too_many_arguments,
5406        reason = "Dart's named arguments, in Dart's order"
5407    )]
5408    pub fn new(
5409        app: &mut App,
5410        child: Option<AnyRenderBox>,
5411        shape: BoxShape,
5412        clip_behavior: Clip,
5413        border_radius: Option<BorderRadius>,
5414        elevation: f64,
5415        color: Color,
5416        shadow_color: Color,
5417    ) -> RenderHandle<RenderPhysicalModel> {
5418        debug_assert!(elevation >= 0.0);
5419        let this = RenderHandle::new_box(
5420            app,
5421            RenderPhysicalModel {
5422                render_object: RenderObjectData::new(),
5423                render_box: RenderBoxData::new(),
5424                child: RenderObjectWithChildData::new(),
5425                custom_clip: RenderCustomClipData::new(None, clip_behavior),
5426                physical_model: RenderPhysicalModelBaseData::new(elevation, color, shadow_color),
5427                shape,
5428                border_radius,
5429            },
5430        );
5431        this.set_child(app, child);
5432        this
5433    }
5434
5435    /// The shape of the layer.
5436    ///
5437    /// Defaults to [`BoxShape::Rectangle`]. The [`border_radius`](Self::border_radius) affects
5438    /// the corners of the rectangle.
5439    pub fn shape(self: RenderHandle<Self>, app: &App) -> BoxShape {
5440        self.get(app).shape
5441    }
5442
5443    /// Sets [`shape`](Self::shape).
5444    pub fn set_shape(self: RenderHandle<Self>, app: &mut App, value: BoxShape) {
5445        if self.shape(app) == value {
5446            return;
5447        }
5448        self.get_mut(app).shape = value;
5449        self.mark_needs_clip(app);
5450    }
5451
5452    /// The border radius of the rounded corners.
5453    ///
5454    /// Values are clamped so that horizontal and vertical radii sums do not
5455    /// exceed width/height.
5456    ///
5457    /// This property is ignored if the [`shape`](Self::shape) is not [`BoxShape::Rectangle`].
5458    ///
5459    /// The value `None` is treated like [`BorderRadius::ZERO`].
5460    pub fn border_radius(self: RenderHandle<Self>, app: &App) -> Option<BorderRadius> {
5461        self.get(app).border_radius
5462    }
5463
5464    /// Sets [`border_radius`](Self::border_radius).
5465    pub fn set_border_radius(self: RenderHandle<Self>, app: &mut App, value: Option<BorderRadius>) {
5466        if self.border_radius(app) == value {
5467            return;
5468        }
5469        self.get_mut(app).border_radius = value;
5470        self.mark_needs_clip(app);
5471    }
5472}
5473
5474impl RenderObjectWithChildMixin for RenderPhysicalModel {
5475    type ChildType = AnyRenderBox;
5476
5477    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
5478        &self.get(app).child
5479    }
5480
5481    fn child_data_mut(
5482        self: RenderHandle<Self>,
5483        app: &mut App,
5484    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
5485        &mut self.get_mut(app).child
5486    }
5487}
5488
5489impl RenderProxyBoxMixin for RenderPhysicalModel {}
5490
5491impl RenderCustomClip<RRect> for RenderPhysicalModel {
5492    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<RRect> {
5493        &self.get(app).custom_clip
5494    }
5495
5496    fn custom_clip_data_mut(
5497        self: RenderHandle<Self>,
5498        app: &mut App,
5499    ) -> &mut RenderCustomClipData<RRect> {
5500        &mut self.get_mut(app).custom_clip
5501    }
5502
5503    fn default_clip(self: RenderHandle<Self>, app: &App) -> RRect {
5504        debug_assert!(self.has_size(app));
5505        let rect = Offset::ZERO & self.size(app);
5506        match self.get(app).shape {
5507            BoxShape::Rectangle => self
5508                .get(app)
5509                .border_radius
5510                .unwrap_or(BorderRadius::ZERO)
5511                .to_rrect(rect),
5512            BoxShape::Circle => RRect::from_rect_xy(rect, rect.width() / 2.0, rect.height() / 2.0),
5513        }
5514    }
5515}
5516
5517impl RenderPhysicalModelBase<RRect> for RenderPhysicalModel {
5518    fn physical_model_data(self: RenderHandle<Self>, app: &App) -> &RenderPhysicalModelBaseData {
5519        &self.get(app).physical_model
5520    }
5521
5522    fn physical_model_data_mut(
5523        self: RenderHandle<Self>,
5524        app: &mut App,
5525    ) -> &mut RenderPhysicalModelBaseData {
5526        &mut self.get_mut(app).physical_model
5527    }
5528}
5529
5530impl RenderObject for RenderPhysicalModel {
5531    crate::render_object_accessors!();
5532
5533    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
5534        if let Some(child) = self.child(app) {
5535            child.as_object().attach(app, owner);
5536        }
5537        RenderCustomClip::did_attach(self, app);
5538    }
5539
5540    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
5541        RenderCustomClip::did_detach(self, app);
5542        if let Some(child) = self.child(app) {
5543            child.as_object().detach(app);
5544        }
5545    }
5546
5547    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
5548        RenderCustomClip::perform_layout(self, app);
5549    }
5550
5551    fn paint(
5552        self: RenderHandle<Self>,
5553        app: &mut App,
5554        context: &mut PaintingContext,
5555        offset: Offset,
5556    ) {
5557        if self.child(app).is_none() {
5558            self.as_object().set_layer(app, None);
5559            return;
5560        }
5561
5562        self.update_clip(app);
5563        let offset_rrect = self.clip(app).shift(offset);
5564        let elevation = self.elevation(app);
5565        let shadow_color = self.shadow_color(app);
5566        let color = self.color(app);
5567
5568        let device_pixel_ratio = device_pixel_ratio_of_view(app, self.as_object());
5569        let canvas = context.canvas();
5570        if elevation != 0.0 {
5571            let mut offset_rrect_as_path = PathBuilder::new();
5572            offset_rrect_as_path.rrect_radii_elliptical(
5573                valo::Rect::from(offset_rrect.outer_rect()),
5574                rrect_radii_elliptical(offset_rrect),
5575            );
5576            #[expect(deprecated, reason = "Dart's paint reads the deprecated `Color.alpha`")]
5577            let transparent_occluder = color.alpha() != 0xFF;
5578            canvas.draw_shadow(
5579                &offset_rrect_as_path.build(),
5580                FillRule::NonZero,
5581                shadow_color.into(),
5582                elevation as f32,
5583                transparent_occluder,
5584                device_pixel_ratio as f32,
5585            );
5586        }
5587        let clip_behavior = self.clip_behavior(app);
5588        let uses_save_layer = clip_behavior == Clip::AntiAliasWithSaveLayer;
5589        if !uses_save_layer {
5590            draw_rrect(
5591                canvas,
5592                offset_rrect,
5593                &Paint {
5594                    color: color.into(),
5595                    ..Paint::default()
5596                },
5597            );
5598        }
5599        let clip = self.clip(app);
5600        let old = self.as_object().layer_as::<ClipRRectLayer>(app);
5601        let layer = context.push_clip_rrect(
5602            app,
5603            self.as_object().needs_compositing(app),
5604            offset,
5605            Offset::ZERO & self.size(app),
5606            clip,
5607            |app, context, offset| {
5608                if uses_save_layer {
5609                    // If we want to avoid the bleeding edge artifact
5610                    // (https://github.com/flutter/flutter/issues/18057#issue-328003931)
5611                    // using saveLayer, we have to call drawPaint instead of drawPath as
5612                    // anti-aliased drawPath will always have such artifacts.
5613                    context.canvas().draw_paint(&Paint {
5614                        color: color.into(),
5615                        ..Paint::default()
5616                    });
5617                }
5618                RenderProxyBoxMixin::paint(self, app, context, offset)
5619            },
5620            clip_behavior,
5621            old,
5622        );
5623        self.as_object()
5624            .set_layer(app, layer.map(|layer| layer.as_container_layer()));
5625    }
5626
5627    fn visit_children(
5628        self: RenderHandle<Self>,
5629        app: &App,
5630        visitor: &mut dyn FnMut(AnyRenderObject),
5631    ) {
5632        if let Some(child) = self.child(app) {
5633            visitor(child.as_object());
5634        }
5635    }
5636}
5637
5638impl RenderBox for RenderPhysicalModel {
5639    crate::render_box_accessors!();
5640
5641    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
5642        RenderProxyBoxMixin::setup_parent_data(self, app, child);
5643    }
5644
5645    fn apply_paint_transform(
5646        self: RenderHandle<Self>,
5647        app: &App,
5648        child: AnyRenderObject,
5649        transform: &mut Matrix4,
5650    ) {
5651        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
5652    }
5653
5654    fn hit_test(
5655        self: RenderHandle<Self>,
5656        app: &mut App,
5657        result: &mut BoxHitTestResult<'_>,
5658        position: Offset,
5659    ) -> bool {
5660        if self.clipper(app).is_some() {
5661            self.update_clip(app);
5662            if !self.clip(app).contains(position) {
5663                return false;
5664            }
5665        }
5666        RenderBoxBase::hit_test(self, app, result, position)
5667    }
5668
5669    fn hit_test_children(
5670        self: RenderHandle<Self>,
5671        app: &mut App,
5672        result: &mut BoxHitTestResult<'_>,
5673        position: Offset,
5674    ) -> bool {
5675        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
5676    }
5677
5678    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5679        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
5680    }
5681
5682    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5683        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
5684    }
5685
5686    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5687        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
5688    }
5689
5690    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5691        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
5692    }
5693
5694    fn compute_distance_to_actual_baseline(
5695        self: RenderHandle<Self>,
5696        app: &mut App,
5697        baseline: TextBaseline,
5698    ) -> Option<f64> {
5699        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
5700    }
5701
5702    fn compute_dry_baseline(
5703        self: RenderHandle<Self>,
5704        app: &mut App,
5705        constraints: BoxConstraints,
5706        baseline: TextBaseline,
5707    ) -> Option<f64> {
5708        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
5709    }
5710
5711    fn compute_dry_layout(
5712        self: RenderHandle<Self>,
5713        app: &mut App,
5714        constraints: BoxConstraints,
5715    ) -> Size {
5716        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
5717    }
5718}
5719
5720/// Creates a physical shape layer that clips its child to a [`Path`].
5721///
5722/// A physical shape layer casts a shadow based on its [`elevation`](RenderPhysicalModelBase::elevation).
5723///
5724/// See also:
5725///
5726///  * [`RenderPhysicalModel`], which is optimized for rounded rectangles and
5727///    circles.
5728pub struct RenderPhysicalShape {
5729    render_object: RenderObjectData,
5730    render_box: RenderBoxData,
5731    child: RenderObjectWithChildData<AnyRenderBox>,
5732    custom_clip: RenderCustomClipData<Path>,
5733    physical_model: RenderPhysicalModelBaseData,
5734}
5735
5736impl RenderPhysicalShape {
5737    /// Creates an arbitrary shape clip.
5738    ///
5739    /// The `color` and `clipper` parameters are required.
5740    ///
5741    /// The `elevation` parameter must be non-negative. Dart's defaults: `clip_behavior`
5742    /// [`Clip::None`], `elevation` 0, `shadow_color` opaque black.
5743    pub fn new(
5744        app: &mut App,
5745        child: Option<AnyRenderBox>,
5746        clipper: Rc<dyn CustomClipper<Path>>,
5747        clip_behavior: Clip,
5748        elevation: f64,
5749        color: Color,
5750        shadow_color: Color,
5751    ) -> RenderHandle<RenderPhysicalShape> {
5752        debug_assert!(elevation >= 0.0);
5753        let this = RenderHandle::new_box(
5754            app,
5755            RenderPhysicalShape {
5756                render_object: RenderObjectData::new(),
5757                render_box: RenderBoxData::new(),
5758                child: RenderObjectWithChildData::new(),
5759                custom_clip: RenderCustomClipData::new(Some(clipper), clip_behavior),
5760                physical_model: RenderPhysicalModelBaseData::new(elevation, color, shadow_color),
5761            },
5762        );
5763        this.set_child(app, child);
5764        this
5765    }
5766}
5767
5768impl RenderObjectWithChildMixin for RenderPhysicalShape {
5769    type ChildType = AnyRenderBox;
5770
5771    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
5772        &self.get(app).child
5773    }
5774
5775    fn child_data_mut(
5776        self: RenderHandle<Self>,
5777        app: &mut App,
5778    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
5779        &mut self.get_mut(app).child
5780    }
5781}
5782
5783impl RenderProxyBoxMixin for RenderPhysicalShape {}
5784
5785impl RenderCustomClip<Path> for RenderPhysicalShape {
5786    fn custom_clip_data(self: RenderHandle<Self>, app: &App) -> &RenderCustomClipData<Path> {
5787        &self.get(app).custom_clip
5788    }
5789
5790    fn custom_clip_data_mut(
5791        self: RenderHandle<Self>,
5792        app: &mut App,
5793    ) -> &mut RenderCustomClipData<Path> {
5794        &mut self.get_mut(app).custom_clip
5795    }
5796
5797    fn default_clip(self: RenderHandle<Self>, app: &App) -> Path {
5798        let mut path = PathBuilder::new();
5799        path.rect((Offset::ZERO & self.size(app)).into());
5800        path.build().into()
5801    }
5802}
5803
5804impl RenderPhysicalModelBase<Path> for RenderPhysicalShape {
5805    fn physical_model_data(self: RenderHandle<Self>, app: &App) -> &RenderPhysicalModelBaseData {
5806        &self.get(app).physical_model
5807    }
5808
5809    fn physical_model_data_mut(
5810        self: RenderHandle<Self>,
5811        app: &mut App,
5812    ) -> &mut RenderPhysicalModelBaseData {
5813        &mut self.get_mut(app).physical_model
5814    }
5815}
5816
5817impl RenderObject for RenderPhysicalShape {
5818    crate::render_object_accessors!();
5819
5820    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
5821        if let Some(child) = self.child(app) {
5822            child.as_object().attach(app, owner);
5823        }
5824        RenderCustomClip::did_attach(self, app);
5825    }
5826
5827    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
5828        RenderCustomClip::did_detach(self, app);
5829        if let Some(child) = self.child(app) {
5830            child.as_object().detach(app);
5831        }
5832    }
5833
5834    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
5835        RenderCustomClip::perform_layout(self, app);
5836    }
5837
5838    fn paint(
5839        self: RenderHandle<Self>,
5840        app: &mut App,
5841        context: &mut PaintingContext,
5842        offset: Offset,
5843    ) {
5844        if self.child(app).is_none() {
5845            self.as_object().set_layer(app, None);
5846            return;
5847        }
5848
5849        self.update_clip(app);
5850        let clip = self.clip(app);
5851        let offset_path = clip.shift(offset);
5852        let elevation = self.elevation(app);
5853        let shadow_color = self.shadow_color(app);
5854        let color = self.color(app);
5855
5856        let device_pixel_ratio = device_pixel_ratio_of_view(app, self.as_object());
5857        let canvas = context.canvas();
5858        if elevation != 0.0 {
5859            #[expect(deprecated, reason = "Dart's paint reads the deprecated `Color.alpha`")]
5860            let transparent_occluder = color.alpha() != 0xFF;
5861            canvas.draw_shadow(
5862                offset_path.as_valo(),
5863                offset_path.fill_type,
5864                shadow_color.into(),
5865                elevation as f32,
5866                transparent_occluder,
5867                device_pixel_ratio as f32,
5868            );
5869        }
5870        let clip_behavior = self.clip_behavior(app);
5871        let uses_save_layer = clip_behavior == Clip::AntiAliasWithSaveLayer;
5872        if !uses_save_layer {
5873            canvas.draw_path(
5874                offset_path.as_valo(),
5875                offset_path.fill_type,
5876                &Paint {
5877                    color: color.into(),
5878                    ..Paint::default()
5879                },
5880            );
5881        }
5882        let old = self.as_object().layer_as::<ClipPathLayer>(app);
5883        let layer = context.push_clip_path(
5884            app,
5885            self.as_object().needs_compositing(app),
5886            offset,
5887            Offset::ZERO & self.size(app),
5888            clip,
5889            |app, context, offset| {
5890                if uses_save_layer {
5891                    // If we want to avoid the bleeding edge artifact
5892                    // (https://github.com/flutter/flutter/issues/18057#issue-328003931)
5893                    // using saveLayer, we have to call drawPaint instead of drawPath as
5894                    // anti-aliased drawPath will always have such artifacts.
5895                    context.canvas().draw_paint(&Paint {
5896                        color: color.into(),
5897                        ..Paint::default()
5898                    });
5899                }
5900                RenderProxyBoxMixin::paint(self, app, context, offset)
5901            },
5902            clip_behavior,
5903            old,
5904        );
5905        self.as_object()
5906            .set_layer(app, layer.map(|layer| layer.as_container_layer()));
5907    }
5908
5909    fn visit_children(
5910        self: RenderHandle<Self>,
5911        app: &App,
5912        visitor: &mut dyn FnMut(AnyRenderObject),
5913    ) {
5914        if let Some(child) = self.child(app) {
5915            visitor(child.as_object());
5916        }
5917    }
5918}
5919
5920impl RenderBox for RenderPhysicalShape {
5921    crate::render_box_accessors!();
5922
5923    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
5924        RenderProxyBoxMixin::setup_parent_data(self, app, child);
5925    }
5926
5927    fn apply_paint_transform(
5928        self: RenderHandle<Self>,
5929        app: &App,
5930        child: AnyRenderObject,
5931        transform: &mut Matrix4,
5932    ) {
5933        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
5934    }
5935
5936    fn hit_test(
5937        self: RenderHandle<Self>,
5938        app: &mut App,
5939        result: &mut BoxHitTestResult<'_>,
5940        position: Offset,
5941    ) -> bool {
5942        if self.clipper(app).is_some() {
5943            self.update_clip(app);
5944            if !self.clip(app).contains(position) {
5945                return false;
5946            }
5947        }
5948        RenderBoxBase::hit_test(self, app, result, position)
5949    }
5950
5951    fn hit_test_children(
5952        self: RenderHandle<Self>,
5953        app: &mut App,
5954        result: &mut BoxHitTestResult<'_>,
5955        position: Offset,
5956    ) -> bool {
5957        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
5958    }
5959
5960    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5961        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
5962    }
5963
5964    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
5965        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
5966    }
5967
5968    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5969        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
5970    }
5971
5972    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
5973        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
5974    }
5975
5976    fn compute_distance_to_actual_baseline(
5977        self: RenderHandle<Self>,
5978        app: &mut App,
5979        baseline: TextBaseline,
5980    ) -> Option<f64> {
5981        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
5982    }
5983
5984    fn compute_dry_baseline(
5985        self: RenderHandle<Self>,
5986        app: &mut App,
5987        constraints: BoxConstraints,
5988        baseline: TextBaseline,
5989    ) -> Option<f64> {
5990        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
5991    }
5992
5993    fn compute_dry_layout(
5994        self: RenderHandle<Self>,
5995        app: &mut App,
5996        constraints: BoxConstraints,
5997    ) -> Size {
5998        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
5999    }
6000}
6001
6002/// Applies a transformation before painting its child.
6003pub struct RenderTransform {
6004    render_object: RenderObjectData,
6005    render_box: RenderBoxData,
6006    child: RenderObjectWithChildData<AnyRenderBox>,
6007    origin: Option<Offset>,
6008    alignment: Option<AlignmentGeometry>,
6009    text_direction: Option<TextDirection>,
6010    transform_hit_tests: bool,
6011    transform: Matrix4,
6012    filter_quality: Option<FilterQuality>,
6013}
6014
6015impl RenderTransform {
6016    /// Creates a render object that transforms its child.
6017    #[allow(clippy::too_many_arguments)]
6018    pub fn new(
6019        app: &mut App,
6020        transform: Matrix4,
6021        origin: Option<Offset>,
6022        alignment: Option<AlignmentGeometry>,
6023        text_direction: Option<TextDirection>,
6024        transform_hit_tests: bool,
6025        filter_quality: Option<FilterQuality>,
6026        child: Option<AnyRenderBox>,
6027    ) -> RenderHandle<RenderTransform> {
6028        let this = RenderHandle::new_box(
6029            app,
6030            RenderTransform {
6031                render_object: RenderObjectData::new(),
6032                render_box: RenderBoxData::new(),
6033                child: RenderObjectWithChildData::new(),
6034                origin,
6035                alignment,
6036                text_direction,
6037                transform_hit_tests,
6038                transform,
6039                filter_quality,
6040            },
6041        );
6042        this.set_child(app, child);
6043        this
6044    }
6045
6046    /// The origin of the coordinate system (relative to the upper left corner of
6047    /// this render object) in which to apply the matrix.
6048    ///
6049    /// Setting an origin is equivalent to conjugating the transform matrix by a
6050    /// translation. This property is provided just for convenience.
6051    pub fn origin(self: RenderHandle<Self>, app: &App) -> Option<Offset> {
6052        self.get(app).origin
6053    }
6054
6055    /// Sets [`origin`](Self::origin).
6056    pub fn set_origin(self: RenderHandle<Self>, app: &mut App, value: Option<Offset>) {
6057        if self.get(app).origin == value {
6058            return;
6059        }
6060        self.get_mut(app).origin = value;
6061        self.mark_needs_paint(app);
6062    }
6063
6064    /// The alignment of the origin, relative to the size of the box.
6065    ///
6066    /// This is equivalent to setting an origin based on the size of the box.
6067    /// If it is specified at the same time as an offset, both are applied.
6068    ///
6069    /// An `AlignmentDirectional::CENTER_START` value is the same as an [`Alignment`]
6070    /// whose `x` value is `-1.0` if [`text_direction`](Self::text_direction) is
6071    /// [`TextDirection::Ltr`], and `1.0` if it is [`TextDirection::Rtl`].
6072    /// Similarly `AlignmentDirectional::CENTER_END` is the same as an [`Alignment`]
6073    /// whose `x` value is `1.0` if [`text_direction`](Self::text_direction) is
6074    /// [`TextDirection::Ltr`], and `-1.0` if it is [`TextDirection::Rtl`].
6075    ///
6076    /// [`Alignment`]: waft_painting::Alignment
6077    pub fn alignment(self: RenderHandle<Self>, app: &App) -> Option<AlignmentGeometry> {
6078        self.get(app).alignment
6079    }
6080
6081    /// Sets [`alignment`](Self::alignment).
6082    pub fn set_alignment(
6083        self: RenderHandle<Self>,
6084        app: &mut App,
6085        value: Option<AlignmentGeometry>,
6086    ) {
6087        if self.get(app).alignment == value {
6088            return;
6089        }
6090        self.get_mut(app).alignment = value;
6091        self.mark_needs_paint(app);
6092    }
6093
6094    /// The text direction with which to resolve [`alignment`](Self::alignment).
6095    ///
6096    /// This may be changed to `None`, but only after [`alignment`](Self::alignment) has been
6097    /// changed to a value that does not depend on the direction.
6098    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
6099        self.get(app).text_direction
6100    }
6101
6102    /// Sets [`text_direction`](Self::text_direction).
6103    pub fn set_text_direction(
6104        self: RenderHandle<Self>,
6105        app: &mut App,
6106        value: Option<TextDirection>,
6107    ) {
6108        if self.get(app).text_direction == value {
6109            return;
6110        }
6111        self.get_mut(app).text_direction = value;
6112        self.mark_needs_paint(app);
6113    }
6114
6115    /// When true, hit tests are performed based on the position of the
6116    /// child as it is painted. When false, hit tests are performed
6117    /// ignoring the transformation.
6118    ///
6119    /// [`RenderBox::apply_paint_transform`], and therefore
6120    /// [`AnyRenderBox::local_to_global`] and [`AnyRenderBox::global_to_local`], always honor
6121    /// the transformation, regardless of the value of this property.
6122    pub fn transform_hit_tests(self: RenderHandle<Self>, app: &App) -> bool {
6123        self.get(app).transform_hit_tests
6124    }
6125
6126    /// Sets [`transform_hit_tests`](Self::transform_hit_tests). Dart's plain field.
6127    pub fn set_transform_hit_tests(self: RenderHandle<Self>, app: &mut App, value: bool) {
6128        self.get_mut(app).transform_hit_tests = value;
6129    }
6130
6131    /// Sets the matrix to transform the child by during painting.
6132    ///
6133    /// There is no getter for the transform, as in Dart, where the matrix is mutable and
6134    /// mutations outside of the control of the render object could not reliably be reflected
6135    /// in the rendering.
6136    pub fn set_transform(self: RenderHandle<Self>, app: &mut App, value: Matrix4) {
6137        if self.get(app).transform == value {
6138            return;
6139        }
6140        self.get_mut(app).transform = value;
6141        self.mark_needs_paint(app);
6142    }
6143
6144    /// The filter quality with which to apply the transform as a bitmap operation.
6145    ///
6146    /// When it is set, the child is painted untransformed into a layer whose pixels an
6147    /// `ImageFilter.matrix` of the transform then moves, at this quality; when it is `None`,
6148    /// the child is painted through the transform itself.
6149    pub fn filter_quality(self: RenderHandle<Self>, app: &App) -> Option<FilterQuality> {
6150        self.get(app).filter_quality
6151    }
6152
6153    /// Sets [`filter_quality`](Self::filter_quality).
6154    pub fn set_filter_quality(
6155        self: RenderHandle<Self>,
6156        app: &mut App,
6157        value: Option<FilterQuality>,
6158    ) {
6159        if self.get(app).filter_quality == value {
6160            return;
6161        }
6162        let did_need_compositing = self.always_needs_compositing(app);
6163        self.get_mut(app).filter_quality = value;
6164        if did_need_compositing != self.always_needs_compositing(app) {
6165            self.mark_needs_compositing_bits_update(app);
6166        }
6167        self.mark_needs_paint(app);
6168    }
6169
6170    /// Sets the transform to the identity matrix.
6171    pub fn set_identity(self: RenderHandle<Self>, app: &mut App) {
6172        self.get_mut(app).transform = Matrix4::IDENTITY;
6173        self.mark_needs_paint(app);
6174    }
6175
6176    /// Concatenates a rotation about the x axis into the transform.
6177    pub fn rotate_x(self: RenderHandle<Self>, app: &mut App, radians: f64) {
6178        let (sin, cos) = (radians.sin() as f32, radians.cos() as f32);
6179        #[rustfmt::skip]
6180        let rotation = Matrix4::from_flutter_array(&[
6181            1.0, 0.0, 0.0, 0.0,
6182            0.0, cos, sin, 0.0,
6183            0.0, -sin, cos, 0.0,
6184            0.0, 0.0, 0.0, 1.0,
6185        ]);
6186        self.concat(app, &rotation);
6187    }
6188
6189    /// Concatenates a rotation about the y axis into the transform.
6190    pub fn rotate_y(self: RenderHandle<Self>, app: &mut App, radians: f64) {
6191        let (sin, cos) = (radians.sin() as f32, radians.cos() as f32);
6192        #[rustfmt::skip]
6193        let rotation = Matrix4::from_flutter_array(&[
6194            cos, 0.0, -sin, 0.0,
6195            0.0, 1.0, 0.0, 0.0,
6196            sin, 0.0, cos, 0.0,
6197            0.0, 0.0, 0.0, 1.0,
6198        ]);
6199        self.concat(app, &rotation);
6200    }
6201
6202    /// Concatenates a rotation about the z axis into the transform.
6203    pub fn rotate_z(self: RenderHandle<Self>, app: &mut App, radians: f64) {
6204        let (sin, cos) = (radians.sin() as f32, radians.cos() as f32);
6205        #[rustfmt::skip]
6206        let rotation = Matrix4::from_flutter_array(&[
6207            cos, sin, 0.0, 0.0,
6208            -sin, cos, 0.0, 0.0,
6209            0.0, 0.0, 1.0, 0.0,
6210            0.0, 0.0, 0.0, 1.0,
6211        ]);
6212        self.concat(app, &rotation);
6213    }
6214
6215    /// Concatenates a translation by (x, y, z) into the transform.
6216    pub fn translate(self: RenderHandle<Self>, app: &mut App, x: f64, y: f64, z: f64) {
6217        #[rustfmt::skip]
6218        let translation = Matrix4::from_flutter_array(&[
6219            1.0, 0.0, 0.0, 0.0,
6220            0.0, 1.0, 0.0, 0.0,
6221            0.0, 0.0, 1.0, 0.0,
6222            x as f32, y as f32, z as f32, 1.0,
6223        ]);
6224        self.concat(app, &translation);
6225    }
6226
6227    /// Concatenates a scale into the transform. Dart's optional `y` and `z` default to `x`.
6228    pub fn scale(self: RenderHandle<Self>, app: &mut App, x: f64, y: Option<f64>, z: Option<f64>) {
6229        let (y, z) = (y.unwrap_or(x) as f32, z.unwrap_or(x) as f32);
6230        #[rustfmt::skip]
6231        let scale = Matrix4::from_flutter_array(&[
6232            x as f32, 0.0, 0.0, 0.0,
6233            0.0, y, 0.0, 0.0,
6234            0.0, 0.0, z, 0.0,
6235            0.0, 0.0, 0.0, 1.0,
6236        ]);
6237        self.concat(app, &scale);
6238    }
6239
6240    /// vector_math's in-place `rotateX` / `translate` / `scale`: a right multiplication of the
6241    /// transform, then a repaint.
6242    fn concat(self: RenderHandle<Self>, app: &mut App, other: &Matrix4) {
6243        crate::object::multiply(&mut self.get_mut(app).transform, other);
6244        self.mark_needs_paint(app);
6245    }
6246
6247    /// Flutter's `_effectiveTransform`: the transform around [`origin`](Self::origin) and the
6248    /// resolved [`alignment`](Self::alignment).
6249    fn effective_transform(self: RenderHandle<Self>, app: &App) -> Matrix4 {
6250        let this = self.get(app);
6251        let resolved_alignment = this
6252            .alignment
6253            .map(|alignment| alignment.resolve(this.text_direction));
6254        let origin = this.origin;
6255        if origin.is_none() && resolved_alignment.is_none() {
6256            return this.transform;
6257        }
6258        let mut result = Matrix4::IDENTITY;
6259        if let Some(origin) = origin {
6260            crate::object::translate(&mut result, origin.dx(), origin.dy());
6261        }
6262        let translation = resolved_alignment.map(|alignment| alignment.along_size(self.size(app)));
6263        if let Some(translation) = translation {
6264            crate::object::translate(&mut result, translation.dx(), translation.dy());
6265        }
6266        crate::object::multiply(&mut result, &self.get(app).transform);
6267        if let Some(translation) = translation {
6268            crate::object::translate(&mut result, -translation.dx(), -translation.dy());
6269        }
6270        if let Some(origin) = origin {
6271            crate::object::translate(&mut result, -origin.dx(), -origin.dy());
6272        }
6273        result
6274    }
6275
6276    /// Dart's `paint` with a `filterQuality`: the child painted at `offset` into an
6277    /// `ImageFilterLayer` whose `ImageFilter.matrix` applies `transform` about `offset`.
6278    fn paint_through_matrix_filter(
6279        self: RenderHandle<Self>,
6280        app: &mut App,
6281        context: &mut PaintingContext,
6282        offset: Offset,
6283        transform: Matrix4,
6284        filter_quality: FilterQuality,
6285    ) {
6286        let mut effective_transform = Matrix4::IDENTITY;
6287        crate::object::translate(&mut effective_transform, offset.dx(), offset.dy());
6288        crate::object::multiply(&mut effective_transform, &transform);
6289        crate::object::translate(&mut effective_transform, -offset.dx(), -offset.dy());
6290        let filter = ImageFilter::matrix(effective_transform, filter_quality);
6291        let layer = match self.as_object().layer_as::<ImageFilterLayer>(app) {
6292            Some(filter_layer) => filter_layer,
6293            None => {
6294                let layer = ImageFilterLayer::new(app);
6295                self.as_object()
6296                    .set_layer(app, Some(layer.as_container_layer()));
6297                layer
6298            }
6299        };
6300        layer.set_image_filter(app, filter);
6301        context.push_layer(
6302            app,
6303            layer.as_container_layer(),
6304            |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
6305            offset,
6306            None,
6307        );
6308    }
6309}
6310
6311impl RenderObjectWithChildMixin for RenderTransform {
6312    type ChildType = AnyRenderBox;
6313
6314    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
6315        &self.get(app).child
6316    }
6317
6318    fn child_data_mut(
6319        self: RenderHandle<Self>,
6320        app: &mut App,
6321    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
6322        &mut self.get_mut(app).child
6323    }
6324}
6325
6326impl RenderProxyBoxMixin for RenderTransform {}
6327
6328impl RenderObject for RenderTransform {
6329    crate::render_object_accessors!();
6330
6331    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
6332        self.child(app).is_some() && self.get(app).filter_quality.is_some()
6333    }
6334
6335    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
6336        RenderProxyBoxMixin::perform_layout(self, app);
6337    }
6338
6339    fn paint(
6340        self: RenderHandle<Self>,
6341        app: &mut App,
6342        context: &mut PaintingContext,
6343        offset: Offset,
6344    ) {
6345        if self.child(app).is_none() {
6346            return;
6347        }
6348        let transform = self.effective_transform(app);
6349        if let Some(filter_quality) = self.filter_quality(app) {
6350            self.paint_through_matrix_filter(app, context, offset, transform, filter_quality);
6351            return;
6352        }
6353        let Some(child_offset) = get_as_translation(transform) else {
6354            // If the matrix is singular the children would be compressed to a line or
6355            // single point, instead short-circuit and paint nothing.
6356            let determinant = transform.determinant();
6357            if determinant == 0.0 || !determinant.is_finite() {
6358                self.as_object().set_layer(app, None);
6359                return;
6360            }
6361            let old = self.as_object().layer_as::<TransformLayer>(app);
6362            let layer = context.push_transform(
6363                app,
6364                self.as_object().needs_compositing(app),
6365                offset,
6366                transform,
6367                |app, context, offset| {
6368                    RenderProxyBoxMixin::paint(self, app, context, offset);
6369                },
6370                old,
6371            );
6372            self.as_object()
6373                .set_layer(app, layer.map(|layer| layer.as_container_layer()));
6374            return;
6375        };
6376        RenderProxyBoxMixin::paint(self, app, context, offset + child_offset);
6377        self.as_object().set_layer(app, None);
6378    }
6379
6380    fn visit_children(
6381        self: RenderHandle<Self>,
6382        app: &App,
6383        visitor: &mut dyn FnMut(AnyRenderObject),
6384    ) {
6385        if let Some(child) = self.child(app) {
6386            visitor(child.as_object());
6387        }
6388    }
6389}
6390
6391impl RenderBox for RenderTransform {
6392    crate::render_box_accessors!();
6393
6394    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
6395        RenderProxyBoxMixin::setup_parent_data(self, app, child);
6396    }
6397
6398    fn apply_paint_transform(
6399        self: RenderHandle<Self>,
6400        app: &App,
6401        _child: AnyRenderObject,
6402        transform: &mut Matrix4,
6403    ) {
6404        crate::object::multiply(transform, &self.effective_transform(app));
6405    }
6406
6407    fn hit_test(
6408        self: RenderHandle<Self>,
6409        app: &mut App,
6410        result: &mut BoxHitTestResult<'_>,
6411        position: Offset,
6412    ) -> bool {
6413        // RenderTransform objects don't check if they are
6414        // themselves hit, because it's confusing to think about
6415        // how the untransformed size and the child's transformed
6416        // position interact.
6417        RenderBox::hit_test_children(self, app, result, position)
6418    }
6419
6420    fn hit_test_children(
6421        self: RenderHandle<Self>,
6422        app: &mut App,
6423        result: &mut BoxHitTestResult<'_>,
6424        position: Offset,
6425    ) -> bool {
6426        let transform = self
6427            .transform_hit_tests(app)
6428            .then(|| self.effective_transform(app));
6429        result.add_with_paint_transform(transform, position, |result, position| {
6430            RenderProxyBoxMixin::hit_test_children(self, app, result, position)
6431        })
6432    }
6433
6434    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
6435        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
6436    }
6437
6438    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
6439        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
6440    }
6441
6442    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
6443        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
6444    }
6445
6446    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
6447        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
6448    }
6449
6450    fn compute_distance_to_actual_baseline(
6451        self: RenderHandle<Self>,
6452        app: &mut App,
6453        baseline: TextBaseline,
6454    ) -> Option<f64> {
6455        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
6456    }
6457
6458    fn compute_dry_baseline(
6459        self: RenderHandle<Self>,
6460        app: &mut App,
6461        constraints: BoxConstraints,
6462        baseline: TextBaseline,
6463    ) -> Option<f64> {
6464        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
6465    }
6466
6467    fn compute_dry_layout(
6468        self: RenderHandle<Self>,
6469        app: &mut App,
6470        constraints: BoxConstraints,
6471    ) -> Size {
6472        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
6473    }
6474}
6475
6476/// Scales and positions its child within itself according to [`fit`](Self::fit).
6477pub struct RenderFittedBox {
6478    render_object: RenderObjectData,
6479    render_box: RenderBoxData,
6480    child: RenderObjectWithChildData<AnyRenderBox>,
6481    fit: BoxFit,
6482    alignment: AlignmentGeometry,
6483    text_direction: Option<TextDirection>,
6484    resolved_alignment: Option<Alignment>,
6485    clip_behavior: Clip,
6486    has_visual_overflow: Option<bool>,
6487    transform: Option<Matrix4>,
6488}
6489
6490/// Whether a change of [`BoxFit`] changes the size this box takes.
6491fn fit_affects_layout(fit: BoxFit) -> bool {
6492    match fit {
6493        BoxFit::ScaleDown => true,
6494        BoxFit::Contain
6495        | BoxFit::Cover
6496        | BoxFit::Fill
6497        | BoxFit::FitHeight
6498        | BoxFit::FitWidth
6499        | BoxFit::None => false,
6500    }
6501}
6502
6503impl RenderFittedBox {
6504    /// Creates a render object that scales and positions its child within itself.
6505    pub fn new(
6506        app: &mut App,
6507        fit: BoxFit,
6508        alignment: AlignmentGeometry,
6509        text_direction: Option<TextDirection>,
6510        child: Option<AnyRenderBox>,
6511    ) -> RenderHandle<RenderFittedBox> {
6512        let this = RenderHandle::new_box(
6513            app,
6514            RenderFittedBox {
6515                render_object: RenderObjectData::new(),
6516                render_box: RenderBoxData::new(),
6517                child: RenderObjectWithChildData::new(),
6518                fit,
6519                alignment,
6520                text_direction,
6521                resolved_alignment: None,
6522                clip_behavior: Clip::None,
6523                has_visual_overflow: None,
6524                transform: None,
6525            },
6526        );
6527        this.set_child(app, child);
6528        this
6529    }
6530
6531    fn resolve(self: RenderHandle<Self>, app: &mut App) -> Alignment {
6532        let this = self.get(app);
6533        if let Some(resolved) = this.resolved_alignment {
6534            return resolved;
6535        }
6536        let resolved = this.alignment.resolve(this.text_direction);
6537        self.get_mut(app).resolved_alignment = Some(resolved);
6538        resolved
6539    }
6540
6541    fn mark_need_resolution(self: RenderHandle<Self>, app: &mut App) {
6542        self.get_mut(app).resolved_alignment = None;
6543        self.mark_needs_paint(app);
6544    }
6545
6546    /// How to inscribe the child into the space allocated during layout.
6547    pub fn fit(self: RenderHandle<Self>, app: &App) -> BoxFit {
6548        self.get(app).fit
6549    }
6550
6551    /// Sets [`fit`](Self::fit).
6552    pub fn set_fit(self: RenderHandle<Self>, app: &mut App, value: BoxFit) {
6553        let last_fit = self.get(app).fit;
6554        if last_fit == value {
6555            return;
6556        }
6557        self.get_mut(app).fit = value;
6558        if fit_affects_layout(last_fit) || fit_affects_layout(value) {
6559            RenderBox::mark_needs_layout(self, app);
6560        } else {
6561            self.clear_paint_data(app);
6562            self.mark_needs_paint(app);
6563        }
6564    }
6565
6566    /// How to align the child within its parent's bounds.
6567    ///
6568    /// An alignment of (0.0, 0.0) aligns the child to the top-left corner of its parent's bounds.
6569    /// An alignment of (1.0, 0.5) aligns the child to the middle of the right edge of its
6570    /// parent's bounds.
6571    pub fn alignment(self: RenderHandle<Self>, app: &App) -> AlignmentGeometry {
6572        self.get(app).alignment
6573    }
6574
6575    /// Sets [`alignment`](Self::alignment).
6576    pub fn set_alignment(self: RenderHandle<Self>, app: &mut App, value: AlignmentGeometry) {
6577        if self.get(app).alignment == value {
6578            return;
6579        }
6580        self.get_mut(app).alignment = value;
6581        self.clear_paint_data(app);
6582        self.mark_need_resolution(app);
6583    }
6584
6585    /// The text direction with which to resolve [`alignment`](Self::alignment).
6586    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
6587        self.get(app).text_direction
6588    }
6589
6590    /// Sets [`text_direction`](Self::text_direction).
6591    pub fn set_text_direction(
6592        self: RenderHandle<Self>,
6593        app: &mut App,
6594        value: Option<TextDirection>,
6595    ) {
6596        if self.get(app).text_direction == value {
6597            return;
6598        }
6599        self.get_mut(app).text_direction = value;
6600        self.clear_paint_data(app);
6601        self.mark_need_resolution(app);
6602    }
6603
6604    /// How to clip a child that overflows this box. Defaults to [`Clip::None`].
6605    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
6606        self.get(app).clip_behavior
6607    }
6608
6609    /// Sets [`clip_behavior`](Self::clip_behavior).
6610    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
6611        if self.get(app).clip_behavior == value {
6612            return;
6613        }
6614        self.get_mut(app).clip_behavior = value;
6615        self.mark_needs_paint(app);
6616    }
6617
6618    fn clear_paint_data(self: RenderHandle<Self>, app: &mut App) {
6619        let this = self.get_mut(app);
6620        this.has_visual_overflow = None;
6621        this.transform = None;
6622    }
6623
6624    /// Flutter's `_updatePaintData`, without the cache: the transform that fits the child into
6625    /// this box, and whether the child overflows it.
6626    fn paint_data(self: RenderHandle<Self>, app: &App) -> (bool, Matrix4) {
6627        let Some(child) = self.child(app) else {
6628            return (false, Matrix4::IDENTITY);
6629        };
6630        let this = self.get(app);
6631        let resolved_alignment = this
6632            .resolved_alignment
6633            .unwrap_or_else(|| this.alignment.resolve(this.text_direction));
6634        let child_size = child.size(app);
6635        let sizes = apply_box_fit(this.fit, child_size, self.size(app));
6636        let scale_x = sizes.destination.width() / sizes.source.width();
6637        let scale_y = sizes.destination.height() / sizes.source.height();
6638        let source_rect = resolved_alignment.inscribe(sizes.source, Offset::ZERO & child_size);
6639        let destination_rect =
6640            resolved_alignment.inscribe(sizes.destination, Offset::ZERO & self.size(app));
6641        debug_assert!(scale_x.is_finite() && scale_y.is_finite());
6642        let mut transform =
6643            Matrix4::translation(destination_rect.left as f32, destination_rect.top as f32);
6644        crate::object::multiply(
6645            &mut transform,
6646            &Matrix4::scale(scale_x as f32, scale_y as f32),
6647        );
6648        crate::object::translate(&mut transform, -source_rect.left, -source_rect.top);
6649        let has_visual_overflow =
6650            source_rect.width() < child_size.width() || source_rect.height() < child_size.height();
6651        (has_visual_overflow, transform)
6652    }
6653
6654    fn update_paint_data(self: RenderHandle<Self>, app: &mut App) {
6655        if self.get(app).transform.is_some() {
6656            return;
6657        }
6658        // Dart's `_resolve()` memoizes the resolved alignment here.
6659        self.resolve(app);
6660        let (has_visual_overflow, transform) = self.paint_data(app);
6661        let this = self.get_mut(app);
6662        this.has_visual_overflow = Some(has_visual_overflow);
6663        this.transform = Some(transform);
6664    }
6665
6666    fn paint_child_with_transform(
6667        self: RenderHandle<Self>,
6668        app: &mut App,
6669        context: &mut PaintingContext,
6670        offset: Offset,
6671    ) -> Option<Handle<TransformLayer>> {
6672        let transform = self.get(app).transform.expect("update_paint_data ran");
6673        match get_as_translation(transform) {
6674            Some(child_offset) => {
6675                RenderProxyBoxMixin::paint(self, app, context, offset + child_offset);
6676                None
6677            }
6678            None => context.push_transform(
6679                app,
6680                self.as_object().needs_compositing(app),
6681                offset,
6682                transform,
6683                |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
6684                self.as_object().layer_as::<TransformLayer>(app),
6685            ),
6686        }
6687    }
6688}
6689
6690impl RenderObjectWithChildMixin for RenderFittedBox {
6691    type ChildType = AnyRenderBox;
6692
6693    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
6694        &self.get(app).child
6695    }
6696
6697    fn child_data_mut(
6698        self: RenderHandle<Self>,
6699        app: &mut App,
6700    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
6701        &mut self.get_mut(app).child
6702    }
6703}
6704
6705impl RenderProxyBoxMixin for RenderFittedBox {}
6706
6707impl RenderObject for RenderFittedBox {
6708    crate::render_object_accessors!();
6709
6710    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
6711        let constraints = self.constraints(app);
6712        let Some(child) = self.child(app) else {
6713            self.set_size(app, constraints.smallest());
6714            return;
6715        };
6716        child.layout(app, BoxConstraints::new(), true);
6717        let child_size = child.size(app);
6718        let size = match self.fit(app) {
6719            BoxFit::ScaleDown => {
6720                let size_constraints = constraints.loosen();
6721                let unconstrained_size = size_constraints
6722                    .constrain_size_and_attempt_to_preserve_aspect_ratio(child_size);
6723                constraints.constrain(unconstrained_size)
6724            }
6725            BoxFit::Contain
6726            | BoxFit::Cover
6727            | BoxFit::Fill
6728            | BoxFit::FitHeight
6729            | BoxFit::FitWidth
6730            | BoxFit::None => {
6731                constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(child_size)
6732            }
6733        };
6734        self.set_size(app, size);
6735        self.clear_paint_data(app);
6736    }
6737
6738    fn paint(
6739        self: RenderHandle<Self>,
6740        app: &mut App,
6741        context: &mut PaintingContext,
6742        offset: Offset,
6743    ) {
6744        let Some(child) = self.child(app) else {
6745            return;
6746        };
6747        if self.size(app).is_empty() || child.size(app).is_empty() {
6748            return;
6749        }
6750        self.update_paint_data(app);
6751        let clip_behavior = self.clip_behavior(app);
6752        if self.get(app).has_visual_overflow == Some(true) && clip_behavior != Clip::None {
6753            let clip_rect = Offset::ZERO & self.size(app);
6754            let old = self.as_object().layer_as::<ClipRectLayer>(app);
6755            let layer = context.push_clip_rect(
6756                app,
6757                self.as_object().needs_compositing(app),
6758                offset,
6759                clip_rect,
6760                |app, context, offset| {
6761                    let _ = self.paint_child_with_transform(app, context, offset);
6762                },
6763                clip_behavior,
6764                old,
6765            );
6766            self.as_object()
6767                .set_layer(app, layer.map(|layer| layer.as_container_layer()));
6768        } else {
6769            let layer = self.paint_child_with_transform(app, context, offset);
6770            self.as_object()
6771                .set_layer(app, layer.map(|layer| layer.as_container_layer()));
6772        }
6773    }
6774
6775    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
6776        debug_assert!(child.parent(app) == Some(self.as_object()));
6777        let child = child.as_box().expect("a fitted box has a box child");
6778        !self.size(app).is_empty() && !child.size(app).is_empty()
6779    }
6780
6781    fn visit_children(
6782        self: RenderHandle<Self>,
6783        app: &App,
6784        visitor: &mut dyn FnMut(AnyRenderObject),
6785    ) {
6786        if let Some(child) = self.child(app) {
6787            visitor(child.as_object());
6788        }
6789    }
6790}
6791
6792impl RenderBox for RenderFittedBox {
6793    crate::render_box_accessors!();
6794
6795    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
6796        RenderProxyBoxMixin::setup_parent_data(self, app, child);
6797    }
6798
6799    fn apply_paint_transform(
6800        self: RenderHandle<Self>,
6801        app: &App,
6802        child: AnyRenderObject,
6803        transform: &mut Matrix4,
6804    ) {
6805        if !RenderObject::paints_child(self, app, child) {
6806            *transform = crate::object::zero_matrix();
6807            return;
6808        }
6809        let (_, fitted) = self.paint_data(app);
6810        crate::object::multiply(transform, &fitted);
6811    }
6812
6813    fn hit_test_children(
6814        self: RenderHandle<Self>,
6815        app: &mut App,
6816        result: &mut BoxHitTestResult<'_>,
6817        position: Offset,
6818    ) -> bool {
6819        let child_is_empty = self
6820            .child(app)
6821            .is_none_or(|child| child.size(app).is_empty());
6822        if self.size(app).is_empty() || child_is_empty {
6823            return false;
6824        }
6825        self.update_paint_data(app);
6826        let transform = self.get(app).transform;
6827        result.add_with_paint_transform(transform, position, |result, position| {
6828            RenderProxyBoxMixin::hit_test_children(self, app, result, position)
6829        })
6830    }
6831
6832    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
6833        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
6834    }
6835
6836    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
6837        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
6838    }
6839
6840    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
6841        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
6842    }
6843
6844    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
6845        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
6846    }
6847
6848    fn compute_distance_to_actual_baseline(
6849        self: RenderHandle<Self>,
6850        app: &mut App,
6851        baseline: TextBaseline,
6852    ) -> Option<f64> {
6853        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
6854    }
6855
6856    fn compute_dry_layout(
6857        self: RenderHandle<Self>,
6858        app: &mut App,
6859        constraints: BoxConstraints,
6860    ) -> Size {
6861        let Some(child) = self.child(app) else {
6862            return constraints.smallest();
6863        };
6864        let child_size = child.get_dry_layout(app, BoxConstraints::new());
6865        match self.fit(app) {
6866            BoxFit::ScaleDown => {
6867                let size_constraints = constraints.loosen();
6868                let unconstrained_size = size_constraints
6869                    .constrain_size_and_attempt_to_preserve_aspect_ratio(child_size);
6870                constraints.constrain(unconstrained_size)
6871            }
6872            BoxFit::Contain
6873            | BoxFit::Cover
6874            | BoxFit::Fill
6875            | BoxFit::FitHeight
6876            | BoxFit::FitWidth
6877            | BoxFit::None => {
6878                constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(child_size)
6879            }
6880        }
6881    }
6882
6883    fn compute_dry_baseline(
6884        self: RenderHandle<Self>,
6885        app: &mut App,
6886        _constraints: BoxConstraints,
6887        baseline: TextBaseline,
6888    ) -> Option<f64> {
6889        // The baseline of the child with unconstrained layout, without applying any transforms
6890        // or scaling that would be applied during paint.
6891        self.child(app)?
6892            .get_dry_baseline(app, BoxConstraints::new(), baseline)
6893    }
6894}
6895
6896/// Applies a translation transformation before painting its child.
6897///
6898/// The translation is expressed as an [`Offset`] scaled to the child's size. For
6899/// example, an [`Offset`] with a `dx` of 0.25 will result in a horizontal
6900/// translation of one quarter the width of the child.
6901///
6902/// Hit tests will only be detected inside the bounds of the
6903/// [`RenderFractionalTranslation`], even if the contents are offset such that
6904/// they overflow.
6905pub struct RenderFractionalTranslation {
6906    render_object: RenderObjectData,
6907    render_box: RenderBoxData,
6908    child: RenderObjectWithChildData<AnyRenderBox>,
6909    translation: Offset,
6910    transform_hit_tests: bool,
6911}
6912
6913impl RenderFractionalTranslation {
6914    /// Creates a render object that translates its child's painting.
6915    pub fn new(
6916        app: &mut App,
6917        translation: Offset,
6918        transform_hit_tests: bool,
6919        child: Option<AnyRenderBox>,
6920    ) -> RenderHandle<RenderFractionalTranslation> {
6921        let this = RenderHandle::new_box(
6922            app,
6923            RenderFractionalTranslation {
6924                render_object: RenderObjectData::new(),
6925                render_box: RenderBoxData::new(),
6926                child: RenderObjectWithChildData::new(),
6927                translation,
6928                transform_hit_tests,
6929            },
6930        );
6931        this.set_child(app, child);
6932        this
6933    }
6934
6935    /// The translation to apply to the child, scaled to the child's size.
6936    ///
6937    /// For example, an [`Offset`] with a `dx` of 0.25 will result in a horizontal
6938    /// translation of one quarter the width of the child.
6939    pub fn translation(self: RenderHandle<Self>, app: &App) -> Offset {
6940        self.get(app).translation
6941    }
6942
6943    /// Sets [`translation`](Self::translation).
6944    pub fn set_translation(self: RenderHandle<Self>, app: &mut App, value: Offset) {
6945        if self.get(app).translation == value {
6946            return;
6947        }
6948        self.get_mut(app).translation = value;
6949        self.mark_needs_paint(app);
6950    }
6951
6952    /// When true, hit tests are performed based on the position of the
6953    /// child as it is painted. When false, hit tests are performed
6954    /// ignoring the transformation.
6955    ///
6956    /// [`RenderBox::apply_paint_transform`], and therefore
6957    /// [`AnyRenderBox::local_to_global`] and [`AnyRenderBox::global_to_local`], always honor
6958    /// the transformation, regardless of the value of this property.
6959    pub fn transform_hit_tests(self: RenderHandle<Self>, app: &App) -> bool {
6960        self.get(app).transform_hit_tests
6961    }
6962
6963    /// Sets [`transform_hit_tests`](Self::transform_hit_tests). Dart's plain field.
6964    pub fn set_transform_hit_tests(self: RenderHandle<Self>, app: &mut App, value: bool) {
6965        self.get_mut(app).transform_hit_tests = value;
6966    }
6967
6968    /// The translation in layout pixels: [`translation`](Self::translation) along the size.
6969    fn absolute_translation(self: RenderHandle<Self>, app: &App) -> Offset {
6970        let translation = self.get(app).translation;
6971        let size = self.size(app);
6972        Offset::new(
6973            translation.dx() * size.width(),
6974            translation.dy() * size.height(),
6975        )
6976    }
6977}
6978
6979impl RenderObjectWithChildMixin for RenderFractionalTranslation {
6980    type ChildType = AnyRenderBox;
6981
6982    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
6983        &self.get(app).child
6984    }
6985
6986    fn child_data_mut(
6987        self: RenderHandle<Self>,
6988        app: &mut App,
6989    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
6990        &mut self.get_mut(app).child
6991    }
6992}
6993
6994impl RenderProxyBoxMixin for RenderFractionalTranslation {}
6995
6996impl RenderObject for RenderFractionalTranslation {
6997    crate::render_object_accessors!();
6998
6999    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7000        RenderProxyBoxMixin::perform_layout(self, app);
7001    }
7002
7003    fn paint(
7004        self: RenderHandle<Self>,
7005        app: &mut App,
7006        context: &mut PaintingContext,
7007        offset: Offset,
7008    ) {
7009        debug_assert!(!self.debug_needs_layout(app));
7010        if self.child(app).is_none() {
7011            return;
7012        }
7013        let translation = self.absolute_translation(app);
7014        RenderProxyBoxMixin::paint(self, app, context, offset + translation);
7015    }
7016
7017    fn visit_children(
7018        self: RenderHandle<Self>,
7019        app: &App,
7020        visitor: &mut dyn FnMut(AnyRenderObject),
7021    ) {
7022        if let Some(child) = self.child(app) {
7023            visitor(child.as_object());
7024        }
7025    }
7026}
7027
7028impl RenderBox for RenderFractionalTranslation {
7029    crate::render_box_accessors!();
7030
7031    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
7032        RenderProxyBoxMixin::setup_parent_data(self, app, child);
7033    }
7034
7035    fn apply_paint_transform(
7036        self: RenderHandle<Self>,
7037        app: &App,
7038        _child: AnyRenderObject,
7039        transform: &mut Matrix4,
7040    ) {
7041        let translation = self.absolute_translation(app);
7042        crate::object::translate(transform, translation.dx(), translation.dy());
7043    }
7044
7045    fn hit_test(
7046        self: RenderHandle<Self>,
7047        app: &mut App,
7048        result: &mut BoxHitTestResult<'_>,
7049        position: Offset,
7050    ) -> bool {
7051        // RenderFractionalTranslation objects don't check if they are
7052        // themselves hit, because it's confusing to think about
7053        // how the untransformed size and the child's transformed
7054        // position interact.
7055        RenderBox::hit_test_children(self, app, result, position)
7056    }
7057
7058    fn hit_test_children(
7059        self: RenderHandle<Self>,
7060        app: &mut App,
7061        result: &mut BoxHitTestResult<'_>,
7062        position: Offset,
7063    ) -> bool {
7064        debug_assert!(!self.debug_needs_layout(app));
7065        let offset = self
7066            .transform_hit_tests(app)
7067            .then(|| self.absolute_translation(app));
7068        result.add_with_paint_offset(offset, position, |result, position| {
7069            RenderProxyBoxMixin::hit_test_children(self, app, result, position)
7070        })
7071    }
7072
7073    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7074        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
7075    }
7076
7077    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7078        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
7079    }
7080
7081    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7082        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
7083    }
7084
7085    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7086        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
7087    }
7088
7089    fn compute_distance_to_actual_baseline(
7090        self: RenderHandle<Self>,
7091        app: &mut App,
7092        baseline: TextBaseline,
7093    ) -> Option<f64> {
7094        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
7095    }
7096
7097    fn compute_dry_baseline(
7098        self: RenderHandle<Self>,
7099        app: &mut App,
7100        constraints: BoxConstraints,
7101        baseline: TextBaseline,
7102    ) -> Option<f64> {
7103        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
7104    }
7105
7106    fn compute_dry_layout(
7107        self: RenderHandle<Self>,
7108        app: &mut App,
7109        constraints: BoxConstraints,
7110    ) -> Size {
7111        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
7112    }
7113}
7114
7115/// A render object that is invisible during hit testing.
7116///
7117/// When [`ignoring`](Self::ignoring) is true, this render object (and its subtree) is invisible
7118/// to hit testing. It still consumes space during layout and paints its child
7119/// as usual. It just cannot be the target of located events, because its render
7120/// object returns false from [`RenderBox::hit_test`].
7121///
7122/// See also:
7123///
7124///  * [`RenderAbsorbPointer`], which takes the pointer events but prevents any
7125///    nodes in the subtree from seeing them.
7126pub struct RenderIgnorePointer {
7127    render_object: RenderObjectData,
7128    render_box: RenderBoxData,
7129    child: RenderObjectWithChildData<AnyRenderBox>,
7130    ignoring: bool,
7131}
7132
7133impl RenderIgnorePointer {
7134    /// Creates a render object that is invisible to hit testing.
7135    pub fn new(
7136        app: &mut App,
7137        ignoring: bool,
7138        child: Option<AnyRenderBox>,
7139    ) -> RenderHandle<RenderIgnorePointer> {
7140        let this = RenderHandle::new_box(
7141            app,
7142            RenderIgnorePointer {
7143                render_object: RenderObjectData::new(),
7144                render_box: RenderBoxData::new(),
7145                child: RenderObjectWithChildData::new(),
7146                ignoring,
7147            },
7148        );
7149        this.set_child(app, child);
7150        this
7151    }
7152
7153    /// Whether this render object is ignored during hit testing.
7154    ///
7155    /// Regardless of whether this render object is ignored during hit testing, it
7156    /// will still consume space during layout and be visible during painting.
7157    pub fn ignoring(self: RenderHandle<Self>, app: &App) -> bool {
7158        self.get(app).ignoring
7159    }
7160
7161    /// Sets [`ignoring`](Self::ignoring).
7162    pub fn set_ignoring(self: RenderHandle<Self>, app: &mut App, value: bool) {
7163        if value == self.get(app).ignoring {
7164            return;
7165        }
7166        self.get_mut(app).ignoring = value;
7167    }
7168}
7169
7170impl RenderObjectWithChildMixin for RenderIgnorePointer {
7171    type ChildType = AnyRenderBox;
7172
7173    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
7174        &self.get(app).child
7175    }
7176
7177    fn child_data_mut(
7178        self: RenderHandle<Self>,
7179        app: &mut App,
7180    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
7181        &mut self.get_mut(app).child
7182    }
7183}
7184
7185impl RenderProxyBoxMixin for RenderIgnorePointer {}
7186
7187impl RenderObject for RenderIgnorePointer {
7188    crate::render_object_accessors!();
7189
7190    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7191        RenderProxyBoxMixin::perform_layout(self, app);
7192    }
7193
7194    fn paint(
7195        self: RenderHandle<Self>,
7196        app: &mut App,
7197        context: &mut PaintingContext,
7198        offset: Offset,
7199    ) {
7200        RenderProxyBoxMixin::paint(self, app, context, offset);
7201    }
7202
7203    fn visit_children(
7204        self: RenderHandle<Self>,
7205        app: &App,
7206        visitor: &mut dyn FnMut(AnyRenderObject),
7207    ) {
7208        if let Some(child) = self.child(app) {
7209            visitor(child.as_object());
7210        }
7211    }
7212}
7213
7214impl RenderBox for RenderIgnorePointer {
7215    crate::render_box_accessors!();
7216
7217    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
7218        RenderProxyBoxMixin::setup_parent_data(self, app, child);
7219    }
7220
7221    fn apply_paint_transform(
7222        self: RenderHandle<Self>,
7223        app: &App,
7224        child: AnyRenderObject,
7225        transform: &mut Matrix4,
7226    ) {
7227        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
7228    }
7229
7230    fn hit_test(
7231        self: RenderHandle<Self>,
7232        app: &mut App,
7233        result: &mut BoxHitTestResult<'_>,
7234        position: Offset,
7235    ) -> bool {
7236        !self.ignoring(app) && RenderBoxBase::hit_test(self, app, result, position)
7237    }
7238
7239    fn hit_test_children(
7240        self: RenderHandle<Self>,
7241        app: &mut App,
7242        result: &mut BoxHitTestResult<'_>,
7243        position: Offset,
7244    ) -> bool {
7245        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
7246    }
7247
7248    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7249        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
7250    }
7251
7252    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7253        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
7254    }
7255
7256    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7257        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
7258    }
7259
7260    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7261        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
7262    }
7263
7264    fn compute_distance_to_actual_baseline(
7265        self: RenderHandle<Self>,
7266        app: &mut App,
7267        baseline: TextBaseline,
7268    ) -> Option<f64> {
7269        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
7270    }
7271
7272    fn compute_dry_baseline(
7273        self: RenderHandle<Self>,
7274        app: &mut App,
7275        constraints: BoxConstraints,
7276        baseline: TextBaseline,
7277    ) -> Option<f64> {
7278        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
7279    }
7280
7281    fn compute_dry_layout(
7282        self: RenderHandle<Self>,
7283        app: &mut App,
7284        constraints: BoxConstraints,
7285    ) -> Size {
7286        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
7287    }
7288}
7289
7290/// Lays the child out as if it was in the tree, but without painting anything,
7291/// without making the child available for hit testing, and without taking any
7292/// room in the parent.
7293pub struct RenderOffstage {
7294    render_object: RenderObjectData,
7295    render_box: RenderBoxData,
7296    child: RenderObjectWithChildData<AnyRenderBox>,
7297    offstage: bool,
7298}
7299
7300impl RenderOffstage {
7301    /// Creates an offstage render object.
7302    pub fn new(
7303        app: &mut App,
7304        offstage: bool,
7305        child: Option<AnyRenderBox>,
7306    ) -> RenderHandle<RenderOffstage> {
7307        let this = RenderHandle::new_box(
7308            app,
7309            RenderOffstage {
7310                render_object: RenderObjectData::new(),
7311                render_box: RenderBoxData::new(),
7312                child: RenderObjectWithChildData::new(),
7313                offstage,
7314            },
7315        );
7316        this.set_child(app, child);
7317        this
7318    }
7319
7320    /// Whether the child is hidden from the rest of the tree.
7321    ///
7322    /// If true, the child is laid out as if it was in the tree, but without
7323    /// painting anything, without making the child available for hit testing, and
7324    /// without taking any room in the parent.
7325    ///
7326    /// If false, the child is included in the tree as normal.
7327    pub fn offstage(self: RenderHandle<Self>, app: &App) -> bool {
7328        self.get(app).offstage
7329    }
7330
7331    /// Sets [`offstage`](Self::offstage).
7332    pub fn set_offstage(self: RenderHandle<Self>, app: &mut App, value: bool) {
7333        if value == self.get(app).offstage {
7334            return;
7335        }
7336        self.get_mut(app).offstage = value;
7337        self.as_object()
7338            .mark_needs_layout_for_sized_by_parent_change(app);
7339    }
7340}
7341
7342impl RenderObjectWithChildMixin for RenderOffstage {
7343    type ChildType = AnyRenderBox;
7344
7345    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
7346        &self.get(app).child
7347    }
7348
7349    fn child_data_mut(
7350        self: RenderHandle<Self>,
7351        app: &mut App,
7352    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
7353        &mut self.get_mut(app).child
7354    }
7355}
7356
7357impl RenderProxyBoxMixin for RenderOffstage {}
7358
7359impl RenderObject for RenderOffstage {
7360    crate::render_object_accessors!();
7361
7362    fn sized_by_parent(self: RenderHandle<Self>, app: &App) -> bool {
7363        self.get(app).offstage
7364    }
7365
7366    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7367        if !self.get(app).offstage {
7368            RenderProxyBoxMixin::perform_layout(self, app);
7369            return;
7370        }
7371        if let Some(child) = self.child(app) {
7372            let constraints = self.constraints(app);
7373            child.layout(app, constraints, false);
7374        }
7375    }
7376
7377    fn paint(
7378        self: RenderHandle<Self>,
7379        app: &mut App,
7380        context: &mut PaintingContext,
7381        offset: Offset,
7382    ) {
7383        if self.get(app).offstage {
7384            return;
7385        }
7386        RenderProxyBoxMixin::paint(self, app, context, offset);
7387    }
7388
7389    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
7390        debug_assert!(child.parent(app) == Some(self.as_object()));
7391        !self.get(app).offstage
7392    }
7393
7394    fn visit_children(
7395        self: RenderHandle<Self>,
7396        app: &App,
7397        visitor: &mut dyn FnMut(AnyRenderObject),
7398    ) {
7399        if let Some(child) = self.child(app) {
7400            visitor(child.as_object());
7401        }
7402    }
7403}
7404
7405impl RenderBox for RenderOffstage {
7406    crate::render_box_accessors!();
7407
7408    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
7409        RenderProxyBoxMixin::setup_parent_data(self, app, child);
7410    }
7411
7412    fn apply_paint_transform(
7413        self: RenderHandle<Self>,
7414        app: &App,
7415        child: AnyRenderObject,
7416        transform: &mut Matrix4,
7417    ) {
7418        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
7419    }
7420
7421    fn hit_test(
7422        self: RenderHandle<Self>,
7423        app: &mut App,
7424        result: &mut BoxHitTestResult<'_>,
7425        position: Offset,
7426    ) -> bool {
7427        !self.get(app).offstage && RenderBoxBase::hit_test(self, app, result, position)
7428    }
7429
7430    fn hit_test_children(
7431        self: RenderHandle<Self>,
7432        app: &mut App,
7433        result: &mut BoxHitTestResult<'_>,
7434        position: Offset,
7435    ) -> bool {
7436        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
7437    }
7438
7439    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7440        if self.get(app).offstage {
7441            return 0.0;
7442        }
7443        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
7444    }
7445
7446    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7447        if self.get(app).offstage {
7448            return 0.0;
7449        }
7450        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
7451    }
7452
7453    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7454        if self.get(app).offstage {
7455            return 0.0;
7456        }
7457        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
7458    }
7459
7460    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7461        if self.get(app).offstage {
7462            return 0.0;
7463        }
7464        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
7465    }
7466
7467    fn compute_distance_to_actual_baseline(
7468        self: RenderHandle<Self>,
7469        app: &mut App,
7470        baseline: TextBaseline,
7471    ) -> Option<f64> {
7472        if self.get(app).offstage {
7473            return None;
7474        }
7475        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
7476    }
7477
7478    fn compute_dry_baseline(
7479        self: RenderHandle<Self>,
7480        app: &mut App,
7481        constraints: BoxConstraints,
7482        baseline: TextBaseline,
7483    ) -> Option<f64> {
7484        if self.get(app).offstage {
7485            return None;
7486        }
7487        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
7488    }
7489
7490    fn compute_dry_layout(
7491        self: RenderHandle<Self>,
7492        app: &mut App,
7493        constraints: BoxConstraints,
7494    ) -> Size {
7495        if self.get(app).offstage {
7496            return constraints.smallest();
7497        }
7498        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
7499    }
7500
7501    /// Flutter's `performResize` asserts and calls `super.performResize`.
7502    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
7503        debug_assert!(self.get(app).offstage);
7504        RenderBoxBase::perform_resize(self, app);
7505    }
7506}
7507
7508/// A render object that absorbs pointers during hit testing.
7509///
7510/// When [`absorbing`](Self::absorbing) is true, this render object prevents its subtree from
7511/// receiving pointer events by terminating hit testing at itself. It still
7512/// consumes space during layout and paints its child as usual. It just prevents
7513/// its children from being the target of located events, because its render
7514/// object returns true from [`RenderBox::hit_test`].
7515///
7516/// See also:
7517///
7518///  * [`RenderIgnorePointer`], which has the opposite effect: removing the
7519///    subtree from considering entirely for the purposes of hit testing.
7520pub struct RenderAbsorbPointer {
7521    render_object: RenderObjectData,
7522    render_box: RenderBoxData,
7523    child: RenderObjectWithChildData<AnyRenderBox>,
7524    absorbing: bool,
7525}
7526
7527impl RenderAbsorbPointer {
7528    /// Creates a render object that absorbs pointers during hit testing.
7529    pub fn new(
7530        app: &mut App,
7531        absorbing: bool,
7532        child: Option<AnyRenderBox>,
7533    ) -> RenderHandle<RenderAbsorbPointer> {
7534        let this = RenderHandle::new_box(
7535            app,
7536            RenderAbsorbPointer {
7537                render_object: RenderObjectData::new(),
7538                render_box: RenderBoxData::new(),
7539                child: RenderObjectWithChildData::new(),
7540                absorbing,
7541            },
7542        );
7543        this.set_child(app, child);
7544        this
7545    }
7546
7547    /// Whether this render object absorbs pointers during hit testing.
7548    ///
7549    /// Regardless of whether this render object absorbs pointers during hit
7550    /// testing, it will still consume space during layout and be visible during
7551    /// painting.
7552    pub fn absorbing(self: RenderHandle<Self>, app: &App) -> bool {
7553        self.get(app).absorbing
7554    }
7555
7556    /// Sets [`absorbing`](Self::absorbing).
7557    pub fn set_absorbing(self: RenderHandle<Self>, app: &mut App, value: bool) {
7558        if self.get(app).absorbing == value {
7559            return;
7560        }
7561        self.get_mut(app).absorbing = value;
7562    }
7563}
7564
7565impl RenderObjectWithChildMixin for RenderAbsorbPointer {
7566    type ChildType = AnyRenderBox;
7567
7568    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
7569        &self.get(app).child
7570    }
7571
7572    fn child_data_mut(
7573        self: RenderHandle<Self>,
7574        app: &mut App,
7575    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
7576        &mut self.get_mut(app).child
7577    }
7578}
7579
7580impl RenderProxyBoxMixin for RenderAbsorbPointer {}
7581
7582impl RenderObject for RenderAbsorbPointer {
7583    crate::render_object_accessors!();
7584
7585    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7586        RenderProxyBoxMixin::perform_layout(self, app);
7587    }
7588
7589    fn paint(
7590        self: RenderHandle<Self>,
7591        app: &mut App,
7592        context: &mut PaintingContext,
7593        offset: Offset,
7594    ) {
7595        RenderProxyBoxMixin::paint(self, app, context, offset);
7596    }
7597
7598    fn visit_children(
7599        self: RenderHandle<Self>,
7600        app: &App,
7601        visitor: &mut dyn FnMut(AnyRenderObject),
7602    ) {
7603        if let Some(child) = self.child(app) {
7604            visitor(child.as_object());
7605        }
7606    }
7607}
7608
7609impl RenderBox for RenderAbsorbPointer {
7610    crate::render_box_accessors!();
7611
7612    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
7613        RenderProxyBoxMixin::setup_parent_data(self, app, child);
7614    }
7615
7616    fn apply_paint_transform(
7617        self: RenderHandle<Self>,
7618        app: &App,
7619        child: AnyRenderObject,
7620        transform: &mut Matrix4,
7621    ) {
7622        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
7623    }
7624
7625    fn hit_test(
7626        self: RenderHandle<Self>,
7627        app: &mut App,
7628        result: &mut BoxHitTestResult<'_>,
7629        position: Offset,
7630    ) -> bool {
7631        if self.absorbing(app) {
7632            return self.size(app).contains(position);
7633        }
7634        RenderBoxBase::hit_test(self, app, result, position)
7635    }
7636
7637    fn hit_test_children(
7638        self: RenderHandle<Self>,
7639        app: &mut App,
7640        result: &mut BoxHitTestResult<'_>,
7641        position: Offset,
7642    ) -> bool {
7643        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
7644    }
7645
7646    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7647        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
7648    }
7649
7650    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7651        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
7652    }
7653
7654    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7655        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
7656    }
7657
7658    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7659        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
7660    }
7661
7662    fn compute_distance_to_actual_baseline(
7663        self: RenderHandle<Self>,
7664        app: &mut App,
7665        baseline: TextBaseline,
7666    ) -> Option<f64> {
7667        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
7668    }
7669
7670    fn compute_dry_baseline(
7671        self: RenderHandle<Self>,
7672        app: &mut App,
7673        constraints: BoxConstraints,
7674        baseline: TextBaseline,
7675    ) -> Option<f64> {
7676        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
7677    }
7678
7679    fn compute_dry_layout(
7680        self: RenderHandle<Self>,
7681        app: &mut App,
7682        constraints: BoxConstraints,
7683    ) -> Size {
7684        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
7685    }
7686}
7687
7688/// Paints its area with a specified [`Color`] and then draws its child on top of that color.
7689///
7690/// Flutter's `_RenderColoredBox`, the render object of the `ColoredBox` widget, in
7691/// `widgets/basic.dart`.
7692pub struct RenderColoredBox {
7693    render_object: RenderObjectData,
7694    render_box: RenderBoxData,
7695    child: RenderObjectWithChildData<AnyRenderBox>,
7696    color: Color,
7697    is_anti_alias: bool,
7698    behavior: HitTestBehavior,
7699}
7700
7701impl RenderColoredBox {
7702    /// Creates a render object that paints its area with `color`.
7703    pub fn new(
7704        app: &mut App,
7705        color: Color,
7706        is_anti_alias: bool,
7707        child: Option<AnyRenderBox>,
7708    ) -> RenderHandle<RenderColoredBox> {
7709        let this = RenderHandle::new_box(
7710            app,
7711            RenderColoredBox {
7712                render_object: RenderObjectData::new(),
7713                render_box: RenderBoxData::new(),
7714                child: RenderObjectWithChildData::new(),
7715                color,
7716                is_anti_alias,
7717                behavior: HitTestBehavior::Opaque,
7718            },
7719        );
7720        this.set_child(app, child);
7721        this
7722    }
7723
7724    /// The fill color for this render object.
7725    pub fn color(self: RenderHandle<Self>, app: &App) -> Color {
7726        self.get(app).color
7727    }
7728
7729    /// Sets [`color`](Self::color).
7730    pub fn set_color(self: RenderHandle<Self>, app: &mut App, value: Color) {
7731        if value == self.get(app).color {
7732            return;
7733        }
7734        self.get_mut(app).color = value;
7735        self.mark_needs_paint(app);
7736    }
7737
7738    /// Whether to apply anti-aliasing when painting the box.
7739    pub fn is_anti_alias(self: RenderHandle<Self>, app: &App) -> bool {
7740        self.get(app).is_anti_alias
7741    }
7742
7743    /// Sets [`is_anti_alias`](Self::is_anti_alias).
7744    pub fn set_is_anti_alias(self: RenderHandle<Self>, app: &mut App, value: bool) {
7745        if value == self.get(app).is_anti_alias {
7746            return;
7747        }
7748        self.get_mut(app).is_anti_alias = value;
7749        self.mark_needs_paint(app);
7750    }
7751}
7752
7753impl RenderObjectWithChildMixin for RenderColoredBox {
7754    type ChildType = AnyRenderBox;
7755
7756    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
7757        &self.get(app).child
7758    }
7759
7760    fn child_data_mut(
7761        self: RenderHandle<Self>,
7762        app: &mut App,
7763    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
7764        &mut self.get_mut(app).child
7765    }
7766}
7767
7768impl RenderProxyBoxMixin for RenderColoredBox {}
7769
7770impl RenderProxyBoxWithHitTestBehavior for RenderColoredBox {
7771    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
7772        self.get(app).behavior
7773    }
7774}
7775
7776impl RenderObject for RenderColoredBox {
7777    crate::render_object_accessors!();
7778
7779    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7780        RenderProxyBoxMixin::perform_layout(self, app);
7781    }
7782
7783    fn paint(
7784        self: RenderHandle<Self>,
7785        app: &mut App,
7786        context: &mut PaintingContext,
7787        offset: Offset,
7788    ) {
7789        // It's tempting to want to optimize out this `draw_rect()` call if the
7790        // color is transparent (alpha==0), but doing so would be incorrect. See
7791        // https://github.com/flutter/flutter/pull/72526#issuecomment-749185938 for
7792        // a good description of why.
7793        let size = self.size(app);
7794        if size.gt(&Size::ZERO) {
7795            let paint = Paint {
7796                color: self.get(app).color.into(),
7797                ..Paint::default()
7798            };
7799            context.canvas().draw_rect(offset & size, &paint);
7800        }
7801        if let Some(child) = self.child(app) {
7802            context.paint_child(app, child.as_object(), offset);
7803        }
7804    }
7805
7806    fn visit_children(
7807        self: RenderHandle<Self>,
7808        app: &App,
7809        visitor: &mut dyn FnMut(AnyRenderObject),
7810    ) {
7811        if let Some(child) = self.child(app) {
7812            visitor(child.as_object());
7813        }
7814    }
7815}
7816
7817impl RenderBox for RenderColoredBox {
7818    crate::render_box_accessors!();
7819
7820    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
7821        RenderProxyBoxMixin::setup_parent_data(self, app, child);
7822    }
7823
7824    fn apply_paint_transform(
7825        self: RenderHandle<Self>,
7826        app: &App,
7827        child: AnyRenderObject,
7828        transform: &mut Matrix4,
7829    ) {
7830        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
7831    }
7832
7833    fn hit_test(
7834        self: RenderHandle<Self>,
7835        app: &mut App,
7836        result: &mut BoxHitTestResult<'_>,
7837        position: Offset,
7838    ) -> bool {
7839        RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
7840    }
7841
7842    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
7843        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
7844    }
7845
7846    fn hit_test_children(
7847        self: RenderHandle<Self>,
7848        app: &mut App,
7849        result: &mut BoxHitTestResult<'_>,
7850        position: Offset,
7851    ) -> bool {
7852        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
7853    }
7854
7855    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7856        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
7857    }
7858
7859    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
7860        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
7861    }
7862
7863    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7864        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
7865    }
7866
7867    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
7868        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
7869    }
7870
7871    fn compute_distance_to_actual_baseline(
7872        self: RenderHandle<Self>,
7873        app: &mut App,
7874        baseline: TextBaseline,
7875    ) -> Option<f64> {
7876        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
7877    }
7878
7879    fn compute_dry_baseline(
7880        self: RenderHandle<Self>,
7881        app: &mut App,
7882        constraints: BoxConstraints,
7883        baseline: TextBaseline,
7884    ) -> Option<f64> {
7885        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
7886    }
7887
7888    fn compute_dry_layout(
7889        self: RenderHandle<Self>,
7890        app: &mut App,
7891        constraints: BoxConstraints,
7892    ) -> Size {
7893        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
7894    }
7895}
7896
7897/// Holds opaque meta data in the render tree.
7898///
7899/// Useful for decorating the render tree with information that will be consumed
7900/// later. For example, you could store information in the render tree that will
7901/// be used when the user interacts with the render tree but has no visual impact
7902/// prior to the interaction.
7903pub struct RenderMetaData {
7904    render_object: RenderObjectData,
7905    render_box: RenderBoxData,
7906    child: RenderObjectWithChildData<AnyRenderBox>,
7907    meta_data: Option<Rc<dyn Any>>,
7908    behavior: HitTestBehavior,
7909}
7910
7911impl RenderMetaData {
7912    /// Creates a render object that hold opaque meta data.
7913    ///
7914    /// The `behavior` argument defaults to [`HitTestBehavior::DeferToChild`].
7915    pub fn new(
7916        app: &mut App,
7917        meta_data: Option<Rc<dyn Any>>,
7918        behavior: HitTestBehavior,
7919        child: Option<AnyRenderBox>,
7920    ) -> RenderHandle<Self> {
7921        let this = RenderHandle::new_box(
7922            app,
7923            RenderMetaData {
7924                render_object: RenderObjectData::new(),
7925                render_box: RenderBoxData::new(),
7926                child: RenderObjectWithChildData::new(),
7927                meta_data,
7928                behavior,
7929            },
7930        );
7931        this.set_child(app, child);
7932        this
7933    }
7934
7935    /// Opaque meta data ignored by the render tree.
7936    pub fn meta_data(self: RenderHandle<Self>, app: &App) -> Option<Rc<dyn Any>> {
7937        self.get(app).meta_data.clone()
7938    }
7939
7940    /// Sets [`meta_data`](Self::meta_data).
7941    pub fn set_meta_data(self: RenderHandle<Self>, app: &mut App, value: Option<Rc<dyn Any>>) {
7942        self.get_mut(app).meta_data = value;
7943    }
7944
7945    /// Sets [`behavior`](RenderProxyBoxWithHitTestBehavior::behavior).
7946    pub fn set_behavior(self: RenderHandle<Self>, app: &mut App, value: HitTestBehavior) {
7947        self.get_mut(app).behavior = value;
7948    }
7949}
7950
7951impl RenderObjectWithChildMixin for RenderMetaData {
7952    type ChildType = AnyRenderBox;
7953
7954    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
7955        &self.get(app).child
7956    }
7957
7958    fn child_data_mut(
7959        self: RenderHandle<Self>,
7960        app: &mut App,
7961    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
7962        &mut self.get_mut(app).child
7963    }
7964}
7965
7966impl RenderProxyBoxMixin for RenderMetaData {}
7967
7968impl RenderProxyBoxWithHitTestBehavior for RenderMetaData {
7969    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
7970        self.get(app).behavior
7971    }
7972}
7973
7974impl RenderObject for RenderMetaData {
7975    crate::render_object_accessors!();
7976
7977    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
7978        RenderProxyBoxMixin::perform_layout(self, app);
7979    }
7980
7981    fn paint(
7982        self: RenderHandle<Self>,
7983        app: &mut App,
7984        context: &mut PaintingContext,
7985        offset: Offset,
7986    ) {
7987        RenderProxyBoxMixin::paint(self, app, context, offset);
7988    }
7989
7990    fn visit_children(
7991        self: RenderHandle<Self>,
7992        app: &App,
7993        visitor: &mut dyn FnMut(AnyRenderObject),
7994    ) {
7995        if let Some(child) = self.child(app) {
7996            visitor(child.as_object());
7997        }
7998    }
7999}
8000
8001impl RenderBox for RenderMetaData {
8002    crate::render_box_accessors!();
8003
8004    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8005        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8006    }
8007
8008    fn apply_paint_transform(
8009        self: RenderHandle<Self>,
8010        app: &App,
8011        child: AnyRenderObject,
8012        transform: &mut Matrix4,
8013    ) {
8014        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8015    }
8016
8017    fn hit_test(
8018        self: RenderHandle<Self>,
8019        app: &mut App,
8020        result: &mut BoxHitTestResult<'_>,
8021        position: Offset,
8022    ) -> bool {
8023        RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
8024    }
8025
8026    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
8027        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
8028    }
8029
8030    fn hit_test_children(
8031        self: RenderHandle<Self>,
8032        app: &mut App,
8033        result: &mut BoxHitTestResult<'_>,
8034        position: Offset,
8035    ) -> bool {
8036        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8037    }
8038
8039    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8040        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8041    }
8042
8043    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8044        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8045    }
8046
8047    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8048        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8049    }
8050
8051    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8052        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8053    }
8054
8055    fn compute_distance_to_actual_baseline(
8056        self: RenderHandle<Self>,
8057        app: &mut App,
8058        baseline: TextBaseline,
8059    ) -> Option<f64> {
8060        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8061    }
8062
8063    fn compute_dry_baseline(
8064        self: RenderHandle<Self>,
8065        app: &mut App,
8066        constraints: BoxConstraints,
8067        baseline: TextBaseline,
8068    ) -> Option<f64> {
8069        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8070    }
8071
8072    fn compute_dry_layout(
8073        self: RenderHandle<Self>,
8074        app: &mut App,
8075        constraints: BoxConstraints,
8076    ) -> Size {
8077        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8078    }
8079}
8080
8081/// Add annotations to the `SemanticsNode` for this subtree.
8082pub struct RenderSemanticsAnnotations {
8083    render_object: RenderObjectData,
8084    render_box: RenderBoxData,
8085    child: RenderObjectWithChildData<AnyRenderBox>,
8086    semantics_annotations: SemanticsAnnotationsData,
8087}
8088
8089impl RenderSemanticsAnnotations {
8090    /// Creates a render object that attaches a semantic annotation.
8091    ///
8092    /// If the [`SemanticsProperties::attributed_label`] is not null, the `text_direction` must
8093    /// also not be null. Dart's defaults: `container`, `explicit_child_nodes`,
8094    /// `exclude_semantics` and `block_user_actions` false.
8095    #[allow(clippy::too_many_arguments)]
8096    pub fn new(
8097        app: &mut App,
8098        properties: Rc<SemanticsProperties>,
8099        container: bool,
8100        explicit_child_nodes: bool,
8101        exclude_semantics: bool,
8102        block_user_actions: bool,
8103        locale_for_subtree: Option<Locale>,
8104        text_direction: Option<TextDirection>,
8105        child: Option<AnyRenderBox>,
8106    ) -> RenderHandle<RenderSemanticsAnnotations> {
8107        let this = RenderHandle::new_box(
8108            app,
8109            RenderSemanticsAnnotations {
8110                render_object: RenderObjectData::new(),
8111                render_box: RenderBoxData::new(),
8112                child: RenderObjectWithChildData::new(),
8113                semantics_annotations: SemanticsAnnotationsData::new(),
8114            },
8115        );
8116        this.set_child(app, child);
8117        this.init_semantics_annotations(
8118            app,
8119            properties,
8120            container,
8121            explicit_child_nodes,
8122            exclude_semantics,
8123            block_user_actions,
8124            locale_for_subtree,
8125            text_direction,
8126        );
8127        this
8128    }
8129}
8130
8131impl SemanticsAnnotationsMixin for RenderSemanticsAnnotations {
8132    fn semantics_annotations_data(
8133        self: RenderHandle<Self>,
8134        app: &App,
8135    ) -> &SemanticsAnnotationsData {
8136        &self.get(app).semantics_annotations
8137    }
8138
8139    fn semantics_annotations_data_mut(
8140        self: RenderHandle<Self>,
8141        app: &mut App,
8142    ) -> &mut SemanticsAnnotationsData {
8143        &mut self.get_mut(app).semantics_annotations
8144    }
8145}
8146
8147impl RenderObjectWithChildMixin for RenderSemanticsAnnotations {
8148    type ChildType = AnyRenderBox;
8149
8150    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8151        &self.get(app).child
8152    }
8153
8154    fn child_data_mut(
8155        self: RenderHandle<Self>,
8156        app: &mut App,
8157    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8158        &mut self.get_mut(app).child
8159    }
8160}
8161
8162impl RenderProxyBoxMixin for RenderSemanticsAnnotations {}
8163
8164impl RenderObject for RenderSemanticsAnnotations {
8165    crate::render_object_accessors!();
8166
8167    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8168        RenderProxyBoxMixin::perform_layout(self, app);
8169    }
8170
8171    fn paint(
8172        self: RenderHandle<Self>,
8173        app: &mut App,
8174        context: &mut PaintingContext,
8175        offset: Offset,
8176    ) {
8177        RenderProxyBoxMixin::paint(self, app, context, offset);
8178    }
8179
8180    fn visit_children(
8181        self: RenderHandle<Self>,
8182        app: &App,
8183        visitor: &mut dyn FnMut(AnyRenderObject),
8184    ) {
8185        if let Some(child) = self.child(app) {
8186            visitor(child.as_object());
8187        }
8188    }
8189}
8190
8191impl RenderBox for RenderSemanticsAnnotations {
8192    crate::render_box_accessors!();
8193
8194    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8195        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8196    }
8197
8198    fn apply_paint_transform(
8199        self: RenderHandle<Self>,
8200        app: &App,
8201        child: AnyRenderObject,
8202        transform: &mut Matrix4,
8203    ) {
8204        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8205    }
8206
8207    fn hit_test_children(
8208        self: RenderHandle<Self>,
8209        app: &mut App,
8210        result: &mut BoxHitTestResult<'_>,
8211        position: Offset,
8212    ) -> bool {
8213        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8214    }
8215
8216    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8217        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8218    }
8219
8220    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8221        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8222    }
8223
8224    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8225        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8226    }
8227
8228    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8229        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8230    }
8231
8232    fn compute_distance_to_actual_baseline(
8233        self: RenderHandle<Self>,
8234        app: &mut App,
8235        baseline: TextBaseline,
8236    ) -> Option<f64> {
8237        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8238    }
8239
8240    fn compute_dry_baseline(
8241        self: RenderHandle<Self>,
8242        app: &mut App,
8243        constraints: BoxConstraints,
8244        baseline: TextBaseline,
8245    ) -> Option<f64> {
8246        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8247    }
8248
8249    fn compute_dry_layout(
8250        self: RenderHandle<Self>,
8251        app: &mut App,
8252        constraints: BoxConstraints,
8253    ) -> Size {
8254        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8255    }
8256}
8257
8258/// Causes the semantics of all earlier render objects below the same semantic
8259/// boundary to be dropped.
8260///
8261/// This is useful in a stack where an opaque mask should prevent interactions
8262/// with the render objects painted below the mask.
8263pub struct RenderBlockSemantics {
8264    render_object: RenderObjectData,
8265    render_box: RenderBoxData,
8266    child: RenderObjectWithChildData<AnyRenderBox>,
8267    blocking: bool,
8268}
8269
8270impl RenderBlockSemantics {
8271    /// Create a render object that blocks semantics for nodes below it in paint
8272    /// order. Dart's default `blocking` is true.
8273    pub fn new(
8274        app: &mut App,
8275        blocking: bool,
8276        child: Option<AnyRenderBox>,
8277    ) -> RenderHandle<RenderBlockSemantics> {
8278        let this = RenderHandle::new_box(
8279            app,
8280            RenderBlockSemantics {
8281                render_object: RenderObjectData::new(),
8282                render_box: RenderBoxData::new(),
8283                child: RenderObjectWithChildData::new(),
8284                blocking,
8285            },
8286        );
8287        this.set_child(app, child);
8288        this
8289    }
8290
8291    /// Whether this render object is blocking semantics of previously painted
8292    /// [`RenderObject`]s below a common semantics boundary from the semantic tree.
8293    pub fn blocking(self: RenderHandle<Self>, app: &App) -> bool {
8294        self.get(app).blocking
8295    }
8296
8297    /// Sets [`blocking`](Self::blocking).
8298    pub fn set_blocking(self: RenderHandle<Self>, app: &mut App, value: bool) {
8299        if value == self.get(app).blocking {
8300            return;
8301        }
8302        self.get_mut(app).blocking = value;
8303    }
8304}
8305
8306impl RenderObjectWithChildMixin for RenderBlockSemantics {
8307    type ChildType = AnyRenderBox;
8308
8309    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8310        &self.get(app).child
8311    }
8312
8313    fn child_data_mut(
8314        self: RenderHandle<Self>,
8315        app: &mut App,
8316    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8317        &mut self.get_mut(app).child
8318    }
8319}
8320
8321impl RenderProxyBoxMixin for RenderBlockSemantics {}
8322
8323impl RenderObject for RenderBlockSemantics {
8324    crate::render_object_accessors!();
8325
8326    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8327        RenderProxyBoxMixin::perform_layout(self, app);
8328    }
8329
8330    fn paint(
8331        self: RenderHandle<Self>,
8332        app: &mut App,
8333        context: &mut PaintingContext,
8334        offset: Offset,
8335    ) {
8336        RenderProxyBoxMixin::paint(self, app, context, offset);
8337    }
8338
8339    fn visit_children(
8340        self: RenderHandle<Self>,
8341        app: &App,
8342        visitor: &mut dyn FnMut(AnyRenderObject),
8343    ) {
8344        if let Some(child) = self.child(app) {
8345            visitor(child.as_object());
8346        }
8347    }
8348}
8349
8350impl RenderBox for RenderBlockSemantics {
8351    crate::render_box_accessors!();
8352
8353    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8354        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8355    }
8356
8357    fn apply_paint_transform(
8358        self: RenderHandle<Self>,
8359        app: &App,
8360        child: AnyRenderObject,
8361        transform: &mut Matrix4,
8362    ) {
8363        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8364    }
8365
8366    fn hit_test_children(
8367        self: RenderHandle<Self>,
8368        app: &mut App,
8369        result: &mut BoxHitTestResult<'_>,
8370        position: Offset,
8371    ) -> bool {
8372        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8373    }
8374
8375    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8376        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8377    }
8378
8379    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8380        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8381    }
8382
8383    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8384        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8385    }
8386
8387    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8388        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8389    }
8390
8391    fn compute_distance_to_actual_baseline(
8392        self: RenderHandle<Self>,
8393        app: &mut App,
8394        baseline: TextBaseline,
8395    ) -> Option<f64> {
8396        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8397    }
8398
8399    fn compute_dry_baseline(
8400        self: RenderHandle<Self>,
8401        app: &mut App,
8402        constraints: BoxConstraints,
8403        baseline: TextBaseline,
8404    ) -> Option<f64> {
8405        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8406    }
8407
8408    fn compute_dry_layout(
8409        self: RenderHandle<Self>,
8410        app: &mut App,
8411        constraints: BoxConstraints,
8412    ) -> Size {
8413        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8414    }
8415}
8416
8417/// Causes the semantics of all descendants to be merged into this
8418/// node such that the entire subtree becomes a single leaf in the
8419/// semantics tree.
8420///
8421/// Useful for combining the semantics of multiple render objects that
8422/// form part of a single conceptual widget, e.g. a checkbox, a label,
8423/// and the gesture detector that goes with them.
8424pub struct RenderMergeSemantics {
8425    render_object: RenderObjectData,
8426    render_box: RenderBoxData,
8427    child: RenderObjectWithChildData<AnyRenderBox>,
8428}
8429
8430impl RenderMergeSemantics {
8431    /// Creates a render object that merges the semantics from its descendants.
8432    pub fn new(app: &mut App, child: Option<AnyRenderBox>) -> RenderHandle<RenderMergeSemantics> {
8433        let this = RenderHandle::new_box(
8434            app,
8435            RenderMergeSemantics {
8436                render_object: RenderObjectData::new(),
8437                render_box: RenderBoxData::new(),
8438                child: RenderObjectWithChildData::new(),
8439            },
8440        );
8441        this.set_child(app, child);
8442        this
8443    }
8444}
8445
8446impl RenderObjectWithChildMixin for RenderMergeSemantics {
8447    type ChildType = AnyRenderBox;
8448
8449    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8450        &self.get(app).child
8451    }
8452
8453    fn child_data_mut(
8454        self: RenderHandle<Self>,
8455        app: &mut App,
8456    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8457        &mut self.get_mut(app).child
8458    }
8459}
8460
8461impl RenderProxyBoxMixin for RenderMergeSemantics {}
8462
8463impl RenderObject for RenderMergeSemantics {
8464    crate::render_object_accessors!();
8465
8466    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8467        RenderProxyBoxMixin::perform_layout(self, app);
8468    }
8469
8470    fn paint(
8471        self: RenderHandle<Self>,
8472        app: &mut App,
8473        context: &mut PaintingContext,
8474        offset: Offset,
8475    ) {
8476        RenderProxyBoxMixin::paint(self, app, context, offset);
8477    }
8478
8479    fn visit_children(
8480        self: RenderHandle<Self>,
8481        app: &App,
8482        visitor: &mut dyn FnMut(AnyRenderObject),
8483    ) {
8484        if let Some(child) = self.child(app) {
8485            visitor(child.as_object());
8486        }
8487    }
8488}
8489
8490impl RenderBox for RenderMergeSemantics {
8491    crate::render_box_accessors!();
8492
8493    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8494        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8495    }
8496
8497    fn apply_paint_transform(
8498        self: RenderHandle<Self>,
8499        app: &App,
8500        child: AnyRenderObject,
8501        transform: &mut Matrix4,
8502    ) {
8503        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8504    }
8505
8506    fn hit_test_children(
8507        self: RenderHandle<Self>,
8508        app: &mut App,
8509        result: &mut BoxHitTestResult<'_>,
8510        position: Offset,
8511    ) -> bool {
8512        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8513    }
8514
8515    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8516        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8517    }
8518
8519    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8520        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8521    }
8522
8523    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8524        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8525    }
8526
8527    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8528        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8529    }
8530
8531    fn compute_distance_to_actual_baseline(
8532        self: RenderHandle<Self>,
8533        app: &mut App,
8534        baseline: TextBaseline,
8535    ) -> Option<f64> {
8536        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8537    }
8538
8539    fn compute_dry_baseline(
8540        self: RenderHandle<Self>,
8541        app: &mut App,
8542        constraints: BoxConstraints,
8543        baseline: TextBaseline,
8544    ) -> Option<f64> {
8545        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8546    }
8547
8548    fn compute_dry_layout(
8549        self: RenderHandle<Self>,
8550        app: &mut App,
8551        constraints: BoxConstraints,
8552    ) -> Size {
8553        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8554    }
8555}
8556
8557/// Excludes this subtree from the semantic tree.
8558///
8559/// When [`excluding`](Self::excluding) is true, this render object (and its subtree) is
8560/// excluded from the semantic tree.
8561///
8562/// Useful e.g. for hiding text that is redundant with other text next
8563/// to it (e.g. text included only for the visual effect).
8564pub struct RenderExcludeSemantics {
8565    render_object: RenderObjectData,
8566    render_box: RenderBoxData,
8567    child: RenderObjectWithChildData<AnyRenderBox>,
8568    excluding: bool,
8569}
8570
8571impl RenderExcludeSemantics {
8572    /// Creates a render object that ignores the semantics of its subtree. Dart's default
8573    /// `excluding` is true.
8574    pub fn new(
8575        app: &mut App,
8576        excluding: bool,
8577        child: Option<AnyRenderBox>,
8578    ) -> RenderHandle<RenderExcludeSemantics> {
8579        let this = RenderHandle::new_box(
8580            app,
8581            RenderExcludeSemantics {
8582                render_object: RenderObjectData::new(),
8583                render_box: RenderBoxData::new(),
8584                child: RenderObjectWithChildData::new(),
8585                excluding,
8586            },
8587        );
8588        this.set_child(app, child);
8589        this
8590    }
8591
8592    /// Whether this render object is excluded from the semantic tree.
8593    pub fn excluding(self: RenderHandle<Self>, app: &App) -> bool {
8594        self.get(app).excluding
8595    }
8596
8597    /// Sets [`excluding`](Self::excluding).
8598    pub fn set_excluding(self: RenderHandle<Self>, app: &mut App, value: bool) {
8599        if value == self.get(app).excluding {
8600            return;
8601        }
8602        self.get_mut(app).excluding = value;
8603    }
8604}
8605
8606impl RenderObjectWithChildMixin for RenderExcludeSemantics {
8607    type ChildType = AnyRenderBox;
8608
8609    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8610        &self.get(app).child
8611    }
8612
8613    fn child_data_mut(
8614        self: RenderHandle<Self>,
8615        app: &mut App,
8616    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8617        &mut self.get_mut(app).child
8618    }
8619}
8620
8621impl RenderProxyBoxMixin for RenderExcludeSemantics {}
8622
8623impl RenderObject for RenderExcludeSemantics {
8624    crate::render_object_accessors!();
8625
8626    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8627        RenderProxyBoxMixin::perform_layout(self, app);
8628    }
8629
8630    fn paint(
8631        self: RenderHandle<Self>,
8632        app: &mut App,
8633        context: &mut PaintingContext,
8634        offset: Offset,
8635    ) {
8636        RenderProxyBoxMixin::paint(self, app, context, offset);
8637    }
8638
8639    fn visit_children(
8640        self: RenderHandle<Self>,
8641        app: &App,
8642        visitor: &mut dyn FnMut(AnyRenderObject),
8643    ) {
8644        if let Some(child) = self.child(app) {
8645            visitor(child.as_object());
8646        }
8647    }
8648}
8649
8650impl RenderBox for RenderExcludeSemantics {
8651    crate::render_box_accessors!();
8652
8653    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8654        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8655    }
8656
8657    fn apply_paint_transform(
8658        self: RenderHandle<Self>,
8659        app: &App,
8660        child: AnyRenderObject,
8661        transform: &mut Matrix4,
8662    ) {
8663        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8664    }
8665
8666    fn hit_test_children(
8667        self: RenderHandle<Self>,
8668        app: &mut App,
8669        result: &mut BoxHitTestResult<'_>,
8670        position: Offset,
8671    ) -> bool {
8672        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8673    }
8674
8675    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8676        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8677    }
8678
8679    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8680        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8681    }
8682
8683    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8684        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8685    }
8686
8687    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8688        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8689    }
8690
8691    fn compute_distance_to_actual_baseline(
8692        self: RenderHandle<Self>,
8693        app: &mut App,
8694        baseline: TextBaseline,
8695    ) -> Option<f64> {
8696        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8697    }
8698
8699    fn compute_dry_baseline(
8700        self: RenderHandle<Self>,
8701        app: &mut App,
8702        constraints: BoxConstraints,
8703        baseline: TextBaseline,
8704    ) -> Option<f64> {
8705        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8706    }
8707
8708    fn compute_dry_layout(
8709        self: RenderHandle<Self>,
8710        app: &mut App,
8711        constraints: BoxConstraints,
8712    ) -> Size {
8713        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8714    }
8715}
8716
8717/// A render objects that annotates semantics with an index.
8718///
8719/// Certain widgets will automatically provide a child index for building
8720/// semantics. For example, the `ScrollView` uses the index of the first
8721/// visible child semantics node to determine the
8722/// `SemanticsConfiguration.scrollIndex`.
8723pub struct RenderIndexedSemantics {
8724    render_object: RenderObjectData,
8725    render_box: RenderBoxData,
8726    child: RenderObjectWithChildData<AnyRenderBox>,
8727    index: i32,
8728}
8729
8730impl RenderIndexedSemantics {
8731    /// Creates a render object that annotates the child semantics with an index.
8732    pub fn new(
8733        app: &mut App,
8734        index: i32,
8735        child: Option<AnyRenderBox>,
8736    ) -> RenderHandle<RenderIndexedSemantics> {
8737        let this = RenderHandle::new_box(
8738            app,
8739            RenderIndexedSemantics {
8740                render_object: RenderObjectData::new(),
8741                render_box: RenderBoxData::new(),
8742                child: RenderObjectWithChildData::new(),
8743                index,
8744            },
8745        );
8746        this.set_child(app, child);
8747        this
8748    }
8749
8750    /// The index used to annotated child semantics.
8751    pub fn index(self: RenderHandle<Self>, app: &App) -> i32 {
8752        self.get(app).index
8753    }
8754
8755    /// Sets [`index`](Self::index).
8756    pub fn set_index(self: RenderHandle<Self>, app: &mut App, value: i32) {
8757        if value == self.index(app) {
8758            return;
8759        }
8760        self.get_mut(app).index = value;
8761    }
8762}
8763
8764impl RenderObjectWithChildMixin for RenderIndexedSemantics {
8765    type ChildType = AnyRenderBox;
8766
8767    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8768        &self.get(app).child
8769    }
8770
8771    fn child_data_mut(
8772        self: RenderHandle<Self>,
8773        app: &mut App,
8774    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8775        &mut self.get_mut(app).child
8776    }
8777}
8778
8779impl RenderProxyBoxMixin for RenderIndexedSemantics {}
8780
8781impl RenderObject for RenderIndexedSemantics {
8782    crate::render_object_accessors!();
8783
8784    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8785        RenderProxyBoxMixin::perform_layout(self, app);
8786    }
8787
8788    fn paint(
8789        self: RenderHandle<Self>,
8790        app: &mut App,
8791        context: &mut PaintingContext,
8792        offset: Offset,
8793    ) {
8794        RenderProxyBoxMixin::paint(self, app, context, offset);
8795    }
8796
8797    fn visit_children(
8798        self: RenderHandle<Self>,
8799        app: &App,
8800        visitor: &mut dyn FnMut(AnyRenderObject),
8801    ) {
8802        if let Some(child) = self.child(app) {
8803            visitor(child.as_object());
8804        }
8805    }
8806}
8807
8808impl RenderBox for RenderIndexedSemantics {
8809    crate::render_box_accessors!();
8810
8811    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8812        RenderProxyBoxMixin::setup_parent_data(self, app, child);
8813    }
8814
8815    fn apply_paint_transform(
8816        self: RenderHandle<Self>,
8817        app: &App,
8818        child: AnyRenderObject,
8819        transform: &mut Matrix4,
8820    ) {
8821        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8822    }
8823
8824    fn hit_test_children(
8825        self: RenderHandle<Self>,
8826        app: &mut App,
8827        result: &mut BoxHitTestResult<'_>,
8828        position: Offset,
8829    ) -> bool {
8830        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8831    }
8832
8833    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8834        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8835    }
8836
8837    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
8838        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8839    }
8840
8841    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8842        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8843    }
8844
8845    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
8846        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8847    }
8848
8849    fn compute_distance_to_actual_baseline(
8850        self: RenderHandle<Self>,
8851        app: &mut App,
8852        baseline: TextBaseline,
8853    ) -> Option<f64> {
8854        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8855    }
8856
8857    fn compute_dry_baseline(
8858        self: RenderHandle<Self>,
8859        app: &mut App,
8860        constraints: BoxConstraints,
8861        baseline: TextBaseline,
8862    ) -> Option<f64> {
8863        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8864    }
8865
8866    fn compute_dry_layout(
8867        self: RenderHandle<Self>,
8868        app: &mut App,
8869        constraints: BoxConstraints,
8870    ) -> Size {
8871        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8872    }
8873}
8874
8875/// Applies a filter to the existing painted content and then paints `child`.
8876///
8877/// This effect is relatively expensive, especially if the filter is non-local,
8878/// such as a blur.
8879pub struct RenderBackdropFilter {
8880    render_object: RenderObjectData,
8881    render_box: RenderBoxData,
8882    child: RenderObjectWithChildData<AnyRenderBox>,
8883    filter_config: ImageFilterConfig,
8884    blend_mode: BlendMode,
8885    enabled: bool,
8886    backdrop_key: Option<BackdropKey>,
8887}
8888
8889impl RenderBackdropFilter {
8890    /// Creates a backdrop filter.
8891    ///
8892    /// The `blend_mode` argument defaults to [`BlendMode::SrcOver`].
8893    pub fn new(
8894        app: &mut App,
8895        filter_config: ImageFilterConfig,
8896        blend_mode: BlendMode,
8897        enabled: bool,
8898        backdrop_key: Option<BackdropKey>,
8899        child: Option<AnyRenderBox>,
8900    ) -> RenderHandle<Self> {
8901        let this = RenderHandle::new_box(
8902            app,
8903            RenderBackdropFilter {
8904                render_object: RenderObjectData::new(),
8905                render_box: RenderBoxData::new(),
8906                child: RenderObjectWithChildData::new(),
8907                filter_config,
8908                blend_mode,
8909                enabled,
8910                backdrop_key,
8911            },
8912        );
8913        this.set_child(app, child);
8914        this
8915    }
8916
8917    /// Whether or not the backdrop filter operation will be applied to the child.
8918    pub fn enabled(self: RenderHandle<Self>, app: &App) -> bool {
8919        self.get(app).enabled
8920    }
8921
8922    /// Sets [`enabled`](Self::enabled).
8923    pub fn set_enabled(self: RenderHandle<Self>, app: &mut App, value: bool) {
8924        if self.get(app).enabled == value {
8925            return;
8926        }
8927        self.get_mut(app).enabled = value;
8928        self.mark_needs_paint(app);
8929    }
8930
8931    /// The image filter to apply to the existing painted content before painting the child.
8932    ///
8933    /// Dart's deprecated `filter` getter: only valid when the configuration was set through
8934    /// [`set_filter`](Self::set_filter).
8935    pub fn filter(self: RenderHandle<Self>, app: &App) -> ImageFilter {
8936        self.get(app)
8937            .filter_config
8938            .filter()
8939            .expect(
8940                "This getter should only be called when the filter is assigned via the \
8941                 `filter` setter.",
8942            )
8943            .clone()
8944    }
8945
8946    /// Sets the filter as a direct configuration (Dart's `filter` setter).
8947    pub fn set_filter(self: RenderHandle<Self>, app: &mut App, value: ImageFilter) {
8948        self.set_filter_config(app, ImageFilterConfig::new(value));
8949    }
8950
8951    /// The configuration that resolves the filter against the paint bounds.
8952    pub fn filter_config(self: RenderHandle<Self>, app: &App) -> &ImageFilterConfig {
8953        &self.get(app).filter_config
8954    }
8955
8956    /// Sets [`filter_config`](Self::filter_config).
8957    pub fn set_filter_config(self: RenderHandle<Self>, app: &mut App, value: ImageFilterConfig) {
8958        if self.get(app).filter_config == value {
8959            return;
8960        }
8961        self.get_mut(app).filter_config = value;
8962        self.mark_needs_paint(app);
8963    }
8964
8965    /// The blend mode to use to apply the filtered background content onto the background
8966    /// surface.
8967    pub fn blend_mode(self: RenderHandle<Self>, app: &App) -> BlendMode {
8968        self.get(app).blend_mode
8969    }
8970
8971    /// Sets [`blend_mode`](Self::blend_mode).
8972    pub fn set_blend_mode(self: RenderHandle<Self>, app: &mut App, value: BlendMode) {
8973        if self.get(app).blend_mode == value {
8974            return;
8975        }
8976        self.get_mut(app).blend_mode = value;
8977        self.mark_needs_paint(app);
8978    }
8979
8980    /// The backdrop key that identifies the shared backdrop this filter belongs to.
8981    pub fn backdrop_key(self: RenderHandle<Self>, app: &App) -> Option<BackdropKey> {
8982        self.get(app).backdrop_key
8983    }
8984
8985    /// Sets [`backdrop_key`](Self::backdrop_key).
8986    pub fn set_backdrop_key(self: RenderHandle<Self>, app: &mut App, value: Option<BackdropKey>) {
8987        if self.get(app).backdrop_key == value {
8988            return;
8989        }
8990        self.get_mut(app).backdrop_key = value;
8991        self.mark_needs_paint(app);
8992    }
8993}
8994
8995impl RenderObjectWithChildMixin for RenderBackdropFilter {
8996    type ChildType = AnyRenderBox;
8997
8998    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
8999        &self.get(app).child
9000    }
9001
9002    fn child_data_mut(
9003        self: RenderHandle<Self>,
9004        app: &mut App,
9005    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
9006        &mut self.get_mut(app).child
9007    }
9008}
9009
9010impl RenderProxyBoxMixin for RenderBackdropFilter {}
9011
9012impl RenderObject for RenderBackdropFilter {
9013    crate::render_object_accessors!();
9014
9015    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
9016        self.child(app).is_some()
9017    }
9018
9019    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
9020        RenderProxyBoxMixin::perform_layout(self, app);
9021    }
9022
9023    fn paint(
9024        self: RenderHandle<Self>,
9025        app: &mut App,
9026        context: &mut PaintingContext,
9027        offset: Offset,
9028    ) {
9029        if !self.get(app).enabled {
9030            RenderProxyBoxMixin::paint(self, app, context, offset);
9031            return;
9032        }
9033        let bounds = offset & self.size(app);
9034        let effective_filter = self
9035            .get(app)
9036            .filter_config
9037            .resolve(ImageFilterContext { bounds });
9038        if self.child(app).is_some() {
9039            debug_assert!(self.as_object().needs_compositing(app));
9040            let (blend_mode, backdrop_key) = {
9041                let this = self.get(app);
9042                (this.blend_mode, this.backdrop_key)
9043            };
9044            let layer = match self.as_object().layer_as::<BackdropFilterLayer>(app) {
9045                Some(layer) => layer,
9046                None => {
9047                    let layer = BackdropFilterLayer::new(app);
9048                    self.as_object()
9049                        .set_layer(app, Some(layer.as_container_layer()));
9050                    layer
9051                }
9052            };
9053            layer.set_filter(app, Some(effective_filter));
9054            layer.set_blend_mode(app, blend_mode);
9055            layer.set_backdrop_key(app, backdrop_key);
9056            context.push_layer(
9057                app,
9058                layer.as_container_layer(),
9059                |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
9060                offset,
9061                None,
9062            );
9063        } else {
9064            self.as_object().set_layer(app, None);
9065        }
9066    }
9067
9068    fn visit_children(
9069        self: RenderHandle<Self>,
9070        app: &App,
9071        visitor: &mut dyn FnMut(AnyRenderObject),
9072    ) {
9073        if let Some(child) = self.child(app) {
9074            visitor(child.as_object());
9075        }
9076    }
9077}
9078
9079impl RenderBox for RenderBackdropFilter {
9080    crate::render_box_accessors!();
9081
9082    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
9083        RenderProxyBoxMixin::setup_parent_data(self, app, child);
9084    }
9085
9086    fn apply_paint_transform(
9087        self: RenderHandle<Self>,
9088        app: &App,
9089        child: AnyRenderObject,
9090        transform: &mut Matrix4,
9091    ) {
9092        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
9093    }
9094
9095    fn hit_test_children(
9096        self: RenderHandle<Self>,
9097        app: &mut App,
9098        result: &mut BoxHitTestResult<'_>,
9099        position: Offset,
9100    ) -> bool {
9101        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
9102    }
9103
9104    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
9105        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
9106    }
9107
9108    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
9109        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
9110    }
9111
9112    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
9113        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
9114    }
9115
9116    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
9117        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
9118    }
9119
9120    fn compute_distance_to_actual_baseline(
9121        self: RenderHandle<Self>,
9122        app: &mut App,
9123        baseline: TextBaseline,
9124    ) -> Option<f64> {
9125        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
9126    }
9127
9128    fn compute_dry_baseline(
9129        self: RenderHandle<Self>,
9130        app: &mut App,
9131        constraints: BoxConstraints,
9132        baseline: TextBaseline,
9133    ) -> Option<f64> {
9134        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
9135    }
9136
9137    fn compute_dry_layout(
9138        self: RenderHandle<Self>,
9139        app: &mut App,
9140        constraints: BoxConstraints,
9141    ) -> Size {
9142        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
9143    }
9144}
9145
9146/// Annotates a region of the layer tree with a value.
9147///
9148/// The value can be retrieved with [`AnyLayer::find`](crate::AnyLayer::find) at a
9149/// position; `AnnotatedRegion` is the widget that inserts one.
9150pub struct RenderAnnotatedRegion<T> {
9151    render_object: RenderObjectData,
9152    render_box: RenderBoxData,
9153    child: RenderObjectWithChildData<AnyRenderBox>,
9154    value: Rc<T>,
9155    sized: bool,
9156    layer_handle: LayerHandle<Handle<AnnotatedRegionLayer>>,
9157}
9158
9159impl<T: PartialEq + 'static> RenderAnnotatedRegion<T> {
9160    /// Creates a new [`RenderAnnotatedRegion`] to insert `value` into the layer tree.
9161    ///
9162    /// If `sized` is true, the layer is provided with the size of this render object to clip
9163    /// the results of [`AnyLayer::find`](crate::AnyLayer::find).
9164    pub fn new(
9165        app: &mut App,
9166        value: Rc<T>,
9167        sized: bool,
9168        child: Option<AnyRenderBox>,
9169    ) -> RenderHandle<RenderAnnotatedRegion<T>> {
9170        let this = RenderHandle::new_box(
9171            app,
9172            RenderAnnotatedRegion {
9173                render_object: RenderObjectData::new(),
9174                render_box: RenderBoxData::new(),
9175                child: RenderObjectWithChildData::new(),
9176                value,
9177                sized,
9178                layer_handle: LayerHandle::new(),
9179            },
9180        );
9181        this.set_child(app, child);
9182        this
9183    }
9184
9185    /// A value which can be retrieved using
9186    /// [`AnyLayer::find`](crate::AnyLayer::find).
9187    pub fn value(self: RenderHandle<Self>, app: &App) -> Rc<T> {
9188        Rc::clone(&self.get(app).value)
9189    }
9190
9191    /// Sets [`value`](Self::value).
9192    pub fn set_value(self: RenderHandle<Self>, app: &mut App, new_value: Rc<T>) {
9193        if *self.get(app).value == *new_value {
9194            return;
9195        }
9196        self.get_mut(app).value = new_value;
9197        self.mark_needs_paint(app);
9198    }
9199
9200    /// Whether the render object will pass its size to the annotated region.
9201    pub fn sized(self: RenderHandle<Self>, app: &App) -> bool {
9202        self.get(app).sized
9203    }
9204
9205    /// Sets [`sized`](Self::sized).
9206    pub fn set_sized(self: RenderHandle<Self>, app: &mut App, value: bool) {
9207        if self.get(app).sized == value {
9208            return;
9209        }
9210        self.get_mut(app).sized = value;
9211        self.mark_needs_paint(app);
9212    }
9213}
9214
9215impl<T: PartialEq + 'static> RenderObjectWithChildMixin for RenderAnnotatedRegion<T> {
9216    type ChildType = AnyRenderBox;
9217
9218    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
9219        &self.get(app).child
9220    }
9221
9222    fn child_data_mut(
9223        self: RenderHandle<Self>,
9224        app: &mut App,
9225    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
9226        &mut self.get_mut(app).child
9227    }
9228}
9229
9230impl<T: PartialEq + 'static> RenderProxyBoxMixin for RenderAnnotatedRegion<T> {}
9231
9232impl<T: PartialEq + 'static> RenderObject for RenderAnnotatedRegion<T> {
9233    crate::render_object_accessors!();
9234
9235    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
9236        true
9237    }
9238
9239    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
9240        RenderProxyBoxMixin::perform_layout(self, app);
9241    }
9242
9243    fn paint(
9244        self: RenderHandle<Self>,
9245        app: &mut App,
9246        context: &mut PaintingContext,
9247        offset: Offset,
9248    ) {
9249        let sized = self.sized(app);
9250        let value: Rc<dyn Any> = self.value(app);
9251        let layer = AnnotatedRegionLayer::new(app, value);
9252        if sized {
9253            layer.set_size(app, Some(self.size(app)));
9254            layer.set_offset(app, offset);
9255        }
9256        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).layer_handle, Some(layer));
9257        context.push_layer(
9258            app,
9259            layer.as_container_layer(),
9260            |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
9261            offset,
9262            None,
9263        );
9264    }
9265
9266    fn dispose(self: RenderHandle<Self>, app: &mut App) {
9267        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).layer_handle, None);
9268        crate::object::RenderObjectBase::dispose(self, app);
9269    }
9270
9271    fn visit_children(
9272        self: RenderHandle<Self>,
9273        app: &App,
9274        visitor: &mut dyn FnMut(AnyRenderObject),
9275    ) {
9276        if let Some(child) = self.child(app) {
9277            visitor(child.as_object());
9278        }
9279    }
9280}
9281
9282impl<T: PartialEq + 'static> RenderBox for RenderAnnotatedRegion<T> {
9283    crate::render_box_accessors!();
9284
9285    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
9286        RenderProxyBoxMixin::setup_parent_data(self, app, child);
9287    }
9288
9289    fn apply_paint_transform(
9290        self: RenderHandle<Self>,
9291        app: &App,
9292        child: AnyRenderObject,
9293        transform: &mut Matrix4,
9294    ) {
9295        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
9296    }
9297
9298    fn hit_test_children(
9299        self: RenderHandle<Self>,
9300        app: &mut App,
9301        result: &mut BoxHitTestResult<'_>,
9302        position: Offset,
9303    ) -> bool {
9304        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
9305    }
9306
9307    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
9308        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
9309    }
9310
9311    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
9312        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
9313    }
9314
9315    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
9316        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
9317    }
9318
9319    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
9320        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
9321    }
9322
9323    fn compute_distance_to_actual_baseline(
9324        self: RenderHandle<Self>,
9325        app: &mut App,
9326        baseline: TextBaseline,
9327    ) -> Option<f64> {
9328        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
9329    }
9330
9331    fn compute_dry_baseline(
9332        self: RenderHandle<Self>,
9333        app: &mut App,
9334        constraints: BoxConstraints,
9335        baseline: TextBaseline,
9336    ) -> Option<f64> {
9337        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
9338    }
9339
9340    fn compute_dry_layout(
9341        self: RenderHandle<Self>,
9342        app: &mut App,
9343        constraints: BoxConstraints,
9344    ) -> Size {
9345        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
9346    }
9347}
9348
9349#[cfg(test)]
9350mod tests {
9351    use waft_animation::{k_always_complete_animation, k_always_dismissed_animation};
9352    use waft_embedder::ColorFilter;
9353    use waft_embedder::valo::{self, Op, Point};
9354    use waft_foundation::AppCell;
9355    use waft_foundation::{Ref, ValueNotifier};
9356    use waft_gestures::HitTestResult;
9357    use waft_painting::BoxDecoration;
9358
9359    use super::*;
9360    use crate::layer::ErasedLayer;
9361    use crate::pipeline_owner::PipelineOwner;
9362    use crate::testing::{
9363        CanvasMethod, EnginePhase, count_calls, layout_with, painted_ops, pump_frame,
9364        test_render_root,
9365    };
9366    use crate::view::ViewConfiguration;
9367    use waft_embedder::SceneBuilder;
9368
9369    fn sized_box(app: &mut App, size: Size) -> RenderHandle<RenderConstrainedBox> {
9370        RenderConstrainedBox::new(app, BoxConstraints::tight(size), None)
9371    }
9372
9373    /// A leaf that reports fixed intrinsic dimensions and takes the size its constraints allow
9374    /// around them.
9375    struct IntrinsicTestBox {
9376        render_object: RenderObjectData,
9377        render_box: RenderBoxData,
9378        intrinsic: Size,
9379    }
9380
9381    impl RenderObject for IntrinsicTestBox {
9382        crate::render_object_accessors!();
9383
9384        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
9385            let intrinsic = self.get(app).intrinsic;
9386            let size = self.constraints(app).constrain(intrinsic);
9387            self.set_size(app, size);
9388        }
9389    }
9390
9391    impl RenderBox for IntrinsicTestBox {
9392        crate::render_box_accessors!();
9393
9394        fn compute_min_intrinsic_width(
9395            self: RenderHandle<Self>,
9396            app: &mut App,
9397            _height: f64,
9398        ) -> f64 {
9399            self.get(app).intrinsic.width()
9400        }
9401
9402        fn compute_max_intrinsic_width(
9403            self: RenderHandle<Self>,
9404            app: &mut App,
9405            _height: f64,
9406        ) -> f64 {
9407            self.get(app).intrinsic.width()
9408        }
9409
9410        fn compute_min_intrinsic_height(
9411            self: RenderHandle<Self>,
9412            app: &mut App,
9413            _width: f64,
9414        ) -> f64 {
9415            self.get(app).intrinsic.height()
9416        }
9417
9418        fn compute_max_intrinsic_height(
9419            self: RenderHandle<Self>,
9420            app: &mut App,
9421            _width: f64,
9422        ) -> f64 {
9423            self.get(app).intrinsic.height()
9424        }
9425
9426        fn compute_dry_layout(
9427            self: RenderHandle<Self>,
9428            app: &mut App,
9429            constraints: BoxConstraints,
9430        ) -> Size {
9431            constraints.constrain(self.get(app).intrinsic)
9432        }
9433    }
9434
9435    fn intrinsic_box(app: &mut App, intrinsic: Size) -> RenderHandle<IntrinsicTestBox> {
9436        RenderHandle::new_box(
9437            app,
9438            IntrinsicTestBox {
9439                render_object: RenderObjectData::new(),
9440                render_box: RenderBoxData::new(),
9441                intrinsic,
9442            },
9443        )
9444    }
9445
9446    /// `box_test.dart`: a `RenderConstrainedBox` reports its child's intrinsics enforced by its
9447    /// additional constraints, and a tight axis reports that tight extent.
9448    #[test]
9449    fn constrained_box_intrinsics_enforce_the_additional_constraints() {
9450        let cell = AppCell::new();
9451        let mut app = cell.borrow_mut();
9452        let child = intrinsic_box(&mut app, Size::new(20.0, 30.0));
9453        let loose = RenderConstrainedBox::new(
9454            &mut app,
9455            BoxConstraints::new().min_width(50.0).max_width(60.0),
9456            Some(child.as_box()),
9457        );
9458        assert_eq!(loose.as_box().get_min_intrinsic_width(&mut app, 0.0), 50.0);
9459        assert_eq!(loose.as_box().get_max_intrinsic_width(&mut app, 0.0), 50.0);
9460        assert_eq!(loose.as_box().get_min_intrinsic_height(&mut app, 0.0), 30.0);
9461
9462        let child = intrinsic_box(&mut app, Size::new(20.0, 30.0));
9463        let tight = RenderConstrainedBox::new(
9464            &mut app,
9465            BoxConstraints::tight(Size::new(80.0, 90.0)),
9466            Some(child.as_box()),
9467        );
9468        assert_eq!(tight.as_box().get_max_intrinsic_width(&mut app, 0.0), 80.0);
9469        assert_eq!(tight.as_box().get_max_intrinsic_height(&mut app, 0.0), 90.0);
9470    }
9471
9472    /// `intrinsic_width_test.dart`: the child is sized to its maximum intrinsic width, snapped to
9473    /// `step_width` when there is one.
9474    #[test]
9475    fn intrinsic_width_sizes_the_child_to_its_max_intrinsic_width() {
9476        let cell = AppCell::new();
9477        let mut app = cell.borrow_mut();
9478        let child = intrinsic_box(&mut app, Size::new(100.0, 40.0));
9479        let intrinsic = RenderIntrinsicWidth::new(&mut app, None, None, Some(child.as_box()));
9480        intrinsic.layout(&mut app, BoxConstraints::new().max_width(500.0), false);
9481        assert_eq!(intrinsic.size(&app), Size::new(100.0, 40.0));
9482        assert_eq!(child.size(&app), Size::new(100.0, 40.0));
9483
9484        intrinsic.set_step_width(&mut app, Some(30.0));
9485        intrinsic.layout(&mut app, BoxConstraints::new().max_width(500.0), false);
9486        assert_eq!(intrinsic.size(&app), Size::new(120.0, 40.0));
9487    }
9488
9489    /// The dry layout of a `RenderIntrinsicWidth` is the size it lays out to.
9490    #[test]
9491    fn intrinsic_width_dry_layout_matches_its_layout() {
9492        let cell = AppCell::new();
9493        let mut app = cell.borrow_mut();
9494        let child = intrinsic_box(&mut app, Size::new(100.0, 40.0));
9495        let intrinsic = RenderIntrinsicWidth::new(&mut app, None, None, Some(child.as_box()));
9496        let constraints = BoxConstraints::new().max_width(500.0);
9497        let dry = intrinsic.as_box().get_dry_layout(&mut app, constraints);
9498        intrinsic.layout(&mut app, constraints, false);
9499        assert_eq!(dry, intrinsic.size(&app));
9500    }
9501
9502    /// `intrinsic_height_test.dart`: the child is sized to its maximum intrinsic height.
9503    #[test]
9504    fn intrinsic_height_sizes_the_child_to_its_max_intrinsic_height() {
9505        let cell = AppCell::new();
9506        let mut app = cell.borrow_mut();
9507        let child = intrinsic_box(&mut app, Size::new(100.0, 40.0));
9508        let intrinsic = RenderIntrinsicHeight::new(&mut app, Some(child.as_box()));
9509        intrinsic.layout(&mut app, BoxConstraints::new().max_height(500.0), false);
9510        assert_eq!(intrinsic.size(&app), Size::new(100.0, 40.0));
9511        assert_eq!(
9512            intrinsic
9513                .as_box()
9514                .get_max_intrinsic_width(&mut app, f64::INFINITY),
9515            100.0
9516        );
9517    }
9518
9519    /// `fitted_box_test.dart`: a `BoxFit::Contain` child is scaled into the box, and the scale
9520    /// shows up in the paint transform.
9521    #[test]
9522    fn fitted_box_scales_its_child_into_itself() {
9523        let cell = AppCell::new();
9524        let mut app = cell.borrow_mut();
9525        let child = sized_box(&mut app, Size::new(100.0, 100.0));
9526        let fitted = RenderFittedBox::new(
9527            &mut app,
9528            BoxFit::Contain,
9529            AlignmentGeometry::CENTER,
9530            None,
9531            Some(child.as_box()),
9532        );
9533        fitted.layout(
9534            &mut app,
9535            BoxConstraints::tight(Size::new(50.0, 50.0)),
9536            false,
9537        );
9538        assert_eq!(fitted.size(&app), Size::new(50.0, 50.0));
9539        assert_eq!(child.size(&app), Size::new(100.0, 100.0));
9540
9541        let mut transform = Matrix4::IDENTITY;
9542        RenderBox::apply_paint_transform(fitted, &app, child.as_object(), &mut transform);
9543        assert_eq!(
9544            waft_painting::transform_point(&transform, Offset::new(100.0, 100.0)),
9545            Offset::new(50.0, 50.0)
9546        );
9547    }
9548
9549    /// `aspect_ratio_test.dart`: the widest width the constraints allow, with the height from the
9550    /// ratio.
9551    #[test]
9552    fn aspect_ratio_sizes_itself_from_the_width() {
9553        let cell = AppCell::new();
9554        let mut app = cell.borrow_mut();
9555        let child = sized_box(&mut app, Size::new(10.0, 10.0));
9556        let aspect = RenderAspectRatio::new(&mut app, 2.0, Some(child.as_box()));
9557        aspect.layout(
9558            &mut app,
9559            BoxConstraints::new().max_width(200.0).max_height(200.0),
9560            false,
9561        );
9562        assert_eq!(aspect.size(&app), Size::new(200.0, 100.0));
9563        assert_eq!(child.size(&app), Size::new(200.0, 100.0));
9564        assert_eq!(
9565            aspect.as_box().get_min_intrinsic_width(&mut app, 50.0),
9566            100.0
9567        );
9568        assert_eq!(
9569            aspect.as_box().get_min_intrinsic_height(&mut app, 50.0),
9570            25.0
9571        );
9572    }
9573
9574    /// An aspect ratio box infers its width from the height when the width is unbounded.
9575    #[test]
9576    fn aspect_ratio_infers_the_width_from_an_unbounded_axis() {
9577        let cell = AppCell::new();
9578        let mut app = cell.borrow_mut();
9579        let aspect = RenderAspectRatio::new(&mut app, 0.5, None);
9580        aspect.layout(&mut app, BoxConstraints::new().max_height(100.0), false);
9581        assert_eq!(aspect.size(&app), Size::new(50.0, 100.0));
9582    }
9583
9584    #[test]
9585    fn constrained_box_without_child() {
9586        let cell = AppCell::new();
9587        let mut app = cell.borrow_mut();
9588        let box_ =
9589            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(80.0, 40.0)), None);
9590        box_.layout(&mut app, BoxConstraints::new(), false);
9591        assert_eq!(box_.size(&app), Size::new(80.0, 40.0));
9592    }
9593
9594    #[test]
9595    fn additional_constraints_change_marks_layout() {
9596        let cell = AppCell::new();
9597        let mut app = cell.borrow_mut();
9598        let box_ =
9599            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
9600        box_.layout(&mut app, BoxConstraints::new(), false);
9601        assert!(!box_.debug_needs_layout(&app));
9602        box_.set_additional_constraints(&mut app, BoxConstraints::tight(Size::new(20.0, 20.0)));
9603        assert!(box_.debug_needs_layout(&app));
9604        box_.layout(&mut app, BoxConstraints::new(), false);
9605        assert_eq!(box_.size(&app), Size::new(20.0, 20.0));
9606    }
9607
9608    /// Flutter's `RenderProxyBoxMixin.setupParentData` gives the child plain `ParentData`.
9609    #[test]
9610    fn proxy_box_child_gets_empty_parent_data() {
9611        let cell = AppCell::new();
9612        let mut app = cell.borrow_mut();
9613        let child = sized_box(&mut app, Size::new(10.0, 10.0));
9614        let parent = RenderConstrainedBox::new(
9615            &mut app,
9616            BoxConstraints::tight(Size::new(10.0, 10.0)),
9617            Some(child.as_box()),
9618        );
9619        parent.layout(&mut app, BoxConstraints::new(), false);
9620        assert!(child.as_box().parent_data_is::<EmptyParentData>(&app));
9621    }
9622
9623    /// `proxy_box_test.dart`: `RenderOpacity does not composite if it is transparent` and the
9624    /// opaque / partially opaque cases. Ours: whether it is a repaint boundary.
9625    #[test]
9626    fn render_opacity_composites_only_when_visible() {
9627        let cell = AppCell::new();
9628        let mut app = cell.borrow_mut();
9629        for (opacity, composites) in [(0.0, false), (1.0, true), (0.1, true)] {
9630            let child = sized_box(&mut app, Size::new(1.0, 1.0));
9631            let opacity = RenderOpacity::new(&mut app, opacity, Some(child.as_box()));
9632            assert_eq!(opacity.as_object().is_repaint_boundary(&app), composites);
9633        }
9634    }
9635
9636    /// `layers_test.dart`: `non-painted layers are detached`.
9637    #[test]
9638    fn non_painted_layers_are_detached() {
9639        let cell = AppCell::new();
9640        let mut app = cell.borrow_mut();
9641        let inner = RenderDecoratedBox::new(
9642            &mut app,
9643            DecorationRef::new(BoxDecoration::new()),
9644            DecorationPosition::Background,
9645            ImageConfiguration::EMPTY,
9646            None,
9647        );
9648        let boundary = RenderRepaintBoundary::new(&mut app, Some(inner.as_box()));
9649        let opacity = RenderOpacity::new(&mut app, 1.0, Some(boundary.as_box()));
9650        layout_with(
9651            &mut app,
9652            opacity.as_box(),
9653            None,
9654            AlignmentGeometry::CENTER,
9655            EnginePhase::Paint,
9656        );
9657        assert!(!inner.as_object().is_repaint_boundary(&app));
9658        assert!(inner.as_object().debug_layer(&app).is_none());
9659        assert!(boundary.as_object().is_repaint_boundary(&app));
9660        let layer = boundary.as_object().debug_layer(&app).expect("painted");
9661        assert!(layer.as_layer().attached(&app), "this time it painted");
9662
9663        opacity.set_opacity(&mut app, 0.0);
9664        pump_frame(&mut app, EnginePhase::Paint);
9665        assert!(inner.as_object().debug_layer(&app).is_none());
9666        let layer = boundary.as_object().debug_layer(&app).expect("kept");
9667        assert!(!layer.as_layer().attached(&app), "this time it did not");
9668
9669        opacity.set_opacity(&mut app, 0.5);
9670        pump_frame(&mut app, EnginePhase::Paint);
9671        let layer = boundary.as_object().debug_layer(&app).expect("kept");
9672        assert!(layer.as_layer().attached(&app), "this time it did again");
9673    }
9674
9675    #[test]
9676    fn animated_opacity_follows_its_animation() {
9677        let cell = AppCell::new();
9678        let mut app = cell.borrow_mut();
9679        let child = sized_box(&mut app, Size::new(1.0, 1.0));
9680        let dismissed = k_always_dismissed_animation(&mut app);
9681        let complete = k_always_complete_animation(&mut app);
9682        let fade = RenderAnimatedOpacity::new(&mut app, dismissed, Some(child.as_box()));
9683        assert!(!fade.as_object().is_repaint_boundary(&app));
9684        layout_with(
9685            &mut app,
9686            fade.as_box(),
9687            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
9688            AlignmentGeometry::CENTER,
9689            EnginePhase::Paint,
9690        );
9691
9692        fade.set_opacity(&mut app, complete);
9693        assert!(fade.as_object().is_repaint_boundary(&app));
9694        assert!(fade.as_object().debug_needs_paint(&app));
9695        pump_frame(&mut app, EnginePhase::Paint);
9696        let layer = fade.as_object().debug_layer(&app).expect("a boundary now");
9697        let opacity = app
9698            .handle::<OpacityLayer>(layer.id())
9699            .expect("an OpacityLayer");
9700        assert_eq!(opacity.alpha(&app), Some(255));
9701    }
9702
9703    /// Dart's `RenderOpacity.paintsChild`: `_alpha > 0`.
9704    #[test]
9705    fn render_opacity_paints_its_child_only_above_zero_opacity() {
9706        let cell = AppCell::new();
9707        let mut app = cell.borrow_mut();
9708        for (opacity, paints) in [(0.0, false), (0.001, false), (0.01, true), (1.0, true)] {
9709            let child = sized_box(&mut app, Size::new(1.0, 1.0));
9710            let opacity = RenderOpacity::new(&mut app, opacity, Some(child.as_box()));
9711            assert_eq!(
9712                opacity.as_object().paints_child(&app, child.as_object()),
9713                paints
9714            );
9715        }
9716    }
9717
9718    /// Dart's `RenderAnimatedOpacityMixin.paintsChild`: the animation's value above zero.
9719    #[test]
9720    fn animated_opacity_paints_its_child_while_its_animation_is_above_zero() {
9721        let cell = AppCell::new();
9722        let mut app = cell.borrow_mut();
9723        let child = sized_box(&mut app, Size::new(1.0, 1.0));
9724        let dismissed = k_always_dismissed_animation(&mut app);
9725        let complete = k_always_complete_animation(&mut app);
9726        let fade = RenderAnimatedOpacity::new(&mut app, dismissed, Some(child.as_box()));
9727        assert!(!fade.as_object().paints_child(&app, child.as_object()));
9728        fade.set_opacity(&mut app, complete);
9729        assert!(fade.as_object().paints_child(&app, child.as_object()));
9730    }
9731
9732    /// Dart's `RenderFittedBox.paintsChild`: neither the box nor its child is empty, and an
9733    /// unpainted child gets a zero paint transform.
9734    #[test]
9735    fn fitted_box_does_not_paint_an_empty_child() {
9736        let cell = AppCell::new();
9737        let mut app = cell.borrow_mut();
9738        let child = sized_box(&mut app, Size::new(0.0, 100.0));
9739        let fitted = RenderFittedBox::new(
9740            &mut app,
9741            BoxFit::Contain,
9742            AlignmentGeometry::CENTER,
9743            None,
9744            Some(child.as_box()),
9745        );
9746        fitted.layout(
9747            &mut app,
9748            BoxConstraints::tight(Size::new(50.0, 50.0)),
9749            false,
9750        );
9751        assert!(!fitted.as_object().paints_child(&app, child.as_object()));
9752        let mut transform = Matrix4::IDENTITY;
9753        RenderBox::apply_paint_transform(fitted, &app, child.as_object(), &mut transform);
9754        assert_eq!(transform, crate::object::zero_matrix());
9755
9756        let painted = sized_box(&mut app, Size::new(100.0, 100.0));
9757        fitted.set_child(&mut app, Some(painted.as_box()));
9758        fitted.layout(
9759            &mut app,
9760            BoxConstraints::tight(Size::new(50.0, 50.0)),
9761            false,
9762        );
9763        assert!(fitted.as_object().paints_child(&app, painted.as_object()));
9764    }
9765
9766    /// Dart's `RenderObject.paintsChild` default: a proxy paints its child.
9767    #[test]
9768    fn a_render_object_paints_its_child_by_default() {
9769        let cell = AppCell::new();
9770        let mut app = cell.borrow_mut();
9771        let child = sized_box(&mut app, Size::new(10.0, 10.0));
9772        let parent = RenderConstrainedBox::new(
9773            &mut app,
9774            BoxConstraints::tight(Size::new(10.0, 10.0)),
9775            Some(child.as_box()),
9776        );
9777        assert!(parent.as_object().paints_child(&app, child.as_object()));
9778    }
9779
9780    #[test]
9781    fn decorated_box_paints_its_decoration() {
9782        let cell = AppCell::new();
9783        let mut app = cell.borrow_mut();
9784        let decorated = RenderDecoratedBox::new(
9785            &mut app,
9786            DecorationRef::new(BoxDecoration::new().color(Color::from_argb(255, 255, 0, 0))),
9787            DecorationPosition::Background,
9788            ImageConfiguration::EMPTY,
9789            None,
9790        );
9791        layout_with(
9792            &mut app,
9793            decorated.as_box(),
9794            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
9795            AlignmentGeometry::CENTER,
9796            EnginePhase::Paint,
9797        );
9798        let ops = scene_ops(&mut app);
9799        assert!(
9800            ops.iter()
9801                .any(|op| matches!(op, waft_embedder::valo::Op::DrawDisplayList { .. })),
9802            "{ops:?}"
9803        );
9804    }
9805
9806    /// A leaf that fills the constraints it is given and is hit anywhere within them.
9807    fn opaque_leaf(app: &mut App) -> RenderHandle<RenderPointerListener> {
9808        RenderPointerListener::new(app, HitTestBehavior::Opaque, None)
9809    }
9810
9811    const RED: Color = Color::from_argb(255, 255, 0, 0);
9812    const BLUE: Color = Color::from_argb(255, 0, 0, 255);
9813
9814    fn red_box(app: &mut App) -> RenderHandle<RenderColoredBox> {
9815        RenderColoredBox::new(app, RED, true, None)
9816    }
9817
9818    /// Hit tests `target` at `position`: whether the hit was absorbed, and the path's length.
9819    fn hit_test(app: &mut App, target: AnyRenderBox, position: Offset) -> (bool, usize) {
9820        let mut result = HitTestResult::new();
9821        let is_hit = target.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
9822        (is_hit, result.path().len())
9823    }
9824
9825    /// Whether `render`, painted on its own, clips.
9826    fn picture_has_clip(app: &mut App, render: AnyRenderObject) -> bool {
9827        painted_ops(app, render)
9828            .iter()
9829            .any(|op| matches!(op, Op::ClipPath { .. }))
9830    }
9831
9832    /// The rect and color of every fill `render` paints.
9833    fn drawn_rects(app: &mut App, render: AnyRenderObject) -> Vec<(valo::Rect, valo::Color)> {
9834        painted_ops(app, render)
9835            .iter()
9836            .filter_map(|op| match op {
9837                Op::DrawRect { rect, paint, .. } => Some((*rect, paint.color)),
9838                _ => None,
9839            })
9840            .collect()
9841    }
9842
9843    fn fill(rect: Rect, color: Color) -> (valo::Rect, valo::Color) {
9844        (rect.into(), color.into())
9845    }
9846
9847    #[test]
9848    fn limited_box_limits_only_unbounded_constraints() {
9849        let cell = AppCell::new();
9850        let mut app = cell.borrow_mut();
9851        let child = opaque_leaf(&mut app);
9852        let limited = RenderLimitedBox::new(&mut app, 100.0, 50.0, Some(child.as_box()));
9853
9854        limited.layout(&mut app, BoxConstraints::new(), false);
9855        assert_eq!(limited.size(&app), Size::new(100.0, 50.0));
9856
9857        limited.layout(
9858            &mut app,
9859            BoxConstraints::loose(Size::new(30.0, 30.0)),
9860            false,
9861        );
9862        assert_eq!(
9863            limited.size(&app),
9864            Size::new(30.0, 30.0),
9865            "a bounded constraint is left alone"
9866        );
9867    }
9868
9869    #[test]
9870    fn limited_box_without_child_is_empty() {
9871        let cell = AppCell::new();
9872        let mut app = cell.borrow_mut();
9873        let limited = RenderLimitedBox::new(&mut app, 100.0, 50.0, None);
9874        limited.layout(&mut app, BoxConstraints::new(), false);
9875        assert_eq!(limited.size(&app), Size::ZERO);
9876    }
9877
9878    /// Clips to the left half of the box, so a test can tell the clip from the bounds.
9879    struct LeftHalfClipper;
9880
9881    impl CustomClipper<Rect> for LeftHalfClipper {
9882        fn get_clip(&self, _app: &App, size: Size) -> Rect {
9883            Rect::from_ltwh(0.0, 0.0, size.width() / 2.0, size.height())
9884        }
9885
9886        fn should_reclip(&self, _app: &App, _old_clipper: &dyn CustomClipper<Rect>) -> bool {
9887            false
9888        }
9889
9890        fn as_any(&self) -> &dyn Any {
9891            self
9892        }
9893    }
9894
9895    impl CustomClipper<RRect> for LeftHalfClipper {
9896        fn get_clip(&self, _app: &App, size: Size) -> RRect {
9897            RRect::from_rect_xy(
9898                Rect::from_ltwh(0.0, 0.0, size.width() / 2.0, size.height()),
9899                0.0,
9900                0.0,
9901            )
9902        }
9903
9904        fn should_reclip(&self, _app: &App, _old_clipper: &dyn CustomClipper<RRect>) -> bool {
9905            false
9906        }
9907
9908        fn as_any(&self) -> &dyn Any {
9909            self
9910        }
9911    }
9912
9913    /// A clipper of the whole box whose `reclip` listenable a test can notify.
9914    struct NotifyingClipper {
9915        reclip: Rc<dyn Listenable>,
9916    }
9917
9918    impl CustomClipper<Rect> for NotifyingClipper {
9919        fn reclip(&self) -> Option<&Rc<dyn Listenable>> {
9920            Some(&self.reclip)
9921        }
9922
9923        fn get_clip(&self, _app: &App, size: Size) -> Rect {
9924            Offset::ZERO & size
9925        }
9926
9927        fn should_reclip(&self, _app: &App, _old_clipper: &dyn CustomClipper<Rect>) -> bool {
9928            false
9929        }
9930
9931        fn as_any(&self) -> &dyn Any {
9932            self
9933        }
9934    }
9935
9936    #[test]
9937    fn clip_rect_pushes_its_clipper_and_clips_hit_tests() {
9938        let cell = AppCell::new();
9939        let mut app = cell.borrow_mut();
9940        let child = opaque_leaf(&mut app);
9941        let clipper: Rc<dyn CustomClipper<Rect>> = Rc::new(LeftHalfClipper);
9942        let clip = RenderClipRect::new(
9943            &mut app,
9944            Some(clipper),
9945            Clip::HardEdge,
9946            Some(child.as_box()),
9947        );
9948        layout_with(
9949            &mut app,
9950            clip.as_box(),
9951            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
9952            AlignmentGeometry::CENTER,
9953            EnginePhase::Paint,
9954        );
9955
9956        let ops = painted_ops(&mut app, clip.as_object());
9957        let clip_path = ops
9958            .iter()
9959            .find_map(|op| match op {
9960                Op::ClipPath { path, .. } => Some(path),
9961                _ => None,
9962            })
9963            .expect("the recording clips");
9964        assert_eq!(
9965            clip_path.bounds(),
9966            Rect::from_ltwh(0.0, 0.0, 50.0, 100.0).into()
9967        );
9968
9969        assert!(hit_test(&mut app, clip.as_box(), Offset::new(25.0, 50.0)).0);
9970        assert!(
9971            !hit_test(&mut app, clip.as_box(), Offset::new(75.0, 50.0)).0,
9972            "outside the clipper's clip"
9973        );
9974    }
9975
9976    #[test]
9977    fn clip_rect_without_clipping_paints_its_child_directly() {
9978        let cell = AppCell::new();
9979        let mut app = cell.borrow_mut();
9980        let child = red_box(&mut app);
9981        let clip = RenderClipRect::new(&mut app, None, Clip::None, Some(child.as_box()));
9982        layout_with(
9983            &mut app,
9984            clip.as_box(),
9985            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
9986            AlignmentGeometry::CENTER,
9987            EnginePhase::Paint,
9988        );
9989
9990        assert!(
9991            !picture_has_clip(&mut app, clip.as_object()),
9992            "Clip::None paints the child directly"
9993        );
9994        assert_eq!(
9995            drawn_rects(&mut app, clip.as_object()),
9996            [fill(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0), RED)]
9997        );
9998    }
9999
10000    #[test]
10001    fn clip_rrect_pushes_its_border_radius() {
10002        let cell = AppCell::new();
10003        let mut app = cell.borrow_mut();
10004        let child = opaque_leaf(&mut app);
10005        let clip = RenderClipRRect::new(
10006            &mut app,
10007            BorderRadiusGeometry::circular(20.0),
10008            None,
10009            Clip::AntiAlias,
10010            None,
10011            Some(child.as_box()),
10012        );
10013        layout_with(
10014            &mut app,
10015            clip.as_box(),
10016            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10017            AlignmentGeometry::CENTER,
10018            EnginePhase::Paint,
10019        );
10020
10021        let bounds = Rect::from_ltwh(0.0, 0.0, 100.0, 100.0);
10022        let ops = painted_ops(&mut app, clip.as_object());
10023        let clip_path = ops
10024            .iter()
10025            .find_map(|op| match op {
10026                Op::ClipPath { path, .. } => Some(path),
10027                _ => None,
10028            })
10029            .expect("the recording starts with the clip");
10030        assert_eq!(clip_path.bounds(), bounds.into());
10031
10032        assert!(
10033            hit_test(&mut app, clip.as_box(), Offset::new(99.0, 99.0)).0,
10034            "without a clipper the hit test is not clipped, as in Dart"
10035        );
10036    }
10037
10038    #[test]
10039    fn clip_rrect_clips_hit_tests_to_its_clipper() {
10040        let cell = AppCell::new();
10041        let mut app = cell.borrow_mut();
10042        let child = opaque_leaf(&mut app);
10043        let clipper: Rc<dyn CustomClipper<RRect>> = Rc::new(LeftHalfClipper);
10044        let clip = RenderClipRRect::new(
10045            &mut app,
10046            BorderRadiusGeometry::ZERO,
10047            Some(clipper),
10048            Clip::AntiAlias,
10049            None,
10050            Some(child.as_box()),
10051        );
10052        clip.layout(
10053            &mut app,
10054            BoxConstraints::tight(Size::new(100.0, 100.0)),
10055            false,
10056        );
10057
10058        assert!(hit_test(&mut app, clip.as_box(), Offset::new(25.0, 50.0)).0);
10059        assert!(!hit_test(&mut app, clip.as_box(), Offset::new(75.0, 50.0)).0);
10060    }
10061
10062    /// The cached clip is dropped when the clipper notifies and when the box is resized.
10063    #[test]
10064    fn clip_rect_reclips_on_notification_and_on_resize() {
10065        let cell = AppCell::new();
10066        let mut app = cell.borrow_mut();
10067        let reclip = app.create(ValueNotifier::new(0));
10068        let clipper: Rc<dyn CustomClipper<Rect>> = Rc::new(NotifyingClipper {
10069            reclip: Rc::new(reclip.clone()),
10070        });
10071        let child = red_box(&mut app);
10072        let clip = RenderClipRect::new(
10073            &mut app,
10074            Some(clipper),
10075            Clip::HardEdge,
10076            Some(child.as_box()),
10077        );
10078        layout_with(
10079            &mut app,
10080            clip.as_box(),
10081            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10082            AlignmentGeometry::CENTER,
10083            EnginePhase::Paint,
10084        );
10085        assert!(clip.custom_clip_data(&app).clip.is_some());
10086
10087        reclip.set_value(&mut app, 1);
10088        assert!(
10089            clip.custom_clip_data(&app).clip.is_none(),
10090            "the clipper's notification dropped the cached clip"
10091        );
10092        assert!(clip.as_object().debug_needs_paint(&app));
10093        pump_frame(&mut app, EnginePhase::Paint);
10094        assert!(clip.custom_clip_data(&app).clip.is_some());
10095
10096        clip.layout(
10097            &mut app,
10098            BoxConstraints::tight(Size::new(50.0, 50.0)),
10099            false,
10100        );
10101        assert!(
10102            clip.custom_clip_data(&app).clip.is_none(),
10103            "a new size dropped the cached clip"
10104        );
10105    }
10106
10107    #[test]
10108    fn transform_paints_under_its_matrix() {
10109        let cell = AppCell::new();
10110        let mut app = cell.borrow_mut();
10111        let child = red_box(&mut app);
10112        let transform = RenderTransform::new(
10113            &mut app,
10114            Matrix4::scale(2.0, 2.0),
10115            None,
10116            None,
10117            None,
10118            true,
10119            None,
10120            Some(child.as_box()),
10121        );
10122        layout_with(
10123            &mut app,
10124            transform.as_box(),
10125            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10126            AlignmentGeometry::CENTER,
10127            EnginePhase::Paint,
10128        );
10129
10130        let ops = painted_ops(&mut app, transform.as_object());
10131        let pushed = ops.iter().find_map(|op| match op {
10132            Op::Transform(transform) => Some(*transform),
10133            _ => None,
10134        });
10135        assert_eq!(pushed, Some(Matrix4::scale(2.0, 2.0)));
10136    }
10137
10138    /// A translation is folded into the child's paint offset instead of a pushed transform.
10139    #[test]
10140    fn transform_by_a_translation_paints_at_an_offset() {
10141        let cell = AppCell::new();
10142        let mut app = cell.borrow_mut();
10143        let child = red_box(&mut app);
10144        let transform = RenderTransform::new(
10145            &mut app,
10146            Matrix4::translation(10.0, 20.0),
10147            None,
10148            None,
10149            None,
10150            true,
10151            None,
10152            Some(child.as_box()),
10153        );
10154        layout_with(
10155            &mut app,
10156            transform.as_box(),
10157            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10158            AlignmentGeometry::CENTER,
10159            EnginePhase::Paint,
10160        );
10161
10162        assert!(
10163            !painted_ops(&mut app, transform.as_object())
10164                .iter()
10165                .any(|op| matches!(op, Op::Transform(_))),
10166            "a translation is folded into the child's paint offset"
10167        );
10168        assert_eq!(
10169            drawn_rects(&mut app, transform.as_object()),
10170            [fill(Rect::from_ltwh(10.0, 20.0, 100.0, 100.0), RED)]
10171        );
10172    }
10173
10174    #[test]
10175    fn transform_hit_tests_through_its_matrix() {
10176        let cell = AppCell::new();
10177        let mut app = cell.borrow_mut();
10178        let child = opaque_leaf(&mut app);
10179        let transform = RenderTransform::new(
10180            &mut app,
10181            Matrix4::scale(2.0, 2.0),
10182            None,
10183            None,
10184            None,
10185            true,
10186            None,
10187            Some(child.as_box()),
10188        );
10189        transform.layout(
10190            &mut app,
10191            BoxConstraints::tight(Size::new(100.0, 100.0)),
10192            false,
10193        );
10194
10195        assert_eq!(
10196            hit_test(&mut app, transform.as_box(), Offset::new(150.0, 50.0)),
10197            (true, 1),
10198            "the child covers twice the box, and the transform does not add itself"
10199        );
10200
10201        transform.set_transform_hit_tests(&mut app, false);
10202        assert!(!hit_test(&mut app, transform.as_box(), Offset::new(150.0, 50.0)).0);
10203        assert!(hit_test(&mut app, transform.as_box(), Offset::new(50.0, 50.0)).0);
10204    }
10205
10206    /// `Transform.scale(alignment: Alignment.center)`: the child grows around the box's centre.
10207    #[test]
10208    fn transform_scales_around_its_alignment_and_origin() {
10209        let cell = AppCell::new();
10210        let mut app = cell.borrow_mut();
10211        let child = opaque_leaf(&mut app);
10212        let transform = RenderTransform::new(
10213            &mut app,
10214            Matrix4::scale(2.0, 2.0),
10215            None,
10216            Some(AlignmentGeometry::CENTER),
10217            None,
10218            true,
10219            None,
10220            Some(child.as_box()),
10221        );
10222        transform.layout(
10223            &mut app,
10224            BoxConstraints::tight(Size::new(100.0, 100.0)),
10225            false,
10226        );
10227        assert!(hit_test(&mut app, transform.as_box(), Offset::new(140.0, 140.0)).0);
10228        assert!(!hit_test(&mut app, transform.as_box(), Offset::new(160.0, 160.0)).0);
10229
10230        transform.set_alignment(&mut app, None);
10231        transform.set_origin(&mut app, Some(Offset::new(50.0, 50.0)));
10232        assert!(
10233            hit_test(&mut app, transform.as_box(), Offset::new(140.0, 140.0)).0,
10234            "an origin at the centre is the same conjugation"
10235        );
10236        assert!(!hit_test(&mut app, transform.as_box(), Offset::new(160.0, 160.0)).0);
10237    }
10238
10239    #[test]
10240    fn transform_applies_its_paint_transform_to_the_child() {
10241        let cell = AppCell::new();
10242        let mut app = cell.borrow_mut();
10243        let child = opaque_leaf(&mut app);
10244        let transform = RenderTransform::new(
10245            &mut app,
10246            Matrix4::translation(10.0, 20.0),
10247            None,
10248            None,
10249            None,
10250            true,
10251            None,
10252            Some(child.as_box()),
10253        );
10254        let mut matrix = Matrix4::IDENTITY;
10255        RenderBox::apply_paint_transform(transform, &app, child.as_object(), &mut matrix);
10256        assert_eq!(matrix, Matrix4::translation(10.0, 20.0));
10257    }
10258
10259    #[test]
10260    fn fractional_translation_offsets_paint_and_hits() {
10261        let cell = AppCell::new();
10262        let mut app = cell.borrow_mut();
10263        let child = red_box(&mut app);
10264        let translated = RenderFractionalTranslation::new(
10265            &mut app,
10266            Offset::new(0.5, 0.0),
10267            true,
10268            Some(child.as_box()),
10269        );
10270        layout_with(
10271            &mut app,
10272            translated.as_box(),
10273            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10274            AlignmentGeometry::CENTER,
10275            EnginePhase::Paint,
10276        );
10277
10278        assert_eq!(
10279            drawn_rects(&mut app, translated.as_object()),
10280            [fill(Rect::from_ltwh(50.0, 0.0, 100.0, 100.0), RED)],
10281            "half the width to the right"
10282        );
10283
10284        assert!(hit_test(&mut app, translated.as_box(), Offset::new(75.0, 50.0)).0);
10285        assert!(!hit_test(&mut app, translated.as_box(), Offset::new(25.0, 50.0)).0);
10286
10287        translated.set_transform_hit_tests(&mut app, false);
10288        assert!(
10289            hit_test(&mut app, translated.as_box(), Offset::new(25.0, 50.0)).0,
10290            "an untransformed hit test reaches the child where it was laid out"
10291        );
10292    }
10293
10294    #[test]
10295    fn ignore_pointer_is_invisible_to_hit_testing() {
10296        let cell = AppCell::new();
10297        let mut app = cell.borrow_mut();
10298        let child = opaque_leaf(&mut app);
10299        let ignoring = RenderIgnorePointer::new(&mut app, true, Some(child.as_box()));
10300        ignoring.layout(
10301            &mut app,
10302            BoxConstraints::tight(Size::new(100.0, 100.0)),
10303            false,
10304        );
10305
10306        assert_eq!(
10307            hit_test(&mut app, ignoring.as_box(), Offset::new(50.0, 50.0)),
10308            (false, 0)
10309        );
10310
10311        ignoring.set_ignoring(&mut app, false);
10312        assert_eq!(
10313            hit_test(&mut app, ignoring.as_box(), Offset::new(50.0, 50.0)),
10314            (true, 2),
10315            "the child and the ignore pointer itself"
10316        );
10317    }
10318
10319    #[test]
10320    fn absorb_pointer_takes_the_hit_from_its_subtree() {
10321        let cell = AppCell::new();
10322        let mut app = cell.borrow_mut();
10323        let child = opaque_leaf(&mut app);
10324        let absorbing = RenderAbsorbPointer::new(&mut app, true, Some(child.as_box()));
10325        absorbing.layout(
10326            &mut app,
10327            BoxConstraints::tight(Size::new(100.0, 100.0)),
10328            false,
10329        );
10330
10331        assert_eq!(
10332            hit_test(&mut app, absorbing.as_box(), Offset::new(50.0, 50.0)),
10333            (true, 0),
10334            "hit testing stops here, and nothing is added to the path"
10335        );
10336        assert_eq!(
10337            hit_test(&mut app, absorbing.as_box(), Offset::new(150.0, 50.0)),
10338            (false, 0)
10339        );
10340
10341        absorbing.set_absorbing(&mut app, false);
10342        assert_eq!(
10343            hit_test(&mut app, absorbing.as_box(), Offset::new(50.0, 50.0)),
10344            (true, 2)
10345        );
10346    }
10347
10348    #[test]
10349    fn offstage_lays_out_without_painting_or_hit_testing() {
10350        let cell = AppCell::new();
10351        let mut app = cell.borrow_mut();
10352        let child = red_box(&mut app);
10353        let offstage = RenderOffstage::new(&mut app, true, Some(child.as_box()));
10354        layout_with(
10355            &mut app,
10356            offstage.as_box(),
10357            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10358            AlignmentGeometry::CENTER,
10359            EnginePhase::Paint,
10360        );
10361
10362        assert!(RenderObject::sized_by_parent(offstage, &app));
10363        assert_eq!(child.size(&app), Size::new(100.0, 100.0), "still laid out");
10364        assert!(
10365            !picture_has_clip(&mut app, offstage.as_object()),
10366            "offstage paints nothing"
10367        );
10368        assert_eq!(
10369            hit_test(&mut app, offstage.as_box(), Offset::new(50.0, 50.0)),
10370            (false, 0)
10371        );
10372        assert!(!offstage.as_object().paints_child(&app, child.as_object()));
10373
10374        offstage.set_offstage(&mut app, false);
10375        pump_frame(&mut app, EnginePhase::Paint);
10376        assert_eq!(
10377            drawn_rects(&mut app, offstage.as_object()),
10378            [fill(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0), RED)]
10379        );
10380        assert!(hit_test(&mut app, offstage.as_box(), Offset::new(50.0, 50.0)).0);
10381        assert!(offstage.as_object().paints_child(&app, child.as_object()));
10382    }
10383
10384    #[test]
10385    fn colored_box_fills_its_bounds() {
10386        let cell = AppCell::new();
10387        let mut app = cell.borrow_mut();
10388        let colored = red_box(&mut app);
10389        layout_with(
10390            &mut app,
10391            colored.as_box(),
10392            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10393            AlignmentGeometry::CENTER,
10394            EnginePhase::Paint,
10395        );
10396
10397        assert_eq!(
10398            drawn_rects(&mut app, colored.as_object()),
10399            [fill(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0), RED)]
10400        );
10401        assert_eq!(
10402            hit_test(&mut app, colored.as_box(), Offset::new(50.0, 50.0)),
10403            (true, 1),
10404            "an opaque box is hit by itself"
10405        );
10406    }
10407
10408    #[test]
10409    fn colored_box_paints_its_child_over_the_color() {
10410        let cell = AppCell::new();
10411        let mut app = cell.borrow_mut();
10412        let child = red_box(&mut app);
10413        let colored = RenderColoredBox::new(&mut app, BLUE, true, Some(child.as_box()));
10414        layout_with(
10415            &mut app,
10416            colored.as_box(),
10417            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10418            AlignmentGeometry::CENTER,
10419            EnginePhase::Paint,
10420        );
10421
10422        let bounds = Rect::from_ltwh(0.0, 0.0, 100.0, 100.0);
10423        assert_eq!(
10424            drawn_rects(&mut app, colored.as_object()),
10425            [fill(bounds, BLUE), fill(bounds, RED)]
10426        );
10427    }
10428
10429    #[test]
10430    fn meta_data_carries_its_payload_and_hit_tests_by_behavior() {
10431        let cell = AppCell::new();
10432        let mut app = cell.borrow_mut();
10433        let payload: Rc<dyn Any> = Rc::new(42u32);
10434        let opaque = RenderMetaData::new(
10435            &mut app,
10436            Some(Rc::clone(&payload)),
10437            HitTestBehavior::Opaque,
10438            None,
10439        );
10440        opaque.layout(
10441            &mut app,
10442            BoxConstraints::tight(Size::new(10.0, 10.0)),
10443            false,
10444        );
10445        assert_eq!(
10446            opaque
10447                .meta_data(&app)
10448                .and_then(|data| data.downcast::<u32>().ok())
10449                .as_deref(),
10450            Some(&42)
10451        );
10452        let mut result = HitTestResult::new();
10453        assert!(opaque.as_box().hit_test(
10454            &mut app,
10455            &mut BoxHitTestResult::wrap(&mut result),
10456            Offset::new(5.0, 5.0)
10457        ));
10458        assert_eq!(result.path().len(), 1);
10459
10460        let deferring = RenderMetaData::new(&mut app, None, HitTestBehavior::DeferToChild, None);
10461        deferring.layout(
10462            &mut app,
10463            BoxConstraints::tight(Size::new(10.0, 10.0)),
10464            false,
10465        );
10466        let mut result = HitTestResult::new();
10467        assert!(!deferring.as_box().hit_test(
10468            &mut app,
10469            &mut BoxHitTestResult::wrap(&mut result),
10470            Offset::new(5.0, 5.0)
10471        ));
10472        assert!(result.path().is_empty());
10473
10474        // Deferring to a child that is hit puts the meta data on the path above it.
10475        let child = opaque_leaf(&mut app);
10476        deferring.set_child(&mut app, Some(child.as_box()));
10477        deferring.layout(
10478            &mut app,
10479            BoxConstraints::tight(Size::new(10.0, 10.0)),
10480            false,
10481        );
10482        let mut result = HitTestResult::new();
10483        assert!(deferring.as_box().hit_test(
10484            &mut app,
10485            &mut BoxHitTestResult::wrap(&mut result),
10486            Offset::new(5.0, 5.0)
10487        ));
10488        assert_eq!(result.path().len(), 2, "the child, then the meta data");
10489    }
10490
10491    /// The scene of the test view after a frame, as display-list ops.
10492    fn scene_ops(app: &mut App) -> Vec<Op> {
10493        let scene = test_render_root(app)
10494            .as_object()
10495            .debug_layer(app)
10496            .expect("painted")
10497            .build_scene(app, SceneBuilder::new());
10498        waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
10499    }
10500
10501    #[test]
10502    fn a_backdrop_filter_blurs_under_its_bounds_before_its_child_paints() {
10503        let cell = AppCell::new();
10504        let mut app = cell.borrow_mut();
10505        let child = RenderColoredBox::new(&mut app, Color::new(0xFF00FF00), true, None);
10506        let filter = RenderBackdropFilter::new(
10507            &mut app,
10508            ImageFilterConfig::new(ImageFilter::blur(6.0, 6.0)),
10509            BlendMode::SrcOver,
10510            true,
10511            None,
10512            Some(child.as_box()),
10513        );
10514        layout_with(
10515            &mut app,
10516            filter.as_box(),
10517            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10518            AlignmentGeometry::CENTER,
10519            EnginePhase::Paint,
10520        );
10521        let ops = scene_ops(&mut app);
10522        let blur = ops
10523            .iter()
10524            .position(|op| {
10525                matches!(
10526                    op,
10527                    Op::SaveLayer {
10528                        backdrop: Some(_),
10529                        ..
10530                    }
10531                )
10532            })
10533            .expect("a backdrop layer");
10534        let draw = ops
10535            .iter()
10536            .position(|op| matches!(op, Op::DrawRect { .. }))
10537            .expect("the child's paint");
10538        assert!(blur < draw, "the blur precedes the child: {ops:?}");
10539        if let Op::SaveLayer {
10540            backdrop: Some(backdrop),
10541            ..
10542        } = &ops[blur]
10543        {
10544            assert_eq!(
10545                backdrop.filter,
10546                waft_embedder::valo::ImageFilter::blur(6.0, 6.0)
10547            );
10548            assert_eq!(backdrop.shared_key, None);
10549        }
10550
10551        let key = BackdropKey::new();
10552        filter.set_backdrop_key(&mut app, Some(key));
10553        pump_frame(&mut app, EnginePhase::Paint);
10554        let ops = scene_ops(&mut app);
10555        assert!(
10556            ops.iter().any(|op| matches!(
10557                op,
10558                Op::SaveLayer {
10559                    backdrop: Some(valo::Backdrop {
10560                        shared_key: Some(_),
10561                        ..
10562                    }),
10563                    ..
10564                }
10565            )),
10566            "a keyed filter shares its blur: {ops:?}"
10567        );
10568
10569        filter.set_enabled(&mut app, false);
10570        pump_frame(&mut app, EnginePhase::Paint);
10571        let ops = scene_ops(&mut app);
10572        assert!(
10573            !ops.iter().any(|op| matches!(
10574                op,
10575                Op::SaveLayer {
10576                    backdrop: Some(_),
10577                    ..
10578                }
10579            )),
10580            "disabled paints the child only: {ops:?}"
10581        );
10582    }
10583
10584    #[test]
10585    fn a_composed_backdrop_filter_reaches_the_backdrop_whole() {
10586        let cell = AppCell::new();
10587        let mut app = cell.borrow_mut();
10588        let child = RenderColoredBox::new(&mut app, Color::new(0xFF00FF00), true, None);
10589        let saturation = ColorFilter::saturation(1.8);
10590        let filter = RenderBackdropFilter::new(
10591            &mut app,
10592            ImageFilterConfig::compose(
10593                ImageFilterConfig::new(ImageFilter::Color(saturation)),
10594                ImageFilterConfig::blur().sigma_x(4.0),
10595            ),
10596            BlendMode::SrcOver,
10597            true,
10598            None,
10599            Some(child.as_box()),
10600        );
10601        layout_with(
10602            &mut app,
10603            filter.as_box(),
10604            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10605            AlignmentGeometry::CENTER,
10606            EnginePhase::Paint,
10607        );
10608        let ops = scene_ops(&mut app);
10609        let composed = valo::ImageFilter::compose(
10610            valo::ImageFilter::Color(saturation.to_valo()),
10611            valo::ImageFilter::blur(4.0, 0.0),
10612        );
10613        assert!(
10614            ops.iter().any(|op| matches!(
10615                op,
10616                Op::SaveLayer {
10617                    backdrop: Some(backdrop),
10618                    ..
10619                } if backdrop.filter == composed
10620            )),
10621            "the saturation and the blur reach the backdrop in their order: {ops:?}"
10622        );
10623    }
10624
10625    #[test]
10626    fn clip_oval_hit_tests_inside_the_inscribed_oval_and_clips_with_its_path() {
10627        let cell = AppCell::new();
10628        let mut app = cell.borrow_mut();
10629        let child = opaque_leaf(&mut app);
10630        let oval = RenderClipOval::new(&mut app, None, Clip::AntiAlias, Some(child.as_box()));
10631        layout_with(
10632            &mut app,
10633            oval.as_box(),
10634            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10635            AlignmentGeometry::CENTER,
10636            EnginePhase::Paint,
10637        );
10638        let hit = |app: &mut App, x: f64, y: f64| {
10639            let mut result = HitTestResult::new();
10640            oval.as_box().hit_test(
10641                app,
10642                &mut BoxHitTestResult::wrap(&mut result),
10643                Offset::new(x, y),
10644            )
10645        };
10646        assert!(hit(&mut app, 50.0, 50.0), "the center is inside");
10647        assert!(!hit(&mut app, 2.0, 2.0), "a corner is outside the oval");
10648        assert!(
10649            picture_has_clip(&mut app, oval.as_object()),
10650            "an oval clips with a path"
10651        );
10652    }
10653
10654    #[test]
10655    fn clip_path_uses_its_clipper_for_hit_tests_and_the_rect_by_default() {
10656        struct Triangle;
10657        impl CustomClipper<Path> for Triangle {
10658            fn get_clip(&self, _app: &App, size: Size) -> Path {
10659                let mut path = PathBuilder::new();
10660                path.move_to(Point::new(0.0, 0.0));
10661                path.line_to(Point::new(size.width() as f32, 0.0));
10662                path.line_to(Point::new(0.0, size.height() as f32));
10663                path.close();
10664                path.build().into()
10665            }
10666
10667            fn should_reclip(&self, _app: &App, _old: &dyn CustomClipper<Path>) -> bool {
10668                false
10669            }
10670
10671            fn as_any(&self) -> &dyn Any {
10672                self
10673            }
10674        }
10675        let cell = AppCell::new();
10676        let mut app = cell.borrow_mut();
10677        let child = opaque_leaf(&mut app);
10678        let clip = RenderClipPath::new(
10679            &mut app,
10680            Some(Rc::new(Triangle)),
10681            Clip::AntiAlias,
10682            Some(child.as_box()),
10683        );
10684        layout_with(
10685            &mut app,
10686            clip.as_box(),
10687            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10688            AlignmentGeometry::CENTER,
10689            EnginePhase::Paint,
10690        );
10691        let hit = |app: &mut App, x: f64, y: f64| {
10692            let mut result = HitTestResult::new();
10693            clip.as_box().hit_test(
10694                app,
10695                &mut BoxHitTestResult::wrap(&mut result),
10696                Offset::new(x, y),
10697            )
10698        };
10699        assert!(hit(&mut app, 10.0, 10.0), "inside the triangle");
10700        assert!(!hit(&mut app, 90.0, 90.0), "outside the triangle");
10701
10702        let plain = RenderClipPath::new(&mut app, None, Clip::HardEdge, None);
10703        plain.layout(
10704            &mut app,
10705            BoxConstraints::tight(Size::new(30.0, 20.0)),
10706            false,
10707        );
10708        assert!(
10709            plain.default_clip(&app).contains(Offset::new(29.0, 19.0)),
10710            "the default clip is the box's rect"
10711        );
10712    }
10713
10714    #[test]
10715    fn clip_path_clips_and_hit_tests_with_the_fill_type_of_its_path() {
10716        struct Ring;
10717        impl CustomClipper<Path> for Ring {
10718            fn get_clip(&self, _app: &App, size: Size) -> Path {
10719                let mut path = PathBuilder::new();
10720                path.rect((Offset::ZERO & size).into());
10721                path.rect(Rect::from_ltwh(25.0, 25.0, 50.0, 50.0).into());
10722                let mut path = Path::new(path.build());
10723                path.fill_type = waft_embedder::PathFillType::EvenOdd;
10724                path
10725            }
10726
10727            fn should_reclip(&self, _app: &App, _old: &dyn CustomClipper<Path>) -> bool {
10728                false
10729            }
10730
10731            fn as_any(&self) -> &dyn Any {
10732                self
10733            }
10734        }
10735        let cell = AppCell::new();
10736        let mut app = cell.borrow_mut();
10737        let child = opaque_leaf(&mut app);
10738        let clip = RenderClipPath::new(
10739            &mut app,
10740            Some(Rc::new(Ring)),
10741            Clip::AntiAlias,
10742            Some(child.as_box()),
10743        );
10744        layout_with(
10745            &mut app,
10746            clip.as_box(),
10747            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10748            AlignmentGeometry::CENTER,
10749            EnginePhase::Paint,
10750        );
10751
10752        let ops = painted_ops(&mut app, clip.as_object());
10753        let fill_rule = ops
10754            .iter()
10755            .find_map(|op| match op {
10756                Op::ClipPath { fill_rule, .. } => Some(*fill_rule),
10757                _ => None,
10758            })
10759            .expect("the recording clips");
10760        assert_eq!(fill_rule, FillRule::EvenOdd);
10761        assert!(hit_test(&mut app, clip.as_box(), Offset::new(10.0, 10.0)).0);
10762        assert!(
10763            !hit_test(&mut app, clip.as_box(), Offset::new(50.0, 50.0)).0,
10764            "the hole the even-odd rule leaves"
10765        );
10766    }
10767
10768    #[test]
10769    fn clip_rsuperellipse_resolves_its_border_radius_and_clips_with_a_path() {
10770        let cell = AppCell::new();
10771        let mut app = cell.borrow_mut();
10772        let child = RenderConstrainedBox::new(&mut app, BoxConstraints::expand(None, None), None);
10773        let clip = RenderClipRSuperellipse::new(
10774            &mut app,
10775            BorderRadiusGeometry::circular(12.0),
10776            None,
10777            Clip::AntiAlias,
10778            Some(TextDirection::Ltr),
10779            Some(child.as_box()),
10780        );
10781        layout_with(
10782            &mut app,
10783            clip.as_box(),
10784            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
10785            AlignmentGeometry::CENTER,
10786            EnginePhase::Paint,
10787        );
10788        clip.update_clip(&mut app);
10789        assert_eq!(clip.clip(&app).tl_radius_x, 12.0);
10790        assert_eq!(
10791            clip.clip(&app).outer_rect(),
10792            Rect::from_ltwh(0.0, 0.0, 100.0, 100.0)
10793        );
10794        assert!(
10795            picture_has_clip(&mut app, clip.as_object()),
10796            "a superellipse clips with its path"
10797        );
10798        clip.set_border_radius(&mut app, BorderRadiusGeometry::circular(4.0));
10799        assert!(
10800            clip.custom_clip_data(&app).clip.is_none(),
10801            "a new radius marks the clip"
10802        );
10803    }
10804
10805    #[test]
10806    fn a_shape_border_clipper_clips_to_the_shape_and_reclips_when_it_changes() {
10807        let square: ShapeBorderRef =
10808            ShapeBorderRef::new(waft_painting::RoundedRectangleBorder::new(
10809                waft_painting::BorderSide::NONE,
10810                waft_painting::BorderRadiusGeometry::circular(10.0),
10811            ));
10812        let cell = AppCell::new();
10813        let app = cell.borrow();
10814        let clipper = ShapeBorderClipper::new(square.clone(), Some(TextDirection::Ltr));
10815        let clip = clipper.get_clip(&app, Size::new(40.0, 40.0));
10816        assert!(clip.contains(Offset::new(20.0, 20.0)));
10817        assert!(!clip.contains(Offset::new(0.5, 0.5)), "a rounded corner");
10818        let same = ShapeBorderClipper::new(square.clone(), Some(TextDirection::Ltr));
10819        assert!(!clipper.should_reclip(&app, &same));
10820        let other = ShapeBorderClipper::new(square, Some(TextDirection::Rtl));
10821        assert!(clipper.should_reclip(&app, &other));
10822    }
10823
10824    /// Dart's `paintsExactlyCountTimes(#drawShadow, n)`: the shadows `render` paints.
10825    fn shadow_count(app: &mut App, render: AnyRenderObject) -> usize {
10826        count_calls(&painted_ops(app, render), CanvasMethod::DrawShadow)
10827    }
10828
10829    fn physical_model(
10830        app: &mut App,
10831        child: Option<AnyRenderBox>,
10832        clip_behavior: Clip,
10833    ) -> RenderHandle<RenderPhysicalModel> {
10834        RenderPhysicalModel::new(
10835            app,
10836            child,
10837            BoxShape::Rectangle,
10838            clip_behavior,
10839            None,
10840            0.0,
10841            Color::new(0xffff00ff),
10842            Color::new(0xFF000000),
10843        )
10844    }
10845
10846    /// `proxy_box_test.dart`: "RenderPhysicalModel compositing".
10847    #[test]
10848    fn a_physical_model_needs_no_compositing_at_any_elevation() {
10849        let cell = AppCell::new();
10850        let mut app = cell.borrow_mut();
10851        let model = physical_model(&mut app, None, Clip::None);
10852        layout_with(
10853            &mut app,
10854            model.as_box(),
10855            None,
10856            AlignmentGeometry::CENTER,
10857            EnginePhase::Paint,
10858        );
10859        assert!(!model.as_object().needs_compositing(&app));
10860
10861        model.set_elevation(&mut app, 1.0);
10862        pump_frame(&mut app, EnginePhase::Paint);
10863        assert!(!model.as_object().needs_compositing(&app));
10864
10865        model.set_elevation(&mut app, 0.0);
10866        pump_frame(&mut app, EnginePhase::Paint);
10867        assert!(!model.as_object().needs_compositing(&app));
10868    }
10869
10870    /// `proxy_box_test.dart`: "RenderPhysicalModel paints shadow only for non-zero elevation".
10871    #[test]
10872    fn a_physical_model_paints_a_shadow_only_at_a_non_zero_elevation() {
10873        let cell = AppCell::new();
10874        let mut app = cell.borrow_mut();
10875        let child = sized_box(&mut app, Size::new(10.0, 10.0));
10876        let model = physical_model(&mut app, Some(child.as_box()), Clip::None);
10877        layout_with(
10878            &mut app,
10879            model.as_box(),
10880            None,
10881            AlignmentGeometry::CENTER,
10882            EnginePhase::Paint,
10883        );
10884        assert_eq!(shadow_count(&mut app, model.as_object()), 0);
10885
10886        model.set_elevation(&mut app, 1.0);
10887        pump_frame(&mut app, EnginePhase::Paint);
10888        assert_eq!(shadow_count(&mut app, model.as_object()), 1);
10889    }
10890
10891    /// `_TestPathClipper` of `proxy_box_test.dart`.
10892    struct TestPathClipper;
10893
10894    impl CustomClipper<Path> for TestPathClipper {
10895        fn get_clip(&self, _app: &App, _size: Size) -> Path {
10896            let mut path = PathBuilder::new();
10897            path.rect(Rect::from_ltwh(50.0, 50.0, 100.0, 100.0).into());
10898            path.build().into()
10899        }
10900
10901        fn should_reclip(&self, _app: &App, _old_clipper: &dyn CustomClipper<Path>) -> bool {
10902            false
10903        }
10904
10905        fn as_any(&self) -> &dyn Any {
10906            self
10907        }
10908    }
10909
10910    /// `proxy_box_test.dart`'s `_testLayerReuse`: a repaint keeps the clip layer.
10911    fn assert_reuses_its_clip_layer<L: 'static>(app: &mut App, clip: AnyRenderBox) {
10912        assert!(clip.as_object().layer_as::<L>(app).is_none());
10913        layout_with(
10914            app,
10915            clip,
10916            Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
10917            AlignmentGeometry::CENTER,
10918            EnginePhase::Paint,
10919        );
10920        let layer = clip
10921            .as_object()
10922            .layer_as::<L>(app)
10923            .expect("the clip pushes its layer");
10924
10925        // Mark for repaint otherwise pump_frame is a noop.
10926        clip.as_object().mark_needs_paint(app);
10927        assert!(clip.as_object().debug_needs_paint(app));
10928        pump_frame(app, EnginePhase::Paint);
10929        assert!(!clip.as_object().debug_needs_paint(app));
10930        assert!(clip.as_object().layer_as::<L>(app) == Some(layer));
10931    }
10932
10933    #[test]
10934    fn a_physical_model_reuses_its_layer() {
10935        let cell = AppCell::new();
10936        let mut app = cell.borrow_mut();
10937        let leaf = sized_box(&mut app, Size::new(1.0, 1.0));
10938        let boundary = RenderRepaintBoundary::new(&mut app, Some(leaf.as_box()));
10939        let model = RenderPhysicalModel::new(
10940            &mut app,
10941            Some(boundary.as_box()),
10942            BoxShape::Rectangle,
10943            Clip::HardEdge,
10944            None,
10945            0.0,
10946            Color::from_rgbo(0, 0, 0, 1.0),
10947            Color::new(0xFF000000),
10948        );
10949        assert_reuses_its_clip_layer::<ClipRRectLayer>(&mut app, model.as_box());
10950    }
10951
10952    #[test]
10953    fn a_physical_shape_reuses_its_layer() {
10954        let cell = AppCell::new();
10955        let mut app = cell.borrow_mut();
10956        let leaf = sized_box(&mut app, Size::new(1.0, 1.0));
10957        let boundary = RenderRepaintBoundary::new(&mut app, Some(leaf.as_box()));
10958        let shape = RenderPhysicalShape::new(
10959            &mut app,
10960            Some(boundary.as_box()),
10961            Rc::new(TestPathClipper),
10962            Clip::HardEdge,
10963            0.0,
10964            Color::from_rgbo(0, 0, 0, 1.0),
10965            Color::new(0xFF000000),
10966        );
10967        assert_reuses_its_clip_layer::<ClipPathLayer>(&mut app, shape.as_box());
10968    }
10969
10970    #[test]
10971    fn a_physical_model_fills_its_shape_and_draws_its_shadow_below_it() {
10972        let cell = AppCell::new();
10973        let mut app = cell.borrow_mut();
10974        let child = sized_box(&mut app, Size::new(10.0, 10.0));
10975        let model = RenderPhysicalModel::new(
10976            &mut app,
10977            Some(child.as_box()),
10978            BoxShape::Rectangle,
10979            Clip::None,
10980            Some(BorderRadius::circular(2.0)),
10981            4.0,
10982            BLUE,
10983            Color::new(0xFF000000),
10984        );
10985        let _owner = first_frame_in_view(&mut app, model.as_box(), 3.0);
10986        let ops = painted_ops(&mut app, model.as_object());
10987        let shadow = ops
10988            .iter()
10989            .position(|op| {
10990                matches!(op, Op::DrawShadow { elevation, transparent_occluder, .. }
10991                    if *elevation == 4.0 && !*transparent_occluder)
10992            })
10993            .expect("a shadow at elevation 4");
10994        let Op::DrawShadow {
10995            round_rect,
10996            device_pixel_ratio,
10997            ..
10998        } = &ops[shadow]
10999        else {
11000            unreachable!("found as a shadow");
11001        };
11002        assert_eq!(
11003            *round_rect,
11004            Some((
11005                valo::Rect::from(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0)),
11006                2.0
11007            )),
11008            "a rounded rect the shadow fills in closed form"
11009        );
11010        assert_eq!(*device_pixel_ratio, 3.0);
11011        let fill = ops
11012            .iter()
11013            .position(|op| {
11014                matches!(op, Op::DrawPath { paint, .. }
11015                    if paint.mask_blur.is_none() && paint.color == BLUE.into())
11016            })
11017            .expect("the rounded fill");
11018        assert!(shadow < fill, "the shadow is drawn under the fill");
11019    }
11020
11021    /// A clipper whose path is a rounded rectangle over the whole box, of corner radius 4.
11022    struct RoundedRectClipper;
11023
11024    impl CustomClipper<Path> for RoundedRectClipper {
11025        fn get_clip(&self, _app: &App, size: Size) -> Path {
11026            let rrect = RRect::from_rect_and_radius(
11027                Rect::from_ltwh(0.0, 0.0, size.width(), size.height()),
11028                waft_embedder::Radius::circular(4.0),
11029            );
11030            let mut path = PathBuilder::new();
11031            path.rrect_radii_elliptical(rrect.outer_rect(), rrect_radii_elliptical(rrect));
11032            path.build().into()
11033        }
11034
11035        fn should_reclip(&self, _app: &App, _old_clipper: &dyn CustomClipper<Path>) -> bool {
11036            false
11037        }
11038
11039        fn as_any(&self) -> &dyn Any {
11040            self
11041        }
11042    }
11043
11044    /// A physical shape painted away from its layer's origin shifts its path as dart:ui's
11045    /// `Path.shift` does, which keeps a rounded rectangle one, so the shadow is drawn in closed
11046    /// form at the shifted place.
11047    #[test]
11048    fn a_shifted_rounded_physical_shape_keeps_its_closed_form_shadow() {
11049        let cell = AppCell::new();
11050        let mut app = cell.borrow_mut();
11051        let child = sized_box(&mut app, Size::new(10.0, 10.0));
11052        let shape = RenderPhysicalShape::new(
11053            &mut app,
11054            Some(child.as_box()),
11055            Rc::new(RoundedRectClipper),
11056            Clip::None,
11057            4.0,
11058            BLUE,
11059            Color::new(0xFF000000),
11060        );
11061        let padding = crate::shifted_box::RenderPadding::new(
11062            &mut app,
11063            waft_painting::EdgeInsetsGeometry::all(20.0),
11064            None,
11065            Some(shape.as_box()),
11066        );
11067        layout_with(
11068            &mut app,
11069            padding.as_box(),
11070            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
11071            AlignmentGeometry::CENTER,
11072            EnginePhase::Paint,
11073        );
11074        let ops = painted_ops(&mut app, padding.as_object());
11075        let round_rect = ops
11076            .iter()
11077            .find_map(|op| match op {
11078                Op::DrawShadow { round_rect, .. } => Some(*round_rect),
11079                _ => None,
11080            })
11081            .expect("a shadow at elevation 4");
11082        assert_eq!(
11083            round_rect,
11084            Some((
11085                valo::Rect::from(Rect::from_ltwh(20.0, 20.0, 60.0, 60.0)),
11086                4.0
11087            )),
11088            "the shifted rounded rect the shadow fills in closed form"
11089        );
11090    }
11091
11092    /// Lays `child` out and paints it under a [`RenderView`] of 100x100 logical pixels at
11093    /// `device_pixel_ratio`: the test view has no device pixel ratio for a shadow to read.
11094    fn first_frame_in_view(
11095        app: &mut App,
11096        child: AnyRenderBox,
11097        device_pixel_ratio: f64,
11098    ) -> Ref<PipelineOwner> {
11099        let constraints = BoxConstraints::tight(Size::new(100.0, 100.0));
11100        let view = RenderView::new(
11101            app,
11102            Some(child),
11103            Some(ViewConfiguration::new(
11104                constraints * device_pixel_ratio,
11105                constraints,
11106                device_pixel_ratio,
11107            )),
11108            Rc::new(waft_test::TestView::new(100.0, 100.0)),
11109        );
11110        let owner = PipelineOwner::new(app, None, None);
11111        owner.set_root_node(app, Some(view.as_object()));
11112        view.prepare_initial_frame(app);
11113        owner.flush_layout(app);
11114        owner.flush_compositing_bits(app);
11115        owner.flush_paint(app);
11116        owner
11117    }
11118
11119    /// Whether `ops` fill with `color` only through a `draw_paint` inside a save layer, as a
11120    /// physical model with [`Clip::AntiAliasWithSaveLayer`] does to avoid the bleeding edge.
11121    fn fills_only_with_draw_paint_inside_a_save_layer(ops: &[Op], color: Color) -> bool {
11122        let filled = |paint: &valo::Paint| paint.color == color.into() && paint.mask_blur.is_none();
11123        let save_layer = ops.iter().position(|op| matches!(op, Op::SaveLayer { .. }));
11124        let draw_paint = ops
11125            .iter()
11126            .position(|op| matches!(op, Op::DrawPaint { paint, .. } if filled(paint)));
11127        let other_fill = ops.iter().any(|op| {
11128            matches!(op, Op::DrawPath { paint, .. } | Op::DrawRect { paint, .. } if filled(paint))
11129        });
11130        matches!((save_layer, draw_paint), (Some(layer), Some(paint)) if layer < paint)
11131            && !other_fill
11132    }
11133
11134    #[test]
11135    fn a_physical_model_clipping_with_a_save_layer_fills_with_draw_paint_inside_the_clip() {
11136        let cell = AppCell::new();
11137        let mut app = cell.borrow_mut();
11138        let child = sized_box(&mut app, Size::new(10.0, 10.0));
11139        let model = RenderPhysicalModel::new(
11140            &mut app,
11141            Some(child.as_box()),
11142            BoxShape::Rectangle,
11143            Clip::AntiAliasWithSaveLayer,
11144            Some(BorderRadius::circular(2.0)),
11145            0.0,
11146            BLUE,
11147            Color::new(0xFF000000),
11148        );
11149        layout_with(
11150            &mut app,
11151            model.as_box(),
11152            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
11153            AlignmentGeometry::CENTER,
11154            EnginePhase::Paint,
11155        );
11156        let ops = painted_ops(&mut app, model.as_object());
11157        assert!(
11158            fills_only_with_draw_paint_inside_a_save_layer(&ops, BLUE),
11159            "{ops:?}"
11160        );
11161    }
11162
11163    #[test]
11164    fn a_physical_shape_clipping_with_a_save_layer_fills_with_draw_paint_inside_the_clip() {
11165        let cell = AppCell::new();
11166        let mut app = cell.borrow_mut();
11167        let child = sized_box(&mut app, Size::new(10.0, 10.0));
11168        let shape = RenderPhysicalShape::new(
11169            &mut app,
11170            Some(child.as_box()),
11171            circle_clipper(),
11172            Clip::AntiAliasWithSaveLayer,
11173            0.0,
11174            BLUE,
11175            Color::new(0xFF000000),
11176        );
11177        layout_with(
11178            &mut app,
11179            shape.as_box(),
11180            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
11181            AlignmentGeometry::CENTER,
11182            EnginePhase::Paint,
11183        );
11184        let ops = painted_ops(&mut app, shape.as_object());
11185        assert!(
11186            fills_only_with_draw_paint_inside_a_save_layer(&ops, BLUE),
11187            "{ops:?}"
11188        );
11189    }
11190
11191    fn circle_clipper() -> Rc<dyn CustomClipper<Path>> {
11192        Rc::new(ShapeBorderClipper::new(
11193            ShapeBorderRef::new(waft_painting::CircleBorder::new(
11194                waft_painting::BorderSide::NONE,
11195                0.0,
11196            )),
11197            None,
11198        ))
11199    }
11200
11201    fn physical_shape(app: &mut App) -> RenderHandle<RenderPhysicalShape> {
11202        RenderPhysicalShape::new(
11203            app,
11204            None,
11205            circle_clipper(),
11206            Clip::None,
11207            0.0,
11208            Color::new(0xffff00ff),
11209            Color::new(0xFF000000),
11210        )
11211    }
11212
11213    /// `proxy_box_test.dart`: "RenderPhysicalShape shape change triggers repaint".
11214    #[test]
11215    fn a_physical_shape_repaints_only_for_a_different_shape() {
11216        let cell = AppCell::new();
11217        let mut app = cell.borrow_mut();
11218        let shape = physical_shape(&mut app);
11219        layout_with(
11220            &mut app,
11221            shape.as_box(),
11222            None,
11223            AlignmentGeometry::CENTER,
11224            EnginePhase::Paint,
11225        );
11226        assert!(!shape.as_object().debug_needs_paint(&app));
11227
11228        // Same shape, no repaint.
11229        shape.set_clipper(&mut app, Some(circle_clipper()));
11230        assert!(!shape.as_object().debug_needs_paint(&app));
11231
11232        // Different shape triggers repaint.
11233        shape.set_clipper(
11234            &mut app,
11235            Some(Rc::new(ShapeBorderClipper::new(
11236                ShapeBorderRef::new(waft_painting::StadiumBorder::default()),
11237                None,
11238            ))),
11239        );
11240        assert!(shape.as_object().debug_needs_paint(&app));
11241    }
11242
11243    /// `proxy_box_test.dart`: "RenderPhysicalShape compositing".
11244    #[test]
11245    fn a_physical_shape_needs_no_compositing_at_any_elevation() {
11246        let cell = AppCell::new();
11247        let mut app = cell.borrow_mut();
11248        let shape = physical_shape(&mut app);
11249        layout_with(
11250            &mut app,
11251            shape.as_box(),
11252            None,
11253            AlignmentGeometry::CENTER,
11254            EnginePhase::Paint,
11255        );
11256        assert!(!shape.as_object().needs_compositing(&app));
11257        shape.set_elevation(&mut app, 1.0);
11258        pump_frame(&mut app, EnginePhase::Paint);
11259        assert!(!shape.as_object().needs_compositing(&app));
11260        shape.set_elevation(&mut app, 0.0);
11261        pump_frame(&mut app, EnginePhase::Paint);
11262        assert!(!shape.as_object().needs_compositing(&app));
11263    }
11264
11265    /// A leaf that takes every hit, wherever it lands, as `_RenderInputPadding` does for hits
11266    /// around its child.
11267    struct EveryHitBox {
11268        render_object: RenderObjectData,
11269        render_box: RenderBoxData,
11270    }
11271
11272    impl RenderObject for EveryHitBox {
11273        crate::render_object_accessors!();
11274
11275        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
11276            let size = self.constraints(app).biggest();
11277            self.set_size(app, size);
11278        }
11279    }
11280
11281    impl RenderBox for EveryHitBox {
11282        crate::render_box_accessors!();
11283
11284        fn hit_test(
11285            self: RenderHandle<Self>,
11286            _app: &mut App,
11287            result: &mut BoxHitTestResult<'_>,
11288            position: Offset,
11289        ) -> bool {
11290            result.add(BoxHitTestEntry::new(self.as_box(), position).into());
11291            true
11292        }
11293    }
11294
11295    use crate::semantics::AttributedString;
11296
11297    fn semantics_annotations(
11298        app: &mut App,
11299        properties: SemanticsProperties,
11300        child: Option<AnyRenderBox>,
11301    ) -> RenderHandle<RenderSemanticsAnnotations> {
11302        RenderSemanticsAnnotations::new(
11303            app,
11304            Rc::new(properties),
11305            false,
11306            false,
11307            false,
11308            false,
11309            None,
11310            None,
11311            child,
11312        )
11313    }
11314
11315    #[test]
11316    fn semantics_annotations_bound_the_hit_test_of_a_child_that_takes_hits_outside_itself() {
11317        let cell = AppCell::new();
11318        let mut app = cell.borrow_mut();
11319        let child = RenderHandle::new_box(
11320            &mut app,
11321            EveryHitBox {
11322                render_object: RenderObjectData::new(),
11323                render_box: RenderBoxData::new(),
11324            },
11325        );
11326        let semantics =
11327            semantics_annotations(&mut app, SemanticsProperties::new(), Some(child.as_box()));
11328        semantics.layout(
11329            &mut app,
11330            BoxConstraints::tight(Size::new(50.0, 50.0)),
11331            false,
11332        );
11333
11334        assert_eq!(
11335            hit_test(&mut app, child.as_box(), Offset::new(75.0, 75.0)),
11336            (true, 1),
11337            "the child alone takes a hit outside itself"
11338        );
11339        assert_eq!(
11340            hit_test(&mut app, semantics.as_box(), Offset::new(75.0, 75.0)),
11341            (false, 0)
11342        );
11343        assert_eq!(
11344            hit_test(&mut app, semantics.as_box(), Offset::new(25.0, 25.0)),
11345            (true, 2),
11346            "the child and the annotations"
11347        );
11348    }
11349
11350    /// Dart's `_RenderNoBaseline`: a 40x20 box that answers no dry baseline.
11351    struct NoBaselineBox {
11352        render_object: RenderObjectData,
11353        render_box: RenderBoxData,
11354    }
11355
11356    impl RenderObject for NoBaselineBox {
11357        crate::render_object_accessors!();
11358
11359        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
11360            let size = self.constraints(app).constrain(Size::new(40.0, 20.0));
11361            self.set_size(app, size);
11362        }
11363    }
11364
11365    impl RenderBox for NoBaselineBox {
11366        crate::render_box_accessors!();
11367
11368        fn compute_dry_layout(
11369            self: RenderHandle<Self>,
11370            _app: &mut App,
11371            constraints: BoxConstraints,
11372        ) -> Size {
11373            constraints.constrain(Size::new(40.0, 20.0))
11374        }
11375
11376        fn compute_dry_baseline(
11377            self: RenderHandle<Self>,
11378            _app: &mut App,
11379            _constraints: BoxConstraints,
11380            _baseline: TextBaseline,
11381        ) -> Option<f64> {
11382            None
11383        }
11384    }
11385
11386    // 'RenderProxyBoxMixin.computeDryBaseline returns null when the child has no baseline'
11387    #[test]
11388    fn a_proxy_box_dry_baseline_is_none_when_the_child_has_no_baseline() {
11389        let cell = AppCell::new();
11390        let mut app = cell.borrow_mut();
11391        let child = RenderHandle::new_box(
11392            &mut app,
11393            NoBaselineBox {
11394                render_object: RenderObjectData::new(),
11395                render_box: RenderBoxData::new(),
11396            },
11397        );
11398        let proxy =
11399            semantics_annotations(&mut app, SemanticsProperties::new(), Some(child.as_box()));
11400        proxy.layout(&mut app, BoxConstraints::new(), false);
11401        assert_eq!(
11402            proxy.as_box().get_dry_baseline(
11403                &mut app,
11404                BoxConstraints::tight_for(Some(40.0), Some(20.0)),
11405                TextBaseline::Alphabetic,
11406            ),
11407            None
11408        );
11409    }
11410
11411    #[test]
11412    fn semantics_annotations_keep_what_they_are_given() {
11413        let cell = AppCell::new();
11414        let mut app = cell.borrow_mut();
11415        let properties = Rc::new(SemanticsProperties::new().label("label").hint("hint"));
11416        let semantics = RenderSemanticsAnnotations::new(
11417            &mut app,
11418            properties.clone(),
11419            true,
11420            false,
11421            false,
11422            true,
11423            Some(Locale::new("es")),
11424            Some(TextDirection::Rtl),
11425            None,
11426        );
11427        assert!(Rc::ptr_eq(&semantics.properties(&app), &properties));
11428        assert!(semantics.container(&app));
11429        assert!(!semantics.explicit_child_nodes(&app));
11430        assert!(!semantics.exclude_semantics(&app));
11431        assert!(semantics.block_user_actions(&app));
11432        assert_eq!(semantics.locale_for_subtree(&app), Some(Locale::new("es")));
11433        assert_eq!(semantics.text_direction(&app), Some(TextDirection::Rtl));
11434        assert_eq!(
11435            semantics.attributed_label(&app),
11436            Some(AttributedString::new("label"))
11437        );
11438        assert_eq!(
11439            semantics.attributed_hint(&app),
11440            Some(AttributedString::new("hint"))
11441        );
11442        assert_eq!(semantics.attributed_value(&app), None);
11443
11444        let attributed_value = AttributedString::new("value");
11445        semantics.set_properties(
11446            &mut app,
11447            Rc::new(
11448                SemanticsProperties::new()
11449                    .attributed_value(attributed_value.clone())
11450                    .decreased_value("less"),
11451            ),
11452        );
11453        assert_eq!(semantics.attributed_label(&app), None);
11454        assert_eq!(semantics.attributed_value(&app), Some(attributed_value));
11455        assert_eq!(
11456            semantics.attributed_decreased_value(&app),
11457            Some(AttributedString::new("less"))
11458        );
11459
11460        semantics.set_container(&mut app, false);
11461        semantics.set_explicit_child_nodes(&mut app, true);
11462        semantics.set_exclude_semantics(&mut app, true);
11463        semantics.set_block_user_actions(&mut app, false);
11464        semantics.set_locale_for_subtree(&mut app, None);
11465        semantics.set_text_direction(&mut app, None);
11466        assert!(!semantics.container(&app));
11467        assert!(semantics.explicit_child_nodes(&app));
11468        assert!(semantics.exclude_semantics(&app));
11469        assert!(!semantics.block_user_actions(&app));
11470        assert_eq!(semantics.locale_for_subtree(&app), None);
11471        assert_eq!(semantics.text_direction(&app), None);
11472    }
11473
11474    #[test]
11475    fn the_block_exclude_and_indexed_semantics_boxes_keep_their_values() {
11476        let cell = AppCell::new();
11477        let mut app = cell.borrow_mut();
11478        let block = RenderBlockSemantics::new(&mut app, true, None);
11479        block.set_blocking(&mut app, false);
11480        assert!(!block.blocking(&app));
11481        let exclude = RenderExcludeSemantics::new(&mut app, true, None);
11482        exclude.set_excluding(&mut app, false);
11483        assert!(!exclude.excluding(&app));
11484        let indexed = RenderIndexedSemantics::new(&mut app, 3, None);
11485        assert_eq!(indexed.index(&app), 3);
11486        indexed.set_index(&mut app, 4);
11487        assert_eq!(indexed.index(&app), 4);
11488        let merge = RenderMergeSemantics::new(&mut app, None);
11489        merge.layout(
11490            &mut app,
11491            BoxConstraints::tight(Size::new(10.0, 10.0)),
11492            false,
11493        );
11494        assert_eq!(merge.size(&app), Size::new(10.0, 10.0));
11495    }
11496}