summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
blob: 11a7196cd6536adf8cd1b9bd0f3f2187ce6bd5dd (plain)
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
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"

#include <memory>
#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/link_highlights.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/layout/fragmentainer_iterator.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_table_row.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_masker.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_root.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h"
#include "third_party/blink/renderer/core/paint/css_mask_painter.h"
#include "third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h"
#include "third_party/blink/renderer/core/paint/find_properties_needing_update.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_printer.h"
#include "third_party/blink/renderer/core/paint/svg_root_painter.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/scroll/overscroll_behavior.h"
#include "third_party/blink/renderer/platform/transforms/transform_state.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"

namespace blink {

namespace {

bool AreSubtreeUpdateReasonsIsolationPiercing(unsigned reasons) {
  // This is written to mean that if we have any reason other than the specified
  // ones then the reasons are isolation piercing. This means that if new
  // reasons are added, they will be isolation piercing by default.
  //  - Isolation establishes a containing block for all descendants, so it is
  //    not piercing.
  // TODO(vmpstr): Investigate if transform style is also isolated.
  return reasons &
         ~(static_cast<unsigned>(
             SubtreePaintPropertyUpdateReason::kContainerChainMayChange));
}

}  // namespace

PaintPropertyTreeBuilderFragmentContext::
    PaintPropertyTreeBuilderFragmentContext()
    : current_effect(&EffectPaintPropertyNode::Root()) {
  current.clip = absolute_position.clip = fixed_position.clip =
      &ClipPaintPropertyNode::Root();
  current.transform = absolute_position.transform = fixed_position.transform =
      &TransformPaintPropertyNode::Root();
  current.scroll = absolute_position.scroll = fixed_position.scroll =
      &ScrollPaintPropertyNode::Root();
}

PaintPropertyTreeBuilderContext::PaintPropertyTreeBuilderContext()
    : force_subtree_update_reasons(0u),
      clip_changed(false),
      is_repeating_fixed_position(false),
      has_svg_hidden_container_ancestor(false),
      supports_composited_raster_invalidation(true) {}

void VisualViewportPaintPropertyTreeBuilder::Update(
    VisualViewport& visual_viewport,
    PaintPropertyTreeBuilderContext& full_context) {
  if (full_context.fragments.IsEmpty())
    full_context.fragments.push_back(PaintPropertyTreeBuilderFragmentContext());

  PaintPropertyTreeBuilderFragmentContext& context = full_context.fragments[0];

  visual_viewport.UpdatePaintPropertyNodesIfNeeded(context);

  context.current.transform = visual_viewport.GetScrollTranslationNode();
  context.absolute_position.transform =
      visual_viewport.GetScrollTranslationNode();
  context.fixed_position.transform = visual_viewport.GetScrollTranslationNode();

  context.current.scroll = visual_viewport.GetScrollNode();
  context.absolute_position.scroll = visual_viewport.GetScrollNode();
  context.fixed_position.scroll = visual_viewport.GetScrollNode();

#if DCHECK_IS_ON()
  paint_property_tree_printer::UpdateDebugNames(visual_viewport);
#endif
}

void PaintPropertyTreeBuilder::SetupContextForFrame(
    LocalFrameView& frame_view,
    PaintPropertyTreeBuilderContext& full_context) {
  if (full_context.fragments.IsEmpty())
    full_context.fragments.push_back(PaintPropertyTreeBuilderFragmentContext());

  PaintPropertyTreeBuilderFragmentContext& context = full_context.fragments[0];
  context.current.paint_offset.MoveBy(frame_view.Location());
  context.current.rendering_context_id = 0;
  context.current.should_flatten_inherited_transform = true;
  context.absolute_position = context.current;
  full_context.container_for_absolute_position = nullptr;
  full_context.container_for_fixed_position = nullptr;
  context.fixed_position = context.current;
  context.fixed_position.fixed_position_children_fixed_to_root = true;
}

namespace {

class FragmentPaintPropertyTreeBuilder {
 public:
  FragmentPaintPropertyTreeBuilder(
      const LayoutObject& object,
      PaintPropertyTreeBuilderContext& full_context,
      PaintPropertyTreeBuilderFragmentContext& context,
      FragmentData& fragment_data)
      : object_(object),
        full_context_(full_context),
        context_(context),
        fragment_data_(fragment_data),
        properties_(fragment_data.PaintProperties()) {}

  ~FragmentPaintPropertyTreeBuilder() {
    if (property_added_or_removed_) {
      // Tree topology changes are blocked by isolation.
      full_context_.force_subtree_update_reasons |=
          PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationBlocked;
    }
#if DCHECK_IS_ON()
    if (properties_)
      paint_property_tree_printer::UpdateDebugNames(object_, *properties_);
#endif
  }

  ALWAYS_INLINE void UpdateForSelf();
  ALWAYS_INLINE void UpdateForChildren();

  bool PropertyChanged() const { return property_changed_; }
  bool PropertyAddedOrRemoved() const { return property_added_or_removed_; }
  bool HasIsolationNodes() const {
    // All or nothing check on the isolation nodes.
    DCHECK(!properties_ ||
           (properties_->TransformIsolationNode() &&
            properties_->ClipIsolationNode() &&
            properties_->EffectIsolationNode()) ||
           (!properties_->TransformIsolationNode() &&
            !properties_->ClipIsolationNode() &&
            !properties_->EffectIsolationNode()));
    return properties_ && properties_->TransformIsolationNode();
  }

 private:
  ALWAYS_INLINE void UpdatePaintOffset();
  ALWAYS_INLINE void UpdateForPaintOffsetTranslation(base::Optional<IntPoint>&);
  ALWAYS_INLINE void UpdatePaintOffsetTranslation(
      const base::Optional<IntPoint>&);
  ALWAYS_INLINE void SetNeedsPaintPropertyUpdateIfNeeded();
  ALWAYS_INLINE void UpdateForObjectLocationAndSize(
      base::Optional<IntPoint>& paint_offset_translation);
  ALWAYS_INLINE void UpdateClipPathCache();
  ALWAYS_INLINE void UpdateStickyTranslation();
  ALWAYS_INLINE void UpdateTransform();
  ALWAYS_INLINE void UpdateTransformForNonRootSVG();
  ALWAYS_INLINE bool EffectCanUseCurrentClipAsOutputClip() const;
  ALWAYS_INLINE void UpdateEffect();
  ALWAYS_INLINE void UpdateLinkHighlightEffect();
  ALWAYS_INLINE void UpdateFilter();
  ALWAYS_INLINE void UpdateFragmentClip();
  ALWAYS_INLINE void UpdateCssClip();
  ALWAYS_INLINE void UpdateClipPathClip(bool spv1_compositing_specific_pass);
  ALWAYS_INLINE void UpdateLocalBorderBoxContext();
  ALWAYS_INLINE bool NeedsOverflowControlsClip() const;
  ALWAYS_INLINE void UpdateOverflowControlsClip();
  ALWAYS_INLINE void UpdateInnerBorderRadiusClip();
  ALWAYS_INLINE void UpdateOverflowClip();
  ALWAYS_INLINE void UpdatePerspective();
  ALWAYS_INLINE void UpdateReplacedContentTransform();
  ALWAYS_INLINE void UpdateScrollAndScrollTranslation();
  ALWAYS_INLINE void UpdateOutOfFlowContext();
  // See core/paint/README.md for the description of isolation nodes.
  ALWAYS_INLINE void UpdateTransformIsolationNode();
  ALWAYS_INLINE void UpdateEffectIsolationNode();
  ALWAYS_INLINE void UpdateClipIsolationNode();

  bool NeedsPaintPropertyUpdate() const {
    return object_.NeedsPaintPropertyUpdate() ||
           full_context_.force_subtree_update_reasons;
  }

  void OnUpdate(const ObjectPaintProperties::UpdateResult& result) {
    property_added_or_removed_ |= result.NewNodeCreated();
    property_changed_ |= !result.Unchanged();
  }
  // Like |OnUpdate| but sets |clip_changed| if the clip values change.
  void OnUpdateClip(const ObjectPaintProperties::UpdateResult& result,
                    bool only_updated_hit_test_values = false) {
    OnUpdate(result);
    full_context_.clip_changed |=
        !(result.Unchanged() || only_updated_hit_test_values);
  }
  // Like |OnUpdate| but forces a piercing subtree update if the scroll tree
  // hierarchy changes because the scroll tree does not have isolation nodes
  // and non-piercing updates can fail to update scroll descendants.
  void OnUpdateScroll(const ObjectPaintProperties::UpdateResult& result) {
    OnUpdate(result);
    if (result.NewNodeCreated()) {
      full_context_.force_subtree_update_reasons |=
          PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationPiercing;
    }
  }
  void OnClear(bool cleared) {
    property_added_or_removed_ |= cleared;
    property_changed_ |= cleared;
  }
  // See: |OnUpdateScroll|.
  void OnClearScroll(bool cleared) {
    OnClear(cleared);
    if (cleared) {
      full_context_.force_subtree_update_reasons |=
          PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationPiercing;
    }
  }
  void OnClearClip(bool cleared) {
    OnClear(cleared);
    full_context_.clip_changed |= cleared;
  }

  const LayoutObject& object_;
  // The tree builder context for the whole object.
  PaintPropertyTreeBuilderContext& full_context_;
  // The tree builder context for the current fragment, which is one of the
  // entries in |full_context.fragments|.
  PaintPropertyTreeBuilderFragmentContext& context_;
  FragmentData& fragment_data_;
  ObjectPaintProperties* properties_;
  bool property_changed_ = false;
  bool property_added_or_removed_ = false;
};

static bool IsRootScroller(const LayoutBox& box) {
  auto* scrollable_area = box.GetScrollableArea();
  DCHECK(scrollable_area);
  auto* layer = scrollable_area->Layer();
  return layer &&
         CompositingReasonFinder::RequiresCompositingForRootScroller(*layer);
}

static bool HasScrollsOverflow(const LayoutBox& box) {
  // TODO(crbug.com/839341): Remove ScrollTimeline check once we support
  // main-thread AnimationWorklet and don't need to promote the scroll-source.
  return box.GetScrollableArea()->ScrollsOverflow() ||
         ScrollTimeline::HasActiveScrollTimeline(box.GetNode());
}

static bool NeedsScrollNode(const LayoutObject& object) {
  if (!object.HasOverflowClip())
    return false;
  const LayoutBox& box = ToLayoutBox(object);
  // TODO(pdr): CAP has invalidation issues (crbug.com/732611) as well as
  // subpixel issues (crbug.com/693741) which prevent us from compositing the
  // root scroller.
  if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
    return HasScrollsOverflow(box);
  return HasScrollsOverflow(box) || IsRootScroller(box);
}

static CompositingReasons CompositingReasonsForScroll(const LayoutBox& box) {
  CompositingReasons compositing_reasons = CompositingReason::kNone;

  if (IsRootScroller(box))
    compositing_reasons |= CompositingReason::kRootScroller;

  // TODO(pdr): Set other compositing reasons for scroll here, see:
  // PaintLayerScrollableArea::ComputeNeedsCompositedScrolling.
  return compositing_reasons;
}

// True if a scroll translation is needed for static scroll offset (e.g.,
// overflow hidden with scroll), or if a scroll node is needed for composited
// scrolling.
static bool NeedsScrollOrScrollTranslation(const LayoutObject& object) {
  if (!object.HasOverflowClip())
    return false;
  IntSize scroll_offset = ToLayoutBox(object).ScrolledContentOffset();
  return !scroll_offset.IsZero() || NeedsScrollNode(object);
}

static bool NeedsReplacedContentTransform(const LayoutObject& object) {
  // Quick reject.
  if (!object.IsLayoutReplaced())
    return false;

  if (object.IsSVGRoot())
    return true;

  // Only directly composited images need a transform node to scale contents
  // to the object-fit box. Note that we don't actually know whether the image
  // will be directly composited. This condition is relaxed to stay on the
  // safe side.
  // TODO(crbug.com/875110): Figure out the condition for CAP.
  bool is_spv1_composited =
      object.HasLayer() &&
      ToLayoutBoxModelObject(object).Layer()->GetCompositedLayerMapping();
  if (object.IsImage() && is_spv1_composited)
    return true;

  return false;
}

static bool NeedsPaintOffsetTranslationForScrollbars(
    const LayoutBoxModelObject& object) {
  if (auto* area = object.GetScrollableArea()) {
    if (area->HorizontalScrollbar() || area->VerticalScrollbar())
      return true;
  }
  return false;
}

static bool NeedsIsolationNodes(const LayoutObject& object) {
  if (!object.HasLayer())
    return false;

  // Paint containment establishes isolation.
  // Style & Layout containment also establish isolation.
  if (object.ShouldApplyPaintContainment() ||
      (object.ShouldApplyStyleContainment() &&
       object.ShouldApplyLayoutContainment())) {
    return true;
  }

  // Layout view establishes isolation with the exception of local roots (since
  // they are already essentially isolated).
  if (object.IsLayoutView()) {
    const auto* parent_frame = object.GetFrame()->Tree().Parent();
    return parent_frame && parent_frame->IsLocalFrame();
  }
  return false;
}

static bool NeedsStickyTranslation(const LayoutObject& object) {
  if (!object.IsBoxModelObject())
    return false;

  return object.StyleRef().HasStickyConstrainedPosition();
}

static bool NeedsPaintOffsetTranslation(const LayoutObject& object) {
  if (!object.IsBoxModelObject())
    return false;

  // <foreignObject> inherits no paint offset, because there is no such
  // concept within SVG. However, the foreign object can have its own paint
  // offset due to the x and y parameters of the element. This affects the
  // offset of painting of the <foreignObject> element and its children.
  // However, <foreignObject> otherwise behaves like other SVG elements, in
  // that the x and y offset is applied *after* any transform, instead of
  // before. Therefore there is no paint offset translation needed.
  if (object.IsSVGForeignObject())
    return false;

  const LayoutBoxModelObject& box_model = ToLayoutBoxModelObject(object);

  if (box_model.IsLayoutView()) {
    // A translation node for LayoutView is always created to ensure fixed and
    // absolute contexts use the correct transform space.
    return true;
  }

  if (NeedsIsolationNodes(box_model)) {
    DCHECK(box_model.HasLayer());
    return true;
  }

  if (box_model.HasLayer() && box_model.Layer()->PaintsWithTransform(
                                  kGlobalPaintFlattenCompositingLayers)) {
    return true;
  }
  if (NeedsScrollOrScrollTranslation(object))
    return true;
  if (NeedsStickyTranslation(object))
    return true;
  if (NeedsPaintOffsetTranslationForScrollbars(box_model))
    return true;
  if (NeedsReplacedContentTransform(object))
    return true;

  // Don't let paint offset cross composited layer boundaries, to avoid
  // unnecessary full layer paint/raster invalidation when paint offset in
  // ancestor transform node changes which should not affect the descendants
  // of the composited layer.
  // TODO(wangxianzhu): For CAP, we also need a avoid unnecessary paint/raster
  // invalidation in composited layers when their paint offset changes.
  if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled() &&
      // For only LayoutBlocks that won't be escaped by floating objects and
      // column spans when finding their containing blocks.
      // TODO(crbug.com/780242): This can be avoided if we have fully correct
      // paint property tree states for floating objects and column spans.
      (object.IsLayoutBlock() || object.IsLayoutReplaced()) &&
      object.HasLayer() &&
      !ToLayoutBoxModelObject(object).Layer()->EnclosingPaginationLayer() &&
      object.GetCompositingState() == kPaintsIntoOwnBacking)
    return true;

