valo-dl 0.2.2

Display-list recording for valo, with the record-time oracle the renderer replays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
use std::sync::Arc;

use valo_geometry::{FillRule, Matrix, Path, PathBuilder, Rect};

use crate::{ClipOp, DisplayList, Image, MaskKind, Op, Paint, Sampling};

/// `DisplayListBuilder` records drawing commands into an immutable display list.
///
/// Recording is GPU-free and may run on any thread. The builder resolves bounds,
/// clips, layer extents, and ordering metadata so rendering does not need to
/// rediscover them.
pub struct DisplayListBuilder {
    ops: Vec<Op>,
    scopes: Vec<Scope>,
    /// Open save layers (innermost last). Layer-scoped oracle state lives
    /// here; `Scope.is_layer` says which restore pops one.
    layers: Vec<LayerScope>,
    /// Shared backdrop keys seen so far, each with the union of the regions
    /// of the backdrop layers carrying it (the replay blurs each union once).
    backdrop_groups: Vec<crate::BackdropGroup>,
    /// Ops indexes of clips awaiting their expiry, one bucket per open scope
    /// (index 0 = the root scope, closed by `build`).
    pending_clips: Vec<Vec<usize>>,
    /// The depth-slot counter: ONE line for the whole list (Impeller's
    /// `current_depth_`) — layer children continue it, never restart it.
    slots: u32,
    bounds: Option<Rect>,
    draw_count: u32,
    /// Backdrop reads in this list, nested lists included — shared or not.
    /// Consumers that freeze pixels (the raster cache) must refuse any list
    /// where this is nonzero.
    backdrop_reads: u32,
}

/// `Backdrop` describes what a backdrop save layer samples from the scene
/// beneath it.
///
/// Today that is a gaussian blur. Further seed-only stages (a color matrix
/// for iOS glass saturation) join as fields here, never as effects on the
/// layer paint — a paint effect would filter the children too.
#[derive(Clone, Copy, Debug)]
pub struct Backdrop {
    /// Gaussian σ in local units at record; replay scales it into device
    /// px. σ ≤ 0 records a plain save layer (nothing to blur — the scene
    /// already shows through).
    pub sigma: f32,
    /// Tiles sharing a key reuse the FIRST tile's blur — and see the scene
    /// as of that tile. Use one key only for tiles over the same
    /// background.
    pub shared_key: Option<u64>,
}

impl Backdrop {
    /// `blur` is a gaussian backdrop blur of `sigma` local units.
    pub fn blur(sigma: f32) -> Self {
        Self {
            sigma,
            shared_key: None,
        }
    }

    /// `shared` marks this backdrop as one tile of a keyed group.
    pub fn shared(mut self, key: u64) -> Self {
        self.shared_key = Some(key);
        self
    }
}

/// One save-scope's state: the transform and the device-space clip bounds
/// (`None` = unclipped). Both restore on `restore()`.
#[derive(Clone, Copy)]
struct Scope {
    transform: Matrix,
    clip: Option<Rect>,
    is_layer: bool,
}

/// Record-time state of an open `save_layer` scope.
struct LayerScope {
    /// The `Op::SaveLayer` to backpatch at restore.
    op_index: usize,
    /// Union of child draw bounds (list-root space, already clip∩hint-cropped).
    bounds: Option<Rect>,
    /// Children so far — for the pairwise-disjoint check (only consulted
    /// while `compatible` still holds).
    child_bounds: Vec<Rect>,
    /// Alpha-linear + disjoint so far (Flutter's
    /// can_distribute_opacity). Clips and nested lists falsify it.
    compatible: bool,
    /// ±3σ (device units) when the composite paint blurs.
    blur_pad: f32,
    /// `(sigma, shared_key)` when this layer opens pre-filled with a blur
    /// of what's beneath it. The keyed group is noted at close, when the
    /// layer's region is known.
    backdrop: Option<(f32, Option<u64>)>,
    /// A caller-supplied bounds hint is a CROP; eliding a hinted layer
    /// would un-crop it. Conservative — Flutter tracks whether the bounds
    /// actually clipped (`kMayClipContents`); valo vetoes on any hint until
    /// a real caller needs the finer rule.
    hinted: bool,
}

impl Default for DisplayListBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl DisplayListBuilder {
    /// `new` creates an empty display-list builder.
    pub fn new() -> Self {
        Self {
            ops: Vec::new(),
            scopes: vec![Scope {
                transform: Matrix::IDENTITY,
                clip: None,
                is_layer: false,
            }],
            layers: Vec::new(),
            backdrop_groups: Vec::new(),
            pending_clips: vec![Vec::new()],
            slots: 0,
            bounds: None,
            draw_count: 0,
            backdrop_reads: 0,
        }
    }

    // ── transform stack (canvas semantics) ─────────────────────────────────

    /// `save` preserves the current transform and clip until the matching `restore`.
    pub fn save(&mut self) {
        self.scopes.push(Scope {
            is_layer: false,
            ..*self.top()
        });
        self.pending_clips.push(Vec::new());
        self.ops.push(Op::Save);
    }

    /// `save_count` returns the current canvas save-stack depth.
    ///
    /// A new builder starts at one. Each `save` or save-layer operation
    /// increments the count, and each matched `restore` decrements it. Hosts
    /// can use the value to verify that callbacks leave shared canvas state balanced.
    pub fn save_count(&self) -> usize {
        self.scopes.len()
    }

    /// `save_layer` begins an offscreen layer composited with `paint` at `restore`.
    ///
    /// `bounds_hint` is a local-space crop, not merely an allocation hint;
    /// content outside it is discarded. Pass `None` to derive bounds from the
    /// recorded children and active clip.
    pub fn save_layer(&mut self, bounds_hint: Option<Rect>, paint: &Paint) {
        self.save_layer_inner(bounds_hint, paint, None, None);
    }

