servo-layout 0.3.0

A component of the servo web-engine.
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
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::cell::{OnceCell, RefCell};
use std::sync::Arc;

use app_units::{AU_PER_PX, Au};
use clip::{Clip, ClipId};
use euclid::{Box2D, Point2D, Rect, Scale, SideOffsets2D, Size2D, UnknownUnit, Vector2D};
use fonts::ShapedTextSlice;
use gradient::WebRenderGradient;
use layout_api::ReflowStatistics;
use net_traits::image_cache::Image as CachedImage;
use paint_api::display_list::{PaintDisplayListInfo, SpatialTreeNodeInfo};
use servo_arc::Arc as ServoArc;
use servo_base::id::{PipelineId, ScrollTreeNodeId};
use servo_config::opts::{DiagnosticsLogging, DiagnosticsLoggingOption};
use servo_config::{pref, prefs};
use servo_url::ServoUrl;
use style::Zero;
use style::color::{AbsoluteColor, ColorSpace};
use style::computed_values::background_blend_mode::SingleComputedValue as BackgroundBlendMode;
use style::computed_values::border_image_outset::T as BorderImageOutset;
use style::computed_values::text_decoration_style::{
    T as ComputedTextDecorationStyle, T as TextDecorationStyle,
};
use style::dom::OpaqueNode;
use style::properties::ComputedValues;
use style::properties::longhands::visibility::computed_value::T as Visibility;
use style::properties::style_structs::Border;
use style::values::computed::{
    BorderImageSideWidth, BorderImageWidth, BorderStyle, LengthPercentage,
    NonNegativeLengthOrNumber, NumberOrPercentage, OutlineStyle,
};
use style::values::generics::NonNegative;
use style::values::generics::color::ColorOrAuto;
use style::values::generics::rect::Rect as StyleRect;
use style::values::specified::text::TextDecorationLine;
use style_traits::{CSSPixel as StyloCSSPixel, DevicePixel as StyloDevicePixel};
use webrender_api::units::{
    DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint, LayoutRect, LayoutSideOffsets, LayoutSize,
};
use webrender_api::{
    self as wr, BorderDetails, BorderRadius, BorderSide, BoxShadowClipMode, BuiltDisplayList,
    ClipChainId, ClipMode, ColorF, CommonItemProperties, ComplexClipRegion, GlyphInstance,
    NinePatchBorder, NinePatchBorderSource, NormalBorder, PrimitiveFlags, PropertyBinding,
    PropertyBindingKey, RasterSpace, SpatialId, SpatialTreeItemKey, StackingContextFlags, units,
};
use wr::units::LayoutVector2D;

use crate::context::{ImageResolver, ResolvedImage};
pub(crate) use crate::display_list::conversions::ToWebRender;
use crate::display_list::stacking_context::StackingContextSection;
use crate::fragment_tree::{
    BackgroundMode, BoxFragment, ContainingBlockCalculation, Fragment, FragmentFlags,
    FragmentStatus, FragmentTree, SpecificLayoutInfo, Tag, TextFragment,
};
use crate::geom::{
    LengthPercentageOrAuto, PhysicalPoint, PhysicalRect, PhysicalSides, PhysicalSize,
};
use crate::replaced::NaturalSizes;
use crate::style_ext::{BorderStyleColor, ComputedValuesExt};

mod background;
mod clip;
mod conversions;
mod gradient;
mod hit_test;
mod paint_timing_handler;
mod stacking_context;

use background::BackgroundPainter;
pub(crate) use hit_test::HitTest;
pub(crate) use paint_timing_handler::PaintTimingHandler;
pub(crate) use stacking_context::*;

const INSERTION_POINT_LOGICAL_WIDTH: Au = Au(AU_PER_PX);

pub(crate) struct DisplayListBuilder<'a> {
    /// The current [ScrollTreeNodeId] for this [DisplayListBuilder]. This
    /// allows only passing the builder instead passing the containing
    /// [stacking_context::StackingContextContent::Fragment] as an argument to display
    /// list building functions.
    current_scroll_node_id: ScrollTreeNodeId,

    /// The current [ScrollTreeNodeId] for this [DisplayListBuilder]. This is necessary in addition
    /// to the [Self::current_scroll_node_id], because some pieces of fragments as backgrounds with
    /// `background-attachment: fixed` need to not scroll while the rest of the fragment does.
    current_reference_frame_scroll_node_id: ScrollTreeNodeId,

    /// The current [`ClipId`] for this [DisplayListBuilder]. This allows
    /// only passing the builder instead passing the containing
    /// [stacking_context::StackingContextContent::Fragment] as an argument to display
    /// list building functions.
    current_clip_id: ClipId,

    /// The [`wr::DisplayListBuilder`] for this Servo [`DisplayListBuilder`].
    pub webrender_display_list_builder: &'a mut wr::DisplayListBuilder,

    /// The [`PaintDisplayListInfo`] used to collect display list items and metadata.
    pub paint_info: &'a mut PaintDisplayListInfo,

    /// Data about the fragments that are highlighted by the inspector, if any.
    ///
    /// This data is collected during the traversal of the fragment tree and used
    /// to paint the highlight at the very end.
    inspector_highlight: Option<InspectorHighlight>,

    /// Whether or not the `<body>` element should be painted. This is false if the root `<html>`
    /// element inherits the `<body>`'s background to paint the page canvas background.
    /// See <https://drafts.csswg.org/css-backgrounds/#body-background>.
    paint_body_background: bool,

    /// A mapping from [`ClipId`] To WebRender [`ClipChainId`] used when building this WebRender
    /// display list.
    clip_map: Vec<ClipChainId>,

    /// An [`ImageResolver`] to use during display list construction.
    image_resolver: Arc<ImageResolver>,

    /// The device pixel ratio used for this `Document`'s display list.
    device_pixel_ratio: Scale<f32, StyloCSSPixel, StyloDevicePixel>,

    /// Handler for all Paint Timings
    paint_timing_handler: &'a mut PaintTimingHandler,

    /// Statistics collected about the reflow, in order to write tests for incremental layout.
    reflow_statistics: &'a mut ReflowStatistics,
}

struct InspectorHighlight {
    /// The node that should be highlighted
    tag: Tag,

    /// Accumulates information about the fragments that belong to the highlighted node.
    ///
    /// This information is collected as the fragment tree is traversed to build the
    /// display list.
    state: Option<HighlightTraversalState>,
}

struct HighlightTraversalState {
    /// The smallest rectangle that fully encloses all fragments created by the highlighted
    /// dom node, if any.
    content_box: Rect<Au, StyloCSSPixel>,

    spatial_id: SpatialId,

    clip_chain_id: ClipChainId,

    /// When the highlighted fragment is a box fragment we remember the information
    /// needed to paint padding, border and margin areas.
    maybe_box_fragment: Option<Arc<BoxFragment>>,
}

impl InspectorHighlight {
    fn for_node(node: OpaqueNode) -> Self {
        Self {
            tag: Tag {
                node,
                // TODO: Support highlighting pseudo-elements.
                pseudo_element_chain: Default::default(),
            },
            state: None,
        }
    }
}