  return false;
}

void FragmentPaintPropertyTreeBuilder::UpdateForPaintOffsetTranslation(
    base::Optional<IntPoint>& paint_offset_translation) {
  if (!NeedsPaintOffsetTranslation(object_))
    return;

  // We should use the same subpixel paint offset values for snapping
  // regardless of whether a transform is present. If there is a transform
  // we round the paint offset but keep around the residual fractional
  // component for the transformed content to paint with.  In spv1 this was
  // called "subpixel accumulation". For more information, see
  // PaintLayer::subpixelAccumulation() and
  // PaintLayerPainter::paintFragmentByApplyingTransform.
  paint_offset_translation = RoundedIntPoint(context_.current.paint_offset);
  LayoutPoint fractional_paint_offset =
      LayoutPoint(context_.current.paint_offset - *paint_offset_translation);
  if (fractional_paint_offset != LayoutPoint()) {
    // If the object has a non-translation transform, discard the fractional
    // paint offset which can't be transformed by the transform.
    TransformationMatrix matrix;
    object_.StyleRef().ApplyTransform(
        matrix, LayoutSize(), ComputedStyle::kExcludeTransformOrigin,
        ComputedStyle::kIncludeMotionPath,
        ComputedStyle::kIncludeIndependentTransformProperties);
    if (!matrix.IsIdentityOrTranslation())
      fractional_paint_offset = LayoutPoint();
  }
  context_.current.paint_offset = fractional_paint_offset;
}

void FragmentPaintPropertyTreeBuilder::UpdatePaintOffsetTranslation(
    const base::Optional<IntPoint>& paint_offset_translation) {
  DCHECK(properties_);

  if (paint_offset_translation) {
    TransformPaintPropertyNode::State state;
    state.matrix.Translate(paint_offset_translation->X(),
                           paint_offset_translation->Y());
    state.flattens_inherited_transform =
        context_.current.should_flatten_inherited_transform;
    state.is_identity_or_2d_translation = true;

    state.affected_by_outer_viewport_bounds_delta =
        object_.StyleRef().GetPosition() == EPosition::kFixed &&
        object_.StyleRef().IsFixedToBottom();

    if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
        RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
      state.rendering_context_id = context_.current.rendering_context_id;
    OnUpdate(properties_->UpdatePaintOffsetTranslation(
        *context_.current.transform, std::move(state)));
    context_.current.transform = properties_->PaintOffsetTranslation();
    if (object_.IsLayoutView()) {
      context_.absolute_position.transform =
          properties_->PaintOffsetTranslation();
      context_.fixed_position.transform = properties_->PaintOffsetTranslation();
    }
  } else {
    OnClear(properties_->ClearPaintOffsetTranslation());
  }
}

void FragmentPaintPropertyTreeBuilder::UpdateStickyTranslation() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsStickyTranslation(object_)) {
      const auto& box_model = ToLayoutBoxModelObject(object_);
      FloatSize sticky_offset(box_model.StickyPositionOffset());
      TransformPaintPropertyNode::State state{AffineTransform::Translation(
          sticky_offset.Width(), sticky_offset.Height())};
      state.is_identity_or_2d_translation = true;
      state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
          box_model.UniqueId(),
          CompositorElementIdNamespace::kStickyTranslation);

      auto* layer = box_model.Layer();
      const auto* scroller_properties = layer->AncestorOverflowLayer()
                                            ->GetLayoutObject()
                                            .FirstFragment()
                                            .PaintProperties();
      // A scroll node is only created if an object can be scrolled manually,
      // while sticky position attaches to anything that clips overflow.
      // No need to (actually can't) setup composited sticky constraint if
      // the clipping ancestor we attach to doesn't have a scroll node.
      // TODO(crbug.com/881555): If the clipping ancestor does have a scroll
      // node, this really should be a DCHECK the current scrolll node
      // matches it. i.e.
      // if (scroller_properties && scroller_properties->Scroll()) {
      //   DCHECK_EQ(scroller_properties->Scroll(), context_.current.scroll);
      // However there is a bug that AncestorOverflowLayer() may be computed
      // incorrectly with clip escaping involved.
      if (scroller_properties &&
          scroller_properties->Scroll() == context_.current.scroll) {
        const StickyPositionScrollingConstraints& layout_constraint =
            layer->AncestorOverflowLayer()
                ->GetScrollableArea()
                ->GetStickyConstraintsMap()
                .at(layer);
        auto constraint = std::make_unique<CompositorStickyConstraint>();
        constraint->is_sticky = true;
        constraint->is_anchored_left = layout_constraint.is_anchored_left;
        constraint->is_anchored_right = layout_constraint.is_anchored_right;
        constraint->is_anchored_top = layout_constraint.is_anchored_top;
        constraint->is_anchored_bottom = layout_constraint.is_anchored_bottom;
        constraint->left_offset = layout_constraint.left_offset;
        constraint->right_offset = layout_constraint.right_offset;
        constraint->top_offset = layout_constraint.top_offset;
        constraint->bottom_offset = layout_constraint.bottom_offset;
        constraint->constraint_box_rect =
            box_model.ComputeStickyConstrainingRect();
        constraint->scroll_container_relative_sticky_box_rect = RoundedIntRect(
            layout_constraint.scroll_container_relative_sticky_box_rect);
        constraint
            ->scroll_container_relative_containing_block_rect = RoundedIntRect(
            layout_constraint.scroll_container_relative_containing_block_rect);
        if (PaintLayer* sticky_box_shifting_ancestor =
                layout_constraint.nearest_sticky_layer_shifting_sticky_box) {
          constraint->nearest_element_shifting_sticky_box =
              CompositorElementIdFromUniqueObjectId(
                  sticky_box_shifting_ancestor->GetLayoutObject().UniqueId(),
                  CompositorElementIdNamespace::kStickyTranslation);
        }
        if (PaintLayer* containing_block_shifting_ancestor =
                layout_constraint
                    .nearest_sticky_layer_shifting_containing_block) {
          constraint->nearest_element_shifting_containing_block =
              CompositorElementIdFromUniqueObjectId(
                  containing_block_shifting_ancestor->GetLayoutObject()
                      .UniqueId(),
                  CompositorElementIdNamespace::kStickyTranslation);
        }
        state.sticky_constraint = std::move(constraint);
      }

      OnUpdate(properties_->UpdateStickyTranslation(*context_.current.transform,
                                                    std::move(state)));
    } else {
      OnClear(properties_->ClearStickyTranslation());
    }
  }

  if (properties_->StickyTranslation())
    context_.current.transform = properties_->StickyTranslation();
}

static bool NeedsTransformForNonRootSVG(const LayoutObject& object) {
  // TODO(pdr): Check for the presence of a transform instead of the value.
  // Checking for an identity matrix will cause the property tree structure
  // to change during animations if the animation passes through the
  // identity matrix.
  return object.IsSVGChild() &&
         !object.LocalToSVGParentTransform().IsIdentity();
}

// SVG does not use the general transform update of |UpdateTransform|, instead
// creating a transform node for SVG-specific transforms without 3D.
void FragmentPaintPropertyTreeBuilder::UpdateTransformForNonRootSVG() {
  DCHECK(properties_);
  DCHECK(object_.IsSVGChild());
  // SVG does not use paint offset internally, except for SVGForeignObject which
  // has different SVG and HTML coordinate spaces.
  DCHECK(object_.IsSVGForeignObject() ||
         context_.current.paint_offset == LayoutPoint());

  if (NeedsPaintPropertyUpdate()) {
    AffineTransform transform = object_.LocalToSVGParentTransform();
    if (NeedsTransformForNonRootSVG(object_)) {
      // The origin is included in the local transform, so leave origin empty.
      OnUpdate(properties_->UpdateTransform(
          *context_.current.transform,
          TransformPaintPropertyNode::State{transform}));
    } else {
      OnClear(properties_->ClearTransform());
    }
  }

  if (properties_->Transform()) {
    context_.current.transform = properties_->Transform();
    context_.current.should_flatten_inherited_transform = false;
    context_.current.rendering_context_id = 0;
  }
}

static CompositingReasons CompositingReasonsForTransform(const LayoutBox& box) {
  if (!box.HasLayer())
    return CompositingReason::kNone;

  const ComputedStyle& style = box.StyleRef();
  CompositingReasons compositing_reasons = CompositingReason::kNone;
  if (CompositingReasonFinder::RequiresCompositingForTransform(box))
    compositing_reasons |= CompositingReason::k3DTransform;

  if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
      RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
    // Currently, we create transform nodes for an element whenever any property
    // is being animated so that the existence of the effect node implies the
    // existence of all nodes.
    // TODO(flackr): Check for nodes for each KeyframeModel target
    // property instead of creating all nodes and only create a transform node
    // if needed, https://crbug.com/900241
    compositing_reasons |=
        CompositingReasonFinder::CompositingReasonsForAnimation(style);
  } else {
    if (CompositingReasonFinder::RequiresCompositingForTransformAnimation(
            style))
      compositing_reasons |= CompositingReason::kActiveTransformAnimation;
  }

  if (style.HasWillChangeCompositingHint() &&
      !style.SubtreeWillChangeContents())
    compositing_reasons |= CompositingReason::kWillChangeCompositingHint;

  if (box.HasLayer() && box.Layer()->Has3DTransformedDescendant()) {
    if (style.HasPerspective())
      compositing_reasons |= CompositingReason::kPerspectiveWith3DDescendants;
    if (style.UsedTransformStyle3D() == ETransformStyle3D::kPreserve3d)
      compositing_reasons |= CompositingReason::kPreserve3DWith3DDescendants;
  }

  return compositing_reasons;
}

static FloatPoint3D TransformOrigin(const LayoutBox& box) {
  const ComputedStyle& style = box.StyleRef();
  // Transform origin has no effect without a transform or motion path.
  if (!style.HasTransform())
    return FloatPoint3D();
  FloatSize border_box_size(box.Size());
  return FloatPoint3D(
      FloatValueForLength(style.TransformOriginX(), border_box_size.Width()),
      FloatValueForLength(style.TransformOriginY(), border_box_size.Height()),
      style.TransformOriginZ());
}

static bool NeedsTransform(const LayoutObject& object) {
  if ((RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
       RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) &&
      object.StyleRef().BackfaceVisibility() == EBackfaceVisibility::kHidden)
    return true;

  if (!object.IsBox())
    return false;
  return object.StyleRef().HasTransform() || object.StyleRef().Preserves3D() ||
         CompositingReasonsForTransform(ToLayoutBox(object)) !=
             CompositingReason::kNone;
}

void FragmentPaintPropertyTreeBuilder::UpdateTransform() {
  if (object_.IsSVGChild()) {
    UpdateTransformForNonRootSVG();
    return;
  }

  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    const ComputedStyle& style = object_.StyleRef();
    // A transform node is allocated for transforms, preserves-3d and any
    // direct compositing reason. The latter is required because this is the
    // only way to represent compositing both an element and its stacking
    // descendants.
    if (NeedsTransform(object_)) {
      TransformPaintPropertyNode::State state;

      if (object_.IsBox()) {
        auto& box = ToLayoutBox(object_);
        state.origin = TransformOrigin(box);
        style.ApplyTransform(
            state.matrix, box.Size(), ComputedStyle::kExcludeTransformOrigin,
            ComputedStyle::kIncludeMotionPath,
            ComputedStyle::kIncludeIndependentTransformProperties);

        if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
            RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
          // TODO(trchen): transform-style should only be respected if a
          // PaintLayer is created. If a node with transform-style: preserve-3d
          // does not exist in an existing rendering context, it establishes a
          // new one.
          state.rendering_context_id = context_.current.rendering_context_id;
          if (style.Preserves3D() && !state.rendering_context_id) {
            state.rendering_context_id =
                PtrHash<const LayoutObject>::GetHash(&object_);
          }
          state.direct_compositing_reasons =
              CompositingReasonsForTransform(box);
        }
      }

      state.flattens_inherited_transform =
          context_.current.should_flatten_inherited_transform;

      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
        state.backface_visibility =
            object_.HasHiddenBackface()
                ? TransformPaintPropertyNode::BackfaceVisibility::kHidden
                : TransformPaintPropertyNode::BackfaceVisibility::kVisible;
        state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
            object_.UniqueId(),
            CompositorElementIdNamespace::kPrimaryTransform);
      }

      OnUpdate(properties_->UpdateTransform(*context_.current.transform,
                                            std::move(state)));
    } else {
      OnClear(properties_->ClearTransform());
    }
  }

  if (properties_->Transform()) {
    context_.current.transform = properties_->Transform();
    if (object_.StyleRef().Preserves3D()) {
      context_.current.rendering_context_id =
          properties_->Transform()->RenderingContextId();
      context_.current.should_flatten_inherited_transform = false;
    } else {
      context_.current.rendering_context_id = 0;
      context_.current.should_flatten_inherited_transform = true;
    }
  }
}

static bool NeedsClipPathClip(const LayoutObject& object) {
  if (!object.StyleRef().ClipPath())
    return false;

  return object.FirstFragment().ClipPathPath();
}

static bool NeedsEffect(const LayoutObject& object) {
  const ComputedStyle& style = object.StyleRef();

  // For now some objects (e.g. LayoutTableCol) with stacking context style
  // don't create layer thus are not actual stacking contexts, so the HasLayer()
  // condition. TODO(crbug.com/892734): Support effects for LayoutTableCol.
  const bool is_css_isolated_group =
      object.HasLayer() && style.IsStackingContext();

  if (!is_css_isolated_group && !object.IsSVG())
    return false;

  if (object.IsSVG()) {
    if (SVGLayoutSupport::IsIsolationRequired(&object))
      return true;
    if (SVGResources* resources =
            SVGResourcesCache::CachedResourcesForLayoutObject(object)) {
      if (resources->Masker()) {
        return true;
      }
    }
  }

  if (is_css_isolated_group) {
    if (object.IsSVGRoot() && object.HasNonIsolatedBlendingDescendants())
      return true;

    const auto* layer = ToLayoutBoxModelObject(object).Layer();
    DCHECK(layer);

    if (layer->HasNonIsolatedDescendantWithBlendMode())
      return true;

    // In SPv1* a mask layer can be created for clip-path in absence of mask,
    // and a mask effect node must be created whether the clip-path is
    // path-based or not.
    if (layer->GetCompositedLayerMapping() &&
        layer->GetCompositedLayerMapping()->MaskLayer())
      return true;

    // An effect node is required by cc if the layer flattens its subtree but it
    // is treated as a 3D object by its parent.
    if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
        !layer->Preserves3D() && layer->HasSelfPaintingLayerDescendant() &&
        layer->Parent() && layer->Parent()->Preserves3D())
      return true;
  }

  SkBlendMode blend_mode = object.IsBlendingAllowed()
                               ? WebCoreCompositeToSkiaComposite(
                                     kCompositeSourceOver, style.GetBlendMode())
                               : SkBlendMode::kSrcOver;
  if (blend_mode != SkBlendMode::kSrcOver)
    return true;

  if (style.Opacity() != 1.0f || style.HasWillChangeOpacityHint())
    return true;

  // Currently, we create effect nodes for an element whenever any property
  // is being animated so that the existence of the effect node implies the
  // existence of all nodes.
  // TODO(flackr): Check for nodes for each KeyframeModel target
  // property instead of creating all nodes and only create an effect node
  // if needed, https://crbug.com/900241
  if ((RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
       RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())) {
    if (CompositingReasonFinder::CompositingReasonsForAnimation(style))
      return true;
  } else {
    if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation(style))
      return true;
  }

  if (object.StyleRef().HasMask())
    return true;

  if (object.StyleRef().ClipPath() &&
      object.FirstFragment().ClipPathBoundingBox() &&
      !object.FirstFragment().ClipPathPath()) {
    // If the object has a valid clip-path but can't use path-based clip-path,
    // a clip-path effect node must be created.
    return true;
  }

  return false;
}