    /// `save_layer_mask` begins a mask layer closed by `restore`.
    ///
    /// The layer's pixels become luminance or alpha coverage according to
    /// `kind`, retaining enclosing content only where the mask has coverage.
    /// `bounds_hint` crops the mask in local space.
    pub fn save_layer_mask(&mut self, bounds_hint: Option<Rect>, kind: MaskKind) {
        let paint = Paint {
            blend_mode: crate::BlendMode::DstIn,
            ..Paint::default()
        };
        self.save_layer_inner(bounds_hint, &paint, Some(kind), None);
    }

    /// `save_layer_backdrop` begins a layer that OPENS pre-filled with the
    /// [`Backdrop`]-filtered scene beneath it (frosted glass). Children
    /// paint over that glass, and `restore` composites glass + children as
    /// one image with `paint` — so a group alpha fades them together
    /// (Flutter's `saveLayer(bounds, paint, backdrop)`).
    ///
    /// Without `bounds_hint` the layer covers the active clip — a backdrop
    /// reads everything beneath it, so a hint-less, clip-less list records
    /// unbounded bounds; hint the layer when the list will be embedded.
    pub fn save_layer_backdrop(
        &mut self,
        bounds_hint: Option<Rect>,
        paint: &Paint,
        backdrop: Backdrop,
    ) {
        // σ ≤ 0 has nothing to sample: keep the layer semantics, drop the
        // read (and the raster-cache poison that rides every real read).
        let backdrop = (backdrop.sigma > 0.0).then_some((backdrop.sigma, backdrop.shared_key));
        self.save_layer_inner(bounds_hint, paint, None, backdrop);
    }

    fn save_layer_inner(
        &mut self,
        bounds_hint: Option<Rect>,
        paint: &Paint,
        mask_composite: Option<MaskKind>,
        backdrop: Option<(f32, Option<u64>)>,
    ) {
        let device_hint = bounds_hint.map(|h| self.top().transform.map_rect(&h));
        let mut scope = Scope {
            is_layer: true,
            ..*self.top()
        };
        // The hint crops children: fold it into the scope clip so child
        // bounds (and everything derived) come pre-cropped.
        if let Some(h) = device_hint {
            scope.clip = Some(match scope.clip {
                None => h,
                Some(c) => c.intersect(&h).unwrap_or_default(),
            });
        }
        // A filter that changes transparent black has output outside child
        // ink. Its input coverage is therefore the explicit/active clip, or
        // the renderer's eventual surface limit when no clip is known yet.
        let floods_scope = paint.blend_mode.is_destructive()
            || paint
                .color_filter
                .is_some_and(|filter| filter.modifies_transparent_black())
            || paint
                .image_filter
                .as_ref()
                .is_some_and(|filter| filter.modifies_transparent_black())
            // A backdrop layer OPENS full of blurred parent, so it paints its
            // whole region whether or not children add ink — and with no
            // hint that region is everything beneath it. Deriving its bounds
            // from children instead would leave a childless glass panel empty.
            || backdrop.is_some();
        let flooded_bounds = floods_scope.then(|| scope.clip.unwrap_or(Rect::EVERYTHING));
        if backdrop.is_some() {
            self.backdrop_reads += 1;
        }
        self.scopes.push(scope);
        self.pending_clips.push(Vec::new());
        self.layers.push(LayerScope {
            op_index: self.ops.len(),
            bounds: flooded_bounds,
            child_bounds: Vec::new(),
            compatible: true,
            // Blurred layers spread ink past their children:
            // pad the recorded bounds so the texture holds the falloff.
            blur_pad: paint.device_effect_padding(&self.top().transform),
            backdrop,
            hinted: device_hint.is_some(),
        });
        // Children keep counting on the SAME depth line (Impeller's global
        // numbering) — the layer's pass rebases against base_slot.
        self.ops.push(Op::SaveLayer {
            paint: paint.clone(),
            mask_composite,
            scope_bounds: Rect::default(), // backpatched at restore
            base_slot: self.slots,
            composite_slot: 0,
            can_elide: false,
            backdrop_sigma: backdrop.map(|(sigma, _)| sigma),
            backdrop_key: backdrop.and_then(|(_, key)| key),
        });
    }

    /// `restore` closes the most recent save, layer, or mask scope.
    ///
    /// An unmatched restore is ignored in release builds and triggers a debug assertion.
    pub fn restore(&mut self) {
        if self.scopes.len() == 1 {
            debug_assert!(false, "restore() without matching save()");
            return;
        }
        let scope = self.scopes.pop().expect("checked above");
        self.expire_scope_clips(); // uses the CURRENT (possibly layer) counter
        if scope.is_layer {
            self.close_layer();
        }
        self.ops.push(Op::Restore);
    }

    /// `translate` offsets subsequent drawing and clipping operations.
    pub fn translate(&mut self, tx: f32, ty: f32) {
        self.concat(&Matrix::translation(tx, ty));
    }

    /// `scale` scales subsequent drawing and clipping operations.
    pub fn scale(&mut self, sx: f32, sy: f32) {
        self.concat(&Matrix::scale(sx, sy));
    }

    /// `rotate` rotates subsequent drawing and clipping operations clockwise.
    ///
    /// Positive angles rotate clockwise in Valo's y-down coordinate system.
    pub fn rotate(&mut self, radians: f32) {
        self.concat(&Matrix::rotation(radians));
    }

    /// `concat` appends a transform for subsequent drawing and clipping operations.
    pub fn concat(&mut self, local: &Matrix) {
        let top = self.top_mut();
        top.transform = top.transform.then(local);
        self.ops.push(Op::Transform(*local));
    }

    // ── clips (depth slots; expiry backpatched when the scope closes) ──────

    /// `clip_rect` applies a rectangular clip until the current scope ends.
    pub fn clip_rect(&mut self, rect: impl Into<Rect>, op: ClipOp) {
        let rect = rect.into();
        self.clip_path(&rect_path(rect), FillRule::NonZero, op);
    }

    /// `clip_rrect` applies a rounded-rectangle clip with one corner radius.
    pub fn clip_rrect(&mut self, rect: impl Into<Rect>, radius: f32, op: ClipOp) {
        let rect = rect.into();
        self.clip_rrect_radii(rect, [radius; 4], op);
    }