impl DisplayListBuilder<'_> {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn build(
        stacking_context_tree: &mut StackingContextTree,
        fragment_tree: &FragmentTree,
        image_resolver: Arc<ImageResolver>,
        device_pixel_ratio: Scale<f32, StyloCSSPixel, StyloDevicePixel>,
        highlighted_dom_node: Option<OpaqueNode>,
        debug: &DiagnosticsLogging,
        paint_timing_handler: &mut PaintTimingHandler,
        reflow_statistics: &mut ReflowStatistics,
    ) -> BuiltDisplayList {
        // Build the rest of the display list which inclues all of the WebRender primitives.
        let paint_info = &mut stacking_context_tree.paint_info;
        let pipeline_id = paint_info.pipeline_id;
        let mut webrender_display_list_builder =
            webrender_api::DisplayListBuilder::new(pipeline_id);
        webrender_display_list_builder.begin();

        // `dump_serialized_display_list` doesn't actually print anything. It sets up
        // the display list for printing the serialized version when `finalize()` is called.
        // We need to call this before adding any display items so that they are printed
        // during `finalize()`.
        if debug.is_enabled(DiagnosticsLoggingOption::DisplayList) {
            webrender_display_list_builder.dump_serialized_display_list();
        }

        let _span = profile_traits::trace_span!("DisplayListBuilder::build").entered();
        let mut builder = DisplayListBuilder {
            current_scroll_node_id: paint_info.root_reference_frame_id,
            current_reference_frame_scroll_node_id: paint_info.root_reference_frame_id,
            current_clip_id: ClipId::INVALID,
            webrender_display_list_builder: &mut webrender_display_list_builder,
            paint_info,
            inspector_highlight: highlighted_dom_node.map(InspectorHighlight::for_node),
            paint_body_background: true,
            clip_map: Default::default(),
            image_resolver,
            device_pixel_ratio,
            paint_timing_handler,
            reflow_statistics,
        };

        // Clear any caret color from previous display list constructions.
        builder.paint_info.caret_property_binding = None;

        builder.add_all_spatial_nodes();

        for clip in stacking_context_tree.clip_store.0.iter() {
            builder.add_clip_to_display_list(clip);
        }

        // Add a single hit test that covers the entire viewport, so that WebRender knows
        // which pipeline it hits when doing hit testing.
        let pipeline_id = builder.paint_info.pipeline_id;
        let viewport_size = builder.paint_info.viewport_details.size;
        let viewport_rect = LayoutRect::from_size(viewport_size.cast_unit());
        builder.wr().push_hit_test(
            viewport_rect,
            ClipChainId::INVALID,
            SpatialId::root_reference_frame(pipeline_id),
            PrimitiveFlags::default(),
            (0, 0), /* tag */
        );

        // Paint the canvas’ background (if any) before/under everything else
        stacking_context_tree
            .root_stacking_context
            .build_canvas_background_display_list(&mut builder, fragment_tree);
        stacking_context_tree
            .root_stacking_context
            .build_display_list(&mut builder);
        builder.paint_dom_inspector_highlight();

        webrender_display_list_builder.end().1
    }

    fn wr(&mut self) -> &mut wr::DisplayListBuilder {
        self.webrender_display_list_builder
    }

    fn pipeline_id(&mut self) -> wr::PipelineId {
        self.paint_info.pipeline_id
    }

    fn mark_is_paintable(&mut self) {
        self.paint_info.is_paintable = true;
    }

    fn mark_is_contentful(&mut self) {
        self.paint_info.is_contentful = true;
    }

    fn spatial_id(&self, id: ScrollTreeNodeId) -> SpatialId {
        self.paint_info.scroll_tree.webrender_id(id)
    }

    fn clip_chain_id(&self, id: ClipId) -> ClipChainId {
        match id {
            ClipId::INVALID => ClipChainId::INVALID,
            _ => *self
                .clip_map
                .get(id.0)
                .expect("Should never try to get clip before adding it to WebRender display list"),
        }
    }

    pub(crate) fn add_all_spatial_nodes(&mut self) {
        // A count of the number of SpatialTree nodes pushed to the WebRender display
        // list. This is merely to ensure that the currently-unused SpatialTreeItemKey
        // produced for every SpatialTree node is unique.
        let mut spatial_tree_count = 0;
        let mut scroll_tree = std::mem::take(&mut self.paint_info.scroll_tree);
        let mut mapping = Vec::with_capacity(scroll_tree.nodes.len());

        mapping.push(SpatialId::root_reference_frame(self.pipeline_id()));
        mapping.push(SpatialId::root_scroll_node(self.pipeline_id()));

        let pipeline_id = self.pipeline_id();
        let pipeline_tag = ((pipeline_id.0 as u64) << 32) | pipeline_id.1 as u64;

        for node in scroll_tree.nodes.iter().skip(2) {
            let parent_scroll_node_id = node
                .parent
                .expect("Should have already added root reference frame");
            let parent_spatial_node_id = mapping
                .get(parent_scroll_node_id.index)
                .expect("Should add spatial nodes to display list in order");

            // Produce a new SpatialTreeItemKey. This is currently unused by WebRender,
            // but has to be unique to the entire scene.
            spatial_tree_count += 1;
            let spatial_tree_item_key = SpatialTreeItemKey::new(pipeline_tag, spatial_tree_count);

            mapping.push(match &node.info {
                SpatialTreeNodeInfo::ReferenceFrame(info) => {
                    let spatial_id = self.wr().push_reference_frame(
                        info.origin,
                        *parent_spatial_node_id,
                        info.transform_style,
                        PropertyBinding::Value(*info.transform.to_transform()),
                        info.kind,
                        spatial_tree_item_key,
                    );
                    self.wr().pop_reference_frame();
                    spatial_id
                },
                SpatialTreeNodeInfo::Scroll(info) => {
                    self.wr().define_scroll_frame(
                        *parent_spatial_node_id,
                        info.external_id,
                        info.content_rect,
                        info.clip_rect,
                        LayoutVector2D::zero(), /* external_scroll_offset */
                        0,                      /* scroll_offset_generation */
                        wr::HasScrollLinkedEffect::No,
                        spatial_tree_item_key,
                    )
                },
                SpatialTreeNodeInfo::Sticky(info) => {
                    self.wr().define_sticky_frame(
                        *parent_spatial_node_id,
                        info.frame_rect,
                        info.margins,
                        info.vertical_offset_bounds,
                        info.horizontal_offset_bounds,
                        LayoutVector2D::zero(), /* previously_applied_offset */
                        spatial_tree_item_key,
                        None, /* transform */
                    )
                },
            });
        }

        scroll_tree.update_mapping(mapping);
        self.paint_info.scroll_tree = scroll_tree;
    }

    /// Add the given [`Clip`] to the WebRender display list and create a mapping from
    /// its [`ClipId`] to a WebRender [`ClipChainId`]. This happens:
    ///  - When WebRender display list construction starts: All clips created during the
    ///    `StackingContextTree` construction are added in one batch. These clips are used
    ///    for things such as `overflow: scroll` elements.
    ///  - When a clip is added during WebRender display list construction for individual
    ///    items. In that case, this is called by [`Self::maybe_create_clip`].
    pub(crate) fn add_clip_to_display_list(&mut self, clip: &Clip) -> ClipChainId {
        assert_eq!(
            clip.id.0,
            self.clip_map.len(),
            "Clips should be added in order"
        );

        let spatial_id = self.spatial_id(clip.parent_scroll_node_id);
        let new_clip_id = if clip.radii.is_zero() {
            self.wr().define_clip_rect(spatial_id, clip.rect)
        } else {
            self.wr().define_clip_rounded_rect(
                spatial_id,
                ComplexClipRegion {
                    rect: clip.rect,
                    radii: clip.radii,
                    mode: ClipMode::Clip,
                },
            )
        };

        // WebRender has two different ways of expressing "no clip." ClipChainId::INVALID should be
        // used for primitives, but `None` is used for stacking contexts and clip chains. We convert
        // to the `Option<ClipChainId>` representation here. Just passing Some(ClipChainId::INVALID)
        // leads to a crash.
        let parent_clip_chain_id = match self.clip_chain_id(clip.parent_clip_id) {
            ClipChainId::INVALID => None,
            parent => Some(parent),
        };
        let clip_chain_id = self
            .wr()
            .define_clip_chain(parent_clip_chain_id, [new_clip_id]);
        self.clip_map.push(clip_chain_id);
        clip_chain_id
    }

    /// Add a new clip to the WebRender display list being built. This only happens during
    /// WebRender display list building and these clips should be added after all clips
    /// from the `StackingContextTree` have already been processed.
    fn maybe_create_clip(
        &mut self,
        radii: wr::BorderRadius,
        rect: units::LayoutRect,
        force_clip_creation: bool,
    ) -> Option<ClipChainId> {
        if radii.is_zero() && !force_clip_creation {
            return None;
        }

        Some(self.add_clip_to_display_list(&Clip {
            id: ClipId(self.clip_map.len()),
            radii,
            rect,
            parent_scroll_node_id: self.current_scroll_node_id,
            parent_clip_id: self.current_clip_id,
        }))
    }

    fn common_properties(
        &self,
        clip_rect: units::LayoutRect,
        style: &ComputedValues,
    ) -> wr::CommonItemProperties {
        // TODO(mrobinson): We should take advantage of this field to pass hit testing
        // information. This will allow us to avoid creating hit testing display items
        // for fragments that paint their entire border rectangle.
        wr::CommonItemProperties {
            clip_rect,
            spatial_id: self.spatial_id(self.current_scroll_node_id),
            clip_chain_id: self.clip_chain_id(self.current_clip_id),
            flags: style.get_webrender_primitive_flags(),
        }
    }

    /// Draw highlights around the node that is currently hovered in the devtools.
    fn paint_dom_inspector_highlight(&mut self) {
        let Some(highlight) = self
            .inspector_highlight
            .take()
            .and_then(|highlight| highlight.state)
        else {
            return;
        };

        const CONTENT_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
            r: 0.23,
            g: 0.7,
            b: 0.87,
            a: 0.5,
        };

        const PADDING_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
            r: 0.49,
            g: 0.3,
            b: 0.7,
            a: 0.5,
        };

        const BORDER_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
            r: 0.2,
            g: 0.2,
            b: 0.2,
            a: 0.5,
        };

        const MARGIN_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
            r: 1.,
            g: 0.93,
            b: 0.,
            a: 0.5,
        };

        // Highlight content box
        let content_box = highlight.content_box.to_webrender();
        let properties = wr::CommonItemProperties {
            clip_rect: content_box,
            spatial_id: highlight.spatial_id,
            clip_chain_id: highlight.clip_chain_id,
            flags: wr::PrimitiveFlags::default(),
        };

        self.wr()
            .push_rect(&properties, content_box, CONTENT_BOX_HIGHLIGHT_COLOR);

        // Highlight margin, border and padding
        if let Some(box_fragment) = highlight.maybe_box_fragment {
            let mut paint_highlight =
                |color: webrender_api::ColorF,
                 fragment_relative_bounds: PhysicalRect<Au>,
                 widths: webrender_api::units::LayoutSideOffsets| {
                    if widths.is_zero() {
                        return;
                    }

                    let bounds = box_fragment
                        .offset_by_containing_block(
                            &fragment_relative_bounds,
                            ContainingBlockCalculation::AlreadyDoneWithStackingContextTree,
                        )
                        .to_webrender();

                    // We paint each highlighted area as if it was a border for simplicity
                    let border_style = wr::BorderSide {
                        color,
                        style: wr::BorderStyle::Solid,
                    };

                    let details = wr::BorderDetails::Normal(wr::NormalBorder {
                        top: border_style,
                        right: border_style,
                        bottom: border_style,
                        left: border_style,
                        radius: webrender_api::BorderRadius::default(),
                        do_aa: true,
                    });

                    let common = wr::CommonItemProperties {
                        clip_rect: bounds,
                        spatial_id: highlight.spatial_id,
                        clip_chain_id: highlight.clip_chain_id,
                        flags: wr::PrimitiveFlags::default(),
                    };
                    self.wr().push_border(&common, bounds, widths, details)
                };

            paint_highlight(
                PADDING_BOX_HIGHLIGHT_COLOR,
                box_fragment.padding_rect(),
                box_fragment.padding.to_webrender(),
            );
            paint_highlight(
                BORDER_BOX_HIGHLIGHT_COLOR,
                box_fragment.border_rect(),
                box_fragment.border.to_webrender(),
            );
            paint_highlight(
                MARGIN_BOX_HIGHLIGHT_COLOR,
                box_fragment.margin_rect(),
                box_fragment.margin.to_webrender(),
            );
        }
    }

    fn check_if_paintable(&mut self, bounds: LayoutRect, clip_rect: LayoutRect, opacity: f32) {
        // From <https://www.w3.org/TR/paint-timing/#paintable>:
        // An element el is paintable when all of the following apply:
        // > el is being rendered.
        // > el’s used visibility is visible.
        // Above conditions are met, as we selectively call this API.

        // > el and all of its ancestors' used opacity is greater than zero.
        if opacity <= 0.0 {
            return;
        }

        // > el’s paintable bounding rect intersects with the scrolling area of the document.
        if self
            .paint_timing_handler
            .check_bounding_rect(bounds, clip_rect)
        {
            self.mark_is_paintable();
        }
    }

    fn check_for_lcp_candidate(
        &mut self,
        clip_rect: LayoutRect,
        bounds: LayoutRect,
        tag: Option<Tag>,
        url: Option<ServoUrl>,
    ) {
        if !pref!(largest_contentful_paint_enabled) {
            return;
        }

        let transform = self
            .paint_info
            .scroll_tree
            .cumulative_node_to_root_transform(self.current_scroll_node_id);

        self.paint_timing_handler
            .update_lcp_candidate(tag, bounds, clip_rect, transform, url);
    }
}