// An effect node can use the current clip as its output clip if the clip won't
// end before the effect ends. Having explicit output clip can let the later
// stages use more optimized code path.
bool FragmentPaintPropertyTreeBuilder::EffectCanUseCurrentClipAsOutputClip()
    const {
  DCHECK(NeedsEffect(object_));

  if (!object_.HasLayer()) {
    // An SVG object's effect never interleaves with clips.
    DCHECK(object_.IsSVG());
    return true;
  }

  const auto* layer = ToLayoutBoxModelObject(object_).Layer();
  // Out-of-flow descendants not contained by this object may escape clips.
  if (layer->HasNonContainedAbsolutePositionDescendant() &&
      object_.ContainerForAbsolutePosition()
              ->FirstFragment()
              .PostOverflowClip() != context_.current.clip)
    return false;
  if (layer->HasFixedPositionDescendant() &&
      !object_.CanContainFixedPositionObjects() &&
      object_.ContainerForFixedPosition()->FirstFragment().PostOverflowClip() !=
          context_.current.clip)
    return false;

  // Some descendants under a pagination container (e.g. composited objects
  // in SPv1 and column spanners) may escape fragment clips.
  // TODO(crbug.com/803649): Remove this when we fix fragment clip hierarchy
  // issues.
  if (layer->EnclosingPaginationLayer())
    return false;

  return true;
}

void FragmentPaintPropertyTreeBuilder::UpdateEffect() {
  DCHECK(properties_);
  const ComputedStyle& style = object_.StyleRef();

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsEffect(object_)) {
      base::Optional<IntRect> mask_clip = CSSMaskPainter::MaskBoundingBox(
          object_, context_.current.paint_offset);
      bool has_clip_path =
          style.ClipPath() && fragment_data_.ClipPathBoundingBox();
      bool is_spv1_composited =
          object_.HasLayer() &&
          ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping();
      bool has_spv1_composited_clip_path = has_clip_path && is_spv1_composited;
      bool has_mask_based_clip_path =
          has_clip_path && !fragment_data_.ClipPathPath();
      base::Optional<IntRect> clip_path_clip;
      if (has_spv1_composited_clip_path || has_mask_based_clip_path) {
        clip_path_clip = fragment_data_.ClipPathBoundingBox();
      } else if (!mask_clip && is_spv1_composited &&
                 ToLayoutBoxModelObject(object_)
                     .Layer()
                     ->GetCompositedLayerMapping()
                     ->MaskLayer()) {
        // TODO(crbug.com/856818): This should never happen.
        // This is a band-aid to avoid nullptr properties on the mask layer
        // crashing the renderer, but will result in incorrect rendering.
        NOTREACHED();
        has_spv1_composited_clip_path = true;
        clip_path_clip = IntRect();
      }

      const auto* output_clip = EffectCanUseCurrentClipAsOutputClip()
                                    ? context_.current.clip
                                    : nullptr;

      if (mask_clip || clip_path_clip) {
        IntRect combined_clip = mask_clip ? *mask_clip : *clip_path_clip;
        if (mask_clip && clip_path_clip)
          combined_clip.Intersect(*clip_path_clip);

        OnUpdateClip(properties_->UpdateMaskClip(
            *context_.current.clip,
            ClipPaintPropertyNode::State{context_.current.transform,
                                         FloatRoundedRect(combined_clip)}));
        output_clip = properties_->MaskClip();
      } else {
        OnClearClip(properties_->ClearMaskClip());
      }

      EffectPaintPropertyNode::State state;
      state.local_transform_space = context_.current.transform;
      state.output_clip = output_clip;
      state.opacity = style.Opacity();
      if (object_.IsBlendingAllowed()) {
        state.blend_mode = WebCoreCompositeToSkiaComposite(
            kCompositeSourceOver, style.GetBlendMode());
      }
      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
        // We may begin to composite our subtree prior to an animation starts,
        // but a compositor element ID is only needed when an animation is
        // current.
        //
        // Currently, we use the existence of this id to check if effect nodes
        // have been created for animations on this element.
        // TODO(flackr): Check for nodes for each KeyframeModel target
        // property instead of creating all nodes and create each type of
        // node as needed, https://crbug.com/900241
        state.direct_compositing_reasons =
            CompositingReasonFinder::CompositingReasonsForAnimation(style);
        if (state.direct_compositing_reasons) {
          state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
              object_.UniqueId(), CompositorElementIdNamespace::kPrimaryEffect);
        } else {
          // The effect node CompositorElementId is used to uniquely identify
          // renderpasses so even if we don't need one for animations we still
          // need to set an id. Using kPrimary avoids confusing cc::Animation
          // into thinking the element has been composited for animations.
          state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
              object_.UniqueId(), CompositorElementIdNamespace::kPrimary);
        }
      }
      OnUpdate(properties_->UpdateEffect(*context_.current_effect,
                                         std::move(state)));

      if (mask_clip || has_spv1_composited_clip_path) {
        EffectPaintPropertyNode::State mask_state;
        mask_state.local_transform_space = context_.current.transform;
        mask_state.output_clip = output_clip;
        mask_state.color_filter = CSSMaskPainter::MaskColorFilter(object_);
        mask_state.blend_mode = SkBlendMode::kDstIn;
        if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
            RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
          mask_state.compositor_element_id =
              CompositorElementIdFromUniqueObjectId(
                  object_.UniqueId(),
                  CompositorElementIdNamespace::kEffectMask);
        }
        OnUpdate(properties_->UpdateMask(*properties_->Effect(),
                                         std::move(mask_state)));
      } else {
        OnClear(properties_->ClearMask());
      }

      if (has_mask_based_clip_path) {
        const EffectPaintPropertyNode& parent = has_spv1_composited_clip_path
                                                    ? *properties_->Mask()
                                                    : *properties_->Effect();
        EffectPaintPropertyNode::State clip_path_state;
        clip_path_state.local_transform_space = context_.current.transform;
        clip_path_state.output_clip = output_clip;
        clip_path_state.blend_mode = SkBlendMode::kDstIn;
        if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
            RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
          clip_path_state.compositor_element_id =
              CompositorElementIdFromUniqueObjectId(
                  object_.UniqueId(),
                  CompositorElementIdNamespace::kEffectClipPath);
        }
        OnUpdate(
            properties_->UpdateClipPath(parent, std::move(clip_path_state)));
      } else {
        OnClear(properties_->ClearClipPath());
      }
    } else {
      OnClear(properties_->ClearEffect());
      OnClear(properties_->ClearMask());
      OnClear(properties_->ClearClipPath());
      OnClearClip(properties_->ClearMaskClip());
    }
  }

  if (properties_->Effect()) {
    context_.current_effect = properties_->Effect();
    if (properties_->MaskClip()) {
      context_.current.clip = context_.absolute_position.clip =
          context_.fixed_position.clip = properties_->MaskClip();
    }
  }
}

static bool NeedsLinkHighlightEffect(const LayoutObject& object) {
  auto* page = object.GetFrame()->GetPage();
  return page->GetLinkHighlights().NeedsHighlightEffect(object);
}

void FragmentPaintPropertyTreeBuilder::UpdateLinkHighlightEffect() {
  if (!NeedsPaintPropertyUpdate())
    return;

  DCHECK(properties_);

  if (!NeedsLinkHighlightEffect(object_)) {
    // Unlike other property nodes, link highlight effect nodes are guaranteed
    // to be leaf nodes and do not require subtree invalidation, so we do not
    // call |OnClear| here.
    properties_->ClearLinkHighlightEffect();
    return;
  }

  if (&fragment_data_ != &object_.FirstFragment()) {
    // All fragments share the same LinkHighlightEffect node.
    DCHECK(object_.FirstFragment().PaintProperties());
    DCHECK(object_.FirstFragment().PaintProperties()->LinkHighlightEffect());
    properties_->SetLinkHighlightEffect(
        object_.FirstFragment().PaintProperties()->LinkHighlightEffect());
    return;
  }

  // While the link highlight uses the current transform space for
  // positioning, it's parent effect is the root so that it is not affected
  // by enclosing filters.
  const auto& parent = EffectPaintPropertyNode::Root();
  EffectPaintPropertyNode::State link_highlight_state;
  link_highlight_state.local_transform_space = context_.current.transform;
  link_highlight_state.compositor_element_id =
      object_.GetFrame()->GetPage()->GetLinkHighlights().element_id(object_);
  link_highlight_state.direct_compositing_reasons =
      CompositingReason::kActiveOpacityAnimation;
  // Unlike other property nodes, link highlight effect nodes are guaranteed
  // to be leaf nodes and do not require subtree invalidation, so we do not
  // call |OnUpdate| here.
  properties_->UpdateLinkHighlightEffect(parent,
                                         std::move(link_highlight_state));
}

static bool NeedsFilter(const LayoutObject& object) {
  // Currently, we create filter nodes for an element whenever any property
  // is being animated so that the existence of the effect node implies the
  // existence of all animation nodes.
  if (!object.IsBoxModelObject() || !ToLayoutBoxModelObject(object).Layer())
    return false;

  // TODO(trchen): SVG caches filters in SVGResources. Implement it.
  if (object.StyleRef().HasFilter() || object.HasReflection() ||
      object.HasBackdropFilter())
    return true;

  // TODO(flackr): Check for nodes for each KeyframeModel target
  // property instead of creating all nodes and only create a filter node
  // if needed, https://crbug.com/900241
  bool needs_compositing_for_animation =
      (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
       RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
          ? CompositingReasonFinder::CompositingReasonsForAnimation(
                object.StyleRef())
          : CompositingReasonFinder::RequiresCompositingForFilterAnimation(
                object.StyleRef());
  return needs_compositing_for_animation;
}

void FragmentPaintPropertyTreeBuilder::UpdateFilter() {
  DCHECK(properties_);
  const ComputedStyle& style = object_.StyleRef();

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsFilter(object_)) {
      EffectPaintPropertyNode::State state;
      state.local_transform_space = context_.current.transform;
      state.filters_origin = FloatPoint(context_.current.paint_offset);

      if (auto* layer = ToLayoutBoxModelObject(object_).Layer()) {
        // Try to use the cached filter.
        if (properties_->Filter()) {
          state.filter = properties_->Filter()->Filter();
          state.backdrop_filter = properties_->Filter()->BackdropFilter();
          state.backdrop_filter_bounds =
              properties_->Filter()->BackdropFilterBounds();
        }

        // With BGPT disabled, UpdateFilterReferenceBox gets called from
        // CompositedLayerMapping::UpdateGraphicsLayerGeometry, but only
        // for composited layers.
        if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
            layer->GetCompositingState() != kPaintsIntoOwnBacking) {
          layer->UpdateFilterReferenceBox();
        }
        layer->UpdateCompositorFilterOperationsForFilter(state.filter);
        layer->UpdateCompositorFilterOperationsForBackdropFilter(
            state.backdrop_filter, &state.backdrop_filter_bounds);
        layer->ClearFilterOnEffectNodeDirty();
      }

      // The CSS filter spec didn't specify how filters interact with overflow
      // clips. The implementation here mimics the old Blink/WebKit behavior for
      // backward compatibility.
      // Basically the output of the filter will be affected by clips that
      // applies to the current element. The descendants that paints into the
      // input of the filter ignores any clips collected so far. For example:
      // <div style="overflow:scroll">
      //   <div style="filter:blur(1px);">
      //     <div>A</div>
      //     <div style="position:absolute;">B</div>
      //   </div>
      // </div>
      // In this example "A" should be clipped if the filter was not present.
      // With the filter, "A" will be rastered without clipping, but instead
      // the blurred result will be clipped.
      // On the other hand, "B" should not be clipped because the overflow clip
      // is not in its containing block chain, but as the filter output will be
      // clipped, so a blurred "B" may still be invisible.
      state.output_clip = context_.current.clip;

      // TODO(trchen): A filter may contain spatial operations such that an
      // output pixel may depend on an input pixel outside of the output clip.
      // We should generate a special clip node to represent this expansion.

      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
        // We may begin to composite our subtree prior to an animation starts,
        // but a compositor element ID is only needed when an animation is
        // current.
        // TODO(flackr): Only set a compositing reason for filter animation
        // once we no longer need to create all nodes, https://crbug.com/900241
        state.direct_compositing_reasons =
            CompositingReasonFinder::CompositingReasonsForAnimation(style);
        DCHECK(!style.HasCurrentFilterAnimation() ||
               state.direct_compositing_reasons != CompositingReason::kNone);

        state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
            object_.UniqueId(), CompositorElementIdNamespace::kEffectFilter);
      }

      OnUpdate(properties_->UpdateFilter(*context_.current_effect,
                                         std::move(state)));
    } else {
      OnClear(properties_->ClearFilter());
    }
  }

  if (properties_->Filter()) {
    context_.current_effect = properties_->Filter();
    // TODO(trchen): Change input clip to expansion hint once implemented.
    const ClipPaintPropertyNode* input_clip =
        properties_->Filter()->OutputClip();
    context_.current.clip = context_.absolute_position.clip =
        context_.fixed_position.clip = input_clip;
  }
}

static FloatRoundedRect ToClipRect(const LayoutRect& rect) {
  return FloatRoundedRect(FloatRect(PixelSnappedIntRect(rect)));
}

void FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (context_.fragment_clip) {
      OnUpdateClip(properties_->UpdateFragmentClip(
          *context_.current.clip,
          ClipPaintPropertyNode::State{context_.current.transform,
                                       ToClipRect(*context_.fragment_clip)}));
    } else {
      OnClearClip(properties_->ClearFragmentClip());
    }
  }

  if (properties_->FragmentClip())
    context_.current.clip = properties_->FragmentClip();
}

static bool NeedsCssClip(const LayoutObject& object) {
  return object.HasClip();
}

void FragmentPaintPropertyTreeBuilder::UpdateCssClip() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsCssClip(object_)) {
      // Create clip node for descendants that are not fixed position.
      // We don't have to setup context.absolutePosition.clip here because this
      // object must be a container for absolute position descendants, and will
      // copy from in-flow context later at updateOutOfFlowContext() step.
      DCHECK(object_.CanContainAbsolutePositionObjects());
      OnUpdateClip(properties_->UpdateCssClip(
          *context_.current.clip,
          ClipPaintPropertyNode::State{context_.current.transform,
                                       ToClipRect(ToLayoutBox(object_).ClipRect(
                                           context_.current.paint_offset))}));
    } else {
      OnClearClip(properties_->ClearCssClip());
    }
  }

  if (properties_->CssClip())
    context_.current.clip = properties_->CssClip();
}

void FragmentPaintPropertyTreeBuilder::UpdateClipPathClip(
    bool spv1_compositing_specific_pass) {
  // In SPv1*, composited path-based clip-path applies to a mask paint chunk
  // instead of actual contents. We have to delay until mask clip node has been
  // created first so we can parent under it.
  bool is_spv1_composited =
      object_.HasLayer() &&
      ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping();
  if (is_spv1_composited != spv1_compositing_specific_pass)
    return;

  if (NeedsPaintPropertyUpdate()) {
    if (!NeedsClipPathClip(object_)) {
      OnClearClip(properties_->ClearClipPathClip());
    } else {
      ClipPaintPropertyNode::State state;
      state.local_transform_space = context_.current.transform;
      state.clip_rect =
          FloatRoundedRect(FloatRect(*fragment_data_.ClipPathBoundingBox()));
      state.clip_path = fragment_data_.ClipPathPath();
      OnUpdateClip(properties_->UpdateClipPathClip(*context_.current.clip,
                                                   std::move(state)));
    }
  }

  if (properties_->ClipPathClip() && !spv1_compositing_specific_pass) {
    context_.current.clip = context_.absolute_position.clip =
        context_.fixed_position.clip = properties_->ClipPathClip();
  }
}

