Skip to main content

waft_rendering/
painting_context.rs

1//! Flutter counterpart: `rendering/object.dart` (`PaintingContext`).
2
3use std::rc::Rc;
4use std::sync::Arc;
5
6use waft_embedder::{Canvas, Clip, Matrix4, Offset, Path, RRect, Rect};
7use waft_foundation::{App, Handle};
8use waft_painting::{ClipContext, inverse_transform_rect};
9
10use crate::layer::{
11    AnyContainerLayer, AnyLayer, ClipPathLayer, ClipRRectLayer, ClipRectLayer, CompositionCallback,
12    ContainerLayer, ErasedLayer, LayerHandle, OffsetLayerMixin, OpacityLayer, PictureLayer,
13    TransformLayer,
14};
15use crate::object::AnyRenderObject;
16use crate::screenshot::SharedRecording;
17
18/// A place to paint.
19///
20/// Rather than holding a canvas directly, [`crate::RenderObject`]s paint using a painting
21/// context. The painting context has a [`Canvas`](ClipContext::canvas), which receives the
22/// individual draw operations, and also has functions for painting child
23/// render objects.
24///
25/// When painting a child render object, the canvas held by the painting context
26/// can change because the draw operations issued before and after painting the
27/// child might be recorded in separate compositing layers. For this reason, do
28/// not hold a reference to the canvas across operations that might paint
29/// child render objects.
30///
31/// New [`PaintingContext`] objects are created automatically when using
32/// [`PaintingContext::repaint_composited_child`] and [`push_layer`](Self::push_layer).
33pub struct PaintingContext {
34    container_layer: AnyContainerLayer,
35    /// An estimate of the bounds within which the painting context's [`canvas`](ClipContext::canvas)
36    /// will record painting commands. This can be useful for debugging.
37    ///
38    /// The canvas will allow painting outside these bounds.
39    ///
40    /// The [`estimated_bounds`](Self::estimated_bounds) rectangle is in the canvas coordinate
41    /// system.
42    pub estimated_bounds: Rect,
43    canvas: Option<Canvas>,
44    is_complex_hint: bool,
45    will_change_hint: bool,
46    /// The widget inspector's screenshot this paint records, until its target is reached: Dart's
47    /// `_ScreenshotPaintingContext`, whose overrides are the branches on this field.
48    screenshot: Option<SharedRecording>,
49}
50
51impl PaintingContext {
52    /// Creates a painting context.
53    ///
54    /// Typically only called by [`repaint_composited_child`](Self::repaint_composited_child)
55    /// and [`push_layer`](Self::push_layer).
56    pub fn new(container_layer: AnyContainerLayer, estimated_bounds: Rect) -> PaintingContext {
57        PaintingContext {
58            container_layer,
59            estimated_bounds,
60            canvas: None,
61            is_complex_hint: false,
62            will_change_hint: false,
63            screenshot: None,
64        }
65    }
66
67    /// A context that paints into `container_layer` as [`new`](Self::new)'s does, and records
68    /// `recording`'s screenshot: Dart's `_ScreenshotPaintingContext`.
69    pub(crate) fn recording_screenshot(
70        container_layer: AnyContainerLayer,
71        estimated_bounds: Rect,
72        recording: SharedRecording,
73    ) -> PaintingContext {
74        PaintingContext {
75            screenshot: Some(recording),
76            ..PaintingContext::new(container_layer, estimated_bounds)
77        }
78    }
79
80    /// Repaints the repaint boundary `child` through `context`, which need not be in need of
81    /// painting: Dart's `debugInstrumentRepaintCompositedChild`.
82    pub(crate) fn debug_instrument_repaint_composited_child(
83        app: &mut App,
84        child: AnyRenderObject,
85        context: PaintingContext,
86    ) {
87        Self::repaint_composited_child_inner(app, child, false, Some(context));
88    }
89
90    /// Repaint the given render object.
91    ///
92    /// The render object must be attached to a [`crate::PipelineOwner`], must have a
93    /// composited layer, and must be in need of painting. The render object's
94    /// layer, if any, is re-used, along with any layers in the subtree that don't
95    /// need to be repainted.
96    pub fn repaint_composited_child(app: &mut App, child: AnyRenderObject) {
97        debug_assert!(child.needs_paint(app));
98        Self::repaint_composited_child_inner(app, child, false, None);
99    }
100
101    fn repaint_composited_child_inner(
102        app: &mut App,
103        child: AnyRenderObject,
104        debug_also_painted_parent: bool,
105        child_context: Option<PaintingContext>,
106    ) {
107        debug_assert!(child.is_repaint_boundary(app));
108        let child_layer = if let Some(child_layer) =
109            child.layer(app).and_then(|layer| layer.as_offset_layer())
110        {
111            debug_assert!(debug_also_painted_parent || child_layer.as_layer().attached(app));
112            let debug_old_offset = if cfg!(debug_assertions) {
113                Some(child_layer.offset(app))
114            } else {
115                None
116            };
117            child_layer.as_container_layer().remove_all_children(app);
118            let updated_layer = child.update_composited_layer(app, Some(child_layer));
119            debug_assert_eq!(
120                updated_layer, child_layer,
121                "{child:?} created a new layer instance {updated_layer:?} instead of reusing the \
122                 existing layer {child_layer:?}. See the documentation of RenderObject.updateCompositedLayer \
123                 for more information on how to correctly implement this method."
124            );
125            debug_assert_eq!(debug_old_offset, Some(updated_layer.offset(app)));
126            child_layer
127        } else {
128            debug_assert!(debug_also_painted_parent);
129            debug_assert!(child.layer(app).is_none());
130
131            // Not using the `layer` setter because the setter asserts that we not
132            // replace the layer for repaint boundaries. That assertion does not
133            // apply here because this is exactly the place designed to create a
134            // layer for repaint boundaries.
135            let layer = child.update_composited_layer(app, None);
136            LayerHandle::set_layer(
137                app,
138                |app| &mut child.data_mut(app).layer,
139                Some(layer.as_container_layer()),
140            );
141            layer
142        };
143        child.set_needs_composited_layer_update(app, false);
144        debug_assert_eq!(Some(child_layer.as_container_layer()), child.layer(app));
145        debug_assert!(
146            child
147                .layer(app)
148                .is_some_and(|layer| layer.as_offset_layer().is_some())
149        );
150
151        let mut child_context = child_context.unwrap_or_else(|| {
152            PaintingContext::new(child_layer.as_container_layer(), child.paint_bounds(app))
153        });
154        child.paint_with_context(app, &mut child_context, Offset::ZERO);
155
156        // Double-check that the paint method did not replace the layer (the first
157        // check is done in the [layer] setter itself).
158        debug_assert_eq!(Some(child_layer.as_container_layer()), child.layer(app));
159        child_context.stop_recording_if_needed(app);
160    }
161
162    /// Update the composited layer of `child` without repainting its children.
163    ///
164    /// The render object must be attached to a [`crate::PipelineOwner`], must have a
165    /// composited layer, and must be in need of a composited layer update but
166    /// not in need of painting. The render object's layer is re-used, and none
167    /// of its children are repaint or their layers updated.
168    pub fn update_layer_properties(app: &mut App, child: AnyRenderObject) {
169        debug_assert!(child.is_repaint_boundary(app) && child.was_repaint_boundary(app));
170        debug_assert!(!child.needs_paint(app));
171        debug_assert!(child.layer(app).is_some());
172
173        let child_layer = child
174            .layer(app)
175            .expect("checked")
176            .as_offset_layer()
177            .expect("a repaint boundary's layer is an OffsetLayer");
178        let debug_old_offset = if cfg!(debug_assertions) {
179            Some(child_layer.offset(app))
180        } else {
181            None
182        };
183        let updated_layer = child.update_composited_layer(app, Some(child_layer));
184        debug_assert_eq!(
185            updated_layer, child_layer,
186            "{child:?} created a new layer instance {updated_layer:?} instead of reusing the \
187             existing layer {child_layer:?}. See the documentation of RenderObject.updateCompositedLayer \
188             for more information on how to correctly implement this method."
189        );
190        debug_assert_eq!(debug_old_offset, Some(updated_layer.offset(app)));
191        child.set_needs_composited_layer_update(app, false);
192    }
193
194    /// Paint a child [`crate::RenderObject`].
195    ///
196    /// If the child has its own composited layer, the child will be composited
197    /// into the layer subtree associated with this painting context. Otherwise,
198    /// the child will be painted into the current PictureLayer for this context.
199    pub fn paint_child(&mut self, app: &mut App, child: AnyRenderObject, offset: Offset) {
200        let is_screenshot_target = self
201            .screenshot
202            .as_ref()
203            .is_some_and(|recording| recording.borrow().target == child);
204        if is_screenshot_target {
205            // The target's drawing goes in pictures of its own, which the screenshot borrows.
206            self.stop_recording_if_needed(app);
207            self.recording().borrow_mut().start_target(offset);
208        }
209        self.paint_child_into_this_context(app, child, offset);
210        if is_screenshot_target {
211            self.stop_recording_if_needed(app);
212            self.recording().borrow_mut().end_target();
213        }
214    }
215
216    /// The screenshot this context records.
217    fn recording(&self) -> &SharedRecording {
218        self.screenshot.as_ref().expect("a screenshot is recording")
219    }
220
221    /// [`paint_child`](Self::paint_child)'s body: Dart's `PaintingContext.paintChild`.
222    fn paint_child_into_this_context(
223        &mut self,
224        app: &mut App,
225        child: AnyRenderObject,
226        offset: Offset,
227    ) {
228        if child.is_repaint_boundary(app) {
229            self.stop_recording_if_needed(app);
230            self.composite_child(app, child, offset);
231        } else if child.was_repaint_boundary(app) {
232            debug_assert!(
233                child
234                    .layer(app)
235                    .is_some_and(|layer| layer.as_offset_layer().is_some())
236            );
237            LayerHandle::set_layer(app, |app| &mut child.data_mut(app).layer, None);
238            child.paint_with_context(app, self, offset);
239        } else {
240            child.paint_with_context(app, self, offset);
241        }
242    }
243
244    fn composite_child(&mut self, app: &mut App, child: AnyRenderObject, offset: Offset) {
245        debug_assert!(!self.is_recording());
246        debug_assert!(child.is_repaint_boundary(app));
247
248        if child.needs_paint(app) || !child.was_repaint_boundary(app) {
249            Self::repaint_composited_child_inner(app, child, true, None);
250        } else if child.needs_composited_layer_update(app) {
251            Self::update_layer_properties(app, child);
252        }
253        debug_assert!(
254            child
255                .layer(app)
256                .is_some_and(|layer| layer.as_offset_layer().is_some())
257        );
258        let child_offset_layer = child
259            .layer(app)
260            .expect("checked")
261            .as_offset_layer()
262            .expect("a repaint boundary's layer is an OffsetLayer");
263        child_offset_layer.set_offset(app, offset);
264        self.append_layer(app, child_offset_layer.as_layer());
265    }
266
267    /// Adds a layer to the recording requiring that the recording is already
268    /// stopped.
269    ///
270    /// Do not call this function directly: call [`add_layer`](Self::add_layer) or
271    /// [`push_layer`](Self::push_layer) instead. This function is called internally when all
272    /// layers not generated from the canvas are added.
273    fn append_layer(&mut self, app: &mut App, layer: AnyLayer) {
274        debug_assert!(!self.is_recording());
275        layer.remove(app);
276        self.append_to_container(app, layer);
277    }
278
279    /// Appends `layer` to this context's container, and to the screenshot when the target is
280    /// painting it.
281    fn append_to_container(&mut self, app: &mut App, layer: AnyLayer) {
282        self.container_layer.append(app, layer);
283        if let Some(recording) = &self.screenshot
284            && recording.borrow().include_in_screenshot
285        {
286            recording.borrow().borrow_layer(app, layer);
287        }
288    }
289
290    fn is_recording(&self) -> bool {
291        self.canvas.is_some()
292    }
293
294    fn start_recording(&mut self) {
295        debug_assert!(!self.is_recording());
296        self.canvas = Some(Canvas::new());
297        self.is_complex_hint = false;
298        self.will_change_hint = false;
299    }
300
301    /// Adds a [`CompositionCallback`] for the current [`AnyContainerLayer`] used by this
302    /// context.
303    pub fn add_composition_callback(
304        &self,
305        app: &mut App,
306        callback: CompositionCallback,
307    ) -> Box<dyn FnOnce(&mut App)> {
308        self.container_layer
309            .as_layer()
310            .add_composition_callback(app, callback)
311    }
312
313    /// Stop recording to a canvas if recording has started.
314    ///
315    /// Do not call this function directly: functions in this class will call
316    /// this method as needed. This function is called internally to ensure that
317    /// recording is stopped before adding layers or finalizing the results of a
318    /// paint.
319    ///
320    /// Creates and appends the [`PictureLayer`] here rather than in
321    /// [`start_recording`](Self::start_recording): [`ClipContext::canvas`] has no `App`. See
322    /// `PORTING.md`.
323    pub fn stop_recording_if_needed(&mut self, app: &mut App) {
324        if !self.is_recording() {
325            return;
326        }
327        let canvas = self.canvas.take().expect("recording");
328        let picture = PictureLayer::new(app, self.estimated_bounds);
329        picture.set_picture(app, Some(Arc::new(canvas.build())));
330        picture.set_is_complex_hint(app, self.is_complex_hint);
331        picture.set_will_change_hint(app, self.will_change_hint);
332        self.is_complex_hint = false;
333        self.will_change_hint = false;
334        self.append_to_container(app, picture.as_layer());
335    }
336
337    /// Hints that the painting in the current layer is complex and would benefit
338    /// from caching.
339    pub fn set_is_complex_hint(&mut self) {
340        if self.canvas.is_none() {
341            self.start_recording();
342        }
343        self.is_complex_hint = true;
344    }
345
346    /// Hints that the painting in the current layer is likely to change next frame.
347    pub fn set_will_change_hint(&mut self) {
348        if self.canvas.is_none() {
349            self.start_recording();
350        }
351        self.will_change_hint = true;
352    }
353
354    /// Adds a composited leaf layer to the recording.
355    ///
356    /// After calling this function, the [`canvas`](ClipContext::canvas) property will change to
357    /// refer to a new [`Canvas`] that draws on top of the given layer.
358    pub fn add_layer(&mut self, app: &mut App, layer: AnyLayer) {
359        self.stop_recording_if_needed(app);
360        self.append_layer(app, layer);
361    }
362
363    /// Appends the given layer to the recording, and calls the `painter` callback
364    /// with that layer, providing the `child_paint_bounds` as the estimated paint
365    /// bounds of the child. The `child_paint_bounds` can be used for debugging but
366    /// have no effect on painting.
367    ///
368    /// The given layer must be an unattached orphan. (Providing a newly created
369    /// object, rather than reusing an existing layer, satisfies that
370    /// requirement.)
371    ///
372    /// The `offset` is the offset to pass to the `painter`. In particular, it is
373    /// not an offset applied to the layer itself. Layers conceptually by default
374    /// have no position or size, though they can transform their contents. For
375    /// example, an [`crate::OffsetLayer`] applies an offset to its children.
376    ///
377    /// If the `child_paint_bounds` are not specified then the current layer's paint
378    /// bounds are used. This is appropriate if the child layer does not apply any
379    /// transformation or clipping to its contents. The `child_paint_bounds`, if
380    /// specified, must be in the coordinate system of the new layer (i.e. as seen
381    /// by its children after it applies whatever transform to its contents), and
382    /// should not go outside the current layer's paint bounds.
383    pub fn push_layer(
384        &mut self,
385        app: &mut App,
386        child_layer: AnyContainerLayer,
387        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
388        offset: Offset,
389        child_paint_bounds: Option<Rect>,
390    ) {
391        // If a layer is being reused, it may already contain children. We remove
392        // them so that `painter` can add children that are relevant for this frame.
393        if child_layer.has_children(app) {
394            child_layer.remove_all_children(app);
395        }
396        self.stop_recording_if_needed(app);
397        self.append_layer(app, child_layer.as_layer());
398        let mut child_context = self.create_child_context(
399            child_layer,
400            child_paint_bounds.unwrap_or(self.estimated_bounds),
401        );
402
403        painter(app, &mut child_context, offset);
404        child_context.stop_recording_if_needed(app);
405    }
406
407    /// Creates a painting context configured to paint into `child_layer`.
408    ///
409    /// The `bounds` are estimated paint bounds for debugging purposes.
410    fn create_child_context(
411        &self,
412        child_layer: AnyContainerLayer,
413        bounds: Rect,
414    ) -> PaintingContext {
415        match &self.screenshot {
416            // Once the target is found, a plain context paints the rest.
417            Some(recording) if !recording.borrow().found_target => {
418                PaintingContext::recording_screenshot(child_layer, bounds, Rc::clone(recording))
419            }
420            _ => PaintingContext::new(child_layer, bounds),
421        }
422    }
423
424    /// Clip further painting using a rectangle.
425    ///
426    /// The `needs_compositing` argument specifies whether the child needs
427    /// compositing. Typically this matches the value of
428    /// [`AnyRenderObject::needs_compositing`] for the caller. If false, this method
429    /// returns `None`, indicating that a layer is no longer necessary. If a render
430    /// object calling this method stores the `old_layer` in its
431    /// [`AnyRenderObject::layer`] field, it should set that field to `None`.
432    ///
433    /// When `needs_compositing` is false, this method will use a more efficient
434    /// way to apply the layer effect than actually creating a layer.
435    ///
436    /// The `offset` argument is the offset from the origin of the canvas'
437    /// coordinate system to the origin of the caller's coordinate system.
438    ///
439    /// The `clip_rect` is the rectangle (in the caller's coordinate system) to use
440    /// to clip the painting done by `painter`. It should not include the
441    /// `offset`.
442    #[allow(clippy::too_many_arguments)]
443    pub fn push_clip_rect(
444        &mut self,
445        app: &mut App,
446        needs_compositing: bool,
447        offset: Offset,
448        clip_rect: Rect,
449        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
450        clip_behavior: Clip,
451        old_layer: Option<Handle<ClipRectLayer>>,
452    ) -> Option<Handle<ClipRectLayer>> {
453        if clip_behavior == Clip::None {
454            painter(app, self, offset);
455            return None;
456        }
457        let offset_clip_rect = clip_rect.shift(offset);
458        if needs_compositing {
459            let layer = old_layer.unwrap_or_else(|| ClipRectLayer::new(app));
460            layer.set_clip_rect(app, Some(offset_clip_rect));
461            layer.set_clip_behavior(app, clip_behavior);
462            self.push_layer(
463                app,
464                layer.as_container_layer(),
465                painter,
466                offset,
467                Some(offset_clip_rect),
468            );
469            Some(layer)
470        } else {
471            self.clip_rect_and_paint(
472                offset_clip_rect,
473                clip_behavior,
474                offset_clip_rect,
475                |context| painter(app, context, offset),
476            );
477            None
478        }
479    }
480
481    /// Clip further painting using a rounded rectangle.
482    #[allow(clippy::too_many_arguments)]
483    pub fn push_clip_rrect(
484        &mut self,
485        app: &mut App,
486        needs_compositing: bool,
487        offset: Offset,
488        bounds: Rect,
489        clip_rrect: RRect,
490        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
491        clip_behavior: Clip,
492        old_layer: Option<Handle<ClipRRectLayer>>,
493    ) -> Option<Handle<ClipRRectLayer>> {
494        if clip_behavior == Clip::None {
495            painter(app, self, offset);
496            return None;
497        }
498        let offset_bounds = bounds.shift(offset);
499        let offset_clip_rrect = clip_rrect.shift(offset);
500        if needs_compositing {
501            let layer = old_layer.unwrap_or_else(|| ClipRRectLayer::new(app));
502            layer.set_clip_rrect(app, Some(offset_clip_rrect));
503            layer.set_clip_behavior(app, clip_behavior);
504            self.push_layer(
505                app,
506                layer.as_container_layer(),
507                painter,
508                offset,
509                Some(offset_bounds),
510            );
511            Some(layer)
512        } else {
513            self.clip_rrect_and_paint(offset_clip_rrect, clip_behavior, offset_bounds, |context| {
514                painter(app, context, offset)
515            });
516            None
517        }
518    }
519
520    /// Clip further painting using a path.
521    #[allow(clippy::too_many_arguments)]
522    pub fn push_clip_path(
523        &mut self,
524        app: &mut App,
525        needs_compositing: bool,
526        offset: Offset,
527        bounds: Rect,
528        clip_path: Path,
529        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
530        clip_behavior: Clip,
531        old_layer: Option<Handle<ClipPathLayer>>,
532    ) -> Option<Handle<ClipPathLayer>> {
533        if clip_behavior == Clip::None {
534            painter(app, self, offset);
535            return None;
536        }
537        let offset_bounds = bounds.shift(offset);
538        let offset_clip_path = clip_path.shift(offset);
539        if needs_compositing {
540            let layer = old_layer.unwrap_or_else(|| ClipPathLayer::new(app));
541            layer.set_clip_path(app, Some(offset_clip_path));
542            layer.set_clip_behavior(app, clip_behavior);
543            self.push_layer(
544                app,
545                layer.as_container_layer(),
546                painter,
547                offset,
548                Some(offset_bounds),
549            );
550            Some(layer)
551        } else {
552            self.clip_path_and_paint(&offset_clip_path, clip_behavior, offset_bounds, |context| {
553                painter(app, context, offset)
554            });
555            None
556        }
557    }
558
559    /// Transform further painting using a matrix.
560    ///
561    /// The `offset` argument is the offset to pass to `painter` and the offset to
562    /// the origin used by `transform`.
563    ///
564    /// The `transform` argument is the [`Matrix4`] with which to transform the
565    /// coordinate system while calling `painter`. It should not include `offset`.
566    /// It is applied effectively after applying `offset`.
567    pub fn push_transform(
568        &mut self,
569        app: &mut App,
570        needs_compositing: bool,
571        offset: Offset,
572        transform: Matrix4,
573        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
574        old_layer: Option<Handle<TransformLayer>>,
575    ) -> Option<Handle<TransformLayer>> {
576        let (dx, dy) = (offset.dx() as f32, offset.dy() as f32);
577        let effective_transform = Matrix4::translation(dx, dy)
578            .then(&transform)
579            .then(&Matrix4::translation(-dx, -dy));
580        if needs_compositing {
581            let layer = old_layer.unwrap_or_else(|| TransformLayer::new(app));
582            layer.set_transform(app, effective_transform);
583            let child_paint_bounds =
584                inverse_transform_rect(effective_transform, self.estimated_bounds);
585            self.push_layer(
586                app,
587                layer.as_container_layer(),
588                painter,
589                offset,
590                Some(child_paint_bounds),
591            );
592            Some(layer)
593        } else {
594            self.canvas().save();
595            self.canvas().concat(&effective_transform);
596            painter(app, self, offset);
597            self.canvas().restore();
598            None
599        }
600    }
601
602    /// Blend further painting with an alpha value.
603    ///
604    /// The `offset` argument indicates an offset to apply to all the children
605    /// (the rendering created by `painter`).
606    ///
607    /// The `alpha` argument is the alpha value to use when blending the painting
608    /// done by `painter`. An alpha value of 0 means the painting is fully
609    /// transparent and an alpha value of 255 means the painting is fully opaque.
610    pub fn push_opacity(
611        &mut self,
612        app: &mut App,
613        offset: Offset,
614        alpha: i32,
615        painter: impl FnOnce(&mut App, &mut PaintingContext, Offset),
616        old_layer: Option<Handle<OpacityLayer>>,
617    ) -> Handle<OpacityLayer> {
618        let layer = old_layer.unwrap_or_else(|| OpacityLayer::new(app));
619        layer.set_alpha(app, alpha);
620        layer.set_offset(app, offset);
621        self.push_layer(app, layer.as_container_layer(), painter, Offset::ZERO, None);
622        layer
623    }
624}
625
626impl ClipContext for PaintingContext {
627    /// The canvas on which to paint.
628    ///
629    /// The current canvas can change whenever you paint a child using this
630    /// context, which means it's fragile to hold a reference to the canvas
631    /// returned by this getter.
632    fn canvas(&mut self) -> &mut Canvas {
633        if self.canvas.is_none() {
634            self.start_recording();
635        }
636        self.canvas.as_mut().expect("recording")
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    use std::cell::Cell;
643    use std::rc::Rc;
644    use waft_foundation::AppCell;
645
646    use waft_embedder::{Color, Effect, EngineLayer, Layer, Paint, SceneBuilder, Size};
647
648    use super::*;
649    use crate::box_::{AnyRenderBox, BoxConstraints, RenderBox, RenderBoxData};
650    use crate::layer::{AnyOffsetLayer, ContainerLayer, ErasedLayer, OpacityLayer};
651    use crate::object::{RenderHandle, RenderObject, RenderObjectData};
652    use waft_painting::AlignmentGeometry;
653
654    use crate::pipeline_owner::PipelineOwner;
655    use crate::testing::{EnginePhase, layout_with, pump_frame, test_pipeline_owner};
656
657    /// Paints one rect and counts its paints. A repaint boundary when told to be, compositing
658    /// through an `OpacityLayer` with `alpha`.
659    struct Leaf {
660        render_object: RenderObjectData,
661        render_box: RenderBoxData,
662        repaint_boundary: bool,
663        alpha: i32,
664        paints: Rc<Cell<u32>>,
665    }
666
667    impl RenderObject for Leaf {
668        crate::render_object_accessors!();
669
670        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
671            let size = self.constraints(app).smallest();
672            self.set_size(app, size);
673        }
674
675        fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
676            self.get(app).repaint_boundary
677        }
678
679        fn update_composited_layer(
680            self: RenderHandle<Self>,
681            app: &mut App,
682            old_layer: Option<AnyOffsetLayer>,
683        ) -> AnyOffsetLayer {
684            debug_assert!(self.is_repaint_boundary(app));
685            let layer = match old_layer {
686                Some(old) => app
687                    .handle::<OpacityLayer>(old.id())
688                    .expect("Leaf reuses an OpacityLayer"),
689                None => OpacityLayer::new(app),
690            };
691            layer.set_alpha(app, self.get(app).alpha);
692            layer.as_offset_layer()
693        }
694
695        fn paint(
696            self: RenderHandle<Self>,
697            app: &mut App,
698            context: &mut PaintingContext,
699            offset: Offset,
700        ) {
701            let paints = Rc::clone(&self.get(app).paints);
702            paints.set(paints.get() + 1);
703            let paint = Paint {
704                color: Color::from_argb(255, 0, 0, 0).into(),
705                ..Paint::default()
706            };
707            context.canvas().draw_rect(offset & self.size(app), &paint);
708        }
709    }
710
711    impl RenderBox for Leaf {
712        crate::render_box_accessors!();
713
714        /// Flutter's `TestRenderObject(allowPaintBounds: true)`: paint bounds before layout.
715        fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
716            self.render_box_data(app)
717                .size
718                .map_or(Rect::ZERO, |size| Offset::ZERO & size)
719        }
720    }
721
722    /// A repaint boundary with one child, painted at the origin unless `paints_child` is off.
723    struct Parent {
724        render_object: RenderObjectData,
725        render_box: RenderBoxData,
726        child: Option<AnyRenderBox>,
727        paints_child: bool,
728        paints: Rc<Cell<u32>>,
729    }
730
731    impl RenderObject for Parent {
732        crate::render_object_accessors!();
733
734        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
735            if let Some(child) = self.get(app).child {
736                child.layout(app, BoxConstraints::tight(Size::new(50.0, 50.0)), false);
737            }
738            self.set_size(app, Size::new(100.0, 100.0));
739        }
740
741        fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
742            true
743        }
744
745        fn visit_children(
746            self: RenderHandle<Self>,
747            app: &App,
748            visitor: &mut dyn FnMut(AnyRenderObject),
749        ) {
750            if let Some(child) = self.get(app).child {
751                visitor(child.as_object());
752            }
753        }
754
755        fn paint(
756            self: RenderHandle<Self>,
757            app: &mut App,
758            context: &mut PaintingContext,
759            offset: Offset,
760        ) {
761            let paints = Rc::clone(&self.get(app).paints);
762            paints.set(paints.get() + 1);
763            if let Some(child) = self.get(app).child
764                && self.get(app).paints_child
765            {
766                context.paint_child(app, child.as_object(), offset);
767            }
768        }
769    }
770
771    impl RenderBox for Parent {
772        crate::render_box_accessors!();
773    }
774
775    struct Tree {
776        parent: RenderHandle<Parent>,
777        leaf: RenderHandle<Leaf>,
778        parent_paints: Rc<Cell<u32>>,
779        leaf_paints: Rc<Cell<u32>>,
780    }
781
782    /// A parent laid out at 100x100 in the test view, holding a leaf.
783    fn tree(app: &mut App, leaf_is_boundary: bool) -> Tree {
784        let leaf_paints = Rc::new(Cell::new(0));
785        let parent_paints = Rc::new(Cell::new(0));
786        let leaf = RenderHandle::new_box(
787            app,
788            Leaf {
789                render_object: RenderObjectData::new(),
790                render_box: RenderBoxData::new(),
791                repaint_boundary: leaf_is_boundary,
792                alpha: 255,
793                paints: Rc::clone(&leaf_paints),
794            },
795        );
796        let parent = RenderHandle::new_box(
797            app,
798            Parent {
799                render_object: RenderObjectData::new(),
800                render_box: RenderBoxData::new(),
801                child: Some(leaf.as_box()),
802                paints_child: true,
803                paints: Rc::clone(&parent_paints),
804            },
805        );
806        parent.adopt_child(app, leaf.as_object());
807        layout_with(
808            app,
809            parent.as_box(),
810            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
811            AlignmentGeometry::CENTER,
812            EnginePhase::Layout,
813        );
814        Tree {
815            parent,
816            leaf,
817            parent_paints,
818            leaf_paints,
819        }
820    }
821
822    fn paints(tree: &Tree) -> (u32, u32) {
823        (tree.parent_paints.get(), tree.leaf_paints.get())
824    }
825
826    fn leaf_layer_attached(app: &App, tree: &Tree) -> bool {
827        tree.leaf
828            .as_object()
829            .debug_layer(app)
830            .expect("leaf has a layer")
831            .as_layer()
832            .attached(app)
833    }
834
835    /// `object_test.dart`: `nodesNeedingPaint updated with paint changes`.
836    #[test]
837    fn nodes_needing_paint_updated_with_paint_changes() {
838        let cell = AppCell::new();
839        let mut app = cell.borrow_mut();
840        let owner = PipelineOwner::new(&mut app, None, None);
841        let node = RenderHandle::new_box(
842            &mut app,
843            Leaf {
844                render_object: RenderObjectData::new(),
845                render_box: RenderBoxData::new(),
846                repaint_boundary: true,
847                alpha: 255,
848                paints: Rc::new(Cell::new(0)),
849            },
850        );
851        node.as_object().attach(&mut app, owner.handle());
852        assert!(owner.nodes_needing_paint(&app).is_empty());
853
854        node.mark_needs_paint(&mut app);
855        let root = OpacityLayer::new(&mut app);
856        root.as_layer().attach(&mut app, node.as_object().id());
857        node.as_object()
858            .schedule_initial_paint(&mut app, root.as_container_layer());
859        assert!(owner.nodes_needing_paint(&app).contains(&node.as_object()));
860
861        owner.flush_compositing_bits(&mut app);
862        owner.flush_paint(&mut app);
863        assert!(owner.nodes_needing_paint(&app).is_empty());
864    }
865
866    #[test]
867    fn child_boundary_repaints_without_its_parent() {
868        let cell = AppCell::new();
869        let mut app = cell.borrow_mut();
870        let tree = tree(&mut app, true);
871        pump_frame(&mut app, EnginePhase::Paint);
872        assert_eq!(paints(&tree), (1, 1));
873        assert!(leaf_layer_attached(&app, &tree));
874        let parent_layer = tree.parent.as_object().debug_layer(&app).expect("parent");
875        let leaf_layer = tree.leaf.as_object().debug_layer(&app).expect("leaf");
876        assert_eq!(leaf_layer.as_layer().parent(&app), Some(parent_layer));
877
878        tree.leaf.mark_needs_paint(&mut app);
879        assert_eq!(
880            test_pipeline_owner(&mut app).nodes_needing_paint(&app),
881            vec![tree.leaf.as_object()]
882        );
883        pump_frame(&mut app, EnginePhase::Paint);
884        assert_eq!(paints(&tree), (1, 2));
885        let parent_layer = tree.parent.as_object().debug_layer(&app).expect("parent");
886        let leaf_layer = tree.leaf.as_object().debug_layer(&app).expect("leaf");
887        assert_eq!(leaf_layer.as_layer().parent(&app), Some(parent_layer));
888    }
889
890    #[test]
891    fn composited_layer_update_does_not_repaint() {
892        let cell = AppCell::new();
893        let mut app = cell.borrow_mut();
894        let tree = tree(&mut app, true);
895        pump_frame(&mut app, EnginePhase::Paint);
896
897        tree.leaf.get_mut(&mut app).alpha = 128;
898        tree.leaf.mark_needs_composited_layer_update(&mut app);
899        assert!(
900            tree.leaf
901                .as_object()
902                .debug_needs_composited_layer_update(&app)
903        );
904        pump_frame(&mut app, EnginePhase::Paint);
905        assert_eq!(paints(&tree), (1, 1));
906        let layer = tree.leaf.as_object().debug_layer(&app).expect("layer");
907        let opacity = app
908            .handle::<OpacityLayer>(layer.id())
909            .expect("OpacityLayer");
910        assert_eq!(opacity.alpha(&app), Some(128));
911    }
912
913    /// `layers_test.dart`: `non-painted layers are detached`.
914    #[test]
915    fn unpainted_boundary_is_detached_and_skipped() {
916        let cell = AppCell::new();
917        let mut app = cell.borrow_mut();
918        let tree = tree(&mut app, true);
919        pump_frame(&mut app, EnginePhase::Paint);
920        assert!(leaf_layer_attached(&app, &tree));
921
922        tree.parent.get_mut(&mut app).paints_child = false;
923        tree.parent.mark_needs_paint(&mut app);
924        pump_frame(&mut app, EnginePhase::Paint);
925        assert_eq!(paints(&tree), (2, 1));
926        assert!(!leaf_layer_attached(&app, &tree));
927
928        tree.leaf.mark_needs_paint(&mut app);
929        pump_frame(&mut app, EnginePhase::Paint);
930        assert_eq!(
931            paints(&tree),
932            (2, 1),
933            "a detached boundary is not repainted"
934        );
935        assert!(tree.leaf.as_object().debug_needs_paint(&app));
936
937        tree.parent.get_mut(&mut app).paints_child = true;
938        tree.parent.mark_needs_paint(&mut app);
939        pump_frame(&mut app, EnginePhase::Paint);
940        assert_eq!(paints(&tree), (3, 2));
941        assert!(leaf_layer_attached(&app, &tree));
942    }
943
944    #[test]
945    fn non_boundary_child_paints_into_the_parent_picture() {
946        let cell = AppCell::new();
947        let mut app = cell.borrow_mut();
948        let tree = tree(&mut app, false);
949        pump_frame(&mut app, EnginePhase::Paint);
950        assert_eq!(paints(&tree), (1, 1));
951        assert!(tree.leaf.as_object().debug_layer(&app).is_none());
952
953        tree.leaf.mark_needs_paint(&mut app);
954        assert_eq!(
955            test_pipeline_owner(&mut app).nodes_needing_paint(&app),
956            vec![tree.parent.as_object()]
957        );
958        pump_frame(&mut app, EnginePhase::Paint);
959        assert_eq!(paints(&tree), (2, 2));
960    }
961
962    #[test]
963    fn composing_the_root_draws_the_child_boundary_through_its_layer() {
964        let cell = AppCell::new();
965        let mut app = cell.borrow_mut();
966        let tree = tree(&mut app, true);
967        tree.leaf.get_mut(&mut app).alpha = 128;
968        pump_frame(&mut app, EnginePhase::Paint);
969
970        let layer = tree.parent.as_object().layer(&app).expect("painted");
971        let scene = layer.build_scene(&mut app, SceneBuilder::new());
972        let parent = only_container(&scene.root.children);
973        let child = only_container(&parent.children);
974        assert!(
975            matches!(child.effect, Effect::Opacity { alpha: 128, .. }),
976            "the child's OpacityLayer: {:?}",
977            child.effect
978        );
979        assert!(
980            matches!(child.children.as_slice(), [Layer::DisplayList(_)]),
981            "the child's picture: {:?}",
982            child.children
983        );
984    }
985
986    /// The one container among `children`, ignoring the pictures beside it.
987    fn only_container(children: &[Layer]) -> &EngineLayer {
988        let mut containers = children.iter().filter_map(|child| match child {
989            Layer::Container(container) => Some(container),
990            _ => None,
991        });
992        let container = containers.next().expect("a container");
993        assert!(containers.next().is_none(), "one container: {children:?}");
994        container
995    }
996}