impl InspectorHighlight {
    fn register_fragment_of_highlighted_dom_node(
        &mut self,
        fragment: &Fragment,
        spatial_id: SpatialId,
        clip_chain_id: ClipChainId,
        containing_block: &PhysicalRect<Au>,
    ) {
        let state = self.state.get_or_insert(HighlightTraversalState {
            content_box: Rect::zero(),
            spatial_id,
            clip_chain_id,
            maybe_box_fragment: None,
        });

        // We only need to highlight the first `SpatialId`. Typically this will include the bottommost
        // fragment for a node, which generally surrounds the entire content.
        if spatial_id != state.spatial_id {
            return;
        }

        if clip_chain_id != ClipChainId::INVALID && state.clip_chain_id != ClipChainId::INVALID {
            debug_assert_eq!(
                clip_chain_id, state.clip_chain_id,
                "Fragments of the same node must either have no clip chain or the same one"
            );
        }

        let Some(fragment_relative_rect) = fragment.base().map(|base| base.rect()) else {
            return;
        };
        state.maybe_box_fragment = match fragment {
            Fragment::Box(fragment) | Fragment::Float(fragment) => Some(fragment.clone()),
            _ => None,
        };

        state.content_box = state
            .content_box
            .union(&fragment_relative_rect.translate(containing_block.origin.to_vector()));
    }
}

impl Fragment {
    pub(crate) fn build_display_list(
        &self,
        builder: &mut DisplayListBuilder,
        containing_block: &PhysicalRect<Au>,
        section: StackingContextSection,
        is_hit_test_for_scrollable_overflow: bool,
        is_collapsed_table_borders: bool,
        text_decorations: &Arc<Vec<FragmentTextDecoration>>,
    ) {
        if let Some(base) = self.base() {
            match base.status() {
                FragmentStatus::New => {
                    builder.reflow_statistics.rebuilt_fragment_count += 1;
                    base.set_status(FragmentStatus::Clean)
                },
                FragmentStatus::StyleChanged => {
                    builder.reflow_statistics.restyle_fragment_count += 1;
                    base.set_status(FragmentStatus::Clean)
                },
                FragmentStatus::OnlyDescendantsChanged => {
                    builder.reflow_statistics.only_descendants_changed_count += 1;
                    base.set_status(FragmentStatus::Clean)
                },
                FragmentStatus::Clean => {},
            }
        }

        let spatial_id = builder.spatial_id(builder.current_scroll_node_id);
        let clip_chain_id = builder.clip_chain_id(builder.current_clip_id);
        if let Some(inspector_highlight) = &mut builder.inspector_highlight &&
            self.tag() == Some(inspector_highlight.tag)
        {
            inspector_highlight.register_fragment_of_highlighted_dom_node(
                self,
                spatial_id,
                clip_chain_id,
                containing_block,
            );
        }

        match self {
            Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => {
                match box_fragment.style().get_inherited_box().visibility {
                    Visibility::Visible => BuilderForBoxFragment::new(
                        box_fragment,
                        containing_block,
                        is_hit_test_for_scrollable_overflow,
                        is_collapsed_table_borders,
                    )
                    .build(builder, section),
                    Visibility::Hidden => (),
                    Visibility::Collapse => (),
                }
            },
            Fragment::AbsoluteOrFixedPositioned(_) | Fragment::Positioning(_) => {},
            Fragment::Image(image) => {
                let style = image.base.style();
                match style.get_inherited_box().visibility {
                    Visibility::Visible => {
                        let image_rendering =
                            style.get_inherited_box().image_rendering.to_webrender();
                        let rect = image
                            .base
                            .rect()
                            .translate(containing_block.origin.to_vector())
                            .to_webrender();
                        let clip = image
                            .clip
                            .translate(containing_block.origin.to_vector())
                            .to_webrender();
                        let common = builder.common_properties(clip, &style);

                        if let Some(image_key) = image.image_key {
                            builder.wr().push_image(
                                &common,
                                rect,
                                image_rendering,
                                wr::AlphaType::PremultipliedAlpha,
                                image_key,
                                wr::ColorF::WHITE,
                            );

                            builder.check_if_paintable(
                                rect,
                                common.clip_rect,
                                style.clone_opacity(),
                            );

                            // From <https://www.w3.org/TR/paint-timing/#contentful>:
                            // An element target is contentful when one or more of the following apply:
                            // > target is a replaced element representing an available image.
                            // From: <https://html.spec.whatwg.org/multipage/#img-available>
                            // When an image request's state is either partially available or completely available,
                            // the image request is said to be available.
                            // Hence, Skip Broken Images.
                            if !image.showing_broken_image_icon {
                                builder.mark_is_contentful();

                                builder.check_for_lcp_candidate(
                                    common.clip_rect,
                                    rect,
                                    image.base.tag,
                                    image.url.clone(),
                                );
                            }
                        }

                        if image.showing_broken_image_icon {
                            self.build_display_list_for_broken_image_border(
                                builder,
                                containing_block,
                                &common,
                            );
                        }
                    },
                    Visibility::Hidden => (),
                    Visibility::Collapse => (),
                }
            },
            Fragment::IFrame(iframe) => {
                let style = iframe.base.style();
                match style.get_inherited_box().visibility {
                    Visibility::Visible => {
                        let rect = iframe
                            .base
                            .rect()
                            .translate(containing_block.origin.to_vector());

                        let common = builder.common_properties(rect.to_webrender(), &style);
                        builder.wr().push_iframe(
                            rect.to_webrender(),
                            common.clip_rect,
                            &wr::SpaceAndClipInfo {
                                spatial_id: common.spatial_id,
                                clip_chain_id: common.clip_chain_id,
                            },
                            iframe.pipeline_id.into(),
                            true,
                        );
                        // From <https://www.w3.org/TR/paint-timing/#mark-paint-timing>:
                        // > A parent frame should not be aware of the paint events from its child iframes, and
                        // > vice versa. This means that a frame that contains just iframes will have first paint
                        // > (due to the enclosing boxes of the iframes) but no first contentful paint.
                        builder.check_if_paintable(
                            rect.to_webrender(),
                            common.clip_rect,
                            style.clone_opacity(),
                        );
                    },
                    Visibility::Hidden => (),
                    Visibility::Collapse => (),
                }
            },
            Fragment::Text(text) => match text.base.style().get_inherited_box().visibility {
                Visibility::Visible => self.build_display_list_for_text_fragment(
                    text,
                    builder,
                    containing_block,
                    text_decorations,
                ),
                Visibility::Hidden => (),
                Visibility::Collapse => (),
            },
        }
    }