// Returns true if we are printing which was initiated by the frame. We should
// ignore clipping and scroll transform on contents. WebLocalFrameImpl will
// issue artificial page clip for each page, and always print from the origin
// of the contents for which no scroll offset should be applied.
static bool IsPrintingRootLayoutView(const LayoutObject& object) {
  if (!object.IsLayoutView())
    return false;

  const auto& frame = *object.GetFrame();
  if (!frame.GetDocument()->Printing())
    return false;

  const auto* parent_frame = frame.Tree().Parent();
  if (!parent_frame)
    return true;
  // TODO(crbug.com/455764): The local frame may be not the root frame of
  // printing when it's printing under a remote frame.
  if (!parent_frame->IsLocalFrame())
    return true;

  // If the parent frame is printing, this frame should clip normally.
  return !ToLocalFrame(parent_frame)->GetDocument()->Printing();
}

// TODO(wangxianzhu): Combine the logic by overriding LayoutBox::
// ComputeShouldClipOverflow() in LayoutReplaced and subclasses and remove
// this function.
static bool NeedsOverflowClipForReplacedContents(
    const LayoutReplaced& replaced) {
  // <svg> may optionally allow overflow. If an overflow clip is required,
  // always create it without checking whether the actual content overflows.
  if (replaced.IsSVGRoot())
    return ToLayoutSVGRoot(replaced).ShouldApplyViewportClip();

  // A replaced element with border-radius always clips the content.
  if (replaced.StyleRef().HasBorderRadius())
    return true;

  // ImagePainter (but not painters for LayoutMedia whose IsImage is also true)
  // won't paint outside of the content box.
  if (replaced.IsImage() && !replaced.IsMedia())
    return false;

  // Non-plugin embedded contents are always sized to fit the content box.
  if (replaced.IsLayoutEmbeddedContent() && !replaced.IsEmbeddedObject())
    return false;

  return true;
}

static bool NeedsOverflowClip(const LayoutObject& object) {
  if (object.IsLayoutReplaced())
    return NeedsOverflowClipForReplacedContents(ToLayoutReplaced(object));

  if (object.IsSVGViewportContainer() &&
      SVGLayoutSupport::IsOverflowHidden(object))
    return true;

  return object.IsBox() && ToLayoutBox(object).ShouldClipOverflow() &&
         !IsPrintingRootLayoutView(object);
}

void FragmentPaintPropertyTreeBuilder::UpdateLocalBorderBoxContext() {
  if (!NeedsPaintPropertyUpdate())
    return;

  if (object_.HasLayer() || properties_) {
    PropertyTreeState local_border_box =
        PropertyTreeState(context_.current.transform, context_.current.clip,
                          context_.current_effect);

    if (!fragment_data_.HasLocalBorderBoxProperties() ||
        local_border_box != fragment_data_.LocalBorderBoxProperties())
      property_added_or_removed_ = true;

    fragment_data_.SetLocalBorderBoxProperties(std::move(local_border_box));
  } else {
    fragment_data_.ClearLocalBorderBoxProperties();
  }
}

bool FragmentPaintPropertyTreeBuilder::NeedsOverflowControlsClip() const {
  if (!object_.HasOverflowClip())
    return false;

  const auto& box = ToLayoutBox(object_);
  const auto* scrollable_area = box.GetScrollableArea();
  IntRect scroll_controls_bounds =
      scrollable_area->ScrollCornerAndResizerRect();
  if (const auto* scrollbar = scrollable_area->HorizontalScrollbar())
    scroll_controls_bounds.Unite(scrollbar->FrameRect());
  if (const auto* scrollbar = scrollable_area->VerticalScrollbar())
    scroll_controls_bounds.Unite(scrollbar->FrameRect());
  auto pixel_snapped_border_box_rect = box.PixelSnappedBorderBoxRect(
      ToLayoutSize(context_.current.paint_offset));
  pixel_snapped_border_box_rect.SetLocation(IntPoint());
  return !pixel_snapped_border_box_rect.Contains(scroll_controls_bounds);
}

static bool NeedsInnerBorderRadiusClip(const LayoutObject& object) {
  // Replaced elements don't have scrollbars thus needs no separate clip
  // for the padding box (InnerBorderRadiusClip) and the client box (padding
  // box minus scrollbar, OverflowClip).
  // Furthermore, replaced elements clip to the content box instead,
  if (object.IsLayoutReplaced())
    return false;

  return object.StyleRef().HasBorderRadius() && object.IsBox() &&
         NeedsOverflowClip(object);
}

static LayoutPoint VisualOffsetFromPaintOffsetRoot(
    const PaintPropertyTreeBuilderFragmentContext& context,
    const PaintLayer* child) {
  const LayoutObject* paint_offset_root = context.current.paint_offset_root;
  PaintLayer* painting_layer = paint_offset_root->PaintingLayer();
  LayoutPoint result = child->VisualOffsetFromAncestor(painting_layer);
  if (!paint_offset_root->HasLayer() ||
      ToLayoutBoxModelObject(paint_offset_root)->Layer() != painting_layer) {
    result.Move(-paint_offset_root->OffsetFromAncestor(
        &painting_layer->GetLayoutObject()));
  }

  // Convert the result into the space of the scrolling contents space.
  if (const auto* properties =
          paint_offset_root->FirstFragment().PaintProperties()) {
    if (const auto* scroll_translation = properties->ScrollTranslation()) {
      DCHECK(scroll_translation->Matrix().IsIdentityOr2DTranslation());
      result += -LayoutSize(scroll_translation->Matrix().To2DTranslation());
    }
  }
  return result;
}

void FragmentPaintPropertyTreeBuilder::UpdateOverflowControlsClip() {
  DCHECK(properties_);

  if (!NeedsPaintPropertyUpdate())
    return;

  if (NeedsOverflowControlsClip()) {
    // Clip overflow controls to the border box rect. Not wrapped with
    // OnUpdateClip() because this clip doesn't affect descendants.
    properties_->UpdateOverflowControlsClip(
        *context_.current.clip,
        ClipPaintPropertyNode::State{
            context_.current.transform,
            ToClipRect(LayoutRect(context_.current.paint_offset,
                                  ToLayoutBox(object_).Size()))});
  } else {
    properties_->ClearOverflowControlsClip();
  }

  // No need to set force_subtree_update_reasons and clip_changed because
  // OverflowControlsClip applies to overflow controls only, not descendants.
  // We also don't walk into custom scrollbars in PrePaintTreeWalk and
  // LayoutObjects under custom scrollbars don't support paint properties.
}

void FragmentPaintPropertyTreeBuilder::UpdateInnerBorderRadiusClip() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsInnerBorderRadiusClip(object_)) {
      const LayoutBox& box = ToLayoutBox(object_);
      ClipPaintPropertyNode::State state;
      state.local_transform_space = context_.current.transform;
      state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor(
          LayoutRect(context_.current.paint_offset, box.Size()));
      OnUpdateClip(properties_->UpdateInnerBorderRadiusClip(
          *context_.current.clip, std::move(state)));
    } else {
      OnClearClip(properties_->ClearInnerBorderRadiusClip());
    }
  }

  if (auto* border_radius_clip = properties_->InnerBorderRadiusClip())
    context_.current.clip = border_radius_clip;
}

static bool CanOmitOverflowClip(const LayoutObject& object) {
  DCHECK(NeedsOverflowClip(object));
  // Some non-block boxes and SVG objects have special overflow rules.
  if (!object.IsLayoutBlock() || object.IsSVG())
    return false;

  const auto& block = ToLayoutBlock(object);
  // Selection may overflow.
  if (block.IsSelected())
    return false;
  // Other cases that the contents may overflow. The conditions are copied from
  // BlockPainter for SPv1 clip. TODO(wangxianzhu): clean up.
  if (block.HasControlClip() || block.ShouldPaintCarets())
    return false;

  // We need OverflowClip for hit-testing if the clip rect excluding overlay
  // scrollbars is different from the normal clip rect.
  auto clip_rect = block.OverflowClipRect(LayoutPoint());
  auto clip_rect_excluding_overlay_scrollbars = block.OverflowClipRect(
      LayoutPoint(), kExcludeOverlayScrollbarSizeForHitTesting);
  if (clip_rect != clip_rect_excluding_overlay_scrollbars)
    return false;

  // Visual overflow extending beyond the clip rect must be clipped.
  // ContentsVisualOverflowRect() does not include self-painting descendants
  // (see comment above |BoxOverflowModel|) so, as a simplification, do not
  // omit the clip if there are any PaintLayer descendants.
  if (block.HasLayer() && block.Layer()->FirstChild())
    return false;
  if (!clip_rect.Contains(block.ContentsVisualOverflowRect()))
    return false;

  // Content can scroll, and needs to be clipped, if the layout overflow extends
  // beyond the clip rect.
  return clip_rect.Contains(block.LayoutOverflowRect());
}

void FragmentPaintPropertyTreeBuilder::UpdateOverflowClip() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsOverflowClip(object_) && !CanOmitOverflowClip(object_)) {
      ClipPaintPropertyNode::State state;
      state.local_transform_space = context_.current.transform;

      if (object_.IsLayoutReplaced()) {
        const LayoutReplaced& replaced = ToLayoutReplaced(object_);
        // LayoutReplaced clips the foreground by rounded content box.
        state.clip_rect = replaced.StyleRef().GetRoundedInnerBorderFor(
            LayoutRect(context_.current.paint_offset, replaced.Size()),
            LayoutRectOutsets(
                -(replaced.PaddingTop() + replaced.BorderTop()),
                -(replaced.PaddingRight() + replaced.BorderRight()),
                -(replaced.PaddingBottom() + replaced.BorderBottom()),
                -(replaced.PaddingLeft() + replaced.BorderLeft())));
        if (replaced.IsLayoutEmbeddedContent()) {
          // Embedded objects are always sized to fit the content rect, but
          // they could overflow by 1px due to pre-snapping. Adjust clip rect
          // to match pre-snapped box as a special case.
          FloatRect adjusted_rect = state.clip_rect.Rect();
          adjusted_rect.SetSize(
              FloatSize(replaced.ReplacedContentRect().Size()));
          state.clip_rect.SetRect(adjusted_rect);
        }
      } else if (object_.IsBox()) {
        state.clip_rect = ToClipRect(ToLayoutBox(object_).OverflowClipRect(
            context_.current.paint_offset));
        state.clip_rect_excluding_overlay_scrollbars =
            ToClipRect(ToLayoutBox(object_).OverflowClipRect(
                context_.current.paint_offset,
                kExcludeOverlayScrollbarSizeForHitTesting));
      } else {
        DCHECK(object_.IsSVGViewportContainer());
        const auto& viewport_container = ToLayoutSVGViewportContainer(object_);
        state.clip_rect = FloatRoundedRect(
            viewport_container.LocalToSVGParentTransform().Inverse().MapRect(
                viewport_container.Viewport()));
      }
      const ClipPaintPropertyNode* existing = properties_->OverflowClip();
      bool equal_ignoring_hit_test_rects =
          !!existing &&
          existing->EqualIgnoringHitTestRects(context_.current.clip, state);
      OnUpdateClip(properties_->UpdateOverflowClip(*context_.current.clip,
                                                   std::move(state)),
                   equal_ignoring_hit_test_rects);
    } else {
      OnClearClip(properties_->ClearOverflowClip());
    }
  }

  if (auto* overflow_clip = properties_->OverflowClip())
    context_.current.clip = overflow_clip;
}

static FloatPoint PerspectiveOrigin(const LayoutBox& box) {
  const ComputedStyle& style = box.StyleRef();
  // Perspective origin has no effect without perspective.
  DCHECK(style.HasPerspective());
  FloatSize border_box_size(box.Size());
  return FloatPointForLengthPoint(style.PerspectiveOrigin(), border_box_size);
}

static bool NeedsPerspective(const LayoutObject& object) {
  return object.IsBox() && object.StyleRef().HasPerspective();
}

void FragmentPaintPropertyTreeBuilder::UpdatePerspective() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsPerspective(object_)) {
      const ComputedStyle& style = object_.StyleRef();
      // The perspective node must not flatten (else nothing will get
      // perspective), but it should still extend the rendering context as
      // most transform nodes do.
      TransformPaintPropertyNode::State state;
      state.matrix.ApplyPerspective(style.Perspective());
      state.origin = PerspectiveOrigin(ToLayoutBox(object_)) +
                     ToLayoutSize(context_.current.paint_offset);
      state.flattens_inherited_transform =
          context_.current.should_flatten_inherited_transform;
      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
        state.rendering_context_id = context_.current.rendering_context_id;
      OnUpdate(properties_->UpdatePerspective(*context_.current.transform,
                                              std::move(state)));
    } else {
      OnClear(properties_->ClearPerspective());
    }
  }

  if (properties_->Perspective()) {
    context_.current.transform = properties_->Perspective();
    context_.current.should_flatten_inherited_transform = false;
  }
}

static bool ImageWasTransposed(const LayoutImage& layout_image,
                               const Image& image) {
  return LayoutObject::ShouldRespectImageOrientation(&layout_image) ==
             kRespectImageOrientation &&
         image.IsBitmapImage() &&
         ToBitmapImage(image).CurrentFrameOrientation().UsesWidthAsHeight();
}

static AffineTransform RectToRect(const FloatRect& src_rect,
                                  const FloatRect& dst_rect) {
  float x_scale = dst_rect.Width() / src_rect.Width();
  float y_scale = dst_rect.Height() / src_rect.Height();
  float x_offset = dst_rect.X() - src_rect.X() * x_scale;
  float y_offset = dst_rect.Y() - src_rect.Y() * y_scale;
  return AffineTransform(x_scale, 0.f, 0.f, y_scale, x_offset, y_offset);
}

void FragmentPaintPropertyTreeBuilder::UpdateReplacedContentTransform() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate() && !NeedsReplacedContentTransform(object_)) {
    OnClear(properties_->ClearReplacedContentTransform());
  } else if (NeedsPaintPropertyUpdate()) {
    AffineTransform content_to_parent_space;
    if (object_.IsSVGRoot()) {
      content_to_parent_space =
          SVGRootPainter(ToLayoutSVGRoot(object_))
              .TransformToPixelSnappedBorderBox(context_.current.paint_offset);
    } else if (object_.IsImage()) {
      const LayoutImage& layout_image = ToLayoutImage(object_);
      LayoutRect layout_replaced_rect = layout_image.ReplacedContentRect();
      layout_replaced_rect.MoveBy(context_.current.paint_offset);
      IntRect replaced_rect = PixelSnappedIntRect(layout_replaced_rect);
      scoped_refptr<Image> image =
          layout_image.ImageResource()->GetImage(replaced_rect.Size());
      if (image && !image->IsNull()) {
        IntRect src_rect = image->Rect();
        if (ImageWasTransposed(layout_image, *image))
          src_rect = src_rect.TransposedRect();
        content_to_parent_space =
            RectToRect(FloatRect(src_rect), FloatRect(replaced_rect));
      }
    } else {
      NOTREACHED();
    }
    if (!content_to_parent_space.IsIdentity()) {
      OnUpdate(properties_->UpdateReplacedContentTransform(
          *context_.current.transform,
          TransformPaintPropertyNode::State{content_to_parent_space}));
    } else {
      OnClear(properties_->ClearReplacedContentTransform());
    }
  }

  if (object_.IsSVGRoot()) {
    // SVG painters don't use paint offset. The paint offset is baked into
    // the transform node instead.
    context_.current.paint_offset = LayoutPoint();

    // Only <svg> paints its subtree as replaced contents. Other replaced
    // element type may have shadow DOM that should not be affected by the
    // replaced object fit.
    if (properties_->ReplacedContentTransform()) {
      context_.current.transform = properties_->ReplacedContentTransform();
      context_.current.should_flatten_inherited_transform = false;
      context_.current.rendering_context_id = 0;
    }
  }
}

