Skip to main content

valo_dl/
builder.rs

1use std::sync::Arc;
2
3use valo_geometry::{Color, FillRule, Matrix, Path, PathBuilder, PathElement, Point, Rect};
4
5use crate::list::Recording;
6use crate::{
7    Backdrop, Bounds, ClipOp, DisplayList, Image, MaskKind, Op, Paint, Sampling, SpotShadow,
8};
9
10/// `DisplayListBuilder` records drawing commands into an immutable display list.
11///
12/// Recording is GPU-free and may run on any thread. The builder resolves bounds,
13/// clips, layer extents, and ordering metadata so rendering does not need to
14/// rediscover them.
15pub struct DisplayListBuilder {
16    ops: Vec<Op>,
17    /// The open scopes, innermost last: the root scope at the bottom, closed
18    /// by `build`, and one per open save or save layer.
19    scopes: Vec<Scope>,
20    /// The depth-slot counter: ONE line for the whole list (Impeller's
21    /// `current_depth_`) — layer children continue it, never restart it.
22    slots: u32,
23    bounds: Bounds,
24    /// The root's group-opacity oracle: what an enclosing layer that embeds
25    /// this list learns about its children.
26    root: GroupOpacity,
27}
28
29/// `Scope` is one open scope — the root, a save, or a save layer — and
30/// everything its restore closes: the transform and clips its children see,
31/// the clips made in it, and, for a save layer, what its restore backpatches.
32struct Scope {
33    transform: Matrix,
34    clip: ClipState,
35    /// Ops indexes of the clips made in this scope, awaiting the expiry its
36    /// restore records.
37    pending_clips: Vec<usize>,
38    /// Set on a save layer's scope.
39    layer: Option<LayerScope>,
40}
41
42/// `ClipState` is where a scope's children can show, list-root space:
43/// unbounded where nothing clips them. Where they can show nowhere, the
44/// scope is a nop: it records nothing more (Flutter's `is_nop`).
45#[derive(Clone, Copy)]
46struct ClipState {
47    /// What a child is culled by: one that shows nowhere inside it is
48    /// dropped, and its bounds are cropped by it.
49    cull: Bounds,
50    /// What the innermost open layer's content bounds are cropped by: the
51    /// clips made since it opened, with its bounds hint. Clips around a
52    /// layer do not crop its content, since a filter on the layer reads past
53    /// them (Flutter's `layer_state`).
54    layer_content: Bounds,
55}
56
57impl ClipState {
58    /// `UNCLIPPED` is the root's: its children show anywhere.
59    const UNCLIPPED: Self = Self {
60        cull: Bounds::Unbounded,
61        layer_content: Bounds::Unbounded,
62    };
63
64    /// `NOWHERE` is a nop scope's: nothing recorded in it could show.
65    const NOWHERE: Self = Self {
66        cull: Bounds::Empty,
67        layer_content: Bounds::Empty,
68    };
69
70    /// `is_nop` reports whether the scope's children can show nowhere.
71    fn is_nop(&self) -> bool {
72        self.cull.is_empty() || self.layer_content.is_empty()
73    }
74}
75
76/// `Footprint` is where one recorded child may show: cropped by the clip,
77/// for culling and the list's bounds, and cropped only by the clips inside
78/// the innermost layer, for that layer's content bounds. Neither is empty.
79#[derive(Clone, Copy)]
80struct Footprint {
81    culled: Bounds,
82    in_layer: Bounds,
83}
84
85impl Footprint {
86    /// `cull_rect` is the rect a draw's op records for replay to cull it
87    /// by: one that fills an unclipped list may show anywhere.
88    fn cull_rect(&self) -> Rect {
89        self.culled.rect().unwrap_or(Rect::EVERYTHING)
90    }
91}
92
93/// Whether a group's alpha distributes over its children: every child
94/// alpha-linear and no two overlapping, so scaling each child's source by α
95/// equals compositing the group at α (Flutter's `is_group_opacity_compatible`).
96/// Kept per open layer, and for the list's root so an embedded list answers
97/// for its own children.
98struct GroupOpacity {
99    /// Alpha-linear + disjoint so far. Clips leave it alone.
100    compatible: bool,
101    /// The union of the children so far. A child inside it counts as an
102    /// overlap even when it misses every earlier child: one rectangle to
103    /// test instead of every child, at the price of a few group textures
104    /// that were not needed (Flutter's `AccumulationRect`).
105    union: Bounds,
106}
107
108impl GroupOpacity {
109    fn new() -> Self {
110        Self {
111            compatible: true,
112            union: Bounds::Empty,
113        }
114    }
115
116    /// One more child: falsify on one that cannot take the group's opacity
117    /// or on the first overlap (disjoint children are what makes shared-z
118    /// elision legal).
119    fn note(&mut self, bounds: Bounds, takes_group_opacity: bool) {
120        if !self.compatible {
121            return;
122        }
123        if !takes_group_opacity || self.union.intersects(&bounds) {
124            self.compatible = false;
125            return;
126        }
127        self.union = self.union.union(&bounds);
128    }
129}
130
131/// Record-time state of an open `save_layer` scope.
132struct LayerScope {
133    /// The `Op::SaveLayer` to backpatch at restore.
134    op_index: usize,
135    /// Union of the children's content bounds (list-root space, cropped by
136    /// the clips inside the layer and the hint).
137    bounds: Bounds,
138    /// Whether the children can take a group alpha.
139    group: GroupOpacity,
140    /// The paint the layer composites with, whose image filter spreads or
141    /// moves the layer's content, and the transform where it applies, which
142    /// maps the layer's local coordinates into list-root space.
143    composite_paint: Paint,
144    transform: Matrix,
145    /// The clip where the layer opens, cropped by the hint: the op's
146    /// `clip_bounds`.
147    opening_clip: Bounds,
148    /// The op's `takes_group_opacity`: an enclosing group's alpha can ride
149    /// the composite, and the composite is nothing but an alpha.
150    takes_group_opacity: bool,
151    /// The op's `floods_clip`.
152    floods: bool,
153    /// The layer opens on a backdrop, which needs a texture to seed.
154    has_backdrop: bool,
155    /// A caller-supplied bounds hint is a CROP; eliding a hinted layer
156    /// would un-crop it. Conservative — Flutter tracks whether the bounds
157    /// actually clipped (`kMayClipContents`); valo vetoes on any hint until
158    /// a real caller needs the finer rule.
159    hinted: bool,
160}
161
162impl Default for DisplayListBuilder {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168impl DisplayListBuilder {
169    /// `new` creates an empty display-list builder.
170    pub fn new() -> Self {
171        Self {
172            ops: Vec::new(),
173            scopes: vec![Scope {
174                transform: Matrix::IDENTITY,
175                clip: ClipState::UNCLIPPED,
176                pending_clips: Vec::new(),
177                layer: None,
178            }],
179            slots: 0,
180            bounds: Bounds::Empty,
181            root: GroupOpacity::new(),
182        }
183    }
184
185    // ── transform stack (canvas semantics) ─────────────────────────────────
186
187    /// `save` preserves the current transform and clip until the matching `restore`.
188    pub fn save(&mut self) {
189        let top = self.top();
190        let scope = Scope {
191            transform: top.transform,
192            clip: top.clip,
193            pending_clips: Vec::new(),
194            layer: None,
195        };
196        self.scopes.push(scope);
197        self.ops.push(Op::Save);
198    }
199
200    /// `save_count` returns the current canvas save-stack depth.
201    ///
202    /// A new builder starts at one. Each `save` or save-layer operation
203    /// increments the count, and each matched `restore` decrements it. Hosts
204    /// can use the value to verify that callbacks leave shared canvas state balanced.
205    pub fn save_count(&self) -> usize {
206        self.scopes.len()
207    }
208
209    /// `save_layer` begins an offscreen layer composited with `paint` at `restore`.
210    ///
211    /// `bounds_hint` is a local-space crop, not merely an allocation hint;
212    /// content outside it is discarded. Pass `None` to derive bounds from the
213    /// recorded children and active clip.
214    pub fn save_layer(&mut self, bounds_hint: Option<Rect>, paint: &Paint) {
215        self.save_layer_inner(bounds_hint, paint, None, None);
216    }
217
218    /// `save_layer_mask` begins a mask layer closed by `restore`.
219    ///
220    /// The layer's pixels become luminance or alpha coverage according to
221    /// `kind`, retaining enclosing content only where the mask has coverage.
222    /// `bounds_hint` crops the mask in local space.
223    pub fn save_layer_mask(&mut self, bounds_hint: Option<Rect>, kind: MaskKind) {
224        let paint = Paint {
225            blend_mode: crate::BlendMode::DstIn,
226            ..Paint::default()
227        };
228        self.save_layer_inner(bounds_hint, &paint, Some(kind), None);
229    }
230
231    /// `save_layer_backdrop` begins a layer that OPENS pre-filled with the
232    /// [`Backdrop`]-filtered scene beneath it (frosted glass). Children
233    /// paint over that glass, and `restore` composites glass + children as
234    /// one image with `paint` — so a group alpha fades them together
235    /// (Flutter's `saveLayer(bounds, paint, backdrop)`).
236    ///
237    /// Without `bounds_hint` the layer covers the active clip — a backdrop
238    /// reads everything beneath it, so a hint-less, clip-less list records
239    /// unbounded bounds; hint the layer when the list will be embedded.
240    pub fn save_layer_backdrop(
241        &mut self,
242        bounds_hint: Option<Rect>,
243        paint: &Paint,
244        backdrop: Backdrop,
245    ) {
246        let backdrop = (!backdrop.filter.is_nop()).then_some(backdrop);
247        self.save_layer_inner(bounds_hint, paint, None, backdrop);
248    }
249
250    fn save_layer_inner(
251        &mut self,
252        bounds_hint: Option<Rect>,
253        paint: &Paint,
254        mask_composite: Option<MaskKind>,
255        backdrop: Option<Backdrop>,
256    ) {
257        // A save layer's paint takes no mask blur: Flutter's display list
258        // leaves it out of a save layer's attributes
259        // (`kSaveLayerWithPaintFlags`), and Impeller has no way to apply one.
260        let paint = Paint {
261            mask_blur: None,
262            ..paint.clone()
263        };
264        if self.top().clip.is_nop() || paint.is_invisible() {
265            // Nothing the layer holds could show: a nop scope (Flutter's
266            // `saveLayer` with no effect).
267            self.save();
268            self.top_mut().clip = ClipState::NOWHERE;
269            return;
270        }
271        let top = self.top();
272        let transform = top.transform;
273        let root_hint =
274            bounds_hint.map_or(Bounds::Unbounded, |hint| Bounds::of(hint).map(&transform));
275        // A filter on the layer reads past the clip, so the children are
276        // culled by what the filter reads to fill the clip (Flutter's
277        // `resetDeviceCullRect` with the filter's input bounds).
278        let cull = paint.device_effect_input_bounds(&top.clip.cull, &transform);
279        let layer = LayerScope {
280            op_index: self.ops.len(),
281            bounds: Bounds::Empty,
282            group: GroupOpacity::new(),
283            composite_paint: paint.clone(),
284            transform,
285            // The hint crops the children, so it joins every clip they see.
286            opening_clip: top.clip.cull.intersect(&root_hint),
287            takes_group_opacity: paint.takes_group_opacity(),
288            floods: floods_its_clip(&paint, backdrop.is_some()),
289            has_backdrop: backdrop.is_some(),
290            hinted: bounds_hint.is_some(),
291        };
292        let clip = ClipState {
293            cull: cull.intersect(&root_hint),
294            layer_content: root_hint,
295        };
296        // Children keep counting on the SAME depth line (Impeller's global
297        // numbering) — the layer's pass rebases against base_slot.
298        self.ops.push(Op::SaveLayer {
299            paint,
300            bounds_hint,
301            mask_composite,
302            scope_bounds: Bounds::Empty, // backpatched at restore
303            clip_bounds: layer.opening_clip,
304            base_slot: self.slots,
305            composite_slot: 0,
306            floods_clip: layer.floods,
307            takes_group_opacity: layer.takes_group_opacity,
308            can_elide: false,
309            backdrop,
310        });
311        self.scopes.push(Scope {
312            transform,
313            clip,
314            pending_clips: Vec::new(),
315            layer: Some(layer),
316        });
317    }
318
319    /// `restore` closes the most recent save, layer, or mask scope.
320    ///
321    /// A restore at the base level, with no save to close, is ignored, as Flutter's
322    /// `DisplayListBuilder::Restore` and Skia's canvas ignore it: a framework that ends a picture
323    /// between a save and its restore, as Flutter's does when a child composites, restores on the
324    /// next picture's fresh canvas.
325    pub fn restore(&mut self) {
326        if self.scopes.len() == 1 {
327            return;
328        }
329        let scope = self.scopes.pop().expect("checked above");
330        self.expire_clips(scope.pending_clips);
331        if let Some(layer) = scope.layer {
332            self.close_layer(layer);
333        }
334        self.ops.push(Op::Restore);
335    }
336
337    /// `translate` offsets subsequent drawing and clipping operations.
338    pub fn translate(&mut self, tx: f32, ty: f32) {
339        self.concat(&Matrix::translation(tx, ty));
340    }
341
342    /// `scale` scales subsequent drawing and clipping operations.
343    pub fn scale(&mut self, sx: f32, sy: f32) {
344        self.concat(&Matrix::scale(sx, sy));
345    }
346
347    /// `rotate` rotates subsequent drawing and clipping operations clockwise.
348    ///
349    /// Positive angles rotate clockwise in Valo's y-down coordinate system.
350    pub fn rotate(&mut self, radians: f32) {
351        self.concat(&Matrix::rotation(radians));
352    }
353
354    /// `concat` appends a transform for subsequent drawing and clipping operations.
355    pub fn concat(&mut self, local: &Matrix) {
356        let top = self.top_mut();
357        top.transform = top.transform.then(local);
358        self.ops.push(Op::Transform(*local));
359    }
360
361    // ── clips (depth slots; expiry backpatched when the scope closes) ──────
362
363    /// `clip_rect` applies a rectangular clip until the current scope ends.
364    ///
365    /// `anti_alias` says whether the clip's edge is anti-aliased, as Skia's
366    /// and Flutter's `doAntiAlias`. An Intersect clip that is not, under a
367    /// transform that only scales and moves, cuts at the nearest whole
368    /// pixels wherever the rectangle lies, and costs the renderer nothing:
369    /// what a scroll view's or a page's clip wants. An anti-aliased one
370    /// covers the pixels its edges cross in part.
371    pub fn clip_rect(&mut self, rect: impl Into<Rect>, op: ClipOp, anti_alias: bool) {
372        let rect = rect.into();
373        self.clip_path(&rect_path(rect), FillRule::NonZero, op, anti_alias);
374    }
375
376    /// `clip_rrect` applies a rounded-rectangle clip with one corner radius.
377    ///
378    /// `anti_alias` is recorded and, for now, changes nothing: a rounded
379    /// rectangle's edge is anti-aliased either way, as in Impeller.
380    pub fn clip_rrect(&mut self, rect: impl Into<Rect>, radius: f32, op: ClipOp, anti_alias: bool) {
381        let rect = rect.into();
382        self.clip_rrect_radii(rect, [radius; 4], op, anti_alias);
383    }
384
385    /// `clip_rrect_radii` applies a rounded-rectangle clip with per-corner radii.
386    ///
387    /// `radii` is ordered clockwise as `[top-left, top-right, bottom-right, bottom-left]`.
388    /// `anti_alias` is as [`Self::clip_rrect`]'s.
389    pub fn clip_rrect_radii(
390        &mut self,
391        rect: impl Into<Rect>,
392        radii: [f32; 4],
393        op: ClipOp,
394        anti_alias: bool,
395    ) {
396        let rect = positive_rect(rect.into());
397        let mut p = PathBuilder::new();
398        p.rrect_radii(rect, radii);
399        self.clip_path(&p.build(), FillRule::NonZero, op, anti_alias);
400    }
401
402    /// `clip_rrect_radii_elliptical` applies per-corner elliptical radii.
403    ///
404    /// Each clockwise corner is `[x_radius, y_radius]`, starting at the top-left.
405    /// `anti_alias` is as [`Self::clip_rrect`]'s.
406    pub fn clip_rrect_radii_elliptical(
407        &mut self,
408        rect: impl Into<Rect>,
409        radii: [[f32; 2]; 4],
410        op: ClipOp,
411        anti_alias: bool,
412    ) {
413        let rect = positive_rect(rect.into());
414        if let Some(circular) = circular_radii(radii) {
415            return self.clip_rrect_radii(rect, circular, op, anti_alias);
416        }
417        let mut p = PathBuilder::new();
418        p.rrect_radii_elliptical(rect, radii);
419        self.clip_path(&p.build(), FillRule::NonZero, op, anti_alias);
420    }
421
422    /// `clip_path` applies a path clip until the current scope ends.
423    ///
424    /// `anti_alias` says whether the clip's edge is anti-aliased. It changes
425    /// what is drawn only for a path that is an axis-aligned rectangle, as
426    /// [`Self::clip_rect`] says; any other shape's edge is anti-aliased
427    /// either way, for now, as in Impeller.
428    ///
429    /// Clips do NOT forfeit an enclosing layer's elision (Flutter's
430    /// opacity distribution ignores clips too): a depth clip records its
431    /// own expiry slot and works identically whether the group's children
432    /// draw in a layer or in the parent, and child bounds are already
433    /// clip-cropped when the disjointness check reads them. The Cupertino
434    /// dialog depends on this — fade → clip → backdrop must keep the fade
435    /// elidable or the glass snapshots a cleared offscreen.
436    pub fn clip_path(
437        &mut self,
438        path: &Arc<Path>,
439        fill_rule: FillRule,
440        op: ClipOp,
441        anti_alias: bool,
442    ) {
443        if self.top().clip.is_nop() {
444            return;
445        }
446        let transform = self.top().transform;
447        self.shrink_clip(op, Bounds::of(path.bounds()).map(&transform));
448        if self.top().clip.is_nop() {
449            // The clip leaves the scope nothing, so the scope records
450            // nothing more, this clip included (Flutter's `is_nop`).
451            return;
452        }
453        let index = self.ops.len();
454        self.top_mut().pending_clips.push(index);
455        self.ops.push(Op::ClipPath {
456            path: Arc::clone(path),
457            fill_rule,
458            op,
459            anti_alias,
460            bounds: transform.map_rect(&path.bounds()),
461            is_axis_aligned_rect: is_rect(path) && scales_and_moves(&transform),
462            expiry_slot: 0, // backpatched by expire_clips
463        });
464    }
465
466    // ── draws (one slot each; bounds pre-clipped for the culling oracle) ───
467
468    /// `draw_paint` fills the whole clip with `paint`, as Flutter's
469    /// `Canvas.drawPaint`: a background, a tint over everything drawn so
470    /// far, or, with a blend such as [`crate::BlendMode::Clear`] or
471    /// [`crate::BlendMode::Src`], a change to every pixel the clip lets
472    /// through, which a shape could not reach.
473    ///
474    /// The paint always fills, and its mask blur is dropped, as Flutter's
475    /// display list records a paint for this draw; its colour, shader,
476    /// filters and blend apply. Where no clip bounds it, the list's bounds
477    /// become unbounded, and a save layer around it covers its own clip.
478    pub fn draw_paint(&mut self, paint: &Paint) {
479        let paint = Paint {
480            style: crate::PaintStyle::Fill,
481            mask_blur: None,
482            ..paint.clone()
483        };
484        if paint.is_nop() {
485            return;
486        }
487        let takes_group_opacity = paint.takes_group_opacity();
488        self.record_op(Bounds::Unbounded, 1, takes_group_opacity, |bounds, slot| {
489            Op::DrawPaint {
490                paint,
491                bounds,
492                slot,
493            }
494        });
495    }
496
497    /// `draw_shadow` records the shadow an occluder of `path`'s shape, filled
498    /// by `fill_rule` and painted `color`, casts from `elevation` logical
499    /// pixels above the canvas, in a view whose device pixel ratio is
500    /// `device_pixel_ratio`: Flutter's `Canvas.drawShadow`, which material
501    /// elevation draws.
502    ///
503    /// The shadow is resolved when it is drawn, as Impeller resolves it: the
504    /// path moves down by the occluder's height, `device_pixel_ratio ×
505    /// elevation` device pixels, and fills with a toned, lighter
506    /// `color` under a blur whose radius is that height over the vertical
507    /// scale of the whole transform it is drawn under, scales of the lists
508    /// and layers around it included. `transparent_occluder` is recorded and
509    /// changes nothing drawn, as in Impeller. A shadow takes no group
510    /// opacity, as in Flutter's display list.
511    pub fn draw_shadow(
512        &mut self,
513        path: &Arc<Path>,
514        fill_rule: FillRule,
515        color: Color,
516        elevation: f32,
517        transparent_occluder: bool,
518        device_pixel_ratio: f32,
519    ) {
520        if path.is_empty() || Paint::from_color(color).is_nop() {
521            return;
522        }
523        let transform = self.top().transform;
524        let Some(spot) = SpotShadow::resolve(color, elevation, device_pixel_ratio, &transform)
525        else {
526            return;
527        };
528        let moved = Matrix::translation(0.0, spot.local_drop(&transform)).map_rect(&path.bounds());
529        let local = spot.paint.effect_bounds(moved);
530        let round_rect = closed_form_shadow(path);
531        let takes_group_opacity = false;
532        self.record_op(local, 1, takes_group_opacity, |bounds, slot| {
533            Op::DrawShadow {
534                path: Arc::clone(path),
535                fill_rule,
536                color,
537                elevation,
538                transparent_occluder,
539                device_pixel_ratio,
540                round_rect,
541                bounds,
542                slot,
543            }
544        });
545    }
546
547    /// `draw_rect` records a filled or stroked rectangle.
548    pub fn draw_rect(&mut self, rect: impl Into<Rect>, paint: &Paint) {
549        let rect = rect.into();
550        if matches!(paint.style, crate::PaintStyle::Stroke(_)) {
551            // Stroked rects are stroked paths — one geometry pipeline.
552            // Zero-area rects still stroke: Skia draws them as a line.
553            return self.draw_path(&rect_path(rect), FillRule::NonZero, paint);
554        }
555        if rect.is_empty() {
556            return;
557        }
558        if is_analytic_blur(paint) {
559            self.record_rrect_blur(rect, [0.0; 4], paint);
560            return;
561        }
562        self.record_draw(rect, paint, paint.takes_group_opacity(), |bounds, slot| {
563            Op::DrawRect {
564                rect,
565                paint: paint.clone(),
566                bounds,
567                slot,
568            }
569        });
570    }
571
572    /// `draw_path` records a filled or stroked path.
573    pub fn draw_path(&mut self, path: &Arc<Path>, fill_rule: FillRule, paint: &Paint) {
574        if path.is_empty() {
575            return;
576        }
577        let scale = self.top().transform.max_scale();
578        let content_bounds = path.bounds().expand(paint.stroke_padding_at_scale(scale));
579        self.record_draw(
580            content_bounds,
581            paint,
582            paint.takes_group_opacity(),
583            |bounds, slot| Op::DrawPath {
584                path: Arc::clone(path),
585                fill_rule,
586                paint: paint.clone(),
587                content_bounds,
588                bounds,
589                slot,
590            },
591        );
592    }
593
594    /// `draw_circle` records a filled or stroked circle.
595    pub fn draw_circle(
596        &mut self,
597        center: impl Into<valo_geometry::Point>,
598        radius: f32,
599        paint: &Paint,
600    ) {
601        let mut p = PathBuilder::new();
602        p.circle(center, radius);
603        self.draw_path(&p.build(), FillRule::NonZero, paint);
604    }
605
606    /// `draw_rrect` records a rounded rectangle with one corner radius.
607    pub fn draw_rrect(&mut self, rect: impl Into<Rect>, radius: f32, paint: &Paint) {
608        let rect = rect.into();
609        self.draw_rrect_radii(rect, [radius; 4], paint);
610    }
611
612    /// `draw_rrect_radii` records a rounded rectangle with per-corner radii.
613    ///
614    /// `radii` is ordered clockwise as `[top-left, top-right, bottom-right, bottom-left]`.
615    pub fn draw_rrect_radii(&mut self, rect: impl Into<Rect>, radii: [f32; 4], paint: &Paint) {
616        let rect = positive_rect(rect.into());
617        if rect.is_empty() {
618            return;
619        }
620        if is_analytic_blur(paint) {
621            self.record_rrect_blur(rect, radii, paint);
622            return;
623        }
624        let mut p = PathBuilder::new();
625        p.rrect_radii(rect, radii);
626        self.draw_path(&p.build(), FillRule::NonZero, paint);
627    }
628
629    /// `draw_rrect_radii_elliptical` records per-corner elliptical radii.
630    ///
631    /// Each clockwise corner is `[x_radius, y_radius]`, starting at the top-left.
632    pub fn draw_rrect_radii_elliptical(
633        &mut self,
634        rect: impl Into<Rect>,
635        radii: [[f32; 2]; 4],
636        paint: &Paint,
637    ) {
638        let rect = positive_rect(rect.into());
639        if let Some(circular) = circular_radii(radii) {
640            return self.draw_rrect_radii(rect, circular, paint);
641        }
642        if rect.is_empty() {
643            return;
644        }
645        let mut p = PathBuilder::new();
646        p.rrect_radii_elliptical(rect, radii);
647        self.draw_path(&p.build(), FillRule::NonZero, paint);
648    }
649
650    /// `draw_image` records the whole image into `dst`.
651    ///
652    /// It uses linear filtering and clamps at the image edges.
653    pub fn draw_image(&mut self, image: &Image, dst: Rect, paint: &Paint) {
654        let src = Rect::new(0.0, 0.0, image.width(), image.height());
655        self.draw_image_rect(image, src, dst, Sampling::default(), paint);
656    }
657
658    /// `draw_image_rect` records a source region into `dst` with explicit sampling.
659    ///
660    /// `src` is measured in source pixels. Tiling applies when `src` extends
661    /// beyond the image bounds.
662    pub fn draw_image_rect(
663        &mut self,
664        image: &Image,
665        src: Rect,
666        dst: Rect,
667        sampling: Sampling,
668        paint: &Paint,
669    ) {
670        if dst.is_empty() || src.is_empty() {
671            return;
672        }
673        self.record_draw(dst, paint, paint.takes_group_opacity(), |bounds, slot| {
674            Op::DrawImage {
675                image: image.clone(),
676                src,
677                dst,
678                sampling,
679                paint: paint.clone(),
680                bounds,
681                slot,
682            }
683        });
684    }
685
686    /// `draw_glyph_run` records positioned glyphs drawn with `font`.
687    ///
688    /// `local_bounds` must enclose the glyph ink in local coordinates, the
689    /// font's synthesis included. `text` is the text the glyphs show, which
690    /// only a PDF reads back; `None` draws the same, its text just can't be
691    /// copied. Valo retains the supplied font and glyph positions in the
692    /// display list.
693    pub fn draw_glyph_run(
694        &mut self,
695        font: crate::RunFont,
696        paint: &Paint,
697        glyphs: Arc<Vec<crate::GlyphPos>>,
698        text: Option<crate::RunText>,
699        local_bounds: Rect,
700    ) {
701        if glyphs.is_empty() {
702            return;
703        }
704        let scale = self.top().transform.max_scale();
705        let content_bounds = local_bounds.expand(paint.stroke_padding_at_scale(scale));
706        // A run never takes a group's alpha (Flutter's rule): its glyphs may
707        // overlap, nothing says whether they do, and an overlap faded glyph
708        // by glyph darkens.
709        let takes_group_opacity = false;
710        self.record_draw(
711            content_bounds,
712            paint,
713            takes_group_opacity,
714            |bounds, slot| Op::GlyphRun {
715                font,
716                paint: paint.clone(),
717                glyphs,
718                text,
719                content_bounds,
720                bounds,
721                slot,
722            },
723        );
724    }
725
726    /// `replay` records `op` again, as the call that recorded it: Flutter's
727    /// display list dispatching to a builder. Drawing a recorded part of a
728    /// list on its own, such as a shadow an exporter draws as pixels, replays
729    /// its ops between the transforms and clips around them.
730    pub fn replay(&mut self, op: &Op) {
731        match op {
732            Op::Save => self.save(),
733            Op::SaveLayer {
734                paint,
735                bounds_hint,
736                mask_composite,
737                backdrop,
738                ..
739            } => match (mask_composite, backdrop) {
740                (Some(kind), _) => self.save_layer_mask(*bounds_hint, *kind),
741                (None, Some(backdrop)) => {
742                    self.save_layer_backdrop(*bounds_hint, paint, backdrop.clone())
743                }
744                (None, None) => self.save_layer(*bounds_hint, paint),
745            },
746            Op::Restore => self.restore(),
747            Op::Transform(matrix) => self.concat(matrix),
748            Op::DrawPaint { paint, .. } => self.draw_paint(paint),
749            Op::DrawRect { rect, paint, .. } => self.draw_rect(*rect, paint),
750            Op::DrawPath {
751                path,
752                fill_rule,
753                paint,
754                ..
755            } => self.draw_path(path, *fill_rule, paint),
756            Op::RRectBlur {
757                rect, radii, paint, ..
758            } => self.draw_rrect_radii(*rect, *radii, paint),
759            Op::DrawShadow {
760                path,
761                fill_rule,
762                color,
763                elevation,
764                transparent_occluder,
765                device_pixel_ratio,
766                ..
767            } => self.draw_shadow(
768                path,
769                *fill_rule,
770                *color,
771                *elevation,
772                *transparent_occluder,
773                *device_pixel_ratio,
774            ),
775            Op::ClipPath {
776                path,
777                fill_rule,
778                op,
779                anti_alias,
780                ..
781            } => self.clip_path(path, *fill_rule, *op, *anti_alias),
782            Op::DrawImage {
783                image,
784                src,
785                dst,
786                sampling,
787                paint,
788                ..
789            } => self.draw_image_rect(image, *src, *dst, *sampling, paint),
790            Op::GlyphRun {
791                font,
792                paint,
793                glyphs,
794                text,
795                content_bounds,
796                ..
797            } => self.draw_glyph_run(
798                font.clone(),
799                paint,
800                Arc::clone(glyphs),
801                text.clone(),
802                *content_bounds,
803            ),
804            Op::DrawDisplayList { list, cache, .. } => {
805                if *cache {
806                    self.draw_display_list_cached(list);
807                } else {
808                    self.draw_display_list(list);
809                }
810            }
811        }
812    }
813
814    /// `draw_display_list` records a nested display list by shared reference.
815    pub fn draw_display_list(&mut self, list: &Arc<DisplayList>) {
816        self.embed_display_list(list, false);
817    }
818
819    /// `draw_display_list_cached` records a nested list as a raster-cache candidate.
820    ///
821    /// Use it for stable, repeatedly drawn lists whose recording is expensive.
822    /// The renderer may still replay the list directly when caching is unsuitable.
823    pub fn draw_display_list_cached(&mut self, list: &Arc<DisplayList>) {
824        self.embed_display_list(list, true);
825    }
826
827    fn embed_display_list(&mut self, list: &Arc<DisplayList>, cache: bool) {
828        // The list answers for its own children (Flutter's
829        // `can_apply_group_opacity`): a picture of one draw elides as the
830        // draw would.
831        let slots = list.depth_slots();
832        self.record_op(
833            list.bounds(),
834            slots,
835            list.supports_opacity(),
836            |bounds, last_slot| Op::DrawDisplayList {
837                list: Arc::clone(list),
838                bounds,
839                base_slot: last_slot - slots,
840                cache,
841            },
842        );
843    }
844
845    // ── build ──────────────────────────────────────────────────────────────
846
847    /// `build` consumes the builder and returns its immutable display list.
848    ///
849    /// Any unmatched save scopes are closed before the list is finalized.
850    pub fn build(mut self) -> DisplayList {
851        // Unbalanced saves are a recording bug, but a recoverable one: close
852        // them so replay's stack discipline holds.
853        while self.scopes.len() > 1 {
854            self.restore();
855        }
856        let root = self.scopes.pop().expect("the root scope is never restored");
857        self.expire_clips(root.pending_clips); // root-scope clips live to end-of-list
858        DisplayList::new(
859            self.ops,
860            Recording {
861                bounds: self.bounds,
862                depth_slots: self.slots,
863                supports_opacity: self.root.compatible,
864            },
865        )
866    }
867
868    // ── internals ──────────────────────────────────────────────────────────
869
870    fn top(&self) -> &Scope {
871        self.scopes.last().expect("scope stack never empty")
872    }
873
874    fn top_mut(&mut self) -> &mut Scope {
875        self.scopes.last_mut().expect("scope stack never empty")
876    }
877
878    /// `close_layer` books a save layer's composite as a child of the scope
879    /// around it and backpatches the layer's op, at its restore. Order
880    /// matters: the layer's clips expired first (the caller did that), so
881    /// their slots sit inside the children's span; the composite takes the
882    /// NEXT slot on the same line.
883    fn close_layer(&mut self, layer: LayerScope) {
884        let footprint = self.root_footprint(layer.composite_region());
885        let composite_slot = self.record_child(footprint, 1, layer.takes_group_opacity);
886        self.backpatch_layer(&layer, composite_slot);
887    }
888
889    /// `backpatch_layer` writes what the layer's children decided into its
890    /// op: its content, its composite's slot, and whether it may elide.
891    fn backpatch_layer(&mut self, layer: &LayerScope, composite: u32) {
892        let Op::SaveLayer {
893            scope_bounds,
894            composite_slot,
895            can_elide,
896            ..
897        } = &mut self.ops[layer.op_index]
898        else {
899            unreachable!("LayerScope.op_index always points at SaveLayer");
900        };
901        *scope_bounds = layer.bounds;
902        *composite_slot = composite;
903        *can_elide = layer.can_elide();
904    }
905
906    /// One-quad closed-form blurred (r)rect; the quad spans the 3σ spread,
907    /// which is the paint's effect padding (an analytic blur has no image
908    /// filter).
909    fn record_rrect_blur(&mut self, rect: Rect, radii: [f32; 4], paint: &Paint) {
910        self.record_draw(rect, paint, paint.takes_group_opacity(), |bounds, slot| {
911            Op::RRectBlur {
912                rect,
913                radii: valo_geometry::constrain_radii(&rect, radii),
914                paint: paint.clone(),
915                bounds,
916                slot,
917            }
918        });
919    }
920
921    /// `record_draw` is the gate every draw goes through: a draw whose
922    /// paint does nothing, or that shows nowhere, is dropped; any other is
923    /// booked as a child of the scope, and `make` builds its op from the rect
924    /// replay culls it by and its slot. `local` is the draw's ink in local
925    /// coordinates, before the paint's effects; `takes_group_opacity` is
926    /// whether a group's alpha can ride the draw: its paint's rule for a
927    /// shape or an image, never for a glyph run.
928    fn record_draw(
929        &mut self,
930        local: Rect,
931        paint: &Paint,
932        takes_group_opacity: bool,
933        make: impl FnOnce(Rect, u32) -> Op,
934    ) {
935        if paint.is_nop() {
936            return;
937        }
938        let local = paint.effect_bounds(local);
939        self.record_op(local, 1, takes_group_opacity, make);
940    }
941
942    /// `record_op` records an op that shows within `local`: dropped when it
943    /// shows nowhere, else booked as a child of `slots` slots and pushed as
944    /// `make` builds it from its cull rect and its last slot.
945    fn record_op(
946        &mut self,
947        local: Bounds,
948        slots: u32,
949        takes_group_opacity: bool,
950        make: impl FnOnce(Rect, u32) -> Op,
951    ) {
952        let Some(footprint) = self.footprint(&local) else {
953            return;
954        };
955        let last_slot = self.record_child(Some(footprint), slots, takes_group_opacity);
956        self.ops.push(make(footprint.cull_rect(), last_slot));
957    }
958
959    /// `footprint` maps local bounds into list-root space and crops them by
960    /// both clips; `None` = provably invisible, don't record.
961    fn footprint(&self, local: &Bounds) -> Option<Footprint> {
962        self.root_footprint(local.map(&self.top().transform))
963    }
964
965    /// `root_footprint` crops bounds already in list-root space.
966    fn root_footprint(&self, bounds: Bounds) -> Option<Footprint> {
967        let clip = self.top().clip;
968        let footprint = Footprint {
969            culled: bounds.intersect(&clip.cull),
970            in_layer: bounds.intersect(&clip.layer_content),
971        };
972        let shows = !footprint.culled.is_empty() && !footprint.in_layer.is_empty();
973        shows.then_some(footprint)
974    }
975
976    /// Intersect clips shrink the recorded clip bounds; Difference is kept
977    /// conservative (bounds unchanged — correct, just not tighter).
978    fn shrink_clip(&mut self, op: ClipOp, shape_bounds: Bounds) {
979        if op == ClipOp::Difference {
980            return;
981        }
982        let clip = &mut self.top_mut().clip;
983        clip.cull = clip.cull.intersect(&shape_bounds);
984        clip.layer_content = clip.layer_content.intersect(&shape_bounds);
985    }
986
987    /// `expire_clips` closes a scope's `pending` clips. Closing a scope that
988    /// recorded clips consumes ONE slot — that slot is every pending clip's
989    /// expiry: scope draws sit below it (ceilinged), later draws above it
990    /// (free). This is how expiry stays record-time.
991    fn expire_clips(&mut self, pending: Vec<usize>) {
992        if pending.is_empty() {
993            return;
994        }
995        self.slots += 1;
996        for index in pending {
997            let Op::ClipPath { expiry_slot, .. } = &mut self.ops[index] else {
998                unreachable!("pending clips index only ClipPath ops");
999            };
1000            *expiry_slot = self.slots;
1001        }
1002    }
1003
1004    /// `record_child` books one child of the current scope: `slots` slots
1005    /// on the depth line and — when it shows anywhere — its `footprint` in
1006    /// the list's bounds and in the innermost open layer's oracle. Returns
1007    /// the child's last slot.
1008    fn record_child(
1009        &mut self,
1010        footprint: Option<Footprint>,
1011        slots: u32,
1012        takes_group_opacity: bool,
1013    ) -> u32 {
1014        self.slots += slots;
1015        if let Some(footprint) = footprint {
1016            self.bounds = self.bounds.union(&footprint.culled);
1017            self.note_layer_child(footprint.in_layer, takes_group_opacity);
1018        }
1019        self.slots
1020    }
1021
1022    /// Feed the innermost open layer's oracle, or the root's outside any
1023    /// layer: union the layer's bounds and note the child for group opacity.
1024    fn note_layer_child(&mut self, bounds: Bounds, takes_group_opacity: bool) {
1025        let innermost = self
1026            .scopes
1027            .iter_mut()
1028            .rev()
1029            .find_map(|scope| scope.layer.as_mut());
1030        let Some(layer) = innermost else {
1031            self.root.note(bounds, takes_group_opacity);
1032            return;
1033        };
1034        layer.bounds = layer.bounds.union(&bounds);
1035        layer.group.note(bounds, takes_group_opacity);
1036    }
1037}
1038
1039impl LayerScope {
1040    /// `can_elide` is the op's `can_elide`: the children take the group's
1041    /// alpha and none overlaps, the composite is nothing but that alpha, no
1042    /// backdrop needs a texture to seed and no hint crops the children.
1043    fn can_elide(&self) -> bool {
1044        self.group.compatible && self.takes_group_opacity && !self.has_backdrop && !self.hinted
1045    }
1046
1047    /// `composite_region` is where the layer's composite shows, list-root
1048    /// space: its whole opening clip when it floods, else its content
1049    /// through the paint's image filter.
1050    fn composite_region(&self) -> Bounds {
1051        if self.floods {
1052            self.opening_clip
1053        } else {
1054            self.composite_paint
1055                .device_effect_bounds(&self.bounds, &self.transform)
1056        }
1057    }
1058}
1059
1060/// `floods_its_clip` reports whether a save layer with `paint` paints its
1061/// whole clip whatever its children draw: a destructive blend changes the
1062/// parent where the layer is transparent, a filter that colours
1063/// transparent pixels has output outside the children's ink, and a backdrop
1064/// layer OPENS full of the filtered parent.
1065fn floods_its_clip(paint: &Paint, has_backdrop: bool) -> bool {
1066    paint.blend_mode.is_destructive() || paint.reveals_transparent() || has_backdrop
1067}
1068
1069/// `Some(circular)` when every corner's rx equals its ry — the case the
1070/// analytic rrect pipelines (blur shadows, uniform clips) can take.
1071fn circular_radii(radii: [[f32; 2]; 4]) -> Option<[f32; 4]> {
1072    radii
1073        .iter()
1074        .all(|[x, y]| x == y)
1075        .then(|| radii.map(|[x, _]| x))
1076}
1077
1078// Flutter's RRect bridge accepts inverted edges and normalizes them before
1079// creating the engine round rect. CupertinoActivityIndicator relies on this.
1080fn positive_rect(rect: Rect) -> Rect {
1081    let x = if rect.width < 0.0 {
1082        rect.x + rect.width
1083    } else {
1084        rect.x
1085    };
1086    let y = if rect.height < 0.0 {
1087        rect.y + rect.height
1088    } else {
1089        rect.y
1090    };
1091    Rect::new(x, y, rect.width.abs(), rect.height.abs())
1092}
1093
1094/// Solid + mask blur = the closed-form quad (Impeller's shadow gate,
1095/// Canvas::IsShadowBlurDrawOperation). Shaders/images take the filter path.
1096fn is_analytic_blur(paint: &Paint) -> bool {
1097    paint.mask_blur.is_some()
1098        && paint.shader.is_none()
1099        // The closed-form quad has nowhere to run a colour filter, so a
1100        // filtered shape takes the general layer path instead of silently
1101        // rendering its unfiltered colour.
1102        && paint.color_filter.is_none()
1103        && paint.effective_image_filter().is_none()
1104        && matches!(paint.style, crate::PaintStyle::Fill)
1105}
1106
1107fn rect_path(r: Rect) -> Arc<Path> {
1108    let mut p = PathBuilder::new();
1109    p.rect(r);
1110    p.build()
1111}
1112
1113/// `is_rect` reports whether `path` is one closed contour of four corners
1114/// with every side along an axis, as [`PathBuilder::rect`] builds: its shape
1115/// is its bounds (Flutter's builder asks a clip path the same, `IsRect`).
1116fn is_rect(path: &Path) -> bool {
1117    let mut elements = path.elements();
1118    let mut corners = [Point::default(); 4];
1119    for (index, corner) in corners.iter_mut().enumerate() {
1120        *corner = match (index, elements.next()) {
1121            (0, Some(PathElement::MoveTo(point))) => point,
1122            (1.., Some(PathElement::LineTo(point))) => point,
1123            _ => return false,
1124        };
1125    }
1126    let closed = elements.next() == Some(PathElement::Close) && elements.next().is_none();
1127    closed && sides_follow_axes(&corners)
1128}
1129
1130/// `sides_follow_axes` reports whether the closed polygon through `corners`
1131/// has every side along an axis, starting with either one.
1132fn sides_follow_axes(corners: &[Point; 4]) -> bool {
1133    let [a, b, c, d] = corners;
1134    let starts_along_x = a.y == b.y && b.x == c.x && c.y == d.y && d.x == a.x;
1135    let starts_along_y = a.x == b.x && b.y == c.y && c.x == d.x && d.y == a.y;
1136    starts_along_x || starts_along_y
1137}
1138
1139/// `closed_form_shadow` is the rectangle and the one circular corner radius
1140/// of `path`, when a shadow of it takes the closed-form blur: Impeller's
1141/// `SimplifyOrDrawPath` draws a closed rectangle, a rounded rectangle whose
1142/// corners are all the same, or an oval as such, and `AttemptDrawBlur` takes
1143/// a rectangle, a rounded rectangle whose common radius is circular, or a
1144/// circle, in closed form. Any other shape is blurred as a path.
1145fn closed_form_shadow(path: &Path) -> Option<(Rect, f32)> {
1146    if is_rect(path) {
1147        return Some((path.bounds(), 0.0));
1148    }
1149    if let Some((_, radii)) = path.as_round_rect() {
1150        let [x, y] = radii[0];
1151        let same = radii
1152            .iter()
1153            .all(|corner| nearly_equal(corner[0], x) && nearly_equal(corner[1], y));
1154        return (same && nearly_equal(x, y)).then(|| (path.bounds(), x));
1155    }
1156    // A square oval is a circle (Impeller's `Rect::IsSquare`, exact).
1157    let oval = path.as_oval()?;
1158    (oval.width == oval.height).then_some((oval, oval.width * 0.5))
1159}
1160
1161/// `nearly_equal` is Impeller's `ScalarNearlyEqual` at its default
1162/// tolerance, `kEhCloseEnough`.
1163fn nearly_equal(a: f32, b: f32) -> bool {
1164    (a - b).abs() <= 1e-3
1165}
1166
1167/// `scales_and_moves` reports whether `transform` only scales and moves, so
1168/// a rectangle's sides stay along the axes under it: Impeller's
1169/// `IsTranslationScaleOnly`, a mirror included.
1170fn scales_and_moves(transform: &Matrix) -> bool {
1171    let [scale_x, shear_y, shear_x, scale_y, ..] = transform.to_affine();
1172    transform.is_affine() && shear_y == 0.0 && shear_x == 0.0 && scale_x != 0.0 && scale_y != 0.0
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177    use super::*;
1178    use crate::{BlendMode, ImageFilter, MaskBlur};
1179    use valo_geometry::Color;
1180
1181    #[test]
1182    fn save_count_tracks_saves_layers_and_restores() {
1183        let mut builder = DisplayListBuilder::new();
1184        assert_eq!(builder.save_count(), 1);
1185
1186        builder.save();
1187        assert_eq!(builder.save_count(), 2);
1188
1189        builder.save_layer(None, &Paint::default());
1190        assert_eq!(builder.save_count(), 3);
1191
1192        builder.restore();
1193        assert_eq!(builder.save_count(), 2);
1194        builder.restore();
1195        assert_eq!(builder.save_count(), 1);
1196    }
1197
1198    #[test]
1199    fn a_restore_with_no_save_to_close_is_ignored_like_flutter() {
1200        let mut builder = DisplayListBuilder::new();
1201        builder.restore();
1202        assert_eq!(builder.save_count(), 1);
1203
1204        builder.draw_rect(Rect::from_ltrb(0.0, 0.0, 1.0, 1.0), &Paint::default());
1205        let list = builder.build();
1206        assert!(
1207            !list.ops().iter().any(|op| matches!(op, Op::Restore)),
1208            "nothing recorded for the ignored restore"
1209        );
1210    }
1211
1212    #[test]
1213    fn rounded_rects_normalize_inverted_edges_like_flutter() {
1214        let mut builder = DisplayListBuilder::new();
1215        builder.draw_rrect(
1216            Rect::from_ltrb(-1.0, -10.0 / 3.0, 1.0, -10.0),
1217            1.0,
1218            &Paint::from_color(Color::WHITE),
1219        );
1220
1221        let list = builder.build();
1222        let Op::DrawPath { path, .. } = &list.ops()[0] else {
1223            panic!("rounded rectangle should record as a path");
1224        };
1225        assert_eq!(
1226            path.bounds(),
1227            Rect::from_ltrb(-1.0, -10.0, 1.0, -10.0 / 3.0)
1228        );
1229    }
1230    fn red() -> Paint {
1231        Paint::from_color(Color::rgb(1.0, 0.0, 0.0))
1232    }
1233
1234    fn alpha_layer(a: f32) -> Paint {
1235        Paint::from_color(Color::rgba(0.0, 0.0, 0.0, a))
1236    }
1237
1238    /// What the one clip `record` records says of its shape: its bounds,
1239    /// whether it is a rectangle along the list's axes, and whether its
1240    /// edge is anti-aliased.
1241    fn recorded_clip(record: impl FnOnce(&mut DisplayListBuilder)) -> (Rect, bool, bool) {
1242        let mut b = DisplayListBuilder::new();
1243        record(&mut b);
1244        let dl = b.build();
1245        match find_clip(&dl).0 {
1246            Op::ClipPath {
1247                anti_alias,
1248                bounds,
1249                is_axis_aligned_rect,
1250                ..
1251            } => (*bounds, *is_axis_aligned_rect, *anti_alias),
1252            other => unreachable!("find_clip finds clips, not {other:?}"),
1253        }
1254    }
1255
1256    /// A clip records its shape's bounds in the list's space, with its
1257    /// edge's flag, and that it is a rectangle along the list's axes when
1258    /// it is one under a transform that only scales and moves, a mirror
1259    /// included: the facts the renderer plans the clip from.
1260    #[test]
1261    fn a_clip_records_its_bounds_its_edge_and_whether_it_is_an_axis_aligned_rect() {
1262        let rect = Rect::new(1.0, 2.0, 3.0, 4.0);
1263        let placed = recorded_clip(|b| {
1264            b.translate(10.0, 20.0);
1265            b.scale(2.0, 3.0);
1266            b.clip_rect(rect, ClipOp::Intersect, false);
1267        });
1268        assert_eq!(placed, (Rect::new(12.0, 26.0, 6.0, 12.0), true, false));
1269
1270        let mirrored = recorded_clip(|b| {
1271            b.scale(-1.0, 1.0);
1272            b.clip_rect(rect, ClipOp::Intersect, true);
1273        });
1274        assert_eq!(mirrored, (Rect::new(-4.0, 2.0, 3.0, 4.0), true, true));
1275
1276        let (_, turned_is_rect, _) = recorded_clip(|b| {
1277            b.rotate(0.5);
1278            b.clip_rect(rect, ClipOp::Intersect, true);
1279        });
1280        assert!(!turned_is_rect, "a turned rectangle's sides leave the axes");
1281
1282        let rounded = recorded_clip(|b| b.clip_rrect(rect, 1.0, ClipOp::Intersect, false));
1283        assert_eq!(rounded, (rect, false, false));
1284
1285        let as_a_path = recorded_clip(|b| {
1286            b.clip_path(
1287                &rect_path(rect),
1288                FillRule::EvenOdd,
1289                ClipOp::Difference,
1290                true,
1291            )
1292        });
1293        assert_eq!(as_a_path, (rect, true, true), "a path that is a rectangle");
1294    }
1295
1296    /// Replaying a clip's op records the clip as its call did, its edge's
1297    /// flag with it.
1298    #[test]
1299    fn replaying_a_clip_keeps_its_edge() {
1300        let mut first = DisplayListBuilder::new();
1301        first.clip_rect(Rect::new(0.5, 0.5, 8.0, 8.0), ClipOp::Intersect, false);
1302        let first = first.build();
1303        let replayed = recorded_clip(|b| b.replay(find_clip(&first).0));
1304        assert_eq!(replayed, (Rect::new(0.5, 0.5, 8.0, 8.0), true, false));
1305    }
1306
1307    fn find_clip(dl: &DisplayList) -> (&Op, u32) {
1308        for op in dl.ops() {
1309            if let Op::ClipPath { expiry_slot, .. } = op {
1310                return (op, *expiry_slot);
1311            }
1312        }
1313        panic!("no clip recorded");
1314    }
1315
1316    /// Every recorded layer's `(scope_bounds, base_slot, composite_slot,
1317    /// can_elide)`, in recording order — so an enclosing layer comes before
1318    /// the layers nested inside it.
1319    fn layer_facts(dl: &DisplayList) -> Vec<(Bounds, u32, u32, bool)> {
1320        dl.ops()
1321            .iter()
1322            .filter_map(|op| match op {
1323                Op::SaveLayer {
1324                    scope_bounds,
1325                    base_slot,
1326                    composite_slot,
1327                    can_elide,
1328                    ..
1329                } => Some((*scope_bounds, *base_slot, *composite_slot, *can_elide)),
1330                _ => None,
1331            })
1332            .collect()
1333    }
1334
1335    fn layer_clip_bounds(dl: &DisplayList) -> Bounds {
1336        dl.ops()
1337            .iter()
1338            .find_map(|op| match op {
1339                Op::SaveLayer { clip_bounds, .. } => Some(*clip_bounds),
1340                _ => None,
1341            })
1342            .expect("no layer recorded")
1343    }
1344
1345    fn find_layer(dl: &DisplayList) -> (Bounds, u32, u32, bool) {
1346        *layer_facts(dl).first().expect("no layer recorded")
1347    }
1348
1349    #[test]
1350    fn oracle_bounds_follow_transforms() {
1351        let mut b = DisplayListBuilder::new();
1352        b.save();
1353        b.translate(100.0, 50.0);
1354        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
1355        b.restore();
1356        let dl = b.build();
1357        assert_eq!(
1358            dl.bounds(),
1359            Bounds::Bounded(Rect::new(100.0, 50.0, 10.0, 10.0))
1360        );
1361        assert_eq!(dl.draw_count(), 1);
1362        assert_eq!(dl.depth_slots(), 1);
1363    }
1364
1365    #[test]
1366    fn clip_shrinks_recorded_draw_bounds() {
1367        let mut b = DisplayListBuilder::new();
1368        b.save();
1369        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1370        b.draw_rect(Rect::new(25.0, 25.0, 100.0, 100.0), &red());
1371        b.restore();
1372        let dl = b.build();
1373        assert_eq!(
1374            dl.bounds(),
1375            Bounds::Bounded(Rect::new(25.0, 25.0, 25.0, 25.0))
1376        );
1377    }
1378
1379    #[test]
1380    fn fully_clipped_draw_is_dropped() {
1381        let mut b = DisplayListBuilder::new();
1382        b.save();
1383        b.clip_rect(Rect::new(0.0, 0.0, 10.0, 10.0), ClipOp::Intersect, true);
1384        b.draw_rect(Rect::new(500.0, 500.0, 10.0, 10.0), &red());
1385        b.restore();
1386        let dl = b.build();
1387        assert_eq!(dl.draw_count(), 0);
1388    }
1389
1390    #[test]
1391    fn clip_expiry_is_the_restore_slot() {
1392        let mut b = DisplayListBuilder::new();
1393        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
1394        b.save();
1395        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1396        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 2
1397        b.restore(); // slot 3 = expiry
1398        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 4
1399        let dl = b.build();
1400        let (_, expiry) = find_clip(&dl);
1401        assert_eq!(expiry, 3);
1402        assert_eq!(dl.depth_slots(), 4);
1403    }
1404
1405    #[test]
1406    fn root_clip_expires_at_end_of_list() {
1407        let mut b = DisplayListBuilder::new();
1408        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1409        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
1410        let dl = b.build();
1411        let (_, expiry) = find_clip(&dl);
1412        assert_eq!(expiry, 2, "root clips expire at the virtual end slot");
1413        assert_eq!(dl.depth_slots(), 2);
1414    }
1415
1416    #[test]
1417    fn difference_clip_keeps_bounds_conservative() {
1418        let mut b = DisplayListBuilder::new();
1419        b.save();
1420        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Difference, true);
1421        b.draw_rect(Rect::new(0.0, 0.0, 100.0, 100.0), &red());
1422        b.restore();
1423        let dl = b.build();
1424        assert_eq!(
1425            dl.bounds(),
1426            Bounds::Bounded(Rect::new(0.0, 0.0, 100.0, 100.0))
1427        );
1428    }
1429
1430    #[test]
1431    fn nested_list_folds_oracle_and_offsets_slots() {
1432        let mut inner = DisplayListBuilder::new();
1433        inner.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
1434        inner.draw_rect(Rect::new(20.0, 0.0, 10.0, 10.0), &red());
1435        let inner = Arc::new(inner.build());
1436
1437        let mut outer = DisplayListBuilder::new();
1438        outer.draw_rect(Rect::new(0.0, 0.0, 5.0, 5.0), &red()); // slot 1
1439        outer.translate(5.0, 5.0);
1440        outer.draw_display_list(&inner); // base_slot 1, child consumes 2
1441        outer.draw_rect(Rect::new(0.0, 0.0, 5.0, 5.0), &red()); // slot 4
1442        let outer = outer.build();
1443
1444        assert_eq!(outer.draw_count(), 4);
1445        assert_eq!(outer.depth_slots(), 4);
1446        let base = outer
1447            .ops()
1448            .iter()
1449            .find_map(|op| match op {
1450                Op::DrawDisplayList { base_slot, .. } => Some(*base_slot),
1451                _ => None,
1452            })
1453            .unwrap();
1454        assert_eq!(base, 1);
1455    }
1456
1457    #[test]
1458    fn nop_draws_are_dropped() {
1459        let mut b = DisplayListBuilder::new();
1460        b.draw_rect(Rect::new(0.0, 0.0, 0.0, 10.0), &red()); // empty rect
1461        b.draw_rect(
1462            Rect::new(0.0, 0.0, 10.0, 10.0),
1463            &Paint {
1464                color: Color::TRANSPARENT,
1465                blend_mode: BlendMode::SrcOver,
1466                ..Default::default()
1467            },
1468        );
1469        let dl = b.build();
1470        assert_eq!(dl.ops().len(), 0);
1471        assert_eq!(dl.bounds(), Bounds::Empty);
1472    }
1473
1474    /// A list's bounds are empty when it draws nothing, a rectangle around
1475    /// what it draws, or unbounded when a draw fills a clip the list does
1476    /// not make.
1477    #[test]
1478    fn a_list_records_one_of_three_cases_of_bounds() {
1479        let fill_red = crate::ColorFilter::Blend(Color::rgb(1.0, 0.0, 0.0), BlendMode::Src);
1480        let flooding = Paint {
1481            image_filter: Some(ImageFilter::color(fill_red)),
1482            ..red()
1483        };
1484        assert_eq!(DisplayListBuilder::new().build().bounds(), Bounds::Empty);
1485
1486        let mut b = DisplayListBuilder::new();
1487        b.draw_rect(Rect::new(4.0, 4.0, 4.0, 4.0), &red());
1488        assert_eq!(
1489            b.build().bounds(),
1490            Bounds::Bounded(Rect::new(4.0, 4.0, 4.0, 4.0))
1491        );
1492
1493        let mut b = DisplayListBuilder::new();
1494        b.translate(1.0e9, 0.0);
1495        b.draw_rect(Rect::new(4.0, 4.0, 4.0, 4.0), &flooding);
1496        let unbounded = b.build();
1497        assert_eq!(unbounded.bounds(), Bounds::Unbounded);
1498
1499        let mut b = DisplayListBuilder::new();
1500        b.scale(2.0, 2.0);
1501        b.draw_display_list(&Arc::new(unbounded));
1502        assert_eq!(
1503            b.build().bounds(),
1504            Bounds::Unbounded,
1505            "an embedded unbounded list stays unbounded wherever it is placed"
1506        );
1507    }
1508
1509    /// A layer whose child fills a clip the layer does not crop has
1510    /// unbounded content; a backdrop layer with neither clip nor hint floods
1511    /// an unbounded clip.
1512    #[test]
1513    fn a_layer_records_unbounded_content_and_clip() {
1514        let fill_red = crate::ColorFilter::Blend(Color::rgb(1.0, 0.0, 0.0), BlendMode::Src);
1515        let mut b = DisplayListBuilder::new();
1516        b.clip_rect(Rect::new(0.0, 0.0, 32.0, 32.0), ClipOp::Intersect, true);
1517        b.save_layer(None, &alpha_layer(0.5));
1518        b.draw_rect(
1519            Rect::new(4.0, 4.0, 4.0, 4.0),
1520            &Paint {
1521                image_filter: Some(ImageFilter::color(fill_red)),
1522                ..red()
1523            },
1524        );
1525        b.restore();
1526        let dl = b.build();
1527        let (content, ..) = find_layer(&dl);
1528        assert_eq!(content, Bounds::Unbounded, "the clip is around the layer");
1529        assert_eq!(
1530            layer_clip_bounds(&dl),
1531            Bounds::Bounded(Rect::new(0.0, 0.0, 32.0, 32.0))
1532        );
1533        assert_eq!(
1534            dl.bounds(),
1535            Bounds::Bounded(Rect::new(0.0, 0.0, 32.0, 32.0))
1536        );
1537
1538        let mut b = DisplayListBuilder::new();
1539        b.save_layer_backdrop(None, &Paint::default(), Backdrop::blur(4.0));
1540        b.restore();
1541        let dl = b.build();
1542        assert_eq!(layer_clip_bounds(&dl), Bounds::Unbounded);
1543        assert_eq!(dl.bounds(), Bounds::Unbounded);
1544    }
1545
1546    /// A save layer whose composite is invisible records nothing inside: no
1547    /// draw, no slot (Flutter's nop `saveLayer`).
1548    #[test]
1549    fn an_invisible_layer_records_nothing_inside() {
1550        let mut b = DisplayListBuilder::new();
1551        b.save_layer(None, &alpha_layer(0.0));
1552        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
1553        b.save_layer(None, &alpha_layer(0.5));
1554        b.draw_rect(Rect::new(20.0, 0.0, 10.0, 10.0), &red());
1555        b.restore();
1556        b.restore();
1557        b.draw_rect(Rect::new(40.0, 0.0, 10.0, 10.0), &red());
1558        let dl = b.build();
1559        assert!(
1560            matches!(
1561                dl.ops(),
1562                [
1563                    Op::Save,
1564                    Op::Save,
1565                    Op::Restore,
1566                    Op::Restore,
1567                    Op::DrawRect { slot: 1, .. }
1568                ]
1569            ),
1570            "{:?}",
1571            dl.ops()
1572        );
1573        assert_eq!(
1574            dl.bounds(),
1575            Bounds::Bounded(Rect::new(40.0, 0.0, 10.0, 10.0))
1576        );
1577        assert_eq!(dl.depth_slots(), 1);
1578    }
1579
1580    /// A clip that leaves its scope nothing makes the scope a nop: neither
1581    /// the clip nor anything after it in the scope is recorded, and the
1582    /// scope's restore ends it.
1583    #[test]
1584    fn a_clip_that_leaves_nothing_makes_its_scope_a_nop() {
1585        let mut b = DisplayListBuilder::new();
1586        b.save();
1587        b.clip_rect(Rect::new(0.0, 0.0, 10.0, 10.0), ClipOp::Intersect, true);
1588        b.clip_rect(Rect::new(20.0, 0.0, 10.0, 10.0), ClipOp::Intersect, true);
1589        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
1590        b.clip_rect(Rect::new(0.0, 0.0, 30.0, 30.0), ClipOp::Difference, true);
1591        b.save_layer(
1592            None,
1593            &Paint {
1594                blend_mode: BlendMode::Clear,
1595                ..Default::default()
1596            },
1597        );
1598        b.restore();
1599        b.restore();
1600        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
1601        let dl = b.build();
1602        let clips = dl
1603            .ops()
1604            .iter()
1605            .filter(|op| matches!(op, Op::ClipPath { .. }))
1606            .count();
1607        assert_eq!(clips, 1, "only the clip that leaves something");
1608        assert!(!dl.ops().iter().any(|op| matches!(op, Op::SaveLayer { .. })));
1609        assert_eq!(dl.draw_count(), 1, "the draw after the scope");
1610        assert_eq!(
1611            dl.depth_slots(),
1612            2,
1613            "the first clip's expiry and the last draw"
1614        );
1615    }
1616
1617    /// A layer whose hint misses its clip is still recorded, with an empty
1618    /// clip: a mask over nothing still erases what is beneath it.
1619    #[test]
1620    fn a_mask_whose_hint_misses_the_clip_is_recorded_with_an_empty_clip() {
1621        let mut b = DisplayListBuilder::new();
1622        b.clip_rect(Rect::new(0.0, 0.0, 10.0, 10.0), ClipOp::Intersect, true);
1623        b.save_layer_mask(Some(Rect::new(20.0, 0.0, 10.0, 10.0)), MaskKind::Alpha);
1624        b.draw_rect(Rect::new(20.0, 0.0, 10.0, 10.0), &red());
1625        b.restore();
1626        let dl = b.build();
1627        assert_eq!(layer_clip_bounds(&dl), Bounds::Empty);
1628        let (content, ..) = find_layer(&dl);
1629        assert_eq!(content, Bounds::Empty, "the hint culls every child");
1630    }
1631
1632    // ── save layers (M4) ────────────────────────────────────────────────────
1633
1634    #[test]
1635    fn layer_oracle_bounds_and_slots() {
1636        let mut b = DisplayListBuilder::new();
1637        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
1638        b.save_layer(None, &alpha_layer(0.5)); // base_slot = 1
1639        b.draw_rect(Rect::new(20.0, 20.0, 30.0, 30.0), &red()); // slot 2
1640        b.draw_rect(Rect::new(60.0, 20.0, 30.0, 30.0), &red()); // slot 3
1641        b.restore(); // composite = slot 4, next on the same line
1642        b.draw_rect(Rect::new(0.0, 40.0, 10.0, 10.0), &red()); // slot 5
1643        let dl = b.build();
1644
1645        let (bounds, base_slot, composite_slot, can_elide) = find_layer(&dl);
1646        assert_eq!(bounds, Bounds::Bounded(Rect::new(20.0, 20.0, 70.0, 30.0)));
1647        assert_eq!(base_slot, 1, "scope opened after one parent draw");
1648        assert_eq!(composite_slot, 4, "children keep the global line");
1649        assert!(
1650            can_elide,
1651            "disjoint SrcOver children + alpha-only composite"
1652        );
1653        assert_eq!(
1654            dl.depth_slots(),
1655            5,
1656            "one global depth line (Impeller's current_depth_)"
1657        );
1658        assert_eq!(dl.draw_count(), 5, "4 rects + the composite");
1659    }
1660
1661    #[test]
1662    fn overlapping_children_forfeit_elision() {
1663        let mut b = DisplayListBuilder::new();
1664        b.save_layer(None, &alpha_layer(0.5));
1665        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
1666        b.draw_rect(Rect::new(10.0, 10.0, 30.0, 30.0), &red()); // overlaps
1667        b.restore();
1668        let (_, _, _, can_elide) = find_layer(&b.build());
1669        assert!(!can_elide);
1670    }
1671
1672    #[test]
1673    fn advanced_blend_composite_forfeits_elision() {
1674        let mut b = DisplayListBuilder::new();
1675        let paint = Paint {
1676            color: Color::rgba(0.0, 0.0, 0.0, 0.5),
1677            blend_mode: BlendMode::Multiply,
1678            ..Default::default()
1679        };
1680        b.save_layer(None, &paint);
1681        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
1682        b.restore();
1683        let (_, _, _, can_elide) = find_layer(&b.build());
1684        assert!(!can_elide);
1685    }
1686
1687    /// A colour-filtered layer's composite takes an alpha in before its
1688    /// filter, so an enclosing group's alpha cannot ride it (Flutter marks
1689    /// such a layer incompatible with group opacity).
1690    #[test]
1691    fn a_colour_filtered_layer_forfeits_its_groups_elision() {
1692        let mut b = DisplayListBuilder::new();
1693        b.save_layer(None, &alpha_layer(0.5));
1694        b.save_layer(
1695            None,
1696            &Paint {
1697                color_filter: Some(crate::ColorFilter::Blend(
1698                    Color::rgb(1.0, 0.0, 0.0),
1699                    BlendMode::SrcOver,
1700                )),
1701                ..Default::default()
1702            },
1703        );
1704        b.draw_rect(Rect::new(4.0, 4.0, 4.0, 4.0), &red());
1705        b.restore();
1706        b.restore();
1707        let layers = layer_facts(&b.build());
1708        assert!(!layers[0].3, "the group keeps its layer");
1709    }
1710
1711    /// The recorded facts of the first layer in a list of one layer around
1712    /// one rect: whether it floods its clip and whether a group's alpha can
1713    /// ride it.
1714    fn layer_flood_and_opacity(paint: &Paint) -> (bool, bool) {
1715        let mut b = DisplayListBuilder::new();
1716        b.save_layer(None, paint);
1717        b.draw_rect(Rect::new(4.0, 4.0, 4.0, 4.0), &red());
1718        b.restore();
1719        b.build()
1720            .ops()
1721            .iter()
1722            .find_map(|op| match op {
1723                Op::SaveLayer {
1724                    floods_clip,
1725                    takes_group_opacity,
1726                    ..
1727                } => Some((*floods_clip, *takes_group_opacity)),
1728                _ => None,
1729            })
1730            .expect("a layer is recorded")
1731    }
1732
1733    /// A layer floods its clip for a destructive blend or for a colour or
1734    /// image filter that colours transparent pixels; a group's alpha rides
1735    /// only a plain `SrcOver` composite.
1736    #[test]
1737    fn a_layer_records_its_flood_and_whether_a_group_alpha_can_ride_it() {
1738        let fill_red = crate::ColorFilter::Blend(Color::rgb(1.0, 0.0, 0.0), BlendMode::Src);
1739        let tint = crate::ColorFilter::Blend(Color::rgb(1.0, 0.0, 0.0), BlendMode::SrcIn);
1740        let layer = |paint: Paint| layer_flood_and_opacity(&paint);
1741        assert_eq!(layer(alpha_layer(0.5)), (false, true));
1742        assert_eq!(
1743            layer(Paint {
1744                blend_mode: BlendMode::SrcIn,
1745                ..Default::default()
1746            }),
1747            (true, false)
1748        );
1749        assert_eq!(
1750            layer(Paint {
1751                color_filter: Some(fill_red),
1752                ..Default::default()
1753            }),
1754            (true, false)
1755        );
1756        assert_eq!(
1757            layer(Paint {
1758                image_filter: Some(ImageFilter::color(fill_red)),
1759                ..Default::default()
1760            }),
1761            (true, false)
1762        );
1763        assert_eq!(
1764            layer(Paint {
1765                color_filter: Some(tint),
1766                ..Default::default()
1767            }),
1768            (false, false)
1769        );
1770    }
1771
1772    /// A draw's colour filter stays inside its shape; its image filter, when
1773    /// it colours transparent pixels, fills the clip.
1774    #[test]
1775    fn a_draws_bounds_flood_for_its_image_filter_but_not_its_colour_filter() {
1776        let fill_red = crate::ColorFilter::Blend(Color::rgb(1.0, 0.0, 0.0), BlendMode::Src);
1777        let bounds = |paint: Paint| {
1778            let mut b = DisplayListBuilder::new();
1779            b.clip_rect(Rect::new(0.0, 0.0, 32.0, 32.0), ClipOp::Intersect, true);
1780            b.draw_rect(Rect::new(4.0, 4.0, 4.0, 4.0), &paint);
1781            b.build().bounds()
1782        };
1783        assert_eq!(
1784            bounds(Paint {
1785                color_filter: Some(fill_red),
1786                ..red()
1787            }),
1788            Bounds::Bounded(Rect::new(4.0, 4.0, 4.0, 4.0))
1789        );
1790        assert_eq!(
1791            bounds(Paint {
1792                image_filter: Some(ImageFilter::color(fill_red)),
1793                ..red()
1794            }),
1795            Bounds::Bounded(Rect::new(0.0, 0.0, 32.0, 32.0))
1796        );
1797    }
1798
1799    #[test]
1800    fn destructive_layer_composite_floods_the_active_clip() {
1801        let mut b = DisplayListBuilder::new();
1802        b.clip_rect(Rect::new(4.0, 6.0, 80.0, 60.0), ClipOp::Intersect, true);
1803        b.save_layer(
1804            None,
1805            &Paint {
1806                blend_mode: BlendMode::SrcIn,
1807                ..Default::default()
1808            },
1809        );
1810        b.draw_rect(Rect::new(20.0, 20.0, 10.0, 10.0), &red());
1811        b.restore();
1812        let dl = b.build();
1813        let (bounds, ..) = find_layer(&dl);
1814        assert_eq!(
1815            bounds,
1816            Bounds::Bounded(Rect::new(20.0, 20.0, 10.0, 10.0)),
1817            "the content"
1818        );
1819        assert_eq!(
1820            layer_clip_bounds(&dl),
1821            Bounds::Bounded(Rect::new(4.0, 6.0, 80.0, 60.0))
1822        );
1823        assert_eq!(
1824            dl.bounds(),
1825            Bounds::Bounded(Rect::new(4.0, 6.0, 80.0, 60.0)),
1826            "the composite paints the clip"
1827        );
1828    }
1829
1830    /// A clip around a blurred layer does not crop its content: the blur
1831    /// reads the content past the clip (Flutter's layer bounds).
1832    #[test]
1833    fn a_clip_around_a_layer_does_not_crop_its_content() {
1834        let mut b = DisplayListBuilder::new();
1835        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1836        b.save_layer(
1837            None,
1838            &Paint {
1839                image_filter: Some(ImageFilter::blur(4.0, 4.0)),
1840                ..Default::default()
1841            },
1842        );
1843        b.draw_rect(Rect::new(40.0, 10.0, 30.0, 10.0), &red());
1844        b.restore();
1845        let dl = b.build();
1846        let (bounds, ..) = find_layer(&dl);
1847        assert_eq!(bounds, Bounds::Bounded(Rect::new(40.0, 10.0, 30.0, 10.0)));
1848        assert_eq!(
1849            layer_clip_bounds(&dl),
1850            Bounds::Bounded(Rect::new(0.0, 0.0, 50.0, 50.0))
1851        );
1852    }
1853
1854    /// A child just outside the clip still reaches inside it through a blur
1855    /// on its layer, so it is kept (Flutter culls a filtered layer's children
1856    /// by the clip widened by what the filter reads).
1857    #[test]
1858    fn a_blurred_layer_keeps_children_its_blur_reaches_across_the_clip() {
1859        let mut b = DisplayListBuilder::new();
1860        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1861        b.save_layer(
1862            None,
1863            &Paint {
1864                image_filter: Some(ImageFilter::blur(4.0, 4.0)),
1865                ..Default::default()
1866            },
1867        );
1868        b.draw_rect(Rect::new(55.0, 10.0, 10.0, 10.0), &red());
1869        b.draw_rect(Rect::new(80.0, 10.0, 10.0, 10.0), &red());
1870        b.restore();
1871        let (bounds, ..) = find_layer(&b.build());
1872        assert_eq!(
1873            bounds,
1874            Bounds::Bounded(Rect::new(55.0, 10.0, 10.0, 10.0)),
1875            "3σ reaches 12 past the clip: the first is kept, the second dropped"
1876        );
1877    }
1878
1879    /// A matrix filter on a layer culls its children by what it moves into
1880    /// the clip, taken through the layer's transform, and the composite shows
1881    /// where it moves them (Flutter's `get_input_device_bounds` and
1882    /// `map_device_bounds` of a `DlMatrixImageFilter`).
1883    #[test]
1884    fn a_matrix_filtered_layer_keeps_the_children_it_moves_into_the_clip() {
1885        let mut b = DisplayListBuilder::new();
1886        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1887        b.scale(2.0, 2.0);
1888        b.save_layer(
1889            None,
1890            &Paint {
1891                image_filter: Some(ImageFilter::matrix(
1892                    Matrix::translation(-30.0, 0.0),
1893                    crate::Sampling::default(),
1894                )),
1895                ..Default::default()
1896            },
1897        );
1898        b.draw_rect(Rect::new(35.0, 5.0, 5.0, 5.0), &red());
1899        b.draw_rect(Rect::new(60.0, 5.0, 5.0, 5.0), &red());
1900        b.restore();
1901        let dl = b.build();
1902        let (bounds, ..) = find_layer(&dl);
1903        assert_eq!(
1904            bounds,
1905            Bounds::Bounded(Rect::new(70.0, 10.0, 10.0, 10.0)),
1906            "moved 60 device pixels left, the first lands in the clip, the second past it"
1907        );
1908        let mut walker = dl.walk();
1909        let layer = walker
1910            .find(|op| matches!(op, Op::SaveLayer { .. }))
1911            .expect("the layer is recorded");
1912        assert_eq!(
1913            walker.matrix_clip().bounds(layer),
1914            Bounds::Bounded(Rect::new(10.0, 10.0, 10.0, 10.0)),
1915            "the composite shows where the matrix moves the content"
1916        );
1917    }
1918
1919    /// A save layer records no mask blur, so it neither blurs the layer nor
1920    /// widens the clip its children are culled by.
1921    #[test]
1922    fn a_save_layer_drops_its_mask_blur() {
1923        let mut b = DisplayListBuilder::new();
1924        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1925        b.save_layer(
1926            None,
1927            &Paint {
1928                mask_blur: Some(crate::MaskBlur::new(4.0)),
1929                ..alpha_layer(0.5)
1930            },
1931        );
1932        b.draw_rect(Rect::new(10.0, 10.0, 10.0, 10.0), &red());
1933        b.draw_rect(Rect::new(55.0, 10.0, 10.0, 10.0), &red());
1934        b.restore();
1935        let dl = b.build();
1936        let paint = dl.ops().iter().find_map(|op| match op {
1937            Op::SaveLayer { paint, .. } => Some(paint),
1938            _ => None,
1939        });
1940        assert_eq!(paint, Some(&alpha_layer(0.5)));
1941        let (bounds, ..) = find_layer(&dl);
1942        assert_eq!(bounds, Bounds::Bounded(Rect::new(10.0, 10.0, 10.0, 10.0)));
1943    }
1944
1945    #[test]
1946    fn a_clip_inside_a_layer_crops_its_content() {
1947        let mut b = DisplayListBuilder::new();
1948        b.save_layer(None, &alpha_layer(0.5));
1949        b.clip_rect(Rect::new(0.0, 0.0, 30.0, 30.0), ClipOp::Intersect, true);
1950        b.draw_rect(Rect::new(20.0, 20.0, 30.0, 30.0), &red());
1951        b.restore();
1952        let dl = b.build();
1953        let (bounds, ..) = find_layer(&dl);
1954        assert_eq!(bounds, Bounds::Bounded(Rect::new(20.0, 20.0, 10.0, 10.0)));
1955        assert_eq!(layer_clip_bounds(&dl), Bounds::Unbounded);
1956    }
1957
1958    #[test]
1959    fn a_stroked_path_records_its_ink_in_local_coordinates() {
1960        let mut b = DisplayListBuilder::new();
1961        b.translate(100.0, 0.0);
1962        b.draw_rect(
1963            Rect::new(10.0, 10.0, 20.0, 20.0),
1964            &Paint {
1965                style: crate::PaintStyle::Stroke(valo_geometry::Stroke {
1966                    join: valo_geometry::Join::Round,
1967                    ..valo_geometry::Stroke::new(4.0)
1968                }),
1969                ..red()
1970            },
1971        );
1972        let dl = b.build();
1973        let content_bounds = dl
1974            .ops()
1975            .iter()
1976            .find_map(|op| match op {
1977                Op::DrawPath { content_bounds, .. } => Some(*content_bounds),
1978                _ => None,
1979            })
1980            .expect("a stroked rect records a path");
1981        // Half the width times the round join's 1.5 on every side.
1982        assert_eq!(content_bounds, Rect::new(7.0, 7.0, 26.0, 26.0));
1983    }
1984
1985    #[test]
1986    fn clip_inside_layer_keeps_elision() {
1987        let mut b = DisplayListBuilder::new();
1988        b.save_layer(None, &alpha_layer(0.5));
1989        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
1990        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
1991        b.restore();
1992        let (_, _, _, can_elide) = find_layer(&b.build());
1993        // A depth clip expires on its own slot either way; Flutter's
1994        // opacity distribution ignores clips too.
1995        assert!(can_elide);
1996    }
1997
1998    #[test]
1999    fn an_embedded_list_of_disjoint_draws_keeps_elision() {
2000        let mut inner = DisplayListBuilder::new();
2001        inner.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2002        inner.draw_rect(Rect::new(40.0, 0.0, 30.0, 30.0), &red());
2003        let inner = Arc::new(inner.build());
2004        assert!(inner.supports_opacity());
2005
2006        let mut b = DisplayListBuilder::new();
2007        b.save_layer(None, &alpha_layer(0.5));
2008        b.draw_display_list(&inner);
2009        b.restore();
2010        let (_, _, _, can_elide) = find_layer(&b.build());
2011        assert!(can_elide, "the list answers for its children");
2012    }
2013
2014    #[test]
2015    fn an_embedded_list_of_overlapping_draws_forfeits_elision() {
2016        let mut inner = DisplayListBuilder::new();
2017        inner.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2018        inner.draw_rect(Rect::new(10.0, 10.0, 30.0, 30.0), &red());
2019        let inner = Arc::new(inner.build());
2020        assert!(!inner.supports_opacity());
2021
2022        let mut b = DisplayListBuilder::new();
2023        b.save_layer(None, &alpha_layer(0.5));
2024        b.draw_display_list(&inner);
2025        b.restore();
2026        let (_, _, _, can_elide) = find_layer(&b.build());
2027        assert!(!can_elide);
2028    }
2029
2030    #[test]
2031    fn two_embedded_lists_that_overlap_forfeit_elision() {
2032        let mut inner = DisplayListBuilder::new();
2033        inner.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2034        let inner = Arc::new(inner.build());
2035
2036        let mut b = DisplayListBuilder::new();
2037        b.save_layer(None, &alpha_layer(0.5));
2038        b.draw_display_list(&inner);
2039        b.translate(10.0, 10.0);
2040        b.draw_display_list(&inner);
2041        b.restore();
2042        let (_, _, _, can_elide) = find_layer(&b.build());
2043        assert!(!can_elide);
2044    }
2045
2046    #[test]
2047    fn a_child_inside_the_union_of_earlier_ones_forfeits_elision() {
2048        // Disjoint from both earlier rects, but inside their union: Flutter's
2049        // `AccumulationRect` calls that an overlap, and so does this.
2050        let mut b = DisplayListBuilder::new();
2051        b.save_layer(None, &alpha_layer(0.5));
2052        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2053        b.draw_rect(Rect::new(40.0, 40.0, 30.0, 30.0), &red());
2054        b.draw_rect(Rect::new(40.0, 0.0, 30.0, 30.0), &red());
2055        b.restore();
2056        let (_, _, _, can_elide) = find_layer(&b.build());
2057        assert!(!can_elide);
2058    }
2059
2060    #[test]
2061    fn a_layer_composite_is_one_child_of_the_root() {
2062        let mut b = DisplayListBuilder::new();
2063        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2064        b.save_layer(None, &alpha_layer(0.5));
2065        b.draw_rect(Rect::new(10.0, 10.0, 30.0, 30.0), &red()); // overlaps the first
2066        b.restore();
2067        assert!(!b.build().supports_opacity());
2068    }
2069
2070    #[test]
2071    fn bounds_hint_crops_the_scope() {
2072        let mut b = DisplayListBuilder::new();
2073        b.save_layer(Some(Rect::new(0.0, 0.0, 40.0, 40.0)), &alpha_layer(0.5));
2074        b.draw_rect(Rect::new(20.0, 20.0, 100.0, 100.0), &red());
2075        b.restore();
2076        let (bounds, ..) = find_layer(&b.build());
2077        assert_eq!(bounds, Bounds::Bounded(Rect::new(20.0, 20.0, 20.0, 20.0)));
2078    }
2079
2080    #[test]
2081    fn clips_inside_layers_expire_within_the_scope_span() {
2082        let mut b = DisplayListBuilder::new();
2083        b.save_layer(None, &alpha_layer(0.5)); // base_slot = 0
2084        b.save();
2085        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect, true);
2086        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red()); // slot 1
2087        b.restore(); // slot 2 = expiry
2088        b.restore(); // composite = slot 3
2089        let dl = b.build();
2090        let (_, expiry) = find_clip(&dl);
2091        assert_eq!(expiry, 2, "expiry sits inside the layer's span");
2092        let (_, base_slot, composite_slot, _) = find_layer(&dl);
2093        assert_eq!((base_slot, composite_slot), (0, 3));
2094    }
2095
2096    // ── mask + backdrop blur (M5) ───────────────────────────────────────────
2097
2098    #[test]
2099    fn solid_mask_blur_records_the_analytic_op() {
2100        let mut b = DisplayListBuilder::new();
2101        let paint = Paint {
2102            mask_blur: Some(crate::MaskBlur::new(4.0)),
2103            ..red()
2104        };
2105        b.draw_rect(Rect::new(20.0, 20.0, 40.0, 40.0), &paint);
2106        b.draw_rrect(Rect::new(100.0, 20.0, 40.0, 40.0), 8.0, &paint);
2107        let dl = b.build();
2108        let blurs: Vec<_> = dl
2109            .ops()
2110            .iter()
2111            .filter_map(|op| match op {
2112                Op::RRectBlur { radii, bounds, .. } => Some((*radii, *bounds)),
2113                _ => None,
2114            })
2115            .collect();
2116        assert_eq!(blurs.len(), 2);
2117        assert_eq!(blurs[0].0, [0.0; 4]);
2118        assert_eq!(blurs[1].0, [8.0; 4]);
2119        // Bounds carry the ±3σ spread.
2120        assert_eq!(blurs[0].1, Rect::new(8.0, 8.0, 64.0, 64.0));
2121    }
2122
2123    #[test]
2124    fn shader_mask_blur_stays_general_but_pads_bounds() {
2125        let mut b = DisplayListBuilder::new();
2126        let paint = Paint {
2127            mask_blur: Some(crate::MaskBlur::new(2.0)),
2128            shader: Some(crate::Shader::linear(
2129                valo_geometry::Point::new(0.0, 0.0),
2130                valo_geometry::Point::new(10.0, 0.0),
2131                Color::BLACK,
2132                Color::WHITE,
2133            )),
2134            color: Color::WHITE,
2135            ..Default::default()
2136        };
2137        b.draw_rect(Rect::new(10.0, 10.0, 20.0, 20.0), &paint);
2138        let dl = b.build();
2139        let Op::DrawRect { bounds, .. } = &dl.ops()[0] else {
2140            panic!("shader paints keep the general op");
2141        };
2142        assert_eq!(*bounds, Rect::new(4.0, 4.0, 32.0, 32.0));
2143    }
2144
2145    #[test]
2146    fn hinted_layer_forfeits_elision() {
2147        let mut b = DisplayListBuilder::new();
2148        b.save_layer(Some(Rect::new(0.0, 0.0, 40.0, 40.0)), &alpha_layer(0.5));
2149        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
2150        b.restore();
2151        let (_, _, _, can_elide) = find_layer(&b.build());
2152        assert!(!can_elide, "the hint is a crop; eliding would un-crop it");
2153    }
2154
2155    // ── backdrop layers ─────────────────────────────────────────────────────
2156
2157    /// A glass panel: a backdrop layer with nothing painted over it.
2158    fn glass(b: &mut DisplayListBuilder, rect: Rect, sigma: f32, key: Option<u64>) {
2159        b.save_layer_backdrop(
2160            Some(rect),
2161            &Paint::default(),
2162            Backdrop {
2163                filter: ImageFilter::blur(sigma, sigma),
2164                shared_key: key,
2165            },
2166        );
2167        b.restore();
2168    }
2169
2170    #[test]
2171    fn shared_backdrops_group_by_key() {
2172        let mut b = DisplayListBuilder::new();
2173        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 8.0, Some(7));
2174        glass(&mut b, Rect::new(100.0, 0.0, 50.0, 50.0), 8.0, Some(7));
2175        glass(&mut b, Rect::new(0.0, 100.0, 50.0, 50.0), 8.0, None);
2176        let dl = b.build();
2177        let group = dl.backdrop_group(7).expect("key 7 recorded");
2178        // Each layer joins its group at close, contributing its scope bounds.
2179        assert_eq!(group.union_bounds, Rect::new(0.0, 0.0, 150.0, 50.0));
2180        assert_eq!(
2181            group.filter,
2182            Some(ImageFilter::blur(8.0, 8.0)),
2183            "one σ across the key: shareable"
2184        );
2185        assert_eq!(dl.draw_count(), 3, "each layer's composite is a draw");
2186        assert_eq!(dl.depth_slots(), 3);
2187    }
2188
2189    #[test]
2190    fn mixed_sigma_under_one_key_clears_the_shared_sigma() {
2191        let mut b = DisplayListBuilder::new();
2192        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, Some(7));
2193        glass(&mut b, Rect::new(100.0, 0.0, 50.0, 50.0), 12.0, Some(7));
2194        let dl = b.build();
2195        let group = dl.backdrop_group(7).expect("key 7 recorded");
2196        assert_eq!(group.filter, None, "disagreeing σ cannot share one blur");
2197    }
2198
2199    #[test]
2200    fn opacity_group_elides_over_a_backdrop_layer() {
2201        let mut b = DisplayListBuilder::new();
2202        b.save_layer(None, &alpha_layer(0.5));
2203        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
2204        b.restore();
2205        let layers = layer_facts(&b.build());
2206        assert_eq!(layers.len(), 2, "the opacity group and the glass inside it");
2207        assert!(
2208            layers[0].3,
2209            "the group's alpha lands on the glass composite — the whole point \
2210             of backdrop-as-a-layer-property: glass keeps blurring while the \
2211             group fades"
2212        );
2213        assert!(!layers[1].3, "the glass itself needs a texture to seed");
2214    }
2215
2216    /// The Cupertino dialog's exact recording shape: fade -> superellipse
2217    /// clip -> glass. The clip must NOT forfeit the fade's elision - a depth
2218    /// clip works identically whether the group's children draw in a layer
2219    /// or the parent, and eliding is what lets the glass snapshot the live
2220    /// scene instead of the fade's cleared offscreen.
2221    #[test]
2222    fn a_clip_does_not_forfeit_elision_around_glass() {
2223        let mut b = DisplayListBuilder::new();
2224        b.save_layer(None, &alpha_layer(0.5));
2225        b.save();
2226        let mut clip = PathBuilder::new();
2227        clip.rect(Rect::new(0.0, 0.0, 60.0, 60.0));
2228        b.clip_path(&clip.build(), FillRule::NonZero, ClipOp::Intersect, true);
2229        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
2230        b.restore();
2231        b.restore();
2232        let layers = layer_facts(&b.build());
2233        assert_eq!(layers.len(), 2);
2234        assert!(layers[0].3, "the clipped fade still elides");
2235        assert!(!layers[1].3);
2236    }
2237
2238    #[test]
2239    fn backdrop_reads_count_unshared_and_nested() {
2240        let mut child = DisplayListBuilder::new();
2241        glass(&mut child, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
2242        let child = Arc::new(child.build());
2243        assert_eq!(child.backdrop_reads(), 1, "unshared reads count too");
2244
2245        let mut parent = DisplayListBuilder::new();
2246        glass(&mut parent, Rect::new(0.0, 0.0, 50.0, 50.0), 8.0, Some(7));
2247        parent.draw_display_list(&child);
2248        let parent = parent.build();
2249        assert_eq!(parent.backdrop_reads(), 2, "own layer + the nested list's");
2250
2251        let mut clean = DisplayListBuilder::new();
2252        clean.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
2253        assert_eq!(clean.build().backdrop_reads(), 0);
2254    }
2255
2256    #[cfg(feature = "serde")]
2257    #[test]
2258    fn serde_dump_is_readable_json() {
2259        // Dump-only by design (plan: diffs + bug reports, never persistence —
2260        // an Image can't be deserialized without a device).
2261        let mut b = DisplayListBuilder::new();
2262        b.translate(1.0, 2.0);
2263        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
2264        let dl = b.build();
2265        let json: serde_json::Value = serde_json::to_value(&dl).unwrap();
2266        assert_eq!(json["ops"].as_array().unwrap().len(), dl.ops().len());
2267        assert!(json["ops"][1]["DrawRect"]["slot"].is_number());
2268    }
2269
2270    #[test]
2271    fn replaying_a_lists_ops_records_the_same_list() {
2272        let mut b = DisplayListBuilder::new();
2273        b.save();
2274        b.translate(10.0, 5.0);
2275        b.clip_rect(Rect::new(0.0, 0.0, 80.0, 60.0), ClipOp::Intersect, true);
2276        b.save_layer(
2277            Some(Rect::new(0.0, 0.0, 40.0, 40.0)),
2278            &Paint {
2279                image_filter: Some(ImageFilter::blur(3.0, 3.0)),
2280                ..Paint::default()
2281            },
2282        );
2283        b.draw_rect(Rect::new(4.0, 4.0, 20.0, 20.0), &Paint::default());
2284        b.restore();
2285        b.draw_rrect(
2286            Rect::new(30.0, 30.0, 20.0, 10.0),
2287            4.0,
2288            &Paint {
2289                mask_blur: Some(MaskBlur::new(2.0)),
2290                ..Paint::default()
2291            },
2292        );
2293        b.draw_paint(&Paint {
2294            blend_mode: BlendMode::Multiply,
2295            ..red()
2296        });
2297        b.draw_shadow(
2298            &rect_path(Rect::new(10.0, 10.0, 30.0, 20.0)),
2299            FillRule::NonZero,
2300            Color::BLACK,
2301            6.0,
2302            true,
2303            2.0,
2304        );
2305        b.restore();
2306        let original = b.build();
2307
2308        let mut again = DisplayListBuilder::new();
2309        for op in original.ops() {
2310            again.replay(op);
2311        }
2312        assert!(again.build() == original);
2313    }
2314
2315    /// A paint fills the clip in force; with none it fills the list
2316    /// everywhere (Flutter's `AccumulateUnbounded`).
2317    #[test]
2318    fn a_paint_fills_the_clip_and_unbounds_an_unclipped_list() {
2319        let mut b = DisplayListBuilder::new();
2320        b.draw_paint(&red());
2321        let dl = b.build();
2322        assert_eq!(dl.bounds(), Bounds::Unbounded);
2323        assert!(
2324            matches!(dl.ops(), [Op::DrawPaint { bounds, .. }] if *bounds == Rect::EVERYTHING),
2325            "{:?}",
2326            dl.ops()
2327        );
2328
2329        let mut b = DisplayListBuilder::new();
2330        b.translate(5.0, 5.0);
2331        b.clip_rect(Rect::new(0.0, 0.0, 20.0, 10.0), ClipOp::Intersect, true);
2332        b.draw_paint(&red());
2333        assert_eq!(
2334            b.build().bounds(),
2335            Bounds::Bounded(Rect::new(5.0, 5.0, 20.0, 10.0))
2336        );
2337    }
2338
2339    /// Flutter's display list records the paint of `drawPaint` without its
2340    /// draw style or mask filter (`kDrawPaintFlags`), and records nothing for
2341    /// a paint that changes nothing.
2342    #[test]
2343    fn a_paint_fills_without_a_mask_blur_and_is_dropped_when_it_changes_nothing() {
2344        let mut b = DisplayListBuilder::new();
2345        b.draw_paint(&Paint {
2346            style: crate::PaintStyle::Stroke(valo_geometry::Stroke::new(3.0)),
2347            mask_blur: Some(MaskBlur::new(4.0)),
2348            ..red()
2349        });
2350        b.draw_paint(&Paint::from_color(Color::TRANSPARENT));
2351        let dl = b.build();
2352        let [Op::DrawPaint { paint, .. }] = dl.ops() else {
2353            panic!("one paint recorded: {:?}", dl.ops());
2354        };
2355        assert_eq!(*paint, red());
2356
2357        let mut b = DisplayListBuilder::new();
2358        b.draw_paint(&Paint {
2359            blend_mode: BlendMode::Clear,
2360            ..Paint::from_color(Color::TRANSPARENT)
2361        });
2362        assert_eq!(
2363            b.build().draw_count(),
2364            1,
2365            "Clear changes pixels whatever its colour"
2366        );
2367    }
2368
2369    /// In a layer that does not crop it, a paint leaves the layer's content
2370    /// unbounded, so the layer covers its clip; it takes the group's alpha
2371    /// alone, and overlaps anything else the layer holds.
2372    #[test]
2373    fn a_paint_unbounds_its_layer_and_overlaps_the_layers_other_draws() {
2374        let mut b = DisplayListBuilder::new();
2375        b.clip_rect(Rect::new(0.0, 0.0, 32.0, 32.0), ClipOp::Intersect, true);
2376        b.save_layer(None, &alpha_layer(0.5));
2377        b.draw_paint(&red());
2378        b.restore();
2379        let (content, .., can_elide) = find_layer(&b.build());
2380        assert_eq!(content, Bounds::Unbounded);
2381        assert!(can_elide);
2382
2383        let mut b = DisplayListBuilder::new();
2384        b.save_layer(None, &alpha_layer(0.5));
2385        b.draw_rect(Rect::new(0.0, 0.0, 4.0, 4.0), &red());
2386        b.draw_paint(&red());
2387        b.restore();
2388        let (.., can_elide) = find_layer(&b.build());
2389        assert!(!can_elide);
2390    }
2391
2392    /// A shadow's bounds are its path moved down by the occluder's height in
2393    /// device pixels — four of them in the path's own coordinates at a scale
2394    /// of two — and spread by its blur, from what the recorder resolves under
2395    /// the transform.
2396    #[test]
2397    fn a_shadow_records_the_bounds_of_its_moved_and_blurred_path() {
2398        let path = rect_path(Rect::new(10.0, 10.0, 20.0, 20.0));
2399        let mut b = DisplayListBuilder::new();
2400        b.scale(2.0, 2.0);
2401        b.draw_shadow(&path, FillRule::NonZero, Color::BLACK, 4.0, false, 2.0);
2402        let dl = b.build();
2403        let [Op::Transform(_), Op::DrawShadow {
2404            round_rect, bounds, ..
2405        }] = dl.ops()
2406        else {
2407            panic!("one shadow recorded: {:?}", dl.ops());
2408        };
2409        assert_eq!(*round_rect, Some((Rect::new(10.0, 10.0, 20.0, 20.0), 0.0)));
2410        // A height of 8 device pixels, 8 / 2 = 4 local units; a radius of
2411        // 8 / 2, a σ of 4 / √3 + 0.5, padded by its 3σ rounded up, 9.
2412        let local = Rect::new(10.0, 14.0, 20.0, 20.0).expand(9.0);
2413        assert_eq!(*bounds, Matrix::scale(2.0, 2.0).map_rect(&local));
2414    }
2415
2416    /// A shadow of a transparent occluder is not recorded, and a shadow never
2417    /// takes a group's alpha (Flutter's `UpdateLayerOpacityCompatibility`).
2418    #[test]
2419    fn a_shadow_takes_no_group_alpha() {
2420        let card = rect_path(Rect::new(10.0, 10.0, 20.0, 20.0));
2421        let mut b = DisplayListBuilder::new();
2422        b.draw_shadow(
2423            &card,
2424            FillRule::NonZero,
2425            Color::TRANSPARENT,
2426            4.0,
2427            false,
2428            1.0,
2429        );
2430        assert_eq!(b.build().draw_count(), 0);
2431
2432        let mut b = DisplayListBuilder::new();
2433        b.save_layer(None, &alpha_layer(0.5));
2434        b.draw_shadow(&card, FillRule::NonZero, Color::BLACK, 4.0, false, 1.0);
2435        b.restore();
2436        let (.., can_elide) = find_layer(&b.build());
2437        assert!(!can_elide);
2438    }
2439
2440    /// The shapes Impeller's `SimplifyOrDrawPath` and `AttemptDrawBlur` draw
2441    /// a shadow of in closed form: a rectangle, a rounded rectangle with one
2442    /// circular radius, a circle. A rounded rectangle with differing or
2443    /// elliptical corners, a non-square oval and any other path are blurred
2444    /// as paths.
2445    #[test]
2446    fn a_shadow_records_the_closed_form_shapes_impeller_finds() {
2447        let shape = |build: &dyn Fn(&mut PathBuilder)| {
2448            let mut path = PathBuilder::new();
2449            build(&mut path);
2450            let mut b = DisplayListBuilder::new();
2451            b.draw_shadow(
2452                &path.build(),
2453                FillRule::NonZero,
2454                Color::BLACK,
2455                4.0,
2456                false,
2457                1.0,
2458            );
2459            let dl = b.build();
2460            match dl.ops() {
2461                [Op::DrawShadow { round_rect, .. }] => *round_rect,
2462                ops => panic!("one shadow recorded: {ops:?}"),
2463            }
2464        };
2465        let r = Rect::new(10.0, 10.0, 40.0, 20.0);
2466        assert_eq!(
2467            shape(&|p| {
2468                p.rect(r);
2469            }),
2470            Some((r, 0.0))
2471        );
2472        assert_eq!(
2473            shape(&|p| {
2474                p.rrect(r, 6.0);
2475            }),
2476            Some((r, 6.0))
2477        );
2478        assert_eq!(
2479            shape(&|p| {
2480                p.circle((30.0, 30.0), 10.0);
2481            }),
2482            Some((Rect::new(20.0, 20.0, 20.0, 20.0), 10.0))
2483        );
2484        let square = Rect::new(0.0, 0.0, 20.0, 20.0);
2485        assert_eq!(
2486            shape(&|p| {
2487                p.rrect(square, 10.0);
2488            }),
2489            Some((square, 10.0)),
2490            "a rounded rect whose radii fill a square is a circle"
2491        );
2492        assert_eq!(
2493            shape(&|p| {
2494                p.rrect_radii(r, [6.0, 6.0, 0.0, 0.0]);
2495            }),
2496            None
2497        );
2498        assert_eq!(
2499            shape(&|p| {
2500                p.rrect_radii_elliptical(r, [[6.0, 3.0]; 4]);
2501            }),
2502            None
2503        );
2504        assert_eq!(
2505            shape(&|p| {
2506                p.rrect(r, 10.0);
2507            }),
2508            Some((r, 10.0)),
2509            "a pill"
2510        );
2511        assert_eq!(
2512            shape(&|p| {
2513                p.rrect_radii_elliptical(r, [[20.0, 10.0]; 4]);
2514            }),
2515            None,
2516            "a non-square oval"
2517        );
2518        assert_eq!(
2519            shape(&|p| {
2520                p.rrect(r, 6.0);
2521                p.line_to((0.0, 0.0));
2522            }),
2523            None,
2524            "a rounded rect with more after it"
2525        );
2526    }
2527
2528    /// A rounded rectangle moved as dart:ui's `Path.shift` moves it
2529    /// (`Path::transformed`, Skia's `SkPath::offset`) still takes the
2530    /// closed form, where the moved one is.
2531    #[test]
2532    fn a_shadow_of_a_moved_round_rect_keeps_the_closed_form() {
2533        let mut path = PathBuilder::new();
2534        path.rrect(Rect::new(10.0, 10.0, 40.0, 20.0), 6.0);
2535        let moved = path.build().transformed(&Matrix::translation(100.0, 50.0));
2536        let mut b = DisplayListBuilder::new();
2537        b.draw_shadow(&moved, FillRule::NonZero, Color::BLACK, 4.0, false, 1.0);
2538        let dl = b.build();
2539        let [Op::DrawShadow { round_rect, .. }] = dl.ops() else {
2540            panic!("one shadow recorded: {:?}", dl.ops());
2541        };
2542        assert_eq!(*round_rect, Some((Rect::new(110.0, 60.0, 40.0, 20.0), 6.0)));
2543    }
2544}