    fn build_display_list_for_text_fragment(
        &self,
        fragment: &TextFragment,
        builder: &mut DisplayListBuilder,
        containing_block: &PhysicalRect<Au>,
        text_decorations: &Arc<Vec<FragmentTextDecoration>>,
    ) {
        // NB: The order of painting text components (CSS Text Decoration Module Level 3) is:
        // shadows, underline, overline, text, text-emphasis, and then line-through.
        let rect = fragment
            .base
            .rect()
            .translate(containing_block.origin.to_vector());
        let mut baseline_origin = rect.origin;
        baseline_origin.y += fragment.font_metrics.ascent;
        let include_whitespace =
            fragment.offsets.is_some() || text_decorations.iter().any(|item| !item.line.is_empty());

        let (glyphs, largest_advance) = glyphs(
            &fragment.glyphs,
            baseline_origin,
            fragment.justification_adjustment,
            include_whitespace,
        );

        if glyphs.is_empty() && !fragment.is_empty_for_text_cursor {
            return;
        }

        let parent_style = fragment.base.style();
        let color = parent_style.clone_color();
        let font_metrics = &fragment.font_metrics;
        let dppx = builder.device_pixel_ratio.get();

        // Gecko gets the text bounding box based on the ink overflow bounds. Since
        // we don't need to calculate this yet (as we do not implement `contain:
        // paint`), we just need to make sure these boundaries are big enough to
        // contain the inked portion of the glyphs. We assume that the descent and
        // ascent are big enough and then just expand the advance-based boundaries by
        // twice the size of the biggest advance in the advance dimention.
        let glyph_bounds = rect
            .inflate(largest_advance.scale_by(2.0), Au::zero())
            .to_webrender();
        let common = builder.common_properties(glyph_bounds, &parent_style);

        // Shadows. According to CSS-BACKGROUNDS, text shadows render in *reverse* order (front to
        // back).
        let shadows = &parent_style.get_inherited_text().text_shadow;
        for shadow in shadows.0.iter().rev() {
            builder.wr().push_shadow(
                &wr::SpaceAndClipInfo {
                    spatial_id: common.spatial_id,
                    clip_chain_id: common.clip_chain_id,
                },
                wr::Shadow {
                    offset: LayoutVector2D::new(shadow.horizontal.px(), shadow.vertical.px()),
                    color: rgba(shadow.color.resolve_to_absolute(&color)),
                    blur_radius: shadow.blur.px(),
                },
                true, /* should_inflate */
            );
        }

        for text_decoration in text_decorations.iter() {
            if text_decoration.line.contains(TextDecorationLine::UNDERLINE) {
                let mut rect = rect;
                rect.origin.y += font_metrics.ascent - font_metrics.underline_offset;
                rect.size.height =
                    Au::from_f32_px(font_metrics.underline_size.to_nearest_pixel(dppx));

                self.build_display_list_for_text_decoration(
                    &parent_style,
                    builder,
                    &rect,
                    text_decoration,
                    TextDecorationLine::UNDERLINE,
                );
            }
        }

        for text_decoration in text_decorations.iter() {
            if text_decoration.line.contains(TextDecorationLine::OVERLINE) {
                let mut rect = rect;
                rect.size.height =
                    Au::from_f32_px(font_metrics.underline_size.to_nearest_pixel(dppx));
                self.build_display_list_for_text_decoration(
                    &parent_style,
                    builder,
                    &rect,
                    text_decoration,
                    TextDecorationLine::OVERLINE,
                );
            }
        }

        self.build_display_list_for_text_selection(
            fragment,
            builder,
            containing_block,
            fragment.base.rect().min_x(),
            fragment.justification_adjustment,
        );

        builder.wr().push_text(
            &common,
            glyph_bounds,
            &glyphs,
            fragment.font_key,
            rgba(color),
            None,
        );

        builder.check_if_paintable(glyph_bounds, common.clip_rect, parent_style.clone_opacity());

        // From <https://www.w3.org/TR/paint-timing/#contentful>:
        // An element target is contentful when one or more of the following apply:
        // > target has a text node child, representing non-empty text, and the node’s used opacity is greater than zero.
        builder.mark_is_contentful();

        for text_decoration in text_decorations.iter() {
            if text_decoration
                .line
                .contains(TextDecorationLine::LINE_THROUGH)
            {
                let mut rect = rect;
                rect.origin.y += font_metrics.ascent - font_metrics.strikeout_offset;
                rect.size.height =
                    Au::from_f32_px(font_metrics.strikeout_size.to_nearest_pixel(dppx));
                self.build_display_list_for_text_decoration(
                    &parent_style,
                    builder,
                    &rect,
                    text_decoration,
                    TextDecorationLine::LINE_THROUGH,
                );
            }
        }

        if !shadows.0.is_empty() {
            builder.wr().pop_all_shadows();
        }
    }

    fn build_display_list_for_text_decoration(
        &self,
        parent_style: &ServoArc<ComputedValues>,
        builder: &mut DisplayListBuilder,
        rect: &PhysicalRect<Au>,
        text_decoration: &FragmentTextDecoration,
        line: TextDecorationLine,
    ) {
        if text_decoration.style == ComputedTextDecorationStyle::MozNone {
            return;
        }

        let mut rect = rect.to_webrender();
        let line_thickness = rect.height().ceil();

        if text_decoration.style == ComputedTextDecorationStyle::Wavy {
            rect = rect.inflate(0.0, line_thickness * 1.0);
        }

        let common_properties = builder.common_properties(rect, parent_style);
        builder.wr().push_line(
            &common_properties,
            &rect,
            line_thickness,
            wr::LineOrientation::Horizontal,
            &rgba(text_decoration.color),
            text_decoration.style.to_webrender(),
        );

        if text_decoration.style == TextDecorationStyle::Double {
            let half_height = (rect.height() / 2.0).floor().max(1.0);
            let y_offset = match line {
                TextDecorationLine::OVERLINE => -rect.height() - half_height,
                _ => rect.height() + half_height,
            };
            let rect = rect.translate(Vector2D::new(0.0, y_offset));
            let common_properties = builder.common_properties(rect, parent_style);
            builder.wr().push_line(
                &common_properties,
                &rect,
                line_thickness,
                wr::LineOrientation::Horizontal,
                &rgba(text_decoration.color),
                text_decoration.style.to_webrender(),
            );
        }
    }

    fn build_display_list_for_broken_image_border(
        &self,
        builder: &mut DisplayListBuilder,
        containing_block: &PhysicalRect<Au>,
        common: &CommonItemProperties,
    ) {
        let border_side = BorderSide {
            color: ColorF::BLACK,
            style: wr::BorderStyle::Inset,
        };
        builder.wr().push_border(
            common,
            containing_block.to_webrender(),
            LayoutSideOffsets::new_all_same(1.0),
            BorderDetails::Normal(NormalBorder {
                left: border_side,
                right: border_side,
                top: border_side,
                bottom: border_side,
                radius: BorderRadius::zero(),
                do_aa: true,
            }),
        );
    }

    // TODO: This caret/text selection implementation currently does not account for vertical text
    // and RTL text properly.
    fn build_display_list_for_text_selection(
        &self,
        fragment: &TextFragment,
        builder: &mut DisplayListBuilder<'_>,
        containing_block_rect: &PhysicalRect<Au>,
        fragment_x_offset: Au,
        justification_adjustment: Au,
    ) {
        let Some(offsets) = fragment.offsets.as_ref() else {
            return;
        };

        let shared_selection = offsets.shared_selection.borrow();
        if !shared_selection.enabled {
            return;
        }

        if offsets.character_range.start > shared_selection.character_range.end ||
            offsets.character_range.end < shared_selection.character_range.start
        {
            return;
        }

        // When there is an active selection, the line is empty, and there is a forced linebreak,
        // layout will push an empty fragment in order to trigger painting of the cursor on an empty line.
        // This code ensure that it is only painted if the cursor is on the starting index of the empty
        // fragment.
        if fragment.is_empty_for_text_cursor &&
            !offsets
                .character_range
                .contains(&shared_selection.character_range.start)
        {
            return;
        }

        let mut current_character_index = offsets.character_range.start;
        let mut current_advance = Au::zero();
        let mut start_advance = None;
        let mut end_advance = None;
        for glyph_store in fragment.glyphs.iter() {
            let glyph_store_character_count = glyph_store.character_count();
            if current_character_index + glyph_store_character_count <
                shared_selection.character_range.start
            {
                current_advance += glyph_store.total_advance() +
                    (justification_adjustment * glyph_store.total_word_separators() as i32);
                current_character_index += glyph_store_character_count;
                continue;
            }

            if current_character_index >= shared_selection.character_range.end {
                break;
            }

            for glyph in glyph_store.glyphs() {
                if current_character_index >= shared_selection.character_range.start {
                    start_advance = start_advance.or(Some(current_advance));
                }

                current_character_index += glyph.character_count();
                current_advance += glyph.advance();
                if glyph.char_is_word_separator() {
                    current_advance += justification_adjustment;
                }

                if current_character_index <= shared_selection.character_range.end {
                    end_advance = Some(current_advance);
                }
            }
        }

        let start_x = start_advance.unwrap_or(current_advance);
        let end_x = end_advance.unwrap_or(current_advance);

        let parent_style = fragment.base.style();
        if !shared_selection.range.is_empty() {
            let selection_rect = Rect::new(
                containing_block_rect.origin +
                    Vector2D::new(fragment_x_offset + start_x, Au::zero()),
                Size2D::new(end_x - start_x, containing_block_rect.height()),
            )
            .to_webrender();

            if let Some(selection_color) = fragment
                .selected_style
                .borrow()
                .clone_background_color()
                .as_absolute()
            {
                let selection_common = builder.common_properties(selection_rect, &parent_style);
                builder
                    .wr()
                    .push_rect(&selection_common, selection_rect, rgba(*selection_color));
            }
            return;
        }

        let insertion_point_rect = Rect::new(
            containing_block_rect.origin + Vector2D::new(start_x + fragment_x_offset, Au::zero()),
            Size2D::new(
                INSERTION_POINT_LOGICAL_WIDTH,
                containing_block_rect.height(),
            ),
        )
        .to_webrender();

        let color = parent_style.clone_color();
        let caret_color = match parent_style.clone_caret_color().0 {
            ColorOrAuto::Color(caret_color) => caret_color.resolve_to_absolute(&color),
            ColorOrAuto::Auto => color,
        };
        let insertion_point_common = builder.common_properties(insertion_point_rect, &parent_style);

        let caret_color = rgba(caret_color);
        let property_binding = if prefs::get().editing_caret_blink_time().is_some() {
            // It's okay to always use the same property binding key for this pipeline, as
            // there is currently only a single thing that animates in this way (the caret).
            // This code should be updated if we ever add more paint-side animations.
            let pipeline_id: PipelineId = builder.paint_info.pipeline_id.into();
            let property_binding_key = PropertyBindingKey::new(pipeline_id.into());
            builder.paint_info.caret_property_binding = Some((property_binding_key, caret_color));
            PropertyBinding::Binding(property_binding_key, caret_color)
        } else {
            PropertyBinding::Value(caret_color)
        };

        builder.wr().push_rect_with_animation(
            &insertion_point_common,
            insertion_point_rect,
            property_binding,
        );
    }
}