static MainThreadScrollingReasons GetMainThreadScrollingReasons(
    const LayoutObject& object,
    MainThreadScrollingReasons ancestor_reasons) {
  auto reasons = ancestor_reasons;
  if (!object.IsBox())
    return reasons;

  if (auto* scrollable_area = ToLayoutBox(object).GetScrollableArea()) {
    if (scrollable_area->HorizontalScrollbar() &&
        scrollable_area->HorizontalScrollbar()->IsCustomScrollbar()) {
      reasons |= MainThreadScrollingReason::kCustomScrollbarScrolling;
    } else if (scrollable_area->VerticalScrollbar() &&
               scrollable_area->VerticalScrollbar()->IsCustomScrollbar()) {
      reasons |= MainThreadScrollingReason::kCustomScrollbarScrolling;
    }
  }

  if (object.IsLayoutView()) {
    if (object.GetFrameView()->HasBackgroundAttachmentFixedObjects()) {
      reasons |=
          MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects;
    }

    // TODO(pdr): This should apply to all scrollable areas, not just the
    // viewport. This is not a user-visible bug because the threaded scrolling
    // setting is only for testing.
    if (!object.GetFrame()->GetSettings()->GetThreadedScrollingEnabled())
      reasons |= MainThreadScrollingReason::kThreadedScrollingDisabled;

    // LocalFrameView::HasVisibleSlowRepaintViewportConstrainedObjects depends
    // on compositing (LayoutBoxModelObject::IsSlowRepaintConstrainedObject
    // calls PaintLayer::GetCompositingState, and PaintLayer::SticksToScroller
    // depends on the ancestor overflow layer) so CompositeAfterPaint cannot
    // use LocalFrameView::HasVisibleSlowRepaintViewportConstrainedObjects.
    if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
      // Force main-thread scrolling if the frame has uncomposited position:
      // fixed elements. Note: we care about this not only for input-scrollable
      // frames but also for overflow: hidden frames, because script can run
      // composited smooth-scroll animations. For this reason, we use
      // HasOverflow instead of ScrollsOverflow (which is false for overflow:
      // hidden).
      if (ToLayoutBox(object).GetScrollableArea()->HasOverflow() &&
          object.StyleRef().VisibleToHitTesting() &&
          object.GetFrameView()
              ->HasVisibleSlowRepaintViewportConstrainedObjects()) {
        reasons |=
            MainThreadScrollingReason::kHasNonLayerViewportConstrainedObjects;
      }
    } else {
      // TODO(pdr): CompositeAfterPaint should use an approach like
      // CompositingReasonFinder::RequiresCompositingForScrollDependentPosition,
      // adding main thread reasons if compositing was not required. This has
      // a small behavior change because main thread reasons will be added in
      // the case where a non-scroll compositing trigger (e.g., transform)
      // requires compositing, even though a main thread reason is not needed.
      // CompositingReasonFinder::RequiresCompositingForScrollDependentPosition
      // will need to be changed to not query PaintLayer::AncestorOverflowLayer.
    }
  }
  return reasons;
}

void FragmentPaintPropertyTreeBuilder::UpdateScrollAndScrollTranslation() {
  DCHECK(properties_);

  if (NeedsPaintPropertyUpdate()) {
    if (NeedsScrollNode(object_)) {
      const LayoutBox& box = ToLayoutBox(object_);
      PaintLayerScrollableArea* scrollable_area = box.GetScrollableArea();
      ScrollPaintPropertyNode::State state;

      // The container bounds are snapped to integers to match the equivalent
      // bounds on cc::ScrollNode. The offset is snapped to match the current
      // integer offsets used in CompositedLayerMapping.
      state.container_rect = PixelSnappedIntRect(
          box.OverflowClipRect(context_.current.paint_offset));
      state.contents_size = scrollable_area->PixelSnappedContentsSize(
          context_.current.paint_offset);

      state.user_scrollable_horizontal =
          scrollable_area->UserInputScrollable(kHorizontalScrollbar);
      state.user_scrollable_vertical =
          scrollable_area->UserInputScrollable(kVerticalScrollbar);

      auto ancestor_reasons =
          context_.current.scroll->GetMainThreadScrollingReasons();
      state.main_thread_scrolling_reasons =
          GetMainThreadScrollingReasons(object_, ancestor_reasons);

      // Main thread scrolling reasons depend on their ancestor's reasons
      // so ensure the entire subtree is updated when reasons change.
      if (auto* existing_scroll = properties_->Scroll()) {
        if (existing_scroll->GetMainThreadScrollingReasons() !=
            state.main_thread_scrolling_reasons) {
          // Main thread scrolling reasons cross into isolation.
          full_context_.force_subtree_update_reasons |=
              PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationPiercing;
        }
      }

      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
        state.compositor_element_id = scrollable_area->GetCompositorElementId();

      state.overscroll_behavior = OverscrollBehavior(
          static_cast<OverscrollBehavior::OverscrollBehaviorType>(
              box.StyleRef().OverscrollBehaviorX()),
          static_cast<OverscrollBehavior::OverscrollBehaviorType>(
              box.StyleRef().OverscrollBehaviorY()));

      auto* snap_coordinator = box.GetDocument().GetSnapCoordinator();
      if (snap_coordinator) {
        state.snap_container_data = snap_coordinator->GetSnapContainerData(box);
      }

      OnUpdateScroll(properties_->UpdateScroll(*context_.current.scroll,
                                               std::move(state)));

      if (scrollable_area->VerticalScrollbar() ||
          scrollable_area->HasLayerForVerticalScrollbar()) {
        EffectPaintPropertyNode::State state;
        state.local_transform_space = context_.current.transform;
        state.direct_compositing_reasons =
            CompositingReason::kActiveOpacityAnimation;
        state.compositor_element_id = scrollable_area->GetScrollbarElementId(
            ScrollbarOrientation::kVerticalScrollbar);
        OnUpdate(properties_->UpdateVerticalScrollbarEffect(
            *context_.current_effect, std::move(state)));
      } else {
        OnClear(properties_->ClearVerticalScrollbarEffect());
      }

      if (scrollable_area->HorizontalScrollbar() ||
          scrollable_area->HasLayerForHorizontalScrollbar()) {
        EffectPaintPropertyNode::State state;
        state.local_transform_space = context_.current.transform;
        state.direct_compositing_reasons =
            CompositingReason::kActiveOpacityAnimation;
        state.compositor_element_id = scrollable_area->GetScrollbarElementId(
            ScrollbarOrientation::kHorizontalScrollbar);
        OnUpdate(properties_->UpdateHorizontalScrollbarEffect(
            *context_.current_effect, std::move(state)));
      } else {
        OnClear(properties_->ClearHorizontalScrollbarEffect());
      }
    } else {
      OnClearScroll(properties_->ClearScroll());
      OnClear(properties_->ClearVerticalScrollbarEffect());
      OnClear(properties_->ClearHorizontalScrollbarEffect());
    }

    // A scroll translation node is created for static offset (e.g., overflow
    // hidden with scroll offset) or cases that scroll and have a scroll node.
    if (NeedsScrollOrScrollTranslation(object_)) {
      const auto& box = ToLayoutBox(object_);
      TransformPaintPropertyNode::State state;
      // Bake ScrollOrigin into ScrollTranslation. See comments for
      // ScrollTranslation in object_paint_properties.h for details.
      auto scroll_position = box.ScrollOrigin() + box.ScrolledContentOffset();
      state.matrix.Translate(-scroll_position.X(), -scroll_position.Y());
      state.flattens_inherited_transform =
          context_.current.should_flatten_inherited_transform;
      state.is_identity_or_2d_translation = true;
      state.direct_compositing_reasons = CompositingReasonsForScroll(box);
      if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
          RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
        state.rendering_context_id = context_.current.rendering_context_id;
      }
      state.scroll = properties_->Scroll();
      OnUpdate(properties_->UpdateScrollTranslation(*context_.current.transform,
                                                    std::move(state)));
    } else {
      OnClear(properties_->ClearScrollTranslation());
    }
  }

  if (properties_->Scroll())
    context_.current.scroll = properties_->Scroll();

  if (properties_->ScrollTranslation()) {
    context_.current.transform = properties_->ScrollTranslation();
    // See comments for ScrollTranslation in object_paint_properties.h for the
    // reason of adding ScrollOrigin().
    context_.current.paint_offset += ToLayoutBox(object_).ScrollOrigin();
  }
}

void FragmentPaintPropertyTreeBuilder::UpdateOutOfFlowContext() {
  if (!object_.IsBoxModelObject() && !properties_)
    return;

  if (object_.IsLayoutBlock())
    context_.paint_offset_for_float = context_.current.paint_offset;

  if (object_.CanContainAbsolutePositionObjects())
    context_.absolute_position = context_.current;

  if (object_.IsLayoutView()) {
    const auto* initial_fixed_transform = context_.fixed_position.transform;
    const auto* initial_fixed_scroll = context_.fixed_position.scroll;

    context_.fixed_position = context_.current;
    context_.fixed_position.fixed_position_children_fixed_to_root = true;

    // Fixed position transform and scroll nodes should not be affected.
    context_.fixed_position.transform = initial_fixed_transform;
    context_.fixed_position.scroll = initial_fixed_scroll;
    if (properties_->ScrollTranslation()) {
      // Also undo the ScrollOrigin part in paint offset that was added when
      // ScrollTranslation was updated.
      context_.fixed_position.paint_offset -=
          ToLayoutBox(object_).ScrollOrigin();
    }
  } else if (object_.CanContainFixedPositionObjects()) {
    context_.fixed_position = context_.current;
    context_.fixed_position.fixed_position_children_fixed_to_root = false;
  } else if (properties_ && properties_->CssClip()) {
    // CSS clip applies to all descendants, even if this object is not a
    // containing block ancestor of the descendant. It is okay for
    // absolute-position descendants because having CSS clip implies being
    // absolute position container. However for fixed-position descendants we
    // need to insert the clip here if we are not a containing block ancestor of
    // them.
    auto* css_clip = properties_->CssClip();

    // Before we actually create anything, check whether in-flow context and
    // fixed-position context has exactly the same clip. Reuse if possible.
    if (context_.fixed_position.clip == css_clip->Parent()) {
      context_.fixed_position.clip = css_clip;
    } else {
      if (NeedsPaintPropertyUpdate()) {
        OnUpdate(properties_->UpdateCssClipFixedPosition(
            *context_.fixed_position.clip,
            ClipPaintPropertyNode::State{css_clip->LocalTransformSpace(),
                                         css_clip->ClipRect()}));
      }
      if (properties_->CssClipFixedPosition())
        context_.fixed_position.clip = properties_->CssClipFixedPosition();
      return;
    }
  }

  if (NeedsPaintPropertyUpdate() && properties_)
    OnClear(properties_->ClearCssClipFixedPosition());
}

void FragmentPaintPropertyTreeBuilder::UpdateTransformIsolationNode() {
  if (NeedsPaintPropertyUpdate()) {
    if (NeedsIsolationNodes(object_)) {
      OnUpdate(properties_->UpdateTransformIsolationNode(
          *context_.current.transform, TransformPaintPropertyNode::State{},
          true /* is_parent_alias */));
    } else {
      OnClear(properties_->ClearTransformIsolationNode());
    }
  }
  if (properties_->TransformIsolationNode())
    context_.current.transform = properties_->TransformIsolationNode();
}

void FragmentPaintPropertyTreeBuilder::UpdateEffectIsolationNode() {
  if (NeedsPaintPropertyUpdate()) {
    if (NeedsIsolationNodes(object_)) {
      OnUpdate(properties_->UpdateEffectIsolationNode(
          *context_.current_effect, EffectPaintPropertyNode::State{},
          true /* is_parent_alias */));
    } else {
      OnClear(properties_->ClearEffectIsolationNode());
    }
  }
  if (properties_->EffectIsolationNode())
    context_.current_effect = properties_->EffectIsolationNode();
}

void FragmentPaintPropertyTreeBuilder::UpdateClipIsolationNode() {
  if (NeedsPaintPropertyUpdate()) {
    if (NeedsIsolationNodes(object_)) {
      OnUpdate(properties_->UpdateClipIsolationNode(
          *context_.current.clip, ClipPaintPropertyNode::State{},
          true /* is_parent_alias */));
    } else {
      OnClear(properties_->ClearClipIsolationNode());
    }
  }
  if (properties_->ClipIsolationNode())
    context_.current.clip = properties_->ClipIsolationNode();
}

static LayoutRect MapLocalRectToAncestorLayer(
    const LayoutBox& box,
    const LayoutRect& local_rect,
    const PaintLayer& ancestor_layer) {
  TransformState transform_state(TransformState::kApplyTransformDirection,
                                 FloatPoint(local_rect.Location()));
  box.MapLocalToAncestor(&ancestor_layer.GetLayoutObject(), transform_state,
                         kApplyContainerFlip);
  transform_state.Flatten();
  return LayoutRect(LayoutPoint(transform_state.LastPlanarPoint()),
                    local_rect.Size());
}

static bool IsRepeatingTableSection(const LayoutObject& object) {
  if (!object.IsTableSection())
    return false;
  const auto& section = ToLayoutTableSection(object);
  return section.IsRepeatingHeaderGroup() || section.IsRepeatingFooterGroup();
}

static LayoutRect BoundingBoxInPaginationContainer(
    const LayoutObject& object,
    const PaintLayer& enclosing_pagination_layer) {
  // The special path for fragmented layers ensures that the bounding box also
  // covers contents visual overflow, so that the fragments will cover all
  // fragments of contents except for self-painting layers, because we initiate
  // fragment painting of contents from the layer.
  if (object.HasLayer() &&
      ToLayoutBoxModelObject(object)
          .Layer()
          ->ShouldFragmentCompositedBounds() &&
      // Table section may repeat, and doesn't need the special layer path
      // because it doesn't have contents visual overflow.
      !object.IsTableSection()) {
    return ToLayoutBoxModelObject(object).Layer()->PhysicalBoundingBox(
        &enclosing_pagination_layer);
  }

  LayoutRect local_bounds;
  const LayoutBox* local_space_object = nullptr;
  if (object.IsBox()) {
    local_space_object = ToLayoutBox(&object);
    local_bounds = local_space_object->BorderBoxRect();
  } else {
    // Non-boxes paint in the space of their containing block.
    local_space_object = object.ContainingBlock();
    // For non-SVG we can get a more accurate result with LocalVisualRect,
    // instead of falling back to the bounds of the enclosing block.
    if (!object.IsSVG()) {
      local_bounds = object.LocalVisualRect();
      local_space_object->FlipForWritingMode(local_bounds);
    } else {
      local_bounds = LayoutRect(SVGLayoutSupport::LocalVisualRect(object));
    }
  }

  // The link highlight covers block visual overflows, continuations, etc. which
  // may intersect with more fragments than the object itself.
  if (NeedsLinkHighlightEffect(object)) {
    local_bounds.Unite(UnionRect(object.PhysicalOutlineRects(
        LayoutPoint(), NGOutlineType::kIncludeBlockVisualOverflow)));
  }

  // Compute the bounding box without transforms.
  auto bounding_box = MapLocalRectToAncestorLayer(
      *local_space_object, local_bounds, enclosing_pagination_layer);

  if (!IsRepeatingTableSection(object))
    return bounding_box;

  const auto& section = ToLayoutTableSection(object);
  const auto& table = *section.Table();

  if (section.IsRepeatingHeaderGroup()) {
    // Now bounding_box covers the original header. Expand it to intersect
    // with all fragments containing the original and repeatings, i.e. to
    // intersect any fragment containing any row.
    if (const auto* bottom_section = table.BottomNonEmptySection()) {
      bounding_box.Unite(MapLocalRectToAncestorLayer(
          *bottom_section, bottom_section->BorderBoxRect(),
          enclosing_pagination_layer));
    }
    return bounding_box;
  }

  DCHECK(section.IsRepeatingFooterGroup());
  // Similar to repeating header, expand bounding_box to intersect any
  // fragment containing any row first.
  if (const auto* top_section = table.TopNonEmptySection()) {
    bounding_box.Unite(MapLocalRectToAncestorLayer(*top_section,
                                                   top_section->BorderBoxRect(),
                                                   enclosing_pagination_layer));
    // However, the first fragment intersecting the expanded bounding_box may
    // not have enough space to contain the repeating footer. Exclude the
    // total height of the first row and repeating footers from the top of
    // bounding_box to exclude the first fragment without enough space.
    auto top_exclusion = table.RowOffsetFromRepeatingFooter();
    if (top_section != section) {
      top_exclusion +=
          top_section->FirstRow()->LogicalHeight() + table.VBorderSpacing();
    }
    // Subtract 1 to ensure overlap of 1 px for a fragment that has exactly
    // one row plus space for the footer.
    if (top_exclusion)
      top_exclusion -= 1;
    bounding_box.ShiftYEdgeTo(bounding_box.Y() + top_exclusion);
  }
  return bounding_box;
}