    /// `clip_rrect_radii` applies a rounded-rectangle clip with per-corner radii.
    ///
    /// `radii` is ordered clockwise as `[top-left, top-right, bottom-right, bottom-left]`.
    pub fn clip_rrect_radii(&mut self, rect: impl Into<Rect>, radii: [f32; 4], op: ClipOp) {
        let rect = positive_rect(rect.into());
        let mut p = PathBuilder::new();
        p.rrect_radii(rect, radii);
        self.clip_path(&p.build(), FillRule::NonZero, op);
    }

    /// `clip_rrect_radii_elliptical` applies per-corner elliptical radii.
    ///
    /// Each clockwise corner is `[x_radius, y_radius]`, starting at the top-left.
    pub fn clip_rrect_radii_elliptical(
        &mut self,
        rect: impl Into<Rect>,
        radii: [[f32; 2]; 4],
        op: ClipOp,
    ) {
        let rect = positive_rect(rect.into());
        if let Some(circular) = circular_radii(radii) {
            return self.clip_rrect_radii(rect, circular, op);
        }
        let mut p = PathBuilder::new();
        p.rrect_radii_elliptical(rect, radii);
        self.clip_path(&p.build(), FillRule::NonZero, op);
    }

    /// `clip_path` applies a path clip until the current scope ends.
    ///
    /// Clips do NOT forfeit an enclosing layer's elision (Flutter's
    /// opacity distribution ignores clips too): a depth clip records its
    /// own expiry slot and works identically whether the group's children
    /// draw in a layer or in the parent, and child bounds are already
    /// clip-cropped when the disjointness check reads them. The Cupertino
    /// dialog depends on this — fade → clip → backdrop must keep the fade
    /// elidable or the glass snapshots a cleared offscreen.
    pub fn clip_path(&mut self, path: &Arc<Path>, fill_rule: FillRule, op: ClipOp) {
        let bounds = self.top().transform.map_rect(&path.bounds());
        self.shrink_clip(op, bounds);
        self.pending_clips
            .last_mut()
            .expect("root scope")
            .push(self.ops.len());
        self.ops.push(Op::ClipPath {
            path: Arc::clone(path),
            fill_rule,
            op,
            expiry_slot: 0, // backpatched by expire_scope_clips
        });
    }

    // ── draws (one slot each; bounds pre-clipped for the culling oracle) ───

    /// `draw_rect` records a filled or stroked rectangle.
    pub fn draw_rect(&mut self, rect: impl Into<Rect>, paint: &Paint) {
        let rect = rect.into();
        if paint.is_nop() {
            return;
        }
        if matches!(paint.style, crate::PaintStyle::Stroke(_)) {
            // Stroked rects are stroked paths — one geometry pipeline.
            // Zero-area rects still stroke: Skia draws them as a line.
            return self.draw_path(&rect_path(rect), FillRule::NonZero, paint);
        }
        if rect.is_empty() {
            return;
        }
        if is_analytic_blur(paint) {
            self.record_rrect_blur(rect, [0.0; 4], paint);
            return;
        }
        let Some(bounds) = self.clipped_device_bounds(&paint.effect_bounds(rect)) else {
            return; // fully clipped at record time
        };
        let slot = self.take_draw_slot(bounds, supports_opacity(paint));
        self.ops.push(Op::DrawRect {
            rect,
            paint: paint.clone(),
            bounds,
            slot,
        });
    }

    /// `draw_path` records a filled or stroked path.
    pub fn draw_path(&mut self, path: &Arc<Path>, fill_rule: FillRule, paint: &Paint) {
        if path.is_empty() || paint.is_nop() {
            return;
        }
        let scale = self.top().transform.max_scale();
        let local = paint.effect_bounds(path.bounds().expand(paint.stroke_padding_at_scale(scale)));
        let Some(bounds) = self.clipped_device_bounds(&local) else {
            return;
        };
        let slot = self.take_draw_slot(bounds, supports_opacity(paint));
        self.ops.push(Op::DrawPath {
            path: Arc::clone(path),
            fill_rule,
            paint: paint.clone(),
            bounds,
            slot,
        });
    }

    /// `draw_circle` records a filled or stroked circle.
    pub fn draw_circle(
        &mut self,
        center: impl Into<valo_geometry::Point>,
        radius: f32,
        paint: &Paint,
    ) {
        let mut p = PathBuilder::new();
        p.circle(center, radius);
        self.draw_path(&p.build(), FillRule::NonZero, paint);
    }

    /// `draw_rrect` records a rounded rectangle with one corner radius.
    pub fn draw_rrect(&mut self, rect: impl Into<Rect>, radius: f32, paint: &Paint) {
        let rect = rect.into();
        self.draw_rrect_radii(rect, [radius; 4], paint);
    }

    /// `draw_rrect_radii` records a rounded rectangle with per-corner radii.
    ///
    /// `radii` is ordered clockwise as `[top-left, top-right, bottom-right, bottom-left]`.
    pub fn draw_rrect_radii(&mut self, rect: impl Into<Rect>, radii: [f32; 4], paint: &Paint) {
        let rect = positive_rect(rect.into());
        if rect.is_empty() || paint.is_nop() {
            return;
        }
        if is_analytic_blur(paint) {
            self.record_rrect_blur(rect, radii, paint);
            return;
        }
        let mut p = PathBuilder::new();
        p.rrect_radii(rect, radii);
        self.draw_path(&p.build(), FillRule::NonZero, paint);
    }

    /// `draw_rrect_radii_elliptical` records per-corner elliptical radii.
    ///
    /// Each clockwise corner is `[x_radius, y_radius]`, starting at the top-left.
    pub fn draw_rrect_radii_elliptical(
        &mut self,
        rect: impl Into<Rect>,
        radii: [[f32; 2]; 4],
        paint: &Paint,
    ) {
        let rect = positive_rect(rect.into());
        if let Some(circular) = circular_radii(radii) {
            return self.draw_rrect_radii(rect, circular, paint);
        }
        if rect.is_empty() || paint.is_nop() {
            return;
        }
        let mut p = PathBuilder::new();
        p.rrect_radii_elliptical(rect, radii);
        self.draw_path(&p.build(), FillRule::NonZero, paint);
    }