struct BuilderForBoxFragment<'a> {
    fragment: &'a BoxFragment,
    containing_block: &'a PhysicalRect<Au>,
    border_rect: units::LayoutRect,
    margin_rect: OnceCell<units::LayoutRect>,
    padding_rect: OnceCell<units::LayoutRect>,
    content_rect: OnceCell<units::LayoutRect>,
    border_radius: wr::BorderRadius,
    border_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
    padding_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
    content_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
    is_hit_test_for_scrollable_overflow: bool,
    is_collapsed_table_borders: bool,
}

impl<'a> BuilderForBoxFragment<'a> {
    fn new(
        fragment: &'a BoxFragment,
        containing_block: &'a PhysicalRect<Au>,
        is_hit_test_for_scrollable_overflow: bool,
        is_collapsed_table_borders: bool,
    ) -> Self {
        let border_rect = fragment
            .border_rect()
            .translate(containing_block.origin.to_vector());
        Self {
            fragment,
            containing_block,
            border_rect: border_rect.to_webrender(),
            border_radius: fragment.border_radius(),
            margin_rect: OnceCell::new(),
            padding_rect: OnceCell::new(),
            content_rect: OnceCell::new(),
            border_edge_clip_chain_id: RefCell::new(None),
            padding_edge_clip_chain_id: RefCell::new(None),
            content_edge_clip_chain_id: RefCell::new(None),
            is_hit_test_for_scrollable_overflow,
            is_collapsed_table_borders,
        }
    }

    fn content_rect(&self) -> &units::LayoutRect {
        self.content_rect.get_or_init(|| {
            self.fragment
                .content_rect()
                .translate(self.containing_block.origin.to_vector())
                .to_webrender()
        })
    }

    fn padding_rect(&self) -> &units::LayoutRect {
        self.padding_rect.get_or_init(|| {
            self.fragment
                .padding_rect()
                .translate(self.containing_block.origin.to_vector())
                .to_webrender()
        })
    }

    fn margin_rect(&self) -> &units::LayoutRect {
        self.margin_rect.get_or_init(|| {
            self.fragment
                .margin_rect()
                .translate(self.containing_block.origin.to_vector())
                .to_webrender()
        })
    }

    fn border_edge_clip(
        &self,
        builder: &mut DisplayListBuilder,
        force_clip_creation: bool,
    ) -> Option<ClipChainId> {
        if let Some(clip) = *self.border_edge_clip_chain_id.borrow() {
            return Some(clip);
        }

        let maybe_clip =
            builder.maybe_create_clip(self.border_radius, self.border_rect, force_clip_creation);
        *self.border_edge_clip_chain_id.borrow_mut() = maybe_clip;
        maybe_clip
    }

    fn padding_edge_clip(
        &self,
        builder: &mut DisplayListBuilder,
        force_clip_creation: bool,
    ) -> Option<ClipChainId> {
        if let Some(clip) = *self.padding_edge_clip_chain_id.borrow() {
            return Some(clip);
        }

        let radii = offset_radii(self.border_radius, -self.fragment.border.to_webrender());
        let maybe_clip =
            builder.maybe_create_clip(radii, *self.padding_rect(), force_clip_creation);
        *self.padding_edge_clip_chain_id.borrow_mut() = maybe_clip;
        maybe_clip
    }

    fn content_edge_clip(
        &self,
        builder: &mut DisplayListBuilder,
        force_clip_creation: bool,
    ) -> Option<ClipChainId> {
        if let Some(clip) = *self.content_edge_clip_chain_id.borrow() {
            return Some(clip);
        }

        let radii = offset_radii(
            self.border_radius,
            -(self.fragment.border + self.fragment.padding).to_webrender(),
        );
        let maybe_clip =
            builder.maybe_create_clip(radii, *self.content_rect(), force_clip_creation);
        *self.content_edge_clip_chain_id.borrow_mut() = maybe_clip;
        maybe_clip
    }

    fn build(&mut self, builder: &mut DisplayListBuilder, section: StackingContextSection) {
        if self.is_hit_test_for_scrollable_overflow &&
            self.fragment.style().get_inherited_ui().pointer_events !=
                style::computed_values::pointer_events::T::None
        {
            self.build_hit_test(
                builder,
                self.fragment
                    .scrollable_overflow()
                    .translate(self.containing_block.origin.to_vector())
                    .to_webrender(),
            );
            return;
        }
        if self.is_collapsed_table_borders {
            self.build_collapsed_table_borders(builder);
            return;
        }

        if section == StackingContextSection::Outline {
            self.build_outline(builder);
            return;
        }

        if self
            .fragment
            .base
            .flags
            .contains(FragmentFlags::DO_NOT_PAINT)
        {
            return;
        }

        self.build_background(builder);
        self.build_box_shadow(builder);
        self.build_border(builder);
    }

    fn build_hit_test(&self, builder: &mut DisplayListBuilder, rect: LayoutRect) {
        let external_scroll_node_id = builder
            .paint_info
            .external_scroll_id_for_scroll_tree_node(builder.current_scroll_node_id);

        let mut common = builder.common_properties(rect, &self.fragment.style());
        if let Some(clip_chain_id) = self.border_edge_clip(builder, false) {
            common.clip_chain_id = clip_chain_id;
        }
        builder.wr().push_hit_test(
            common.clip_rect,
            common.clip_chain_id,
            common.spatial_id,
            common.flags,
            (external_scroll_node_id.0, 0), /* tag */
        );
    }

    fn build_background_for_painter(
        &mut self,
        builder: &mut DisplayListBuilder,
        painter: &BackgroundPainter,
    ) {
        let b = painter.style.get_background();
        let background_color = painter.style.resolve_color(&b.background_color);
        if background_color.alpha > 0.0 {
            // https://drafts.csswg.org/css-backgrounds/#background-color
            // “The background color is clipped according to the background-clip
            //  value associated with the bottom-most background image layer.”
            let layer_index = b.background_image.0.len() - 1;
            let bounds = painter.painting_area(self, builder, layer_index);
            let common = painter.common_properties(self, builder, layer_index, bounds);
            builder
                .wr()
                .push_rect(&common, bounds, rgba(background_color));

            // From <https://www.w3.org/TR/paint-timing/#sec-terminology>:
            // First paint ... includes non-default background paint and the enclosing box of an iframe.
            // The spec is vague. See also: https://github.com/w3c/paint-timing/issues/122
            let default_background_color = servo_config::pref!(shell_background_color_rgba);
            let default_background_color = AbsoluteColor::new(
                ColorSpace::Srgb,
                default_background_color[0] as f32,
                default_background_color[1] as f32,
                default_background_color[2] as f32,
                default_background_color[3] as f32,
            )
            .into_srgb_legacy();
            if background_color != default_background_color {
                builder.mark_is_paintable();
            }
        }

        self.build_background_image(builder, painter);
    }

    fn build_background(&mut self, builder: &mut DisplayListBuilder) {
        let flags = self.fragment.base.flags;

        // The root element's background is painted separately as it might inherit the `<body>`'s
        // background.
        if flags.intersects(FragmentFlags::IS_ROOT_ELEMENT) {
            return;
        }
        // If the `<body>` background was inherited by the root element, don't paint it again here.
        if !builder.paint_body_background &&
            flags.intersects(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT)
        {
            return;
        }

        // If this BoxFragment does not paint a background, do nothing.
        if let BackgroundMode::None = self.fragment.background_mode {
            return;
        }

        // Paint all extra backgrounds for this BoxFragment. These are painted first, as that's
        // the order that they are expected to be painted for table cells (where this feature
        // is used).
        if let BackgroundMode::Extra(ref extra_backgrounds) = self.fragment.background_mode {
            for extra_background in extra_backgrounds {
                let positioning_area = extra_background.rect;
                let painter = BackgroundPainter {
                    style: &extra_background.style.borrow_mut(),
                    painting_area_override: None,
                    positioning_area_override: Some(
                        positioning_area
                            .translate(self.containing_block.origin.to_vector())
                            .to_webrender(),
                    ),
                };
                self.build_background_for_painter(builder, &painter);
            }
        }

        let painter = BackgroundPainter {
            style: &self.fragment.style(),
            painting_area_override: None,
            positioning_area_override: None,
        };
        self.build_background_for_painter(builder, &painter);
    }