static LayoutPoint PaintOffsetInPaginationContainer(
    const LayoutObject& object,
    const PaintLayer& enclosing_pagination_layer) {
  // Non-boxes use their containing blocks' paint offset.
  if (!object.IsBox() && !object.HasLayer()) {
    return PaintOffsetInPaginationContainer(*object.ContainingBlock(),
                                            enclosing_pagination_layer);
  }

  TransformState transform_state(TransformState::kApplyTransformDirection,
                                 FloatPoint());
  object.MapLocalToAncestor(&enclosing_pagination_layer.GetLayoutObject(),
                            transform_state, kApplyContainerFlip);
  transform_state.Flatten();
  return LayoutPoint(transform_state.LastPlanarPoint());
}

void FragmentPaintPropertyTreeBuilder::UpdatePaintOffset() {
  // Paint offsets for fragmented content are computed from scratch.
  const auto* enclosing_pagination_layer =
      full_context_.painting_layer->EnclosingPaginationLayer();
  if (enclosing_pagination_layer &&
      // Except if the paint_offset_root is below the pagination container,
      // in which case fragmentation offsets are already baked into the paint
      // offset transform for paint_offset_root.
      !context_.current.paint_offset_root->PaintingLayer()
           ->EnclosingPaginationLayer()) {
    // Set fragment visual paint offset.
    LayoutPoint paint_offset =
        PaintOffsetInPaginationContainer(object_, *enclosing_pagination_layer);

    paint_offset.MoveBy(fragment_data_.PaginationOffset());
    paint_offset.Move(context_.repeating_paint_offset_adjustment);
    paint_offset.MoveBy(
        VisualOffsetFromPaintOffsetRoot(context_, enclosing_pagination_layer));

    // The paint offset root can have a subpixel paint offset adjustment.
    // The paint offset root always has one fragment.
    const auto& paint_offset_root_fragment =
        context_.current.paint_offset_root->FirstFragment();
    paint_offset.MoveBy(paint_offset_root_fragment.PaintOffset());

    context_.current.paint_offset = paint_offset;
    return;
  }

  if (object_.IsFloating() && !object_.IsInLayoutNGInlineFormattingContext())
    context_.current.paint_offset = context_.paint_offset_for_float;

  // Multicolumn spanners are painted starting at the multicolumn container (but
  // still inherit properties in layout-tree order) so reset the paint offset.
  if (object_.IsColumnSpanAll()) {
    context_.current.paint_offset =
        object_.Container()->FirstFragment().PaintOffset();
  }

  if (object_.IsBoxModelObject()) {
    const LayoutBoxModelObject& box_model_object =
        ToLayoutBoxModelObject(object_);
    switch (box_model_object.StyleRef().GetPosition()) {
      case EPosition::kStatic:
        break;
      case EPosition::kRelative:
        context_.current.paint_offset +=
            box_model_object.OffsetForInFlowPosition();
        break;
      case EPosition::kAbsolute: {
        DCHECK(full_context_.container_for_absolute_position ==
               box_model_object.Container());
        context_.current = context_.absolute_position;

        // Absolutely positioned content in an inline should be positioned
        // relative to the inline.
        const auto* container = full_context_.container_for_absolute_position;
        if (container && container->IsLayoutInline()) {
          DCHECK(container->CanContainAbsolutePositionObjects());
          DCHECK(box_model_object.IsBox());
          context_.current.paint_offset +=
              ToLayoutInline(container)->OffsetForInFlowPositionedInline(
                  ToLayoutBox(box_model_object));
        }
        break;
      }
      case EPosition::kSticky:
        break;
      case EPosition::kFixed: {
        DCHECK(full_context_.container_for_fixed_position ==
               box_model_object.Container());
        context_.current = context_.fixed_position;
        // Fixed-position elements that are fixed to the vieport have a
        // transform above the scroll of the LayoutView. Child content is
        // relative to that transform, and hence the fixed-position element.
        if (context_.fixed_position.fixed_position_children_fixed_to_root)
          context_.current.paint_offset_root = &box_model_object;

        const auto* container = full_context_.container_for_fixed_position;
        if (container && container->IsLayoutInline()) {
          DCHECK(container->CanContainFixedPositionObjects());
          DCHECK(box_model_object.IsBox());
          context_.current.paint_offset +=
              ToLayoutInline(container)->OffsetForInFlowPositionedInline(
                  ToLayoutBox(box_model_object));
        }
        break;
      }
      default:
        NOTREACHED();
    }
  }

  if (object_.IsBox()) {
    // TODO(pdr): Several calls in this function walk back up the tree to
    // calculate containers (e.g., physicalLocation, offsetForInFlowPosition*).
    // The containing block and other containers can be stored on
    // PaintPropertyTreeBuilderFragmentContext instead of recomputing them.
    context_.current.paint_offset.MoveBy(
        ToLayoutBox(object_).PhysicalLocation());

    // This is a weird quirk that table cells paint as children of table rows,
    // but their location have the row's location baked-in.
    // Similar adjustment is done in LayoutTableCell::offsetFromContainer().
    if (object_.IsTableCell()) {
      LayoutObject* parent_row = object_.Parent();
      DCHECK(parent_row && parent_row->IsTableRow());
      context_.current.paint_offset.MoveBy(
          -ToLayoutBox(parent_row)->PhysicalLocation());
    }
  }

  context_.current.paint_offset.Move(
      context_.repeating_paint_offset_adjustment);
}

void FragmentPaintPropertyTreeBuilder::SetNeedsPaintPropertyUpdateIfNeeded() {
  if (!object_.IsBox())
    return;

  const LayoutBox& box = ToLayoutBox(object_);

  if (NeedsOverflowClip(box)) {
    bool had_overflow_clip = properties_ && properties_->OverflowClip();
    if (had_overflow_clip == CanOmitOverflowClip(box))
      box.GetMutableForPainting().SetNeedsPaintPropertyUpdate();
  }

  if (box.IsLayoutReplaced() &&
      box.PreviousPhysicalContentBoxRect() != box.PhysicalContentBoxRect())
    box.GetMutableForPainting().SetNeedsPaintPropertyUpdate();

  if (box.Size() == box.PreviousSize())
    return;

  // CSS mask and clip-path comes with an implicit clip to the border box.
  // Currently only CAP generate and take advantage of those.
  const bool box_generates_property_nodes_for_mask_and_clip_path =
      box.HasMask() || box.HasClipPath();
  // The overflow clip paint property depends on the border box rect through
  // overflowClipRect(). The border box rect's size equals the frame rect's
  // size so we trigger a paint property update when the frame rect changes.
  if (NeedsOverflowClip(box) || NeedsInnerBorderRadiusClip(box) ||
      // The used value of CSS clip may depend on size of the box, e.g. for
      // clip: rect(auto auto auto -5px).
      NeedsCssClip(box) ||
      // Relative lengths (e.g., percentage values) in transform, perspective,
      // transform-origin, and perspective-origin can depend on the size of the
      // frame rect, so force a property update if it changes. TODO(pdr): We
      // only need to update properties if there are relative lengths.
      box.StyleRef().HasTransform() || NeedsPerspective(box) ||
      box_generates_property_nodes_for_mask_and_clip_path) {
    box.GetMutableForPainting().SetNeedsPaintPropertyUpdate();
  }

  if (box.HasClipPath())
    box.GetMutableForPainting().InvalidateClipPathCache();

  // The filter generated for reflection depends on box size.
  if (box.HasReflection()) {
    DCHECK(box.HasLayer());
    box.Layer()->SetFilterOnEffectNodeDirty();
    box.GetMutableForPainting().SetNeedsPaintPropertyUpdate();
  }
}

void FragmentPaintPropertyTreeBuilder::UpdateForObjectLocationAndSize(
    base::Optional<IntPoint>& paint_offset_translation) {
  context_.old_paint_offset = fragment_data_.PaintOffset();
  UpdatePaintOffset();
  UpdateForPaintOffsetTranslation(paint_offset_translation);

  if (fragment_data_.PaintOffset() != context_.current.paint_offset) {
    // Many paint properties depend on paint offset so we force an update of
    // the entire subtree on paint offset changes.
    // However, they are blocked by isolation.
    full_context_.force_subtree_update_reasons |=
        PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationBlocked;

    object_.GetMutableForPainting().SetShouldCheckForPaintInvalidation();
    fragment_data_.SetPaintOffset(context_.current.paint_offset);
    fragment_data_.InvalidateClipPathCache();

    object_.GetFrameView()->SetIntersectionObservationState(
        LocalFrameView::kDesired);
  }

  if (paint_offset_translation)
    context_.current.paint_offset_root = &ToLayoutBoxModelObject(object_);
}

void FragmentPaintPropertyTreeBuilder::UpdateClipPathCache() {
  if (fragment_data_.IsClipPathCacheValid())
    return;

  if (!object_.StyleRef().ClipPath())
    return;

  base::Optional<FloatRect> bounding_box =
      ClipPathClipper::LocalClipPathBoundingBox(object_);
  if (!bounding_box) {
    fragment_data_.SetClipPathCache(base::nullopt, nullptr);
    return;
  }
  bounding_box->MoveBy(FloatPoint(fragment_data_.PaintOffset()));

  bool is_valid = false;
  base::Optional<Path> path = ClipPathClipper::PathBasedClip(
      object_, object_.IsSVGChild(),
      ClipPathClipper::LocalReferenceBox(object_), is_valid);
  DCHECK(is_valid);
  if (path)
    path->Translate(ToFloatSize(FloatPoint(fragment_data_.PaintOffset())));
  fragment_data_.SetClipPathCache(
      EnclosingIntRect(*bounding_box),
      path ? AdoptRef(new RefCountedPath(std::move(*path))) : nullptr);
}

void FragmentPaintPropertyTreeBuilder::UpdateForSelf() {
#if DCHECK_IS_ON()
  FindPaintOffsetNeedingUpdateScope check_paint_offset(
      object_, fragment_data_, full_context_.is_actually_needed);
#endif

  // This is not in FindObjectPropertiesNeedingUpdateScope because paint offset
  // can change without NeedsPaintPropertyUpdate.
  base::Optional<IntPoint> paint_offset_translation;
  UpdateForObjectLocationAndSize(paint_offset_translation);
  if (&fragment_data_ == &object_.FirstFragment())
    SetNeedsPaintPropertyUpdateIfNeeded();
  UpdateClipPathCache();

  if (properties_) {
    {
#if DCHECK_IS_ON()
      FindPropertiesNeedingUpdateScope check_fragment_clip(
          object_, fragment_data_, full_context_.force_subtree_update_reasons);
#endif
      UpdateFragmentClip();
    }
    // Update of PaintOffsetTranslation is checked by
    // FindPaintOffsetNeedingUpdateScope.
    UpdatePaintOffsetTranslation(paint_offset_translation);
  }

#if DCHECK_IS_ON()
  FindPropertiesNeedingUpdateScope check_paint_properties(
      object_, fragment_data_, full_context_.force_subtree_update_reasons);
#endif

  if (properties_) {
    UpdateStickyTranslation();
    UpdateTransform();
    UpdateClipPathClip(false);
    UpdateEffect();
    UpdateLinkHighlightEffect();
    UpdateClipPathClip(true);  // Special pass for SPv1 composited clip-path.
    UpdateCssClip();
    UpdateFilter();
    UpdateOverflowControlsClip();
  }
  UpdateLocalBorderBoxContext();
}

void FragmentPaintPropertyTreeBuilder::UpdateForChildren() {
#if DCHECK_IS_ON()
  // Paint offset should not change during this function.
  const bool needs_paint_offset_update = false;
  FindPaintOffsetNeedingUpdateScope check_paint_offset(
      object_, fragment_data_, needs_paint_offset_update);

  FindPropertiesNeedingUpdateScope check_paint_properties(
      object_, fragment_data_, full_context_.force_subtree_update_reasons);
#endif

  if (properties_) {
    UpdateInnerBorderRadiusClip();
    UpdateOverflowClip();
    UpdatePerspective();
    UpdateReplacedContentTransform();
    UpdateScrollAndScrollTranslation();
    UpdateTransformIsolationNode();
    UpdateEffectIsolationNode();
    UpdateClipIsolationNode();
  }
  UpdateOutOfFlowContext();

#if DCHECK_IS_ON()
  if (properties_)
    properties_->Validate();
#endif
}

}  // namespace

void PaintPropertyTreeBuilder::InitFragmentPaintProperties(
    FragmentData& fragment,
    bool needs_paint_properties,
    const LayoutPoint& pagination_offset,
    LayoutUnit logical_top_in_flow_thread) {
  if (needs_paint_properties) {
    fragment.EnsurePaintProperties();
  } else if (fragment.PaintProperties()) {
    // Tree topology changes are blocked by isolation.
    context_.force_subtree_update_reasons |=
        PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationBlocked;
    fragment.ClearPaintProperties();
  }
  fragment.SetPaginationOffset(pagination_offset);
  fragment.SetLogicalTopInFlowThread(logical_top_in_flow_thread);
}

void PaintPropertyTreeBuilder::InitSingleFragmentFromParent(
    bool needs_paint_properties) {
  FragmentData& first_fragment =
      object_.GetMutableForPainting().FirstFragment();
  first_fragment.ClearNextFragment();
  InitFragmentPaintProperties(first_fragment, needs_paint_properties);
  if (context_.fragments.IsEmpty()) {
    context_.fragments.push_back(PaintPropertyTreeBuilderFragmentContext());
  } else {
    context_.fragments.resize(1);
    context_.fragments[0].fragment_clip.reset();
    context_.fragments[0].logical_top_in_flow_thread = LayoutUnit();
  }

  // Column-span:all skips pagination container in the tree hierarchy, so it
  // should also skip any fragment clip created by the skipped pagination
  // container. We also need to skip fragment clip if the object is a paint
  // invalidation container which doesn't allow fragmentation.
  // TODO(crbug.com/803649): This may also skip necessary clips under the
  // skipped fragment clip.
  if (object_.IsColumnSpanAll() ||
      (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled() &&
       object_.IsPaintInvalidationContainer() &&
       ToLayoutBoxModelObject(object_).Layer()->EnclosingPaginationLayer())) {
    if (const auto* pagination_layer_in_tree_hierarchy =
            object_.Parent()->EnclosingLayer()->EnclosingPaginationLayer()) {
      const auto& clip_container =
          pagination_layer_in_tree_hierarchy->GetLayoutObject();
      const auto* properties = clip_container.FirstFragment().PaintProperties();
      if (properties && properties->FragmentClip()) {
        // However, because we don't allow an object's clip to escape the
        // output clip of the object's effect, we can't skip fragment clip if
        // between this object and the container there is any effect that has
        // an output clip. TODO(crbug.com/803649): Fix this workaround.
        const auto* clip_container_effect =
            clip_container.FirstFragment().PostIsolationEffect();
        for (const auto* effect = context_.fragments[0].current_effect;
             effect != clip_container_effect; effect = effect->Parent()) {
          if (effect->OutputClip())
            return;
        }
        context_.fragments[0].current.clip =
            properties->FragmentClip()->Parent();
      }
    }
  }
}