    /// `draw_image` records the whole image into `dst`.
    ///
    /// It uses linear filtering and clamps at the image edges.
    pub fn draw_image(&mut self, image: &Image, dst: Rect, paint: &Paint) {
        let src = Rect::new(0.0, 0.0, image.width(), image.height());
        self.draw_image_rect(image, src, dst, Sampling::default(), paint);
    }

    /// `draw_image_rect` records a source region into `dst` with explicit sampling.
    ///
    /// `src` is measured in source pixels. Tiling applies when `src` extends
    /// beyond the image bounds.
    pub fn draw_image_rect(
        &mut self,
        image: &Image,
        src: Rect,
        dst: Rect,
        sampling: Sampling,
        paint: &Paint,
    ) {
        if dst.is_empty() || src.is_empty() || paint.is_nop() {
            return;
        }
        let Some(bounds) = self.clipped_device_bounds(&paint.effect_bounds(dst)) else {
            return;
        };
        let slot = self.take_draw_slot(bounds, supports_opacity(paint));
        self.ops.push(Op::DrawImage {
            image: image.clone(),
            src,
            dst,
            sampling,
            paint: paint.clone(),
            bounds,
            slot,
        });
    }

    /// `draw_glyph_run` records positioned glyphs from one font and size.
    ///
    /// `local_bounds` must enclose the glyph ink in local coordinates. Valo
    /// retains the supplied font and glyph positions in the display list.
    pub fn draw_glyph_run(
        &mut self,
        font: std::sync::Arc<valo_text::Font>,
        size: f32,
        paint: &Paint,
        glyphs: Arc<Vec<crate::GlyphPos>>,
        local_bounds: Rect,
    ) {
        if glyphs.is_empty() || paint.is_nop() {
            return;
        }
        let scale = self.top().transform.max_scale();
        let padded = paint.effect_bounds(local_bounds.expand(paint.stroke_padding_at_scale(scale)));
        let Some(bounds) = self.clipped_device_bounds(&padded) else {
            return;
        };
        // Shader text desugars into a two-draw layer at plan time; group
        // opacity can't ride its children (it would apply twice).
        let distributes = supports_opacity(paint) && paint.shader.is_none();
        let slot = self.take_draw_slot(bounds, distributes);
        self.ops.push(Op::GlyphRun {
            font,
            size,
            paint: paint.clone(),
            glyphs,
            bounds,
            slot,
        });
    }

    /// `draw_display_list` records a nested display list by shared reference.
    pub fn draw_display_list(&mut self, list: &Arc<DisplayList>) {
        self.embed_display_list(list, false);
    }

    /// `draw_display_list_cached` records a nested list as a raster-cache candidate.
    ///
    /// Use it for stable, repeatedly drawn lists whose recording is expensive.
    /// The renderer may still replay the list directly when caching is unsuitable.
    pub fn draw_display_list_cached(&mut self, list: &Arc<DisplayList>) {
        self.embed_display_list(list, true);
    }

    fn embed_display_list(&mut self, list: &Arc<DisplayList>, cache: bool) {
        let Some(child_bounds) = list.bounds() else {
            return; // draws nothing
        };
        let Some(bounds) = self.clipped_device_bounds(&child_bounds) else {
            return;
        };
        let base_slot = self.slots;
        self.slots += list.depth_slots();
        self.draw_count += list.draw_count();
        self.backdrop_reads += list.backdrop_reads();
        self.union_bounds(bounds);
        // Conservative: a nested list's internal structure is opaque here.
        self.note_layer_child(bounds, false);
        self.ops.push(Op::DrawDisplayList {
            list: Arc::clone(list),
            bounds,
            base_slot,
            cache,
        });
    }

    // ── build ──────────────────────────────────────────────────────────────

    /// `build` consumes the builder and returns its immutable display list.
    ///
    /// Any unmatched save scopes are closed before the list is finalized.
    pub fn build(mut self) -> DisplayList {
        // Unbalanced saves are a recording bug, but a recoverable one: close
        // them so replay's stack discipline holds.
        while self.scopes.len() > 1 {
            self.restore();
        }
        self.expire_scope_clips(); // root-scope clips live to end-of-list
        DisplayList::new(
            self.ops,
            self.bounds,
            self.draw_count,
            self.slots,
            self.backdrop_groups,
            self.backdrop_reads,
        )
    }

    // ── internals ──────────────────────────────────────────────────────────

    fn top(&self) -> &Scope {
        self.scopes.last().expect("scope stack never empty")
    }

    fn top_mut(&mut self) -> &mut Scope {
        self.scopes.last_mut().expect("scope stack never empty")
    }

    /// Backpatch the layer's oracle at its restore. Order matters: the
    /// layer's clips expired first (caller did that), so their slots sit
    /// inside the children's span; the composite takes the NEXT slot on the
    /// same line.
    fn close_layer(&mut self) {
        let layer = self.layers.pop().expect("is_layer scope had a LayerScope");
        self.slots += 1; // the composite's slot, next after the children's span
        let mut scope_bounds = layer.bounds.unwrap_or_default();
        if layer.blur_pad > 0.0 && !scope_bounds.is_empty() {
            scope_bounds = scope_bounds.expand(layer.blur_pad);
        }

        let Op::SaveLayer {
            paint,
            mask_composite: _,
            scope_bounds: sb,
            base_slot: _,
            composite_slot,
            can_elide,
            ..
        } = &mut self.ops[layer.op_index]
        else {
            unreachable!("LayerScope.op_index always points at SaveLayer");
        };
        *sb = scope_bounds;
        *composite_slot = self.slots;
        // A backdrop layer never elides (its seed needs a texture); a hinted
        // layer never elides (the hint is a crop that eliding would undo).
        *can_elide = layer.compatible
            && paint.is_opacity_only()
            && layer.backdrop.is_none()
            && !layer.hinted;

        // One SrcOver composite quad — an ENCLOSING opacity group can still
        // distribute its alpha onto it. This is what lets a fading group
        // elide over a backdrop layer: the alpha lands once, on the glass
        // and its children together.
        let supports = paint.blend_mode == crate::BlendMode::SrcOver;
        if let Some((sigma, Some(key))) = layer.backdrop {
            self.note_backdrop_group(key, scope_bounds, sigma);
        }
        self.draw_count += 1; // the composite draws
        self.union_bounds(scope_bounds);
        self.note_layer_child(scope_bounds, supports);
    }