    fn build_background_image(
        &mut self,
        builder: &mut DisplayListBuilder,
        painter: &BackgroundPainter,
    ) {
        let style = painter.style;
        let b = style.get_background();
        let need_blend_container = b
            .background_blend_mode
            .0
            .iter()
            .take(b.background_image.0.len())
            .any(|background_blend_mode| background_blend_mode != &BackgroundBlendMode::Normal);

        let push_stacking_context = |builder: &mut DisplayListBuilder,
                                     blend_mode: BackgroundBlendMode,
                                     flags: StackingContextFlags|
         -> bool {
            let spatial_id = builder.spatial_id(builder.current_scroll_node_id);
            builder.wr().push_stacking_context(
                LayoutPoint::zero(), // origin
                spatial_id,
                PrimitiveFlags::empty(),
                None,
                webrender_api::TransformStyle::Flat,
                blend_mode.to_webrender(),
                &[],
                &[],
                &[],
                RasterSpace::Screen,
                flags,
                None,
            );
            true
        };

        if need_blend_container {
            push_stacking_context(
                builder,
                BackgroundBlendMode::Normal,
                StackingContextFlags::IS_BLEND_CONTAINER,
            );
        }

        let node = self.fragment.base.tag.map(|tag| tag.node);
        // Reverse because the property is top layer first, we want to paint bottom layer first.
        for (index, image) in b.background_image.0.iter().enumerate().rev() {
            match builder.image_resolver.resolve_image(node, image) {
                Err(_) => {},
                Ok(ResolvedImage::Gradient(gradient)) => {
                    let intrinsic = NaturalSizes::empty();
                    let Some(layer) =
                        &background::layout_layer(self, painter, builder, index, intrinsic)
                    else {
                        continue;
                    };

                    let needs_blending = layer.blend_mode != BackgroundBlendMode::Normal;
                    if needs_blending {
                        push_stacking_context(builder, layer.blend_mode, Default::default());
                    }

                    match gradient::build(style, gradient, layer.tile_size, builder) {
                        WebRenderGradient::Linear(linear_gradient) => builder.wr().push_gradient(
                            &layer.common,
                            layer.bounds,
                            linear_gradient,
                            layer.tile_size,
                            layer.tile_spacing,
                        ),
                        WebRenderGradient::Radial(radial_gradient) => {
                            builder.wr().push_radial_gradient(
                                &layer.common,
                                layer.bounds,
                                radial_gradient,
                                layer.tile_size,
                                layer.tile_spacing,
                            )
                        },
                        WebRenderGradient::Conic(conic_gradient) => {
                            builder.wr().push_conic_gradient(
                                &layer.common,
                                layer.bounds,
                                conic_gradient,
                                layer.tile_size,
                                layer.tile_spacing,
                            )
                        },
                    }

                    if needs_blending {
                        builder.wr().pop_stacking_context();
                    }

                    builder.check_if_paintable(
                        layer.bounds,
                        layer.common.clip_rect,
                        style.clone_opacity(),
                    );
                },
                Ok(ResolvedImage::Image { image, size }) => {
                    // FIXME: https://drafts.csswg.org/css-images-4/#the-image-resolution
                    let dppx = 1.0;
                    let intrinsic =
                        NaturalSizes::from_width_and_height(size.width / dppx, size.height / dppx);
                    let layer = background::layout_layer(self, painter, builder, index, intrinsic);

                    let image_wr_key = match image {
                        CachedImage::Raster(raster_image) => raster_image.id,
                        CachedImage::Vector(vector_image) => {
                            let scale = builder.device_pixel_ratio.get();
                            let default_size: DeviceIntSize =
                                Size2D::new(size.width * scale, size.height * scale).to_i32();
                            let layer_size = layer.as_ref().map(|layer| {
                                Size2D::new(
                                    layer.tile_size.width * scale,
                                    layer.tile_size.height * scale,
                                )
                                .to_i32()
                            });

                            node.and_then(|node| {
                                let size = layer_size.unwrap_or(default_size);
                                builder.image_resolver.rasterize_vector_image(
                                    vector_image.id,
                                    size,
                                    node,
                                    vector_image.svg_id,
                                )
                            })
                            .and_then(|rasterized_image| rasterized_image.id)
                        },
                    };

                    let Some(image_key) = image_wr_key else {
                        continue;
                    };

                    if let Some(layer) = layer {
                        let needs_blending = layer.blend_mode != BackgroundBlendMode::Normal;
                        if needs_blending {
                            push_stacking_context(builder, layer.blend_mode, Default::default());
                        }

                        if layer.repeat {
                            builder.wr().push_repeating_image(
                                &layer.common,
                                layer.bounds,
                                layer.tile_size,
                                layer.tile_spacing,
                                style.clone_image_rendering().to_webrender(),
                                wr::AlphaType::PremultipliedAlpha,
                                image_key,
                                wr::ColorF::WHITE,
                            )
                        } else {
                            builder.wr().push_image(
                                &layer.common,
                                layer.bounds,
                                style.clone_image_rendering().to_webrender(),
                                wr::AlphaType::PremultipliedAlpha,
                                image_key,
                                wr::ColorF::WHITE,
                            )
                        }

                        if needs_blending {
                            builder.wr().pop_stacking_context();
                        }

                        builder.check_if_paintable(
                            layer.bounds,
                            layer.common.clip_rect,
                            style.clone_opacity(),
                        );

                        // From <https://www.w3.org/TR/paint-timing/#sec-terminology>:
                        // An element target is contentful when one or more of the following apply:
                        // > target has a background-image which is a contentful image, and its used
                        // > background-size has non-zero width and height values.
                        builder.mark_is_contentful();

                        builder.check_for_lcp_candidate(
                            layer.common.clip_rect,
                            layer.bounds,
                            self.fragment.base.tag,
                            None,
                        );
                    }
                },
            }
        }

        if need_blend_container {
            builder.wr().pop_stacking_context();
        }
    }

    fn build_border_side(&mut self, style_color: BorderStyleColor) -> wr::BorderSide {
        wr::BorderSide {
            color: rgba(style_color.color),
            style: match style_color.style {
                BorderStyle::None => wr::BorderStyle::None,
                BorderStyle::Solid => wr::BorderStyle::Solid,
                BorderStyle::Double => wr::BorderStyle::Double,
                BorderStyle::Dotted => wr::BorderStyle::Dotted,
                BorderStyle::Dashed => wr::BorderStyle::Dashed,
                BorderStyle::Hidden => wr::BorderStyle::Hidden,
                BorderStyle::Groove => wr::BorderStyle::Groove,
                BorderStyle::Ridge => wr::BorderStyle::Ridge,
                BorderStyle::Inset => wr::BorderStyle::Inset,
                BorderStyle::Outset => wr::BorderStyle::Outset,
            },
        }
    }

    fn build_collapsed_table_borders(&mut self, builder: &mut DisplayListBuilder) {
        let layout_info = self.fragment.specific_layout_info();
        let Some(SpecificLayoutInfo::TableGridWithCollapsedBorders(table_info)) =
            layout_info.as_deref()
        else {
            return;
        };
        let mut common =
            builder.common_properties(units::LayoutRect::default(), &self.fragment.style());
        let radius = wr::BorderRadius::default();
        let mut column_sum = Au::zero();
        for (x, column_size) in table_info.track_sizes.x.iter().enumerate() {
            let mut row_sum = Au::zero();
            for (y, row_size) in table_info.track_sizes.y.iter().enumerate() {
                let left_border = &table_info.collapsed_borders.x[x][y];
                let right_border = &table_info.collapsed_borders.x[x + 1][y];
                let top_border = &table_info.collapsed_borders.y[y][x];
                let bottom_border = &table_info.collapsed_borders.y[y + 1][x];
                let details = wr::BorderDetails::Normal(wr::NormalBorder {
                    left: self.build_border_side(left_border.style_color.clone()),
                    right: self.build_border_side(right_border.style_color.clone()),
                    top: self.build_border_side(top_border.style_color.clone()),
                    bottom: self.build_border_side(bottom_border.style_color.clone()),
                    radius,
                    do_aa: true,
                });
                let mut border_widths = PhysicalSides::new(
                    top_border.width,
                    right_border.width,
                    bottom_border.width,
                    left_border.width,
                );
                let left_adjustment = if x == 0 {
                    -border_widths.left / 2
                } else {
                    std::mem::take(&mut border_widths.left) / 2
                };
                let top_adjustment = if y == 0 {
                    -border_widths.top / 2
                } else {
                    std::mem::take(&mut border_widths.top) / 2
                };
                let origin =
                    PhysicalPoint::new(column_sum + left_adjustment, row_sum + top_adjustment);
                let size = PhysicalSize::new(
                    *column_size - left_adjustment + border_widths.right / 2,
                    *row_size - top_adjustment + border_widths.bottom / 2,
                );
                let border_rect = PhysicalRect::new(origin, size)
                    .translate(self.fragment.content_rect().origin.to_vector())
                    .translate(self.containing_block.origin.to_vector())
                    .to_webrender();
                common.clip_rect = border_rect;
                builder.wr().push_border(
                    &common,
                    border_rect,
                    border_widths.to_webrender(),
                    details,
                );
                row_sum += *row_size;
            }
            column_sum += *column_size;
        }
    }