void PaintPropertyTreeBuilder::UpdateCompositedLayerPaginationOffset() {
  if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
    return;

  const auto* enclosing_pagination_layer =
      context_.painting_layer->EnclosingPaginationLayer();
  if (!enclosing_pagination_layer)
    return;

  // We reach here because context_.painting_layer is in a composited layer
  // under the pagination layer. SPv1* doesn't fragment composited layers,
  // but we still need to set correct pagination offset for correct paint
  // offset calculation.
  DCHECK(!context_.painting_layer->ShouldFragmentCompositedBounds());
  FragmentData& first_fragment =
      object_.GetMutableForPainting().FirstFragment();
  bool is_paint_invalidation_container = object_.IsPaintInvalidationContainer();
  const auto* parent_composited_layer =
      context_.painting_layer->EnclosingLayerWithCompositedLayerMapping(
          is_paint_invalidation_container ? kExcludeSelf : kIncludeSelf);
  if (is_paint_invalidation_container &&
      (!parent_composited_layer ||
       !parent_composited_layer->EnclosingPaginationLayer())) {
    // |object_| establishes the top level composited layer under the
    // pagination layer.
    FragmentainerIterator iterator(
        ToLayoutFlowThread(enclosing_pagination_layer->GetLayoutObject()),
        BoundingBoxInPaginationContainer(object_, *enclosing_pagination_layer));
    if (!iterator.AtEnd()) {
      first_fragment.SetPaginationOffset(
          ToLayoutPoint(iterator.PaginationOffset()));
      first_fragment.SetLogicalTopInFlowThread(
          iterator.FragmentainerLogicalTopInFlowThread());
    }
  } else if (parent_composited_layer) {
    // All objects under the composited layer use the same pagination offset.
    const auto& fragment =
        parent_composited_layer->GetLayoutObject().FirstFragment();
    first_fragment.SetPaginationOffset(fragment.PaginationOffset());
    first_fragment.SetLogicalTopInFlowThread(fragment.LogicalTopInFlowThread());
  }
}

void PaintPropertyTreeBuilder::
    UpdateRepeatingTableSectionPaintOffsetAdjustment() {
  if (!context_.repeating_table_section)
    return;

  if (object_ == context_.repeating_table_section) {
    if (ToLayoutTableSection(object_).IsRepeatingHeaderGroup())
      UpdateRepeatingTableHeaderPaintOffsetAdjustment();
    else if (ToLayoutTableSection(object_).IsRepeatingFooterGroup())
      UpdateRepeatingTableFooterPaintOffsetAdjustment();
  } else if (!context_.painting_layer->EnclosingPaginationLayer()) {
    // When repeating a table section in paged media, paint_offset is inherited
    // by descendants, so we only need to adjust point offset for the table
    // section.
    for (auto& fragment_context : context_.fragments) {
      fragment_context.repeating_paint_offset_adjustment = LayoutSize();
    }
  }

  // Otherwise the object is a descendant of the object which initiated the
  // repeating. It just uses repeating_paint_offset_adjustment in its fragment
  // contexts inherited from the initiating object.
}

// TODO(wangxianzhu): For now this works for horizontal-bt writing mode only.
// Need to support vertical writing modes.
void PaintPropertyTreeBuilder::
    UpdateRepeatingTableHeaderPaintOffsetAdjustment() {
  const auto& section = ToLayoutTableSection(object_);
  DCHECK(section.IsRepeatingHeaderGroup());

  LayoutUnit fragment_height;
  LayoutUnit original_offset_in_flow_thread =
      context_.repeating_table_section_bounding_box.Y();
  LayoutUnit original_offset_in_fragment;
  const LayoutFlowThread* flow_thread = nullptr;
  if (const auto* pagination_layer =
          context_.painting_layer->EnclosingPaginationLayer()) {
    flow_thread = &ToLayoutFlowThread(pagination_layer->GetLayoutObject());
    // TODO(crbug.com/757947): This shouldn't be possible but happens to
    // column-spanners in nested multi-col contexts.
    if (!flow_thread->IsPageLogicalHeightKnown())
      return;

    fragment_height =
        flow_thread->PageLogicalHeightForOffset(original_offset_in_flow_thread);
    original_offset_in_fragment =
        fragment_height - flow_thread->PageRemainingLogicalHeightForOffset(
                              original_offset_in_flow_thread,
                              LayoutBox::kAssociateWithLatterPage);
  } else {
    // The containing LayoutView serves as the virtual pagination container
    // for repeating table section in paged media.
    fragment_height = object_.View()->PageLogicalHeight();
    original_offset_in_fragment =
        IntMod(original_offset_in_flow_thread, fragment_height);
  }

  // This is total height of repeating headers seen by the table - height of
  // this header (which is the lowest repeating header seen by this table.
  auto repeating_offset_in_fragment =
      section.Table()->RowOffsetFromRepeatingHeader() - section.LogicalHeight();

  // For a repeating table header, the original location (which may be in the
  // middle of the fragment) and repeated locations (which should be always,
  // together with repeating headers of outer tables, aligned to the top of
  // the fragments) may be different. Therefore, for fragments other than the
  // first, adjust by |alignment_offset|.
  auto adjustment = repeating_offset_in_fragment - original_offset_in_fragment;

  auto fragment_offset_in_flow_thread =
      original_offset_in_flow_thread - original_offset_in_fragment;
  for (wtf_size_t i = 0; i < context_.fragments.size(); ++i) {
    auto& fragment_context = context_.fragments[i];
    fragment_context.repeating_paint_offset_adjustment = LayoutSize();
    // Adjust paint offsets of repeatings (not including the original).
    if (i)
      fragment_context.repeating_paint_offset_adjustment.SetHeight(adjustment);

    // Calculate the adjustment for the repeating which will appear in the next
    // fragment.
    adjustment += fragment_height;
    // Calculate the offset of the next fragment in flow thread. It's used to
    // get the height of that fragment.
    fragment_offset_in_flow_thread += fragment_height;

    if (flow_thread) {
      fragment_height = flow_thread->PageLogicalHeightForOffset(
          fragment_offset_in_flow_thread);
    }
  }
}

void PaintPropertyTreeBuilder::
    UpdateRepeatingTableFooterPaintOffsetAdjustment() {
  const auto& section = ToLayoutTableSection(object_);
  DCHECK(section.IsRepeatingFooterGroup());

  LayoutUnit fragment_height;
  LayoutUnit original_offset_in_flow_thread =
      context_.repeating_table_section_bounding_box.MaxY() -
      section.LogicalHeight();
  LayoutUnit original_offset_in_fragment;
  const LayoutFlowThread* flow_thread = nullptr;
  if (const auto* pagination_layer =
          context_.painting_layer->EnclosingPaginationLayer()) {
    flow_thread = &ToLayoutFlowThread(pagination_layer->GetLayoutObject());
    // TODO(crbug.com/757947): This shouldn't be possible but happens to
    // column-spanners in nested multi-col contexts.
    if (!flow_thread->IsPageLogicalHeightKnown())
      return;

    fragment_height =
        flow_thread->PageLogicalHeightForOffset(original_offset_in_flow_thread);
    original_offset_in_fragment =
        fragment_height - flow_thread->PageRemainingLogicalHeightForOffset(
                              original_offset_in_flow_thread,
                              LayoutBox::kAssociateWithLatterPage);
  } else {
    // The containing LayoutView serves as the virtual pagination container
    // for repeating table section in paged media.
    fragment_height = object_.View()->PageLogicalHeight();
    original_offset_in_fragment =
        IntMod(original_offset_in_flow_thread, fragment_height);
  }

  const auto& table = *section.Table();
  // TODO(crbug.com/798153): This keeps the existing behavior of repeating
  // footer painting in TableSectionPainter. Should change both places when
  // tweaking border-spacing for repeating footers.
  auto repeating_offset_in_fragment = fragment_height -
                                      table.RowOffsetFromRepeatingFooter() -
                                      table.VBorderSpacing();
  // We should show the whole bottom border instead of half if the table
  // collapses borders.
  if (table.ShouldCollapseBorders())
    repeating_offset_in_fragment -= table.BorderBottom();

  // Similar to repeating header, this is to adjust the repeating footer from
  // its original location to the repeating location.
  auto adjustment = repeating_offset_in_fragment - original_offset_in_fragment;

  auto fragment_offset_in_flow_thread =
      original_offset_in_flow_thread - original_offset_in_fragment;
  for (auto i = context_.fragments.size(); i > 0; --i) {
    auto& fragment_context = context_.fragments[i - 1];
    fragment_context.repeating_paint_offset_adjustment = LayoutSize();
    // Adjust paint offsets of repeatings.
    if (i != context_.fragments.size())
      fragment_context.repeating_paint_offset_adjustment.SetHeight(adjustment);

    // Calculate the adjustment for the repeating which will appear in the
    // previous fragment.
    adjustment -= fragment_height;
    // Calculate the offset of the previous fragment in flow thread. It's used
    // to get the height of that fragment.
    fragment_offset_in_flow_thread -= fragment_height;

    if (flow_thread) {
      fragment_height = flow_thread->PageLogicalHeightForOffset(
          fragment_offset_in_flow_thread);
    }
  }
}

static LayoutUnit FragmentLogicalTopInParentFlowThread(
    const LayoutFlowThread& flow_thread,
    LayoutUnit logical_top_in_current_flow_thread) {
  const auto* parent_pagination_layer =
      flow_thread.Layer()->Parent()->EnclosingPaginationLayer();
  if (!parent_pagination_layer)
    return LayoutUnit();

  const auto* parent_flow_thread =
      &ToLayoutFlowThread(parent_pagination_layer->GetLayoutObject());

  LayoutPoint location(LayoutUnit(), logical_top_in_current_flow_thread);
  // TODO(crbug.com/467477): Should we flip for writing-mode? For now regardless
  // of flipping, fast/multicol/vertical-rl/nested-columns.html fails.
  if (!flow_thread.IsHorizontalWritingMode())
    location = location.TransposedPoint();

  // Convert into parent_flow_thread's coordinates.
  location = LayoutPoint(flow_thread.LocalToAncestorPoint(FloatPoint(location),
                                                          parent_flow_thread));
  if (!parent_flow_thread->IsHorizontalWritingMode())
    location = location.TransposedPoint();

  if (location.X() >= parent_flow_thread->LogicalWidth()) {
    // TODO(crbug.com/803649): We hit this condition for
    // external/wpt/css/css-multicol/multicol-height-block-child-001.xht.
    // The normal path would cause wrong FragmentClip hierarchy.
    // Return -1 to force standalone FragmentClip in the case.
    return LayoutUnit(-1);
  }

  // Return the logical top of the containing fragment in parent_flow_thread.
  return location.Y() +
         parent_flow_thread->PageRemainingLogicalHeightForOffset(
             location.Y(), LayoutBox::kAssociateWithLatterPage) -
         parent_flow_thread->PageLogicalHeightForOffset(location.Y());
}

// Find from parent contexts with matching |logical_top_in_flow_thread|, if any,
// to allow for correct property tree parenting of fragments.
PaintPropertyTreeBuilderFragmentContext
PaintPropertyTreeBuilder::ContextForFragment(
    const base::Optional<LayoutRect>& fragment_clip,
    LayoutUnit logical_top_in_flow_thread) const {
  const auto& parent_fragments = context_.fragments;
  if (parent_fragments.IsEmpty())
    return PaintPropertyTreeBuilderFragmentContext();

  // This will be used in the loop finding matching fragment from ancestor flow
  // threads after no matching from parent_fragments.
  LayoutUnit logical_top_in_containing_flow_thread;

  if (object_.IsLayoutFlowThread()) {
    const auto& flow_thread = ToLayoutFlowThread(object_);
    // If this flow thread is under another flow thread, find the fragment in
    // the parent flow thread containing this fragment. Otherwise, the following
    // code will just match parent_contexts[0].
    logical_top_in_containing_flow_thread =
        FragmentLogicalTopInParentFlowThread(flow_thread,
                                             logical_top_in_flow_thread);
    for (const auto& parent_context : parent_fragments) {
      if (logical_top_in_containing_flow_thread ==
          parent_context.logical_top_in_flow_thread) {
        auto context = parent_context;
        context.fragment_clip = fragment_clip;
        context.logical_top_in_flow_thread = logical_top_in_flow_thread;
        return context;
      }
    }
  } else {
    bool parent_is_under_same_flow_thread;
    auto* pagination_layer =
        context_.painting_layer->EnclosingPaginationLayer();
    if (object_.IsColumnSpanAll()) {
      parent_is_under_same_flow_thread = false;
    } else if (object_.IsOutOfFlowPositioned()) {
      parent_is_under_same_flow_thread =
          (object_.Parent()->PaintingLayer()->EnclosingPaginationLayer() ==
           pagination_layer);
    } else {
      parent_is_under_same_flow_thread = true;
    }

    // Match against parent_fragments if the fragment and parent_fragments are
    // under the same flow thread.
    if (parent_is_under_same_flow_thread) {
      DCHECK(object_.Parent()->PaintingLayer()->EnclosingPaginationLayer() ==
             pagination_layer);
      for (const auto& parent_context : parent_fragments) {
        if (logical_top_in_flow_thread ==
            parent_context.logical_top_in_flow_thread) {
          auto context = parent_context;
          // The context inherits fragment clip from parent so we don't need
          // to issue fragment clip again.
          context.fragment_clip = base::nullopt;
          return context;
        }
      }
    }

    logical_top_in_containing_flow_thread = logical_top_in_flow_thread;
  }

  // Found no matching parent fragment. Use parent_fragments[0] to inherit
  // transforms and effects from ancestors, and adjust the clip state.
  // TODO(crbug.com/803649): parent_fragments[0] is not always correct because
  // some ancestor transform/effect may be missing in the fragment if the
  // ancestor doesn't intersect with the first fragment of the flow thread.
  auto context = parent_fragments[0];
  context.logical_top_in_flow_thread = logical_top_in_flow_thread;
  context.fragment_clip = fragment_clip;

  // We reach here because of the following reasons:
  // 1. the parent doesn't have the corresponding fragment because the fragment
  //    overflows the parent;
  // 2. the fragment and parent_fragments are not under the same flow thread
  //    (e.g. column-span:all or some out-of-flow positioned).
  // For each case, we need to adjust context.current.clip. For now it's the
  // first parent fragment's FragmentClip which is not the correct clip for
  // object_.
  for (const auto* container = object_.Container(); container;
       container = container->Container()) {
    if (!container->FirstFragment().HasLocalBorderBoxProperties())
      continue;

    for (const auto* fragment = &container->FirstFragment(); fragment;
         fragment = fragment->NextFragment()) {
      if (fragment->LogicalTopInFlowThread() ==
          logical_top_in_containing_flow_thread) {
        // Found a matching fragment in an ancestor container. Use the
        // container's content clip as the clip state.
        DCHECK(fragment->PostOverflowClip());
        context.current.clip = fragment->PostOverflowClip();
        return context;
      }
    }

    if (container->IsLayoutFlowThread()) {
      logical_top_in_containing_flow_thread =
          FragmentLogicalTopInParentFlowThread(
              ToLayoutFlowThread(*container),
              logical_top_in_containing_flow_thread);
    }
  }

  // We should always find a matching ancestor fragment in the above loop
  // because logical_top_in_containing_flow_thread will be zero when we traverse
  // across the top-level flow thread and it should match the first fragment of
  // a non-fragmented ancestor container.
  NOTREACHED();
  return context;
}