    /// One-quad closed-form blurred (r)rect; the quad spans the 3σ spread.
    fn record_rrect_blur(&mut self, rect: Rect, radii: [f32; 4], paint: &Paint) {
        let Some(bounds) = self.clipped_device_bounds(&rect.expand(paint.mask_padding())) else {
            return;
        };
        let slot = self.take_draw_slot(bounds, supports_opacity(paint));
        self.ops.push(Op::RRectBlur {
            rect,
            radii: valo_geometry::constrain_radii(&rect, radii),
            paint: paint.clone(),
            bounds,
            slot,
        });
    }

    fn note_backdrop_group(&mut self, key: u64, bounds: Rect, sigma: f32) {
        match self.backdrop_groups.iter_mut().find(|g| g.key == key) {
            Some(group) => {
                group.union_bounds = group.union_bounds.union(&bounds);
                if group.sigma != Some(sigma) {
                    group.sigma = None; // mixed σ under one key: no sharing
                }
            }
            None => self.backdrop_groups.push(crate::BackdropGroup {
                key,
                union_bounds: bounds,
                sigma: Some(sigma),
            }),
        }
    }

    /// Draw bounds in list-root space, pre-intersected with the clip stack;
    /// `None` = provably invisible, don't record.
    fn clipped_device_bounds(&self, local: &Rect) -> Option<Rect> {
        let device = self.top().transform.map_rect(local);
        match self.top().clip {
            None => Some(device),
            Some(clip) => device.intersect(&clip),
        }
    }

    /// Intersect clips shrink the recorded clip bounds; Difference is kept
    /// conservative (bounds unchanged — correct, just not tighter).
    fn shrink_clip(&mut self, op: ClipOp, shape_bounds: Rect) {
        if op == ClipOp::Difference {
            return;
        }
        let top = self.top_mut();
        top.clip = Some(match top.clip {
            None => shape_bounds,
            Some(c) => c.intersect(&shape_bounds).unwrap_or_default(), // empty = all clipped
        });
    }

    /// Closing a scope that recorded clips consumes ONE slot — that slot is
    /// every pending clip's expiry: scope draws sit below it (ceilinged),
    /// later draws above it (free). This is how expiry stays record-time.
    fn expire_scope_clips(&mut self) {
        let pending = self.pending_clips.pop().expect("scope stack never empty");
        if !pending.is_empty() {
            self.slots += 1;
            for idx in pending {
                let Op::ClipPath { expiry_slot, .. } = &mut self.ops[idx] else {
                    unreachable!("pending_clips indexes only ClipPath ops");
                };
                *expiry_slot = self.slots;
            }
        }
        if self.pending_clips.is_empty() {
            self.pending_clips.push(Vec::new()); // keep the root bucket alive
        }
    }

    fn take_draw_slot(&mut self, device_bounds: Rect, supports_opacity: bool) -> u32 {
        self.slots += 1;
        self.draw_count += 1;
        self.union_bounds(device_bounds);
        self.note_layer_child(device_bounds, supports_opacity);
        self.slots
    }

    fn union_bounds(&mut self, b: Rect) {
        self.bounds = Some(match self.bounds {
            Some(cur) => cur.union(&b),
            None => b,
        });
    }

    /// Feed the innermost open layer's oracle: union its bounds; falsify
    /// compatibility on an alpha-nonlinear child or the first overlap
    /// (pairwise-disjoint is what makes shared-z elision legal).
    fn note_layer_child(&mut self, bounds: Rect, supports_opacity: bool) {
        let Some(layer) = self.layers.last_mut() else {
            return;
        };
        layer.bounds = Some(match layer.bounds {
            Some(cur) => cur.union(&bounds),
            None => bounds,
        });
        if !layer.compatible {
            return;
        }
        if !supports_opacity {
            layer.compatible = false;
            return;
        }
        if layer
            .child_bounds
            .iter()
            .any(|prior| prior.intersects(&bounds))
        {
            layer.compatible = false;
            return;
        }
        layer.child_bounds.push(bounds);
    }
}

/// Group opacity distributes over a child iff scaling its src by α equals
/// compositing the group at α: true for SrcOver and Plus (both linear in
/// src), false for dst-multiplying and advanced modes.
fn supports_opacity(paint: &Paint) -> bool {
    // A colour filter is affine, not linear: distributing the group's alpha
    // into the paint colour would filter the DIMMED colour, and
    // `matrix(c · α) != matrix(c) · α` wherever the matrix translates or
    // clamps. Filtered draws keep their own layer.
    paint.color_filter.is_none()
        && paint.effective_image_filter().is_none()
        && matches!(
            paint.blend_mode,
            crate::BlendMode::SrcOver | crate::BlendMode::Plus
        )
}

/// Solid + mask blur = the closed-form quad (Impeller's shadow gate,
/// Canvas::IsShadowBlurDrawOperation). Shaders/images take the filter path.
/// `Some(circular)` when every corner's rx equals its ry — the case the
/// analytic rrect pipelines (blur shadows, uniform clips) can take.
fn circular_radii(radii: [[f32; 2]; 4]) -> Option<[f32; 4]> {
    radii
        .iter()
        .all(|[x, y]| x == y)
        .then(|| radii.map(|[x, _]| x))
}

// Flutter's RRect bridge accepts inverted edges and normalizes them before
// creating the engine round rect. CupertinoActivityIndicator relies on this.
fn positive_rect(rect: Rect) -> Rect {
    let x = if rect.width < 0.0 {
        rect.x + rect.width
    } else {
        rect.x
    };
    let y = if rect.height < 0.0 {
        rect.y + rect.height
    } else {
        rect.y
    };
    Rect::new(x, y, rect.width.abs(), rect.height.abs())
}