    fn build_border(&mut self, builder: &mut DisplayListBuilder) {
        if self.fragment.has_collapsed_borders() {
            // Avoid painting borders for tables and table parts in collapsed-borders mode,
            // since the resulting collapsed borders are painted on their own in a special way.
            return;
        }

        let style = self.fragment.style();
        let border = style.get_border();
        let border_widths = self.fragment.border.to_webrender();

        if border_widths == SideOffsets2D::zero() {
            return;
        }

        // `border-image` replaces an element's border entirely.
        if self.build_border_image(builder, border, border_widths) {
            return;
        }

        let current_color = style.get_inherited_text().clone_color();
        let style_color = BorderStyleColor::from_border(border, &current_color);
        let details = wr::BorderDetails::Normal(wr::NormalBorder {
            top: self.build_border_side(style_color.top),
            right: self.build_border_side(style_color.right),
            bottom: self.build_border_side(style_color.bottom),
            left: self.build_border_side(style_color.left),
            radius: self.border_radius,
            do_aa: true,
        });
        let common = builder.common_properties(self.border_rect, &style);
        builder
            .wr()
            .push_border(&common, self.border_rect, border_widths, details)
    }

    /// Add a display item for image borders if necessary.
    fn build_border_image(
        &self,
        builder: &mut DisplayListBuilder,
        border: &Border,
        border_widths: SideOffsets2D<f32, LayoutPixel>,
    ) -> bool {
        let style = self.fragment.style();
        let border_style_struct = style.get_border();
        let border_image_outset =
            resolve_border_image_outset(border_style_struct.border_image_outset, border_widths);
        let border_image_area = self.border_rect.to_rect().outer_rect(border_image_outset);
        let border_image_size = border_image_area.size;
        let border_image_widths = resolve_border_image_width(
            &border_style_struct.border_image_width,
            border_widths,
            border_image_size,
        );
        let border_image_repeat = &border_style_struct.border_image_repeat;
        let border_image_fill = border_style_struct.border_image_slice.fill;
        let border_image_slice = &border_style_struct.border_image_slice.offsets;
        let common = builder.common_properties(border_image_area.to_box2d(), &style);

        let stops = Vec::new();
        let mut width = border_image_size.width;
        let mut height = border_image_size.height;
        let node = self.fragment.base.tag.map(|tag| tag.node);
        let source = match builder
            .image_resolver
            .resolve_image(node, &border.border_image_source)
        {
            Err(_) => return false,
            Ok(ResolvedImage::Image { image, size }) => {
                let image_key = match image {
                    CachedImage::Raster(raster_image) => raster_image.id,
                    CachedImage::Vector(vector_image) => {
                        let scale = builder.device_pixel_ratio.get();
                        let size = Size2D::new(size.width * scale, size.height * scale).to_i32();
                        node.and_then(|node| {
                            builder.image_resolver.rasterize_vector_image(
                                vector_image.id,
                                size,
                                node,
                                vector_image.svg_id,
                            )
                        })
                        .and_then(|rasterized_image| rasterized_image.id)
                    },
                };

                let Some(key) = image_key else {
                    return false;
                };

                builder.check_if_paintable(
                    Box2D::from_size(size.cast_unit()),
                    common.clip_rect,
                    style.clone_opacity(),
                );

                // From <https://www.w3.org/TR/paint-timing/#contentful>:
                // An element target is contentful when one or more of the following apply:
                // > target has a background-image which is a contentful image,
                // > and its used background-size has non-zero width and height values.
                builder.mark_is_contentful();

                width = size.width;
                height = size.height;
                let image_rendering = style.clone_image_rendering().to_webrender();
                NinePatchBorderSource::Image(key, image_rendering)
            },
            Ok(ResolvedImage::Gradient(gradient)) => {
                match gradient::build(&style, gradient, border_image_size, builder) {
                    WebRenderGradient::Linear(gradient) => {
                        NinePatchBorderSource::Gradient(gradient)
                    },
                    WebRenderGradient::Radial(gradient) => {
                        NinePatchBorderSource::RadialGradient(gradient)
                    },
                    WebRenderGradient::Conic(gradient) => {
                        NinePatchBorderSource::ConicGradient(gradient)
                    },
                }
            },
        };

        let size = Size2D::new(width as i32, height as i32);

        // If the size of the border is zero or the size of the border image is zero, just
        // don't render anything. Zero-sized gradients cause problems in WebRender.
        if size.is_empty() || border_image_size.is_empty() {
            return true;
        }

        let details = BorderDetails::NinePatch(NinePatchBorder {
            source,
            width: size.width,
            height: size.height,
            slice: resolve_border_image_slice(border_image_slice, size),
            fill: border_image_fill,
            repeat_horizontal: border_image_repeat.0.to_webrender(),
            repeat_vertical: border_image_repeat.1.to_webrender(),
        });
        builder.wr().push_border(
            &common,
            border_image_area.to_box2d(),
            border_image_widths,
            details,
        );
        builder.wr().push_stops(&stops);
        true
    }

    fn build_outline(&mut self, builder: &mut DisplayListBuilder) {
        let style = self.fragment.style();
        let outline = style.get_outline();
        if outline.outline_style.none_or_hidden() {
            return;
        }
        let width = outline.outline_width.0.to_f32_px();
        if width == 0.0 {
            return;
        }
        // <https://drafts.csswg.org/css-ui-3/#outline-offset>
        // > Negative values must cause the outline to shrink into the border box. Both
        // > the height and the width of outside of the shape drawn by the outline should
        // > not become smaller than twice the computed value of the outline-width
        // > property, to make sure that an outline can be rendered even with large
        // > negative values. User agents should apply this constraint independently in
        // > each dimension. If the outline is drawn as multiple disconnected shapes, this
        // > constraint applies to each shape separately.
        let offset = outline.outline_offset.to_f32_px() + width;
        let outline_rect = self.border_rect.inflate(
            offset.max(-self.border_rect.width() / 2.0 + width),
            offset.max(-self.border_rect.height() / 2.0 + width),
        );
        let common = builder.common_properties(outline_rect, &style);
        let widths = SideOffsets2D::new_all_same(width);
        let border_style = match outline.outline_style {
            // TODO: treating 'auto' as 'solid' is allowed by the spec,
            // but we should do something better.
            OutlineStyle::Auto => BorderStyle::Solid,
            OutlineStyle::BorderStyle(s) => s,
        };
        let side = self.build_border_side(BorderStyleColor {
            style: border_style,
            color: style.resolve_color(&outline.outline_color),
        });
        let details = wr::BorderDetails::Normal(wr::NormalBorder {
            top: side,
            right: side,
            bottom: side,
            left: side,
            radius: offset_radii(self.border_radius, SideOffsets2D::new_all_same(offset)),
            do_aa: true,
        });
        builder
            .wr()
            .push_border(&common, outline_rect, widths, details)
    }

    fn build_box_shadow(&self, builder: &mut DisplayListBuilder<'_>) {
        let style = self.fragment.style();
        let box_shadows = &style.get_effects().box_shadow.0;
        if box_shadows.is_empty() {
            return;
        }

        // Note: According to CSS-BACKGROUNDS, box shadows render in *reverse* order (front to back).
        for box_shadow in box_shadows.iter().rev() {
            let (rect, clip_mode) = if box_shadow.inset {
                (*self.padding_rect(), BoxShadowClipMode::Inset)
            } else {
                (self.border_rect, BoxShadowClipMode::Outset)
            };

            let offset = LayoutVector2D::new(
                box_shadow.base.horizontal.px(),
                box_shadow.base.vertical.px(),
            );
            let spread = box_shadow.spread.px();
            let blur = box_shadow.base.blur.px();
            let clip_rect = match clip_mode {
                // Inset shadows are always inside the rect.
                BoxShadowClipMode::Inset => rect,
                // Match webrender's box_shadow.rs Gaussian blur inflation.
                // (BLUR_SAMPLE_SCALE * blur).ceil(). BLUR_SAMPLE_SCALE is 3.0.
                BoxShadowClipMode::Outset => {
                    let extra_size_from_blur = (blur * 3.0).ceil();
                    rect.translate(offset)
                        .inflate(spread, spread)
                        .inflate(extra_size_from_blur, extra_size_from_blur)
                },
            };
            let common = builder.common_properties(clip_rect, &style);

            builder.wr().push_box_shadow(
                &common,
                rect,
                offset,
                rgba(style.resolve_color(&box_shadow.base.color)),
                blur,
                spread,
                self.border_radius,
                clip_mode,
            );
        }
    }
}

fn rgba(color: AbsoluteColor) -> wr::ColorF {
    let rgba = color.to_color_space(ColorSpace::Srgb);
    wr::ColorF::new(
        rgba.components.0.clamp(0.0, 1.0),
        rgba.components.1.clamp(0.0, 1.0),
        rgba.components.2.clamp(0.0, 1.0),
        rgba.alpha,
    )
}