void PaintPropertyTreeBuilder::CreateFragmentContextsInFlowThread(
    bool needs_paint_properties) {
  // We need at least the fragments for all fragmented objects, which store
  // their local border box properties and paint invalidation data (such
  // as paint offset and visual rect) on each fragment.
  PaintLayer* paint_layer = context_.painting_layer;
  PaintLayer* enclosing_pagination_layer =
      paint_layer->EnclosingPaginationLayer();

  const auto& flow_thread =
      ToLayoutFlowThread(enclosing_pagination_layer->GetLayoutObject());
  LayoutRect object_bounding_box_in_flow_thread;
  if (context_.repeating_table_section) {
    // The object is a descendant of a repeating object. It should use the
    // repeating bounding box to repeat in the same fragments as its
    // repeating ancestor.
    object_bounding_box_in_flow_thread =
        context_.repeating_table_section_bounding_box;
  } else {
    object_bounding_box_in_flow_thread =
        BoundingBoxInPaginationContainer(object_, *enclosing_pagination_layer);
    if (IsRepeatingTableSection(object_)) {
      context_.repeating_table_section = &ToLayoutTableSection(object_);
      context_.repeating_table_section_bounding_box =
          object_bounding_box_in_flow_thread;
    }
  }

  FragmentData* current_fragment_data = nullptr;
  FragmentainerIterator iterator(flow_thread,
                                 object_bounding_box_in_flow_thread);
  bool fragments_changed = false;
  Vector<PaintPropertyTreeBuilderFragmentContext, 1> new_fragment_contexts;
  for (; !iterator.AtEnd(); iterator.Advance()) {
    auto pagination_offset = ToLayoutPoint(iterator.PaginationOffset());
    auto logical_top_in_flow_thread =
        iterator.FragmentainerLogicalTopInFlowThread();
    base::Optional<LayoutRect> fragment_clip;

    if (object_.HasLayer()) {
      // 1. Compute clip in flow thread space.
      fragment_clip = iterator.ClipRectInFlowThread();

      // We skip empty clip fragments, since they can share the same logical top
      // with the subsequent fragments. Since we skip drawing empty fragments
      // anyway, it doesn't affect the paint output, but it allows us to use
      // logical top to uniquely identify fragments in an object.
      if (fragment_clip->IsEmpty())
        continue;

      // 2. Convert #1 to visual coordinates in the space of the flow thread.
      fragment_clip->MoveBy(pagination_offset);
      // 3. Adjust #2 to visual coordinates in the containing "paint offset"
      // space.
      {
        DCHECK(context_.fragments[0].current.paint_offset_root);
        LayoutPoint pagination_visual_offset = VisualOffsetFromPaintOffsetRoot(
            context_.fragments[0], enclosing_pagination_layer);
        // Adjust for paint offset of the root, which may have a subpixel
        // component. The paint offset root never has more than one fragment.
        pagination_visual_offset.MoveBy(
            context_.fragments[0]
                .current.paint_offset_root->FirstFragment()
                .PaintOffset());
        fragment_clip->MoveBy(pagination_visual_offset);
      }
    }

    // Match to parent fragments from the same containing flow thread.
    new_fragment_contexts.push_back(
        ContextForFragment(fragment_clip, logical_top_in_flow_thread));

    if (current_fragment_data) {
      if (!current_fragment_data->NextFragment())
        fragments_changed = true;
      current_fragment_data = &current_fragment_data->EnsureNextFragment();
    } else {
      current_fragment_data = &object_.GetMutableForPainting().FirstFragment();
    }

    fragments_changed |= logical_top_in_flow_thread !=
                         current_fragment_data->LogicalTopInFlowThread();
    if (!fragments_changed) {
      const ClipPaintPropertyNode* old_fragment_clip = nullptr;
      if (const auto* properties = current_fragment_data->PaintProperties())
        old_fragment_clip = properties->FragmentClip();
      const base::Optional<LayoutRect>& new_fragment_clip =
          new_fragment_contexts.back().fragment_clip;
      fragments_changed =
          !!old_fragment_clip != !!new_fragment_clip ||
          (old_fragment_clip && new_fragment_clip &&
           old_fragment_clip->ClipRect() != ToClipRect(*new_fragment_clip));
    }

    InitFragmentPaintProperties(
        *current_fragment_data,
        needs_paint_properties || new_fragment_contexts.back().fragment_clip,
        pagination_offset, logical_top_in_flow_thread);
  }

  if (!current_fragment_data) {
    // This will be an empty fragment - get rid of it?
    InitSingleFragmentFromParent(needs_paint_properties);
  } else {
    if (current_fragment_data->NextFragment())
      fragments_changed = true;
    current_fragment_data->ClearNextFragment();
    context_.fragments = std::move(new_fragment_contexts);
  }

  // Need to update subtree paint properties for the changed fragments.
  if (fragments_changed) {
    object_.GetMutableForPainting().AddSubtreePaintPropertyUpdateReason(
        SubtreePaintPropertyUpdateReason::kFragmentsChanged);
  }
}

bool PaintPropertyTreeBuilder::ObjectIsRepeatingTableSectionInPagedMedia()
    const {
  if (!IsRepeatingTableSection(object_))
    return false;

  // The table section repeats in the pagination layer instead of paged media.
  if (context_.painting_layer->EnclosingPaginationLayer())
    return false;

  if (!object_.View()->PageLogicalHeight())
    return false;

  // TODO(crbug.com/619094): Figure out the correct behavior for repeating
  // objects in paged media with vertical writing modes.
  if (!object_.View()->IsHorizontalWritingMode())
    return false;

  return true;
}

void PaintPropertyTreeBuilder::
    CreateFragmentContextsForRepeatingFixedPosition() {
  DCHECK(object_.IsFixedPositionObjectInPagedMedia());

  LayoutView* view = object_.View();
  auto page_height = view->PageLogicalHeight();
  int page_count = ceilf(view->DocumentRect().Height() / page_height);
  context_.fragments.resize(page_count);

  context_.fragments[0].fixed_position.paint_offset.Move(LayoutUnit(),
                                                         -view->ScrollTop());
  for (int page = 1; page < page_count; page++) {
    context_.fragments[page] = context_.fragments[page - 1];
    context_.fragments[page].fixed_position.paint_offset.Move(LayoutUnit(),
                                                              page_height);
    context_.fragments[page].logical_top_in_flow_thread += page_height;
  }
}

void PaintPropertyTreeBuilder::
    CreateFragmentContextsForRepeatingTableSectionInPagedMedia() {
  DCHECK(ObjectIsRepeatingTableSectionInPagedMedia());

  // The containing LayoutView serves as the virtual pagination container
  // for repeating table section in paged media.
  LayoutView* view = object_.View();
  context_.repeating_table_section_bounding_box =
      BoundingBoxInPaginationContainer(object_, *view->Layer());
  // Convert the bounding box into the scrolling contents space.
  context_.repeating_table_section_bounding_box.Move(LayoutUnit(),
                                                     view->ScrollTop());

  auto page_height = view->PageLogicalHeight();
  const auto& bounding_box = context_.repeating_table_section_bounding_box;
  int first_page = floorf(bounding_box.Y() / page_height);
  int last_page = ceilf(bounding_box.MaxY() / page_height) - 1;
  if (first_page >= last_page)
    return;

  context_.fragments.resize(last_page - first_page + 1);
  for (int page = first_page; page <= last_page; page++) {
    if (page > first_page)
      context_.fragments[page - first_page] = context_.fragments[0];
    context_.fragments[page - first_page].logical_top_in_flow_thread =
        page * page_height;
  }
}

bool PaintPropertyTreeBuilder::IsRepeatingInPagedMedia() const {
  return context_.is_repeating_fixed_position ||
         (context_.repeating_table_section &&
          !context_.painting_layer->EnclosingPaginationLayer());
}

void PaintPropertyTreeBuilder::CreateFragmentDataForRepeatingInPagedMedia(
    bool needs_paint_properties) {
  DCHECK(IsRepeatingInPagedMedia());

  FragmentData* fragment_data = nullptr;
  for (auto& fragment_context : context_.fragments) {
    fragment_data = fragment_data
                        ? &fragment_data->EnsureNextFragment()
                        : &object_.GetMutableForPainting().FirstFragment();
    InitFragmentPaintProperties(*fragment_data, needs_paint_properties,
                                LayoutPoint(),
                                fragment_context.logical_top_in_flow_thread);
  }
  DCHECK(fragment_data);
  fragment_data->ClearNextFragment();
}

bool PaintPropertyTreeBuilder::UpdateFragments() {
  bool had_paint_properties = object_.FirstFragment().PaintProperties();
  // Note: It is important to short-circuit on object_.StyleRef().ClipPath()
  // because NeedsClipPathClip() and NeedsEffect() requires the clip path
  // cache to be resolved, but the clip path cache invalidation must delayed
  // until the paint offset and border box has been computed.
  bool needs_paint_properties =
      object_.StyleRef().ClipPath() || NeedsPaintOffsetTranslation(object_) ||
      NeedsStickyTranslation(object_) || NeedsTransform(object_) ||
      NeedsClipPathClip(object_) || NeedsEffect(object_) ||
      NeedsTransformForNonRootSVG(object_) || NeedsFilter(object_) ||
      NeedsCssClip(object_) || NeedsInnerBorderRadiusClip(object_) ||
      NeedsOverflowClip(object_) || NeedsPerspective(object_) ||
      NeedsReplacedContentTransform(object_) ||
      NeedsLinkHighlightEffect(object_) ||
      NeedsScrollOrScrollTranslation(object_);
  // Need of fragmentation clip will be determined in CreateFragmentContexts().

  if (object_.IsFixedPositionObjectInPagedMedia()) {
    // This flag applies to the object itself and descendants.
    context_.is_repeating_fixed_position = true;
    CreateFragmentContextsForRepeatingFixedPosition();
  } else if (ObjectIsRepeatingTableSectionInPagedMedia()) {
    context_.repeating_table_section = &ToLayoutTableSection(object_);
    CreateFragmentContextsForRepeatingTableSectionInPagedMedia();
  }

  if (IsRepeatingInPagedMedia()) {
    CreateFragmentDataForRepeatingInPagedMedia(needs_paint_properties);
  } else if (context_.painting_layer->ShouldFragmentCompositedBounds()) {
    CreateFragmentContextsInFlowThread(needs_paint_properties);
  } else {
    InitSingleFragmentFromParent(needs_paint_properties);
    UpdateCompositedLayerPaginationOffset();
    context_.is_repeating_fixed_position = false;
    context_.repeating_table_section = nullptr;
  }

  if (object_.IsSVGHiddenContainer()) {
    // SVG resources are painted within one or more other locations in the
    // SVG during paint, and hence have their own independent paint property
    // trees, paint offset, etc.
    context_.fragments.clear();
    context_.fragments.Grow(1);
    context_.has_svg_hidden_container_ancestor = true;
    PaintPropertyTreeBuilderFragmentContext& fragment_context =
        context_.fragments[0];

    fragment_context.current.paint_offset_root =
        fragment_context.absolute_position.paint_offset_root =
            fragment_context.fixed_position.paint_offset_root = &object_;

    object_.GetMutableForPainting().FirstFragment().ClearNextFragment();
  }

  if (object_.HasLayer()) {
    ToLayoutBoxModelObject(object_).Layer()->SetIsUnderSVGHiddenContainer(
        context_.has_svg_hidden_container_ancestor);
  }

  UpdateRepeatingTableSectionPaintOffsetAdjustment();

  return needs_paint_properties != had_paint_properties;
}

bool PaintPropertyTreeBuilder::ObjectTypeMightNeedPaintProperties() const {
  return object_.IsBoxModelObject() || object_.IsSVG() ||
         context_.painting_layer->EnclosingPaginationLayer() ||
         context_.repeating_table_section ||
         context_.is_repeating_fixed_position;
}

void PaintPropertyTreeBuilder::UpdatePaintingLayer() {
  bool changed_painting_layer = false;
  if (object_.HasLayer() &&
      ToLayoutBoxModelObject(object_).HasSelfPaintingLayer()) {
    context_.painting_layer = ToLayoutBoxModelObject(object_).Layer();
    changed_painting_layer = true;
  } else if (object_.IsColumnSpanAll() ||
             object_.IsFloatingWithNonContainingBlockParent()) {
    // See LayoutObject::paintingLayer() for the special-cases of floating under
    // inline and multicolumn.
    context_.painting_layer = object_.PaintingLayer();
    changed_painting_layer = true;
  }
  DCHECK(context_.painting_layer == object_.PaintingLayer());
}

bool PaintPropertyTreeBuilder::UpdateForSelf() {
  UpdatePaintingLayer();

  bool property_added_or_removed = false;
  if (ObjectTypeMightNeedPaintProperties())
    property_added_or_removed = UpdateFragments();
  else
    object_.GetMutableForPainting().FirstFragment().ClearNextFragment();

  bool property_changed = false;
  auto* fragment_data = &object_.GetMutableForPainting().FirstFragment();
  for (auto& fragment_context : context_.fragments) {
    FragmentPaintPropertyTreeBuilder builder(object_, context_,
                                             fragment_context, *fragment_data);
    builder.UpdateForSelf();
    property_changed |= builder.PropertyChanged();
    property_added_or_removed |= builder.PropertyAddedOrRemoved();
    fragment_data = fragment_data->NextFragment();
  }
  DCHECK(!fragment_data);

  // We need to update property tree states of paint chunks.
  if (property_added_or_removed)
    context_.painting_layer->SetNeedsRepaint();

  if (!context_.supports_composited_raster_invalidation)
    return property_changed || property_added_or_removed;

  return property_changed;
}

bool PaintPropertyTreeBuilder::UpdateForChildren() {
  if (!ObjectTypeMightNeedPaintProperties())
    return false;

  bool property_changed = false;
  bool property_added_or_removed = false;
  auto* fragment_data = &object_.GetMutableForPainting().FirstFragment();
  // For now, only consider single fragment elements as possible isolation
  // boundaries.
  // TODO(crbug.com/890932): See if this is needed.
  bool is_isolated = context_.fragments.size() == 1u;
  for (auto& fragment_context : context_.fragments) {
    FragmentPaintPropertyTreeBuilder builder(object_, context_,
                                             fragment_context, *fragment_data);
    // The element establishes an isolation boundary if it has isolation nodes
    // before and after updating the children. In other words, if it didn't have
    // isolation nodes previously then we still want to do a subtree walk. If it
    // now doesn't have isolation nodes, then of course it is also not isolated.
    is_isolated &= builder.HasIsolationNodes();
    builder.UpdateForChildren();
    is_isolated &= builder.HasIsolationNodes();

    property_changed |= builder.PropertyChanged();
    property_added_or_removed |= builder.PropertyAddedOrRemoved();
    fragment_data = fragment_data->NextFragment();
  }
  DCHECK(!fragment_data);
  if (object_.SubtreePaintPropertyUpdateReasons() !=
      static_cast<unsigned>(SubtreePaintPropertyUpdateReason::kNone)) {
    if (AreSubtreeUpdateReasonsIsolationPiercing(
            object_.SubtreePaintPropertyUpdateReasons())) {
      context_.force_subtree_update_reasons |=
          PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationPiercing;
    } else {
      context_.force_subtree_update_reasons |=
          PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationBlocked;
    }
  }
  if (object_.CanContainAbsolutePositionObjects())
    context_.container_for_absolute_position = &object_;
  if (object_.CanContainFixedPositionObjects())
    context_.container_for_fixed_position = &object_;

  if (is_isolated) {
    context_.force_subtree_update_reasons &=
        ~PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationBlocked;
  }

  // We need to update property tree states of paint chunks.
  if (property_added_or_removed)
    context_.painting_layer->SetNeedsRepaint();

  return property_changed;
}

}  // namespace blink