fn is_analytic_blur(paint: &Paint) -> bool {
    paint.mask_blur.is_some()
        && paint.shader.is_none()
        // The closed-form quad has nowhere to run a colour filter, so a
        // filtered shape takes the general layer path instead of silently
        // rendering its unfiltered colour.
        && paint.color_filter.is_none()
        && paint.effective_image_filter().is_none()
        && matches!(paint.style, crate::PaintStyle::Fill)
}

fn rect_path(r: Rect) -> Arc<Path> {
    let mut p = PathBuilder::new();
    p.rect(r);
    p.build()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::BlendMode;
    use valo_geometry::Color;

    #[test]
    fn save_count_tracks_saves_layers_and_restores() {
        let mut builder = DisplayListBuilder::new();
        assert_eq!(builder.save_count(), 1);

        builder.save();
        assert_eq!(builder.save_count(), 2);

        builder.save_layer(None, &Paint::default());
        assert_eq!(builder.save_count(), 3);

        builder.restore();
        assert_eq!(builder.save_count(), 2);
        builder.restore();
        assert_eq!(builder.save_count(), 1);
    }

    #[test]
    fn rounded_rects_normalize_inverted_edges_like_flutter() {
        let mut builder = DisplayListBuilder::new();
        builder.draw_rrect(
            Rect::from_ltrb(-1.0, -10.0 / 3.0, 1.0, -10.0),
            1.0,
            &Paint::from_color(Color::WHITE),
        );

        let list = builder.build();
        let Op::DrawPath { path, .. } = &list.ops()[0] else {
            panic!("rounded rectangle should record as a path");
        };
        assert_eq!(
            path.bounds(),
            Rect::from_ltrb(-1.0, -10.0, 1.0, -10.0 / 3.0)
        );
    }
    fn red() -> Paint {
        Paint::from_color(Color::rgb(1.0, 0.0, 0.0))
    }

    fn alpha_layer(a: f32) -> Paint {
        Paint::from_color(Color::rgba(0.0, 0.0, 0.0, a))
    }

    fn find_clip(dl: &DisplayList) -> (&Op, u32) {
        for op in dl.ops() {
            if let Op::ClipPath { expiry_slot, .. } = op {
                return (op, *expiry_slot);
            }
        }
        panic!("no clip recorded");
    }

    /// Every recorded layer's `(scope_bounds, base_slot, composite_slot,
    /// can_elide)`, in recording order — so an enclosing layer comes before
    /// the layers nested inside it.
    fn layer_facts(dl: &DisplayList) -> Vec<(Rect, u32, u32, bool)> {
        dl.ops()
            .iter()
            .filter_map(|op| match op {
                Op::SaveLayer {
                    scope_bounds,
                    base_slot,
                    composite_slot,
                    can_elide,
                    ..
                } => Some((*scope_bounds, *base_slot, *composite_slot, *can_elide)),
                _ => None,
            })
            .collect()
    }

    fn find_layer(dl: &DisplayList) -> (Rect, u32, u32, bool) {
        *layer_facts(dl).first().expect("no layer recorded")
    }

    #[test]
    fn oracle_bounds_follow_transforms() {
        let mut b = DisplayListBuilder::new();
        b.save();
        b.translate(100.0, 50.0);
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
        b.restore();
        let dl = b.build();
        assert_eq!(dl.bounds(), Some(Rect::new(100.0, 50.0, 10.0, 10.0)));
        assert_eq!(dl.draw_count(), 1);
        assert_eq!(dl.depth_slots(), 1);
    }

    #[test]
    fn clip_shrinks_recorded_draw_bounds() {
        let mut b = DisplayListBuilder::new();
        b.save();
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(25.0, 25.0, 100.0, 100.0), &red());
        b.restore();
        let dl = b.build();
        assert_eq!(dl.bounds(), Some(Rect::new(25.0, 25.0, 25.0, 25.0)));
    }

    #[test]
    fn fully_clipped_draw_is_dropped() {
        let mut b = DisplayListBuilder::new();
        b.save();
        b.clip_rect(Rect::new(0.0, 0.0, 10.0, 10.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(500.0, 500.0, 10.0, 10.0), &red());
        b.restore();
        let dl = b.build();
        assert_eq!(dl.draw_count(), 0);
    }

    #[test]
    fn clip_expiry_is_the_restore_slot() {
        let mut b = DisplayListBuilder::new();
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
        b.save();
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 2
        b.restore(); // slot 3 = expiry
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 4
        let dl = b.build();
        let (_, expiry) = find_clip(&dl);
        assert_eq!(expiry, 3);
        assert_eq!(dl.depth_slots(), 4);
    }

    #[test]
    fn root_clip_expires_at_end_of_list() {
        let mut b = DisplayListBuilder::new();
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
        let dl = b.build();
        let (_, expiry) = find_clip(&dl);
        assert_eq!(expiry, 2, "root clips expire at the virtual end slot");
        assert_eq!(dl.depth_slots(), 2);
    }

    #[test]
    fn difference_clip_keeps_bounds_conservative() {
        let mut b = DisplayListBuilder::new();
        b.save();
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Difference);
        b.draw_rect(Rect::new(0.0, 0.0, 100.0, 100.0), &red());
        b.restore();
        let dl = b.build();
        assert_eq!(dl.bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
    }

    #[test]
    fn nested_list_folds_oracle_and_offsets_slots() {
        let mut inner = DisplayListBuilder::new();
        inner.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
        inner.draw_rect(Rect::new(20.0, 0.0, 10.0, 10.0), &red());
        let inner = Arc::new(inner.build());

        let mut outer = DisplayListBuilder::new();
        outer.draw_rect(Rect::new(0.0, 0.0, 5.0, 5.0), &red()); // slot 1
        outer.translate(5.0, 5.0);
        outer.draw_display_list(&inner); // base_slot 1, child consumes 2
        outer.draw_rect(Rect::new(0.0, 0.0, 5.0, 5.0), &red()); // slot 4
        let outer = outer.build();

        assert_eq!(outer.draw_count(), 4);
        assert_eq!(outer.depth_slots(), 4);
        let base = outer
            .ops()
            .iter()
            .find_map(|op| match op {
                Op::DrawDisplayList { base_slot, .. } => Some(*base_slot),
                _ => None,
            })
            .unwrap();
        assert_eq!(base, 1);
    }

    #[test]
    fn nop_draws_are_dropped() {
        let mut b = DisplayListBuilder::new();
        b.draw_rect(Rect::new(0.0, 0.0, 0.0, 10.0), &red()); // empty rect
        b.draw_rect(
            Rect::new(0.0, 0.0, 10.0, 10.0),
            &Paint {
                color: Color::TRANSPARENT,
                blend_mode: BlendMode::SrcOver,
                ..Default::default()
            },
        );
        let dl = b.build();
        assert_eq!(dl.ops().len(), 0);
        assert_eq!(dl.bounds(), None);
    }

    // ── save layers (M4) ────────────────────────────────────────────────────

    #[test]
    fn layer_oracle_bounds_and_slots() {
        let mut b = DisplayListBuilder::new();
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red()); // slot 1
        b.save_layer(None, &alpha_layer(0.5)); // base_slot = 1
        b.draw_rect(Rect::new(20.0, 20.0, 30.0, 30.0), &red()); // slot 2
        b.draw_rect(Rect::new(60.0, 20.0, 30.0, 30.0), &red()); // slot 3
        b.restore(); // composite = slot 4, next on the same line
        b.draw_rect(Rect::new(0.0, 40.0, 10.0, 10.0), &red()); // slot 5
        let dl = b.build();

        let (bounds, base_slot, composite_slot, can_elide) = find_layer(&dl);
        assert_eq!(bounds, Rect::new(20.0, 20.0, 70.0, 30.0));
        assert_eq!(base_slot, 1, "scope opened after one parent draw");
        assert_eq!(composite_slot, 4, "children keep the global line");
        assert!(
            can_elide,
            "disjoint SrcOver children + alpha-only composite"
        );
        assert_eq!(
            dl.depth_slots(),
            5,
            "one global depth line (Impeller's current_depth_)"
        );
        assert_eq!(dl.draw_count(), 5, "4 rects + the composite");
    }

    #[test]
    fn overlapping_children_forfeit_elision() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(None, &alpha_layer(0.5));
        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
        b.draw_rect(Rect::new(10.0, 10.0, 30.0, 30.0), &red()); // overlaps
        b.restore();
        let (_, _, _, can_elide) = find_layer(&b.build());
        assert!(!can_elide);
    }

    #[test]
    fn advanced_blend_composite_forfeits_elision() {
        let mut b = DisplayListBuilder::new();
        let paint = Paint {
            color: Color::rgba(0.0, 0.0, 0.0, 0.5),
            blend_mode: BlendMode::Multiply,
            ..Default::default()
        };
        b.save_layer(None, &paint);
        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
        b.restore();
        let (_, _, _, can_elide) = find_layer(&b.build());
        assert!(!can_elide);
    }

    #[test]
    fn destructive_layer_composite_floods_the_active_clip() {
        let mut b = DisplayListBuilder::new();
        b.clip_rect(Rect::new(4.0, 6.0, 80.0, 60.0), ClipOp::Intersect);
        b.save_layer(
            None,
            &Paint {
                blend_mode: BlendMode::SrcIn,
                ..Default::default()
            },
        );
        b.draw_rect(Rect::new(20.0, 20.0, 10.0, 10.0), &red());
        b.restore();
        let (bounds, ..) = find_layer(&b.build());
        assert_eq!(bounds, Rect::new(4.0, 6.0, 80.0, 60.0));
    }

    #[test]
    fn clip_inside_layer_keeps_elision() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(None, &alpha_layer(0.5));
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
        b.restore();
        let (_, _, _, can_elide) = find_layer(&b.build());
        // A depth clip expires on its own slot either way; Flutter's
        // opacity distribution ignores clips too.
        assert!(can_elide);
    }

    #[test]
    fn bounds_hint_crops_the_scope() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(Some(Rect::new(0.0, 0.0, 40.0, 40.0)), &alpha_layer(0.5));
        b.draw_rect(Rect::new(20.0, 20.0, 100.0, 100.0), &red());
        b.restore();
        let (bounds, ..) = find_layer(&b.build());
        assert_eq!(bounds, Rect::new(20.0, 20.0, 20.0, 20.0));
    }

    #[test]
    fn clips_inside_layers_expire_within_the_scope_span() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(None, &alpha_layer(0.5)); // base_slot = 0
        b.save();
        b.clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0), ClipOp::Intersect);
        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red()); // slot 1
        b.restore(); // slot 2 = expiry
        b.restore(); // composite = slot 3
        let dl = b.build();
        let (_, expiry) = find_clip(&dl);
        assert_eq!(expiry, 2, "expiry sits inside the layer's span");
        let (_, base_slot, composite_slot, _) = find_layer(&dl);
        assert_eq!((base_slot, composite_slot), (0, 3));
    }

    // ── mask + backdrop blur (M5) ───────────────────────────────────────────

    #[test]
    fn solid_mask_blur_records_the_analytic_op() {
        let mut b = DisplayListBuilder::new();
        let paint = Paint {
            mask_blur: Some(crate::MaskBlur::new(4.0)),
            ..red()
        };
        b.draw_rect(Rect::new(20.0, 20.0, 40.0, 40.0), &paint);
        b.draw_rrect(Rect::new(100.0, 20.0, 40.0, 40.0), 8.0, &paint);
        let dl = b.build();
        let blurs: Vec<_> = dl
            .ops()
            .iter()
            .filter_map(|op| match op {
                Op::RRectBlur { radii, bounds, .. } => Some((*radii, *bounds)),
                _ => None,
            })
            .collect();
        assert_eq!(blurs.len(), 2);
        assert_eq!(blurs[0].0, [0.0; 4]);
        assert_eq!(blurs[1].0, [8.0; 4]);
        // Bounds carry the ±3σ spread.
        assert_eq!(blurs[0].1, Rect::new(8.0, 8.0, 64.0, 64.0));
    }

    #[test]
    fn shader_mask_blur_stays_general_but_pads_bounds() {
        let mut b = DisplayListBuilder::new();
        let paint = Paint {
            mask_blur: Some(crate::MaskBlur::new(2.0)),
            shader: Some(crate::Shader::linear(
                valo_geometry::Point::new(0.0, 0.0),
                valo_geometry::Point::new(10.0, 0.0),
                Color::BLACK,
                Color::WHITE,
            )),
            color: Color::WHITE,
            ..Default::default()
        };
        b.draw_rect(Rect::new(10.0, 10.0, 20.0, 20.0), &paint);
        let dl = b.build();
        let Op::DrawRect { bounds, .. } = &dl.ops()[0] else {
            panic!("shader paints keep the general op");
        };
        assert_eq!(*bounds, Rect::new(4.0, 4.0, 32.0, 32.0));
    }

    #[test]
    fn hinted_layer_forfeits_elision() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(Some(Rect::new(0.0, 0.0, 40.0, 40.0)), &alpha_layer(0.5));
        b.draw_rect(Rect::new(0.0, 0.0, 30.0, 30.0), &red());
        b.restore();
        let (_, _, _, can_elide) = find_layer(&b.build());
        assert!(!can_elide, "the hint is a crop; eliding would un-crop it");
    }

    // ── backdrop layers ─────────────────────────────────────────────────────

    /// A glass panel: a backdrop layer with nothing painted over it.
    fn glass(b: &mut DisplayListBuilder, rect: Rect, sigma: f32, key: Option<u64>) {
        b.save_layer_backdrop(
            Some(rect),
            &Paint::default(),
            Backdrop {
                sigma,
                shared_key: key,
            },
        );
        b.restore();
    }

    #[test]
    fn shared_backdrops_group_by_key() {
        let mut b = DisplayListBuilder::new();
        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 8.0, Some(7));
        glass(&mut b, Rect::new(100.0, 0.0, 50.0, 50.0), 8.0, Some(7));
        glass(&mut b, Rect::new(0.0, 100.0, 50.0, 50.0), 8.0, None);
        let dl = b.build();
        let group = dl.backdrop_group(7).expect("key 7 recorded");
        // Each layer joins its group at close, contributing its scope bounds.
        assert_eq!(group.union_bounds, Rect::new(0.0, 0.0, 150.0, 50.0));
        assert_eq!(group.sigma, Some(8.0), "one σ across the key: shareable");
        assert_eq!(dl.draw_count(), 3, "each layer's composite is a draw");
        assert_eq!(dl.depth_slots(), 3);
    }

    #[test]
    fn mixed_sigma_under_one_key_clears_the_shared_sigma() {
        let mut b = DisplayListBuilder::new();
        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, Some(7));
        glass(&mut b, Rect::new(100.0, 0.0, 50.0, 50.0), 12.0, Some(7));
        let dl = b.build();
        let group = dl.backdrop_group(7).expect("key 7 recorded");
        assert_eq!(group.sigma, None, "disagreeing σ cannot share one blur");
    }

    #[test]
    fn opacity_group_elides_over_a_backdrop_layer() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(None, &alpha_layer(0.5));
        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
        b.restore();
        let layers = layer_facts(&b.build());
        assert_eq!(layers.len(), 2, "the opacity group and the glass inside it");
        assert!(
            layers[0].3,
            "the group's alpha lands on the glass composite — the whole point \
             of backdrop-as-a-layer-property: glass keeps blurring while the \
             group fades"
        );
        assert!(!layers[1].3, "the glass itself needs a texture to seed");
    }

    /// The Cupertino dialog's exact recording shape: fade -> superellipse
    /// clip -> glass. The clip must NOT forfeit the fade's elision - a depth
    /// clip works identically whether the group's children draw in a layer
    /// or the parent, and eliding is what lets the glass snapshot the live
    /// scene instead of the fade's cleared offscreen.
    #[test]
    fn a_clip_does_not_forfeit_elision_around_glass() {
        let mut b = DisplayListBuilder::new();
        b.save_layer(None, &alpha_layer(0.5));
        b.save();
        let mut clip = PathBuilder::new();
        clip.rect(Rect::new(0.0, 0.0, 60.0, 60.0));
        b.clip_path(&clip.build(), FillRule::NonZero, ClipOp::Intersect);
        glass(&mut b, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
        b.restore();
        b.restore();
        let layers = layer_facts(&b.build());
        assert_eq!(layers.len(), 2);
        assert!(layers[0].3, "the clipped fade still elides");
        assert!(!layers[1].3);
    }

    #[test]
    fn backdrop_reads_count_unshared_and_nested() {
        let mut child = DisplayListBuilder::new();
        glass(&mut child, Rect::new(0.0, 0.0, 50.0, 50.0), 4.0, None);
        let child = Arc::new(child.build());
        assert_eq!(child.backdrop_reads(), 1, "unshared reads count too");

        let mut parent = DisplayListBuilder::new();
        glass(&mut parent, Rect::new(0.0, 0.0, 50.0, 50.0), 8.0, Some(7));
        parent.draw_display_list(&child);
        let parent = parent.build();
        assert_eq!(parent.backdrop_reads(), 2, "own layer + the nested list's");

        let mut clean = DisplayListBuilder::new();
        clean.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
        assert_eq!(clean.build().backdrop_reads(), 0);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_dump_is_readable_json() {
        // Dump-only by design (plan: diffs + bug reports, never persistence —
        // an Image can't be deserialized without a device).
        let mut b = DisplayListBuilder::new();
        b.translate(1.0, 2.0);
        b.draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &red());
        let dl = b.build();
        let json: serde_json::Value = serde_json::to_value(&dl).unwrap();
        assert_eq!(json["ops"].as_array().unwrap().len(), dl.ops().len());
        assert!(json["ops"][1]["DrawRect"]["slot"].is_number());
    }
}