fn glyphs(
    shaped_text_slices: &[Arc<ShapedTextSlice>],
    mut baseline_origin: PhysicalPoint<Au>,
    justification_adjustment: Au,
    include_whitespace: bool,
) -> (Vec<GlyphInstance>, Au) {
    let mut glyphs = vec![];
    let mut largest_advance = Au::zero();

    for shaped_text_slice in shaped_text_slices {
        for glyph in shaped_text_slice.glyphs() {
            if !shaped_text_slice.is_whitespace() || include_whitespace {
                let glyph_offset = glyph.offset().unwrap_or(Point2D::zero());
                let point = LayoutPoint::new(
                    baseline_origin.x.to_f32_px() + glyph_offset.x.to_f32_px(),
                    baseline_origin.y.to_f32_px() + glyph_offset.y.to_f32_px(),
                );
                let glyph_instance = GlyphInstance {
                    index: glyph.id(),
                    point,
                };
                glyphs.push(glyph_instance);
            }

            if glyph.char_is_word_separator() {
                baseline_origin.x += justification_adjustment;
            }

            let advance = glyph.advance();
            baseline_origin.x += advance;
            largest_advance.max_assign(advance);
        }
    }
    (glyphs, largest_advance)
}

/// Given a set of corner radii for a rectangle, this function returns the corresponding radii
/// for the [outer rectangle][`Rect::outer_rect`] resulting from expanding the original
/// rectangle by the given offsets.
fn offset_radii(mut radii: BorderRadius, offsets: LayoutSideOffsets) -> BorderRadius {
    let expand = |radius: &mut f32, offset: f32| {
        // For negative offsets, just shrink the radius by that amount.
        if offset < 0.0 {
            *radius = (*radius + offset).max(0.0);
            return;
        }

        // For positive offsets, expand the radius by that amount. But only if the
        // radius is positive, in order to preserve sharp corners.
        // TODO: this behavior is not continuous, we should use this algorithm instead:
        // https://github.com/w3c/csswg-drafts/issues/7103#issuecomment-3357331922
        if *radius > 0.0 {
            *radius += offset;
        }
    };
    if offsets.left != 0.0 {
        expand(&mut radii.top_left.width, offsets.left);
        expand(&mut radii.bottom_left.width, offsets.left);
    }
    if offsets.right != 0.0 {
        expand(&mut radii.top_right.width, offsets.right);
        expand(&mut radii.bottom_right.width, offsets.right);
    }
    if offsets.top != 0.0 {
        expand(&mut radii.top_left.height, offsets.top);
        expand(&mut radii.top_right.height, offsets.top);
    }
    if offsets.bottom != 0.0 {
        expand(&mut radii.bottom_right.height, offsets.bottom);
        expand(&mut radii.bottom_left.height, offsets.bottom);
    }
    radii
}

/// Resolve the WebRender border-image outset area from the style values.
fn resolve_border_image_outset(
    outset: BorderImageOutset,
    border: SideOffsets2D<f32, LayoutPixel>,
) -> SideOffsets2D<f32, LayoutPixel> {
    fn image_outset_for_side(outset: NonNegativeLengthOrNumber, border_width: f32) -> f32 {
        match outset {
            NonNegativeLengthOrNumber::Length(length) => length.px(),
            NonNegativeLengthOrNumber::Number(factor) => border_width * factor.0,
        }
    }

    SideOffsets2D::new(
        image_outset_for_side(outset.0, border.top),
        image_outset_for_side(outset.1, border.right),
        image_outset_for_side(outset.2, border.bottom),
        image_outset_for_side(outset.3, border.left),
    )
}

/// Resolve the WebRender border-image width from the style values.
fn resolve_border_image_width(
    width: &BorderImageWidth,
    border: SideOffsets2D<f32, LayoutPixel>,
    border_area: Size2D<f32, LayoutPixel>,
) -> SideOffsets2D<f32, LayoutPixel> {
    fn image_width_for_side(
        border_image_width: &BorderImageSideWidth,
        border_width: f32,
        total_length: f32,
    ) -> f32 {
        match border_image_width {
            BorderImageSideWidth::LengthPercentage(v) => {
                v.to_used_value(Au::from_f32_px(total_length)).to_f32_px()
            },
            BorderImageSideWidth::Number(x) => border_width * x.0,
            BorderImageSideWidth::Auto => border_width,
        }
    }

    SideOffsets2D::new(
        image_width_for_side(&width.0, border.top, border_area.height),
        image_width_for_side(&width.1, border.right, border_area.width),
        image_width_for_side(&width.2, border.bottom, border_area.height),
        image_width_for_side(&width.3, border.left, border_area.width),
    )
}

/// Resolve the WebRender border-image slice from the style values.
fn resolve_border_image_slice(
    border_image_slice: &StyleRect<NonNegative<NumberOrPercentage>>,
    size: Size2D<i32, UnknownUnit>,
) -> SideOffsets2D<i32, DevicePixel> {
    fn resolve_percentage(value: NonNegative<NumberOrPercentage>, length: i32) -> i32 {
        match value.0 {
            NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as i32,
            NumberOrPercentage::Number(n) => n.round() as i32,
        }
    }

    SideOffsets2D::new(
        resolve_percentage(border_image_slice.0, size.height),
        resolve_percentage(border_image_slice.1, size.width),
        resolve_percentage(border_image_slice.2, size.height),
        resolve_percentage(border_image_slice.3, size.width),
    )
}

pub(super) fn normalize_radii(rect: &units::LayoutRect, radius: &mut wr::BorderRadius) {
    // Normalize radii that add up to > 100%.
    // https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
    // > Let f = min(L_i/S_i), where i ∈ {top, right, bottom, left},
    // > S_i is the sum of the two corresponding radii of the corners on side i,
    // > and L_top = L_bottom = the width of the box,
    // > and L_left = L_right = the height of the box.
    // > If f < 1, then all corner radii are reduced by multiplying them by f.
    let f = (rect.width() / (radius.top_left.width + radius.top_right.width))
        .min(rect.width() / (radius.bottom_left.width + radius.bottom_right.width))
        .min(rect.height() / (radius.top_left.height + radius.bottom_left.height))
        .min(rect.height() / (radius.top_right.height + radius.bottom_right.height));
    if f < 1.0 {
        radius.top_left *= f;
        radius.top_right *= f;
        radius.bottom_right *= f;
        radius.bottom_left *= f;
    }
}

/// <https://drafts.csswg.org/css-shapes-1/#valdef-shape-box-margin-box>
/// > The corner radii of this shape are determined by the corresponding
/// > border-radius and margin values. If the ratio of border-radius/margin is 1 or more,
/// > or margin is negative or zero, then the margin box corner radius is
/// > max(border-radius + margin, 0). If the ratio of border-radius/margin is less than 1,
/// > and margin is positive, then the margin box corner radius is
/// > border-radius + margin * (1 + (ratio-1)^3).
pub(super) fn compute_margin_box_radius(
    radius: wr::BorderRadius,
    layout_rect: LayoutSize,
    fragment: &BoxFragment,
) -> wr::BorderRadius {
    let style = fragment.style();
    let margin = style.physical_margin();
    let adjust_radius = |radius: f32, margin: f32| -> f32 {
        if margin <= 0. || (radius / margin) >= 1. {
            (radius + margin).max(0.)
        } else {
            radius + (margin * (1. + (radius / margin - 1.).powf(3.)))
        }
    };
    let compute_margin_radius = |radius: LayoutSize,
                                 layout_rect: LayoutSize,
                                 margin: Size2D<LengthPercentageOrAuto, UnknownUnit>|
     -> LayoutSize {
        let zero = LengthPercentage::zero();
        let width = margin
            .width
            .auto_is(|| &zero)
            .to_used_value(Au::from_f32_px(layout_rect.width));
        let height = margin
            .height
            .auto_is(|| &zero)
            .to_used_value(Au::from_f32_px(layout_rect.height));
        LayoutSize::new(
            adjust_radius(radius.width, width.to_f32_px()),
            adjust_radius(radius.height, height.to_f32_px()),
        )
    };
    wr::BorderRadius {
        top_left: compute_margin_radius(
            radius.top_left,
            layout_rect,
            Size2D::new(margin.left, margin.top),
        ),
        top_right: compute_margin_radius(
            radius.top_right,
            layout_rect,
            Size2D::new(margin.right, margin.top),
        ),
        bottom_left: compute_margin_radius(
            radius.bottom_left,
            layout_rect,
            Size2D::new(margin.left, margin.bottom),
        ),
        bottom_right: compute_margin_radius(
            radius.bottom_right,
            layout_rect,
            Size2D::new(margin.right, margin.bottom),
        ),
    }
}

impl BoxFragment {
    fn border_radius(&self) -> BorderRadius {
        let style = self.style();
        let border = style.get_border();
        if border.border_top_left_radius.0.is_zero() &&
            border.border_top_right_radius.0.is_zero() &&
            border.border_bottom_right_radius.0.is_zero() &&
            border.border_bottom_left_radius.0.is_zero()
        {
            return BorderRadius::zero();
        }

        let border_rect = self.border_rect();
        let resolve =
            |radius: &LengthPercentage, box_size: Au| radius.to_used_value(box_size).to_f32_px();
        let corner = |corner: &style::values::computed::BorderCornerRadius| {
            Size2D::new(
                resolve(&corner.0.width.0, border_rect.size.width),
                resolve(&corner.0.height.0, border_rect.size.height),
            )
        };

        let mut radius = wr::BorderRadius {
            top_left: corner(&border.border_top_left_radius),
            top_right: corner(&border.border_top_right_radius),
            bottom_right: corner(&border.border_bottom_right_radius),
            bottom_left: corner(&border.border_bottom_left_radius),
        };

        normalize_radii(&border_rect.to_webrender(), &mut radius);
        radius
    }
}