summaryrefslogtreecommitdiffstats
path: root/layout/generic/nsGfxScrollFrame.cpp
blob: 97e6b614dc51c0b4753a89d2a262e2f2b382ffb6 (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
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* rendering object to wrap rendering objects that should be scrollable */

#include "nsGfxScrollFrame.h"

#include "ScrollPositionUpdate.h"
#include "mozilla/layers/LayersTypes.h"
#include "nsIXULRuntime.h"
#include "base/compiler_specific.h"
#include "DisplayItemClip.h"
#include "nsCOMPtr.h"
#include "nsIDocumentViewer.h"
#include "nsPresContext.h"
#include "nsView.h"
#include "nsViewportInfo.h"
#include "nsContainerFrame.h"
#include "nsGkAtoms.h"
#include "nsNameSpaceManager.h"
#include "mozilla/intl/BidiEmbeddingLevel.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/gfx/gfxVars.h"
#include "nsFontMetrics.h"
#include "mozilla/dom/NodeInfo.h"
#include "nsScrollbarFrame.h"
#include "nsINode.h"
#include "nsIScrollbarMediator.h"
#include "nsITextControlFrame.h"
#include "nsILayoutHistoryState.h"
#include "nsNodeInfoManager.h"
#include "nsContentCreatorFunctions.h"
#include "nsStyleTransformMatrix.h"
#include "mozilla/PresState.h"
#include "nsContentUtils.h"
#include "nsDisplayList.h"
#include "nsHTMLDocument.h"
#include "nsLayoutUtils.h"
#include "nsBidiPresUtils.h"
#include "nsBidiUtils.h"
#include "nsDocShell.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/DisplayPortUtils.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/ScrollbarPreferences.h"
#include "mozilla/ScrollingMetrics.h"
#include "mozilla/StaticPrefs_bidi.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_toolkit.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/SVGOuterSVGFrame.h"
#include "mozilla/ViewportUtils.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/HTMLMarqueeElement.h"
#include "mozilla/dom/ScrollTimeline.h"
#include "mozilla/dom/BrowserChild.h"
#include <stdint.h>
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Telemetry.h"
#include "nsSubDocumentFrame.h"
#include "mozilla/Attributes.h"
#include "ScrollbarActivity.h"
#include "nsRefreshDriver.h"
#include "nsStyleConsts.h"
#include "nsIScrollPositionListener.h"
#include "StickyScrollContainer.h"
#include "nsIFrameInlines.h"
#include "gfxPlatform.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_general.h"
#include "mozilla/StaticPrefs_layers.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_mousewheel.h"
#include "mozilla/ToString.h"
#include "ScrollAnimationPhysics.h"
#include "ScrollAnimationBezierPhysics.h"
#include "ScrollAnimationMSDPhysics.h"
#include "ScrollSnap.h"
#include "UnitTransforms.h"
#include "nsSliderFrame.h"
#include "ViewportFrame.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/layers/APZCCallbackHelper.h"
#include "mozilla/layers/APZPublicUtils.h"
#include "mozilla/layers/AxisPhysicsModel.h"
#include "mozilla/layers/AxisPhysicsMSDModel.h"
#include "mozilla/layers/ScrollingInteractionContext.h"
#include "mozilla/layers/ScrollLinkedEffectDetector.h"
#include "mozilla/Unused.h"
#include "MobileViewportManager.h"
#include "VisualViewport.h"
#include "WindowRenderer.h"
#include <algorithm>
#include <cstdlib>  // for std::abs(int/long)
#include <cmath>    // for std::abs(float/double)
#include <tuple>    // for std::tie

static mozilla::LazyLogModule sApzPaintSkipLog("apz.paintskip");
#define PAINT_SKIP_LOG(...) \
  MOZ_LOG(sApzPaintSkipLog, LogLevel::Debug, (__VA_ARGS__))
static mozilla::LazyLogModule sScrollRestoreLog("scrollrestore");
#define SCROLLRESTORE_LOG(...) \
  MOZ_LOG(sScrollRestoreLog, LogLevel::Debug, (__VA_ARGS__))
static mozilla::LazyLogModule sRootScrollbarsLog("rootscrollbars");
#define ROOT_SCROLLBAR_LOG(...)                                  \
  if (mIsRoot) {                                                 \
    MOZ_LOG(sRootScrollbarsLog, LogLevel::Debug, (__VA_ARGS__)); \
  }
static mozilla::LazyLogModule sDisplayportLog("apz.displayport");

using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::layout;
using nsStyleTransformMatrix::TransformReferenceBox;

static ScrollDirections GetOverflowChange(const nsRect& aCurScrolledRect,
                                          const nsRect& aPrevScrolledRect) {
  ScrollDirections result;
  if (aPrevScrolledRect.x != aCurScrolledRect.x ||
      aPrevScrolledRect.width != aCurScrolledRect.width) {
    result += ScrollDirection::eHorizontal;
  }
  if (aPrevScrolledRect.y != aCurScrolledRect.y ||
      aPrevScrolledRect.height != aCurScrolledRect.height) {
    result += ScrollDirection::eVertical;
  }
  return result;
}

/**
 * This class handles the dispatching of scroll events to content.
 *
 * Scroll events are posted to the refresh driver via
 * nsRefreshDriver::PostScrollEvent(), and they are fired during a refresh
 * driver tick, after running requestAnimationFrame callbacks but before
 * the style flush. This allows rAF callbacks to perform scrolling and have
 * that scrolling be reflected on the same refresh driver tick, while at
 * the same time allowing scroll event listeners to make style changes and
 * have those style changes be reflected on the same refresh driver tick.
 *
 * ScrollEvents cannot be refresh observers, because none of the existing
 * categories of refresh observers (FlushType::Style, FlushType::Layout,
 * and FlushType::Display) are run at the desired time in a refresh driver
 * tick. They behave similarly to refresh observers in that their presence
 * causes the refresh driver to tick.
 *
 * ScrollEvents are one-shot runnables; the refresh driver drops them after
 * running them.
 */
class nsHTMLScrollFrame::ScrollEvent : public Runnable {
 public:
  NS_DECL_NSIRUNNABLE
  explicit ScrollEvent(nsHTMLScrollFrame* aHelper, bool aDelayed);
  void Revoke() { mHelper = nullptr; }

 private:
  nsHTMLScrollFrame* mHelper;
};

class nsHTMLScrollFrame::ScrollEndEvent : public Runnable {
 public:
  NS_DECL_NSIRUNNABLE
  explicit ScrollEndEvent(nsHTMLScrollFrame* aHelper, bool aDelayed);
  void Revoke() { mHelper = nullptr; }

 private:
  nsHTMLScrollFrame* mHelper;
};

class nsHTMLScrollFrame::AsyncScrollPortEvent : public Runnable {
 public:
  NS_DECL_NSIRUNNABLE
  explicit AsyncScrollPortEvent(nsHTMLScrollFrame* helper)
      : Runnable("nsHTMLScrollFrame::AsyncScrollPortEvent"), mHelper(helper) {}
  void Revoke() { mHelper = nullptr; }

 private:
  nsHTMLScrollFrame* mHelper;
};

class nsHTMLScrollFrame::ScrolledAreaEvent : public Runnable {
 public:
  NS_DECL_NSIRUNNABLE
  explicit ScrolledAreaEvent(nsHTMLScrollFrame* helper)
      : Runnable("nsHTMLScrollFrame::ScrolledAreaEvent"), mHelper(helper) {}
  void Revoke() { mHelper = nullptr; }

 private:
  nsHTMLScrollFrame* mHelper;
};

//----------------------------------------------------------------------

//----------nsHTMLScrollFrame-------------------------------------------

class ScrollFrameActivityTracker final
    : public nsExpirationTracker<nsHTMLScrollFrame, 4> {
 public:
  // Wait for 3-4s between scrolls before we remove our layers.
  // That's 4 generations of 1s each.
  enum { TIMEOUT_MS = 1000 };
  explicit ScrollFrameActivityTracker(nsIEventTarget* aEventTarget)
      : nsExpirationTracker<nsHTMLScrollFrame, 4>(
            TIMEOUT_MS, "ScrollFrameActivityTracker", aEventTarget) {}
  ~ScrollFrameActivityTracker() { AgeAllGenerations(); }

  virtual void NotifyExpired(nsHTMLScrollFrame* aObject) override {
    RemoveObject(aObject);
    aObject->MarkNotRecentlyScrolled();
  }
};
static StaticAutoPtr<ScrollFrameActivityTracker> gScrollFrameActivityTracker;

nsHTMLScrollFrame* NS_NewHTMLScrollFrame(PresShell* aPresShell,
                                         ComputedStyle* aStyle, bool aIsRoot) {
  return new (aPresShell)
      nsHTMLScrollFrame(aStyle, aPresShell->GetPresContext(), aIsRoot);
}

NS_IMPL_FRAMEARENA_HELPERS(nsHTMLScrollFrame)

nsHTMLScrollFrame::nsHTMLScrollFrame(ComputedStyle* aStyle,
                                     nsPresContext* aPresContext,
                                     nsIFrame::ClassID aID, bool aIsRoot)
    : nsContainerFrame(aStyle, aPresContext, aID),
      mHScrollbarBox(nullptr),
      mVScrollbarBox(nullptr),
      mScrolledFrame(nullptr),
      mScrollCornerBox(nullptr),
      mResizerBox(nullptr),
      mReferenceFrameDuringPainting(nullptr),
      mAsyncScroll(nullptr),
      mAsyncSmoothMSDScroll(nullptr),
      mLastScrollOrigin(ScrollOrigin::None),
      mDestination(0, 0),
      mRestorePos(-1, -1),
      mLastPos(-1, -1),
      mApzScrollPos(0, 0),
      mLastUpdateFramesPos(-1, -1),
      mScrollParentID(mozilla::layers::ScrollableLayerGuid::NULL_SCROLL_ID),
      mAnchor(this),
      mCurrentAPZScrollAnimationType(APZScrollAnimationType::No),
      mIsFirstScrollableFrameSequenceNumber(Nothing()),
      mInScrollingGesture(InScrollingGesture::No),
      mAllowScrollOriginDowngrade(false),
      mHadDisplayPortAtLastFrameUpdate(false),
      mHasVerticalScrollbar(false),
      mHasHorizontalScrollbar(false),
      mOnlyNeedVScrollbarToScrollVVInsideLV(false),
      mOnlyNeedHScrollbarToScrollVVInsideLV(false),
      mFrameIsUpdatingScrollbar(false),
      mDidHistoryRestore(false),
      mIsRoot(aIsRoot),
      mSuppressScrollbarUpdate(false),
      mSkippedScrollbarLayout(false),
      mHadNonInitialReflow(false),
      mFirstReflow(true),
      mHorizontalOverflow(false),
      mVerticalOverflow(false),
      mPostedReflowCallback(false),
      mMayHaveDirtyFixedChildren(false),
      mUpdateScrollbarAttributes(false),
      mHasBeenScrolledRecently(false),
      mWillBuildScrollableLayer(false),
      mIsParentToActiveScrollFrames(false),
      mHasBeenScrolled(false),
      mIgnoreMomentumScroll(false),
      mTransformingByAPZ(false),
      mScrollableByAPZ(false),
      mZoomableByAPZ(false),
      mHasOutOfFlowContentInsideFilter(false),
      mSuppressScrollbarRepaints(false),
      mIsUsingMinimumScaleSize(false),
      mMinimumScaleSizeChanged(false),
      mProcessingScrollEvent(false),
      mApzAnimationRequested(false),
      mApzAnimationTriggeredByScriptRequested(false),
      mReclampVVOffsetInReflowFinished(false),
      mMayScheduleScrollAnimations(false),
#ifdef MOZ_WIDGET_ANDROID
      mHasVerticalOverflowForDynamicToolbar(false),
#endif
      mVelocityQueue(PresContext()) {
  AppendScrollUpdate(ScrollPositionUpdate::NewScrollframe(nsPoint()));

  if (UsesOverlayScrollbars()) {
    mScrollbarActivity = new ScrollbarActivity(this);
  }

  if (mIsRoot) {
    mZoomableByAPZ = PresShell()->GetZoomableByAPZ();
  }
}

nsHTMLScrollFrame::~nsHTMLScrollFrame() = default;

void nsHTMLScrollFrame::ScrollbarActivityStarted() const {
  if (mScrollbarActivity) {
    mScrollbarActivity->ActivityStarted();
  }
}

void nsHTMLScrollFrame::ScrollbarActivityStopped() const {
  if (mScrollbarActivity) {
    mScrollbarActivity->ActivityStopped();
  }
}

void nsHTMLScrollFrame::Destroy(DestroyContext& aContext) {
  DestroyAbsoluteFrames(aContext);
  if (mIsRoot) {
    PresShell()->ResetVisualViewportOffset();
  }

  mAnchor.Destroy();

  if (mScrollbarActivity) {
    mScrollbarActivity->Destroy();
    mScrollbarActivity = nullptr;
  }

  // Unbind the content created in CreateAnonymousContent later...
  aContext.AddAnonymousContent(mHScrollbarContent.forget());
  aContext.AddAnonymousContent(mVScrollbarContent.forget());
  aContext.AddAnonymousContent(mScrollCornerContent.forget());
  aContext.AddAnonymousContent(mResizerContent.forget());

  if (mPostedReflowCallback) {
    PresShell()->CancelReflowCallback(this);
    mPostedReflowCallback = false;
  }

  if (mDisplayPortExpiryTimer) {
    mDisplayPortExpiryTimer->Cancel();
    mDisplayPortExpiryTimer = nullptr;
  }
  if (mActivityExpirationState.IsTracked()) {
    gScrollFrameActivityTracker->RemoveObject(this);
  }
  if (gScrollFrameActivityTracker && gScrollFrameActivityTracker->IsEmpty()) {
    gScrollFrameActivityTracker = nullptr;
  }

  if (mScrollActivityTimer) {
    mScrollActivityTimer->Cancel();
    mScrollActivityTimer = nullptr;
  }
  RemoveObservers();
  if (mScrollEvent) {
    mScrollEvent->Revoke();
  }
  if (mScrollEndEvent) {
    mScrollEndEvent->Revoke();
  }
  nsContainerFrame::Destroy(aContext);
}

void nsHTMLScrollFrame::SetInitialChildList(ChildListID aListID,
                                            nsFrameList&& aChildList) {
  nsContainerFrame::SetInitialChildList(aListID, std::move(aChildList));
  ReloadChildFrames();
}

void nsHTMLScrollFrame::AppendFrames(ChildListID aListID,
                                     nsFrameList&& aFrameList) {
  NS_ASSERTION(aListID == FrameChildListID::Principal,
               "Only main list supported");
  mFrames.AppendFrames(nullptr, std::move(aFrameList));
  ReloadChildFrames();
}

void nsHTMLScrollFrame::InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
                                     const nsLineList::iterator* aPrevFrameLine,
                                     nsFrameList&& aFrameList) {
  NS_ASSERTION(aListID == FrameChildListID::Principal,
               "Only main list supported");
  NS_ASSERTION(!aPrevFrame || aPrevFrame->GetParent() == this,
               "inserting after sibling frame with different parent");
  mFrames.InsertFrames(nullptr, aPrevFrame, std::move(aFrameList));
  ReloadChildFrames();
}

void nsHTMLScrollFrame::RemoveFrame(DestroyContext& aContext,
                                    ChildListID aListID, nsIFrame* aOldFrame) {
  NS_ASSERTION(aListID == FrameChildListID::Principal,
               "Only main list supported");
  mFrames.DestroyFrame(aContext, aOldFrame);
  ReloadChildFrames();
}

/**
 HTML scrolling implementation

 All other things being equal, we prefer layouts with fewer scrollbars showing.
*/

namespace mozilla {

enum class ShowScrollbar : uint8_t {
  Auto,
  Always,
  // Never is a misnomer. We can still get a scrollbar if we need to scroll the
  // visual viewport inside the layout viewport. Thus this enum is best thought
  // of as value used by layout, which does not know about the visual viewport.
  // The visual viewport does not affect any layout sizes, so this is sound.
  Never,
};

static ShowScrollbar ShouldShowScrollbar(StyleOverflow aOverflow) {
  switch (aOverflow) {
    case StyleOverflow::Scroll:
      return ShowScrollbar::Always;
    case StyleOverflow::Hidden:
      return ShowScrollbar::Never;
    default:
    case StyleOverflow::Auto:
      return ShowScrollbar::Auto;
  }
}

struct MOZ_STACK_CLASS ScrollReflowInput {
  // === Filled in by the constructor. Members in this section shouldn't change
  // their values after the constructor. ===
  const ReflowInput& mReflowInput;
  ShowScrollbar mHScrollbar;
  // If the horizontal scrollbar is allowed (even if mHScrollbar ==
  // ShowScrollbar::Never) provided that it is for scrolling the visual viewport
  // inside the layout viewport only.
  bool mHScrollbarAllowedForScrollingVVInsideLV = true;
  ShowScrollbar mVScrollbar;
  // If the vertical scrollbar is allowed (even if mVScrollbar ==
  // ShowScrollbar::Never) provided that it is for scrolling the visual viewport
  // inside the layout viewport only.
  bool mVScrollbarAllowedForScrollingVVInsideLV = true;
  nsMargin mComputedBorder;

  // === Filled in by ReflowScrolledFrame ===
  OverflowAreas mContentsOverflowAreas;
  // The scrollbar gutter sizes used in the most recent reflow of
  // mScrolledFrame. The writing-mode is the same as the scroll
  // container.
  LogicalMargin mScrollbarGutterFromLastReflow;
  // True if the most recent reflow of mScrolledFrame is with the
  // horizontal scrollbar.
  bool mReflowedContentsWithHScrollbar = false;
  // True if the most recent reflow of mScrolledFrame is with the
  // vertical scrollbar.
  bool mReflowedContentsWithVScrollbar = false;

  // === Filled in when TryLayout succeeds ===
  // The size of the inside-border area
  nsSize mInsideBorderSize;
  // Whether we decided to show the horizontal scrollbar in the most recent
  // TryLayout.
  bool mShowHScrollbar = false;
  // Whether we decided to show the vertical scrollbar in the most recent
  // TryLayout.
  bool mShowVScrollbar = false;
  // If mShow(H|V)Scrollbar is true then
  // mOnlyNeed(V|H)ScrollbarToScrollVVInsideLV indicates if the only reason we
  // need that scrollbar is to scroll the visual viewport inside the layout
  // viewport. These scrollbars are special in that even if they are layout
  // scrollbars they do not take up any layout space.
  bool mOnlyNeedHScrollbarToScrollVVInsideLV = false;
  bool mOnlyNeedVScrollbarToScrollVVInsideLV = false;

  ScrollReflowInput(nsHTMLScrollFrame* aFrame, const ReflowInput& aReflowInput);

  nscoord VScrollbarMinHeight() const { return mVScrollbarPrefSize.height; }
  nscoord VScrollbarPrefWidth() const { return mVScrollbarPrefSize.width; }
  nscoord HScrollbarMinWidth() const { return mHScrollbarPrefSize.width; }
  nscoord HScrollbarPrefHeight() const { return mHScrollbarPrefSize.height; }

  // Returns the sizes occupied by the scrollbar gutters. If aShowVScroll or
  // aShowHScroll is true, the sizes occupied by the scrollbars are also
  // included.
  nsMargin ScrollbarGutter(bool aShowVScrollbar, bool aShowHScrollbar,
                           bool aScrollbarOnRight) const {
    if (mOverlayScrollbars) {
      return mScrollbarGutter;
    }
    nsMargin gutter = mScrollbarGutter;
    if (aShowVScrollbar && gutter.right == 0 && gutter.left == 0) {
      const nscoord w = VScrollbarPrefWidth();
      if (aScrollbarOnRight) {
        gutter.right = w;
      } else {
        gutter.left = w;
      }
    }
    if (aShowHScrollbar && gutter.bottom == 0) {
      // The horizontal scrollbar is always at the bottom side.
      gutter.bottom = HScrollbarPrefHeight();
    }
    return gutter;
  }

  bool OverlayScrollbars() const { return mOverlayScrollbars; }

 private:
  // Filled in by the constructor. Put variables here to keep them unchanged
  // after initializing them in the constructor.
  nsSize mVScrollbarPrefSize;
  nsSize mHScrollbarPrefSize;
  bool mOverlayScrollbars = false;
  // The scrollbar gutter sizes resolved from the scrollbar-gutter and
  // scrollbar-width property.
  nsMargin mScrollbarGutter;
};

ScrollReflowInput::ScrollReflowInput(nsHTMLScrollFrame* aFrame,
                                     const ReflowInput& aReflowInput)
    : mReflowInput(aReflowInput),
      mComputedBorder(aReflowInput.ComputedPhysicalBorderPadding() -
                      aReflowInput.ComputedPhysicalPadding()),
      mScrollbarGutterFromLastReflow(aFrame->GetWritingMode()) {
  ScrollStyles styles = aFrame->GetScrollStyles();
  mHScrollbar = ShouldShowScrollbar(styles.mHorizontal);
  mVScrollbar = ShouldShowScrollbar(styles.mVertical);
  mOverlayScrollbars = aFrame->UsesOverlayScrollbars();

  if (nsScrollbarFrame* scrollbar = aFrame->GetScrollbarBox(false)) {
    scrollbar->SetScrollbarMediatorContent(mReflowInput.mFrame->GetContent());
    mHScrollbarPrefSize = scrollbar->ScrollbarMinSize();
    // A zero minimum size is a bug with non-overlay scrollbars. That means
    // we'll always try to place the scrollbar, even if it will ultimately not
    // fit, see bug 1809630. XUL collapsing is the exception because the
    // front-end uses it.
    MOZ_ASSERT(mHScrollbarPrefSize.width && mHScrollbarPrefSize.height,
               "Shouldn't have a zero horizontal scrollbar-size");
  } else {
    mHScrollbar = ShowScrollbar::Never;
    mHScrollbarAllowedForScrollingVVInsideLV = false;
  }
  if (nsScrollbarFrame* scrollbar = aFrame->GetScrollbarBox(true)) {
    scrollbar->SetScrollbarMediatorContent(mReflowInput.mFrame->GetContent());
    mVScrollbarPrefSize = scrollbar->ScrollbarMinSize();
    // See above.
    MOZ_ASSERT(mVScrollbarPrefSize.width && mVScrollbarPrefSize.height,
               "Shouldn't have a zero vertical scrollbar-size");
  } else {
    mVScrollbar = ShowScrollbar::Never;
    mVScrollbarAllowedForScrollingVVInsideLV = false;
  }

  const auto* scrollbarStyle =
      nsLayoutUtils::StyleForScrollbar(mReflowInput.mFrame);
  // Hide the scrollbar when the scrollbar-width is set to none.
  //
  // Note: In some cases this is unnecessary, because scrollbar-width:none
  // makes us suppress scrollbars in CreateAnonymousContent. But if this frame
  // initially had a non-'none' scrollbar-width and dynamically changed to
  // 'none', then we'll need to handle it here.
  const auto scrollbarWidth = scrollbarStyle->StyleUIReset()->ScrollbarWidth();
  if (scrollbarWidth == StyleScrollbarWidth::None) {
    mHScrollbar = ShowScrollbar::Never;
    mHScrollbarAllowedForScrollingVVInsideLV = false;
    mVScrollbar = ShowScrollbar::Never;
    mVScrollbarAllowedForScrollingVVInsideLV = false;
  }

  mScrollbarGutter = aFrame->ComputeStableScrollbarGutter(
      scrollbarWidth, scrollbarStyle->StyleDisplay()->mScrollbarGutter);
}

}  // namespace mozilla

static nsSize ComputeInsideBorderSize(const ScrollReflowInput& aState,
                                      const nsSize& aDesiredInsideBorderSize) {
  // aDesiredInsideBorderSize is the frame size; i.e., it includes
  // borders and padding (but the scrolled child doesn't have
  // borders). The scrolled child has the same padding as us.
  const WritingMode wm = aState.mReflowInput.GetWritingMode();
  const LogicalSize desiredInsideBorderSize(wm, aDesiredInsideBorderSize);
  LogicalSize contentSize = aState.mReflowInput.ComputedSize();
  const LogicalMargin padding = aState.mReflowInput.ComputedLogicalPadding(wm);

  if (contentSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
    contentSize.ISize(wm) =
        desiredInsideBorderSize.ISize(wm) - padding.IStartEnd(wm);
  }
  if (contentSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
    contentSize.BSize(wm) =
        desiredInsideBorderSize.BSize(wm) - padding.BStartEnd(wm);
  }

  contentSize.ISize(wm) =
      aState.mReflowInput.ApplyMinMaxISize(contentSize.ISize(wm));
  contentSize.BSize(wm) =
      aState.mReflowInput.ApplyMinMaxBSize(contentSize.BSize(wm));

  return (contentSize + padding.Size(wm)).GetPhysicalSize(wm);
}

/**
 * Assuming that we know the metrics for our wrapped frame and
 * whether the horizontal and/or vertical scrollbars are present,
 * compute the resulting layout and return true if the layout is
 * consistent. If the layout is consistent then we fill in the
 * computed fields of the ScrollReflowInput.
 *
 * The layout is consistent when both scrollbars are showing if and only
 * if they should be showing. A horizontal scrollbar should be showing if all
 * following conditions are met:
 * 1) the style is not HIDDEN
 * 2) our inside-border height is at least the scrollbar height (i.e., the
 * scrollbar fits vertically)
 * 3) the style is SCROLL, or the kid's overflow-area XMost is
 * greater than the scrollport width
 *
 * @param aForce if true, then we just assume the layout is consistent.
 */
bool nsHTMLScrollFrame::TryLayout(ScrollReflowInput& aState,
                                  ReflowOutput* aKidMetrics,
                                  bool aAssumeHScroll, bool aAssumeVScroll,
                                  bool aForce) {
  if ((aState.mVScrollbar == ShowScrollbar::Never && aAssumeVScroll) ||
      (aState.mHScrollbar == ShowScrollbar::Never && aAssumeHScroll)) {
    NS_ASSERTION(!aForce, "Shouldn't be forcing a hidden scrollbar to show!");
    return false;
  }

  const auto wm = GetWritingMode();
  const nsMargin scrollbarGutter = aState.ScrollbarGutter(
      aAssumeVScroll, aAssumeHScroll, IsScrollbarOnRight());
  const LogicalMargin logicalScrollbarGutter(wm, scrollbarGutter);

  const bool inlineEndsGutterChanged =
      aState.mScrollbarGutterFromLastReflow.IStartEnd(wm) !=
      logicalScrollbarGutter.IStartEnd(wm);
  const bool blockEndsGutterChanged =
      aState.mScrollbarGutterFromLastReflow.BStartEnd(wm) !=
      logicalScrollbarGutter.BStartEnd(wm);
  const bool shouldReflowScrolledFrame =
      inlineEndsGutterChanged ||
      (blockEndsGutterChanged && ScrolledContentDependsOnBSize(aState));

  if (shouldReflowScrolledFrame) {
    if (blockEndsGutterChanged) {
      nsLayoutUtils::MarkIntrinsicISizesDirtyIfDependentOnBSize(mScrolledFrame);
    }
    aKidMetrics->mOverflowAreas.Clear();
    ROOT_SCROLLBAR_LOG(
        "TryLayout reflowing scrolled frame with scrollbars h=%d, v=%d\n",
        aAssumeHScroll, aAssumeVScroll);
    ReflowScrolledFrame(aState, aAssumeHScroll, aAssumeVScroll, aKidMetrics);
  }

  const nsSize scrollbarGutterSize(scrollbarGutter.LeftRight(),
                                   scrollbarGutter.TopBottom());

  // First, compute our inside-border size and scrollport size
  nsSize kidSize = GetContainSizeAxes().ContainSize(
      aKidMetrics->PhysicalSize(), *aState.mReflowInput.mFrame);
  const nsSize desiredInsideBorderSize = kidSize + scrollbarGutterSize;
  aState.mInsideBorderSize =
      ComputeInsideBorderSize(aState, desiredInsideBorderSize);

  nsSize layoutSize =
      mIsUsingMinimumScaleSize ? mMinimumScaleSize : aState.mInsideBorderSize;

  const nsSize scrollPortSize =
      Max(nsSize(0, 0), layoutSize - scrollbarGutterSize);
  if (mIsUsingMinimumScaleSize) {
    mICBSize =
        Max(nsSize(0, 0), aState.mInsideBorderSize - scrollbarGutterSize);
  }

  nsSize visualViewportSize = scrollPortSize;
  ROOT_SCROLLBAR_LOG("TryLayout with VV %s\n",
                     ToString(visualViewportSize).c_str());
  mozilla::PresShell* presShell = PresShell();
  // Note: we check for a non-null MobileViepwortManager here, but ideally we
  // should be able to drop that clause as well. It's just that in some cases
  // with extension popups the composition size comes back as stale, because
  // the content viewer is only resized after the popup contents are reflowed.
  // That case also happens to have no APZ and no MVM, so we use that as a
  // way to detect the scenario. Bug 1648669 tracks removing this clause.
  if (mIsRoot && presShell->GetMobileViewportManager()) {
    visualViewportSize = nsLayoutUtils::CalculateCompositionSizeForFrame(
        this, false, &layoutSize);
    visualViewportSize =
        Max(nsSize(0, 0), visualViewportSize - scrollbarGutterSize);

    float resolution = presShell->GetResolution();
    visualViewportSize.width /= resolution;
    visualViewportSize.height /= resolution;
    ROOT_SCROLLBAR_LOG("TryLayout now with VV %s\n",
                       ToString(visualViewportSize).c_str());
  }

  nsRect overflowRect = aState.mContentsOverflowAreas.ScrollableOverflow();
  // If the content height expanded by the minimum-scale will be taller than
  // the scrollable overflow area, we need to expand the area here to tell
  // properly whether we need to render the overlay vertical scrollbar.
  // NOTE: This expanded size should NOT be used for non-overley scrollbars
  // cases since putting the vertical non-overlay scrollbar will make the
  // content width narrow a little bit, which in turn the minimum scale value
  // becomes a bit bigger than before, then the vertical scrollbar is no longer
  // needed, which means the content width becomes the original width, then the
  // minimum-scale is changed to the original one, and so forth.
  if (UsesOverlayScrollbars() && mIsUsingMinimumScaleSize &&
      mMinimumScaleSize.height > overflowRect.YMost()) {
    overflowRect.height += mMinimumScaleSize.height - overflowRect.YMost();
  }
  nsRect scrolledRect =
      GetUnsnappedScrolledRectInternal(overflowRect, scrollPortSize);
  ROOT_SCROLLBAR_LOG(
      "TryLayout scrolledRect:%s overflowRect:%s scrollportSize:%s\n",
      ToString(scrolledRect).c_str(), ToString(overflowRect).c_str(),
      ToString(scrollPortSize).c_str());
  nscoord oneDevPixel = PresContext()->DevPixelsToAppUnits(1);

  bool showHScrollbar = aAssumeHScroll;
  bool showVScrollbar = aAssumeVScroll;
  if (!aForce) {
    nsSize sizeToCompare = visualViewportSize;
    if (gfxPlatform::UseDesktopZoomingScrollbars()) {
      sizeToCompare = scrollPortSize;
    }

    // No need to compute showHScrollbar if we got ShowScrollbar::Never.
    if (aState.mHScrollbar != ShowScrollbar::Never) {
      showHScrollbar =
          aState.mHScrollbar == ShowScrollbar::Always ||
          scrolledRect.XMost() >= sizeToCompare.width + oneDevPixel ||
          scrolledRect.x <= -oneDevPixel;
      // TODO(emilio): This should probably check this scrollbar's minimum size
      // in both axes, for consistency?
      if (aState.mHScrollbar == ShowScrollbar::Auto &&
          scrollPortSize.width < aState.HScrollbarMinWidth()) {
        showHScrollbar = false;
      }
      ROOT_SCROLLBAR_LOG("TryLayout wants H Scrollbar: %d =? %d\n",
                         showHScrollbar, aAssumeHScroll);
    }

    // No need to compute showVScrollbar if we got ShowScrollbar::Never.
    if (aState.mVScrollbar != ShowScrollbar::Never) {
      showVScrollbar =
          aState.mVScrollbar == ShowScrollbar::Always ||
          scrolledRect.YMost() >= sizeToCompare.height + oneDevPixel ||
          scrolledRect.y <= -oneDevPixel;
      // TODO(emilio): This should probably check this scrollbar's minimum size
      // in both axes, for consistency?
      if (aState.mVScrollbar == ShowScrollbar::Auto &&
          scrollPortSize.height < aState.VScrollbarMinHeight()) {
        showVScrollbar = false;
      }
      ROOT_SCROLLBAR_LOG("TryLayout wants V Scrollbar: %d =? %d\n",
                         showVScrollbar, aAssumeVScroll);
    }

    if (showHScrollbar != aAssumeHScroll || showVScrollbar != aAssumeVScroll) {
      const nsMargin wantedScrollbarGutter = aState.ScrollbarGutter(
          showVScrollbar, showHScrollbar, IsScrollbarOnRight());
      // We report an inconsistent layout only when the desired visibility of
      // the scrollbars can change the size of the scrollbar gutters.
      if (scrollbarGutter != wantedScrollbarGutter) {
        return false;
      }
    }
  }

  // If we reach here, the layout is consistent. Record the desired visibility
  // of the scrollbars.
  aState.mShowHScrollbar = showHScrollbar;
  aState.mShowVScrollbar = showVScrollbar;
  const nsPoint scrollPortOrigin(
      aState.mComputedBorder.left + scrollbarGutter.left,
      aState.mComputedBorder.top + scrollbarGutter.top);
  SetScrollPort(nsRect(scrollPortOrigin, scrollPortSize));

  if (mIsRoot && gfxPlatform::UseDesktopZoomingScrollbars()) {
    bool vvChanged = true;
    const bool overlay = aState.OverlayScrollbars();
    // This loop can run at most twice since we can only add a scrollbar once.
    // At this point we've already decided that this layout is consistent so we
    // will return true. Scrollbars added here never take up layout space even
    // if they are layout scrollbars so any changes made here will not make us
    // return false.
    while (vvChanged) {
      vvChanged = false;
      if (!aState.mShowHScrollbar &&
          aState.mHScrollbarAllowedForScrollingVVInsideLV) {
        if (ScrollPort().width >= visualViewportSize.width + oneDevPixel &&
            (overlay ||
             visualViewportSize.width >= aState.HScrollbarMinWidth())) {
          vvChanged = true;
          if (!overlay) {
            visualViewportSize.height -= aState.HScrollbarPrefHeight();
          }
          aState.mShowHScrollbar = true;
          aState.mOnlyNeedHScrollbarToScrollVVInsideLV = true;
          ROOT_SCROLLBAR_LOG("TryLayout added H scrollbar for VV, VV now %s\n",
                             ToString(visualViewportSize).c_str());
        }
      }

      if (!aState.mShowVScrollbar &&
          aState.mVScrollbarAllowedForScrollingVVInsideLV) {
        if (ScrollPort().height >= visualViewportSize.height + oneDevPixel &&
            (overlay ||
             visualViewportSize.height >= aState.VScrollbarMinHeight())) {
          vvChanged = true;
          if (!overlay) {
            visualViewportSize.width -= aState.VScrollbarPrefWidth();
          }
          aState.mShowVScrollbar = true;
          aState.mOnlyNeedVScrollbarToScrollVVInsideLV = true;
          ROOT_SCROLLBAR_LOG("TryLayout added V scrollbar for VV, VV now %s\n",
                             ToString(visualViewportSize).c_str());
        }
      }
    }
  }

  return true;
}

bool nsHTMLScrollFrame::ScrolledContentDependsOnBSize(
    const ScrollReflowInput& aState) const {
  return mScrolledFrame->HasAnyStateBits(
             NS_FRAME_CONTAINS_RELATIVE_BSIZE |
             NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE) ||
         aState.mReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE ||
         aState.mReflowInput.ComputedMinBSize() > 0 ||
         aState.mReflowInput.ComputedMaxBSize() != NS_UNCONSTRAINEDSIZE;
}

void nsHTMLScrollFrame::ReflowScrolledFrame(ScrollReflowInput& aState,
                                            bool aAssumeHScroll,
                                            bool aAssumeVScroll,
                                            ReflowOutput* aMetrics) {
  const WritingMode wm = GetWritingMode();

  // these could be NS_UNCONSTRAINEDSIZE ... std::min arithmetic should
  // be OK
  LogicalMargin padding = aState.mReflowInput.ComputedLogicalPadding(wm);
  nscoord availISize =
      aState.mReflowInput.ComputedISize() + padding.IStartEnd(wm);

  nscoord computedBSize = aState.mReflowInput.ComputedBSize();
  nscoord computedMinBSize = aState.mReflowInput.ComputedMinBSize();
  nscoord computedMaxBSize = aState.mReflowInput.ComputedMaxBSize();
  if (!ShouldPropagateComputedBSizeToScrolledContent()) {
    computedBSize = NS_UNCONSTRAINEDSIZE;
    computedMinBSize = 0;
    computedMaxBSize = NS_UNCONSTRAINEDSIZE;
  }

  const LogicalMargin scrollbarGutter(
      wm, aState.ScrollbarGutter(aAssumeVScroll, aAssumeHScroll,
                                 IsScrollbarOnRight()));
  if (const nscoord inlineEndsGutter = scrollbarGutter.IStartEnd(wm);
      inlineEndsGutter > 0) {
    availISize = std::max(0, availISize - inlineEndsGutter);
  }
  if (const nscoord blockEndsGutter = scrollbarGutter.BStartEnd(wm);
      blockEndsGutter > 0) {
    if (computedBSize != NS_UNCONSTRAINEDSIZE) {
      computedBSize = std::max(0, computedBSize - blockEndsGutter);
    }
    computedMinBSize = std::max(0, computedMinBSize - blockEndsGutter);
    if (computedMaxBSize != NS_UNCONSTRAINEDSIZE) {
      computedMaxBSize = std::max(0, computedMaxBSize - blockEndsGutter);
    }
  }

  nsPresContext* presContext = PresContext();

  // Pass InitFlags::CallerWillInit so we can pass in the correct padding.
  ReflowInput kidReflowInput(presContext, aState.mReflowInput, mScrolledFrame,
                             LogicalSize(wm, availISize, NS_UNCONSTRAINEDSIZE),
                             Nothing(), ReflowInput::InitFlag::CallerWillInit);
  const WritingMode kidWM = kidReflowInput.GetWritingMode();
  kidReflowInput.Init(presContext, Nothing(), Nothing(),
                      Some(padding.ConvertTo(kidWM, wm)));
  kidReflowInput.mFlags.mAssumingHScrollbar = aAssumeHScroll;
  kidReflowInput.mFlags.mAssumingVScrollbar = aAssumeVScroll;
  kidReflowInput.mFlags.mTreatBSizeAsIndefinite =
      aState.mReflowInput.mFlags.mTreatBSizeAsIndefinite;
  kidReflowInput.SetComputedBSize(computedBSize);
  kidReflowInput.SetComputedMinBSize(computedMinBSize);
  kidReflowInput.SetComputedMaxBSize(computedMaxBSize);
  if (aState.mReflowInput.IsBResizeForWM(kidWM)) {
    kidReflowInput.SetBResize(true);
  }
  if (aState.mReflowInput.IsBResizeForPercentagesForWM(kidWM)) {
    kidReflowInput.mFlags.mIsBResizeForPercentages = true;
  }

  // Temporarily set mHasHorizontalScrollbar/mHasVerticalScrollbar to
  // reflect our assumptions while we reflow the child.
  bool didHaveHorizontalScrollbar = mHasHorizontalScrollbar;
  bool didHaveVerticalScrollbar = mHasVerticalScrollbar;
  mHasHorizontalScrollbar = aAssumeHScroll;
  mHasVerticalScrollbar = aAssumeVScroll;

  nsReflowStatus status;
  // No need to pass a true container-size to ReflowChild or
  // FinishReflowChild, because it's only used there when positioning
  // the frame (i.e. if ReflowChildFlags::NoMoveFrame isn't set)
  const nsSize dummyContainerSize;
  ReflowChild(mScrolledFrame, presContext, *aMetrics, kidReflowInput, wm,
              LogicalPoint(wm), dummyContainerSize,
              ReflowChildFlags::NoMoveFrame, status);

  mHasHorizontalScrollbar = didHaveHorizontalScrollbar;
  mHasVerticalScrollbar = didHaveVerticalScrollbar;

  // Don't resize or position the view (if any) because we're going to resize
  // it to the correct size anyway in PlaceScrollArea. Allowing it to
  // resize here would size it to the natural height of the frame,
  // which will usually be different from the scrollport height;
  // invalidating the difference will cause unnecessary repainting.
  FinishReflowChild(
      mScrolledFrame, presContext, *aMetrics, &kidReflowInput, wm,
      LogicalPoint(wm), dummyContainerSize,
      ReflowChildFlags::NoMoveFrame | ReflowChildFlags::NoSizeView);

  if (mScrolledFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
    // Propagate NS_FRAME_CONTAINS_RELATIVE_BSIZE from our inner scrolled frame
    // to ourselves so that our containing block is aware of it.
    //
    // Note: If the scrolled frame has any child whose block-size depends on the
    // containing block's block-size, the NS_FRAME_CONTAINS_RELATIVE_BSIZE bit
    // is set on the scrolled frame when initializing the child's ReflowInput in
    // ReflowInput::InitResizeFlags(). Therefore, we propagate the bit here
    // after we reflowed the scrolled frame.
    AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
  }

  // XXX Some frames (e.g. nsFrameFrame, nsTextFrame) don't
  // bother setting their mOverflowArea. This is wrong because every frame
  // should always set mOverflowArea. In fact nsFrameFrame doesn't
  // support the 'outline' property because of this. Rather than fix the
  // world right now, just fix up the overflow area if necessary. Note that we
  // don't check HasOverflowRect() because it could be set even though the
  // overflow area doesn't include the frame bounds.
  aMetrics->UnionOverflowAreasWithDesiredBounds();

  auto* disp = StyleDisplay();
  if (MOZ_UNLIKELY(disp->mOverflowClipBoxInline ==
                   StyleOverflowClipBox::ContentBox)) {
    // The scrolled frame is scrollable in the inline axis with
    // `overflow-clip-box:content-box`. To prevent its content from being
    // clipped at the scroll container's padding edges, we inflate its
    // children's scrollable overflow area with its inline padding, and union
    // its scrollable overflow area with its children's inflated scrollable
    // overflow area.
    OverflowAreas childOverflow;
    mScrolledFrame->UnionChildOverflow(childOverflow);
    nsRect childScrollableOverflow = childOverflow.ScrollableOverflow();

    const LogicalMargin inlinePadding =
        padding.ApplySkipSides(LogicalSides(wm, LogicalSides::BBoth));
    childScrollableOverflow.Inflate(inlinePadding.GetPhysicalMargin(wm));

    nsRect& so = aMetrics->ScrollableOverflow();
    so = so.UnionEdges(childScrollableOverflow);
  }

  aState.mContentsOverflowAreas = aMetrics->mOverflowAreas;
  aState.mScrollbarGutterFromLastReflow = scrollbarGutter;
  aState.mReflowedContentsWithHScrollbar = aAssumeHScroll;
  aState.mReflowedContentsWithVScrollbar = aAssumeVScroll;
}

bool nsHTMLScrollFrame::GuessHScrollbarNeeded(const ScrollReflowInput& aState) {
  if (aState.mHScrollbar != ShowScrollbar::Auto) {
    // no guessing required
    return aState.mHScrollbar == ShowScrollbar::Always;
  }
  // We only care about scrollbars that might take up space when trying to guess
  // if we need a scrollbar, so we ignore scrollbars only created to scroll the
  // visual viewport inside the layout viewport because they take up no layout
  // space.
  return mHasHorizontalScrollbar && !mOnlyNeedHScrollbarToScrollVVInsideLV;
}

bool nsHTMLScrollFrame::GuessVScrollbarNeeded(const ScrollReflowInput& aState) {
  if (aState.mVScrollbar != ShowScrollbar::Auto) {
    // no guessing required
    return aState.mVScrollbar == ShowScrollbar::Always;
  }

  // If we've had at least one non-initial reflow, then just assume
  // the state of the vertical scrollbar will be what we determined
  // last time.
  if (mHadNonInitialReflow) {
    // We only care about scrollbars that might take up space when trying to
    // guess if we need a scrollbar, so we ignore scrollbars only created to
    // scroll the visual viewport inside the layout viewport because they take
    // up no layout space.
    return mHasVerticalScrollbar && !mOnlyNeedVScrollbarToScrollVVInsideLV;
  }

  // If this is the initial reflow, guess false because usually
  // we have very little content by then.
  if (InInitialReflow()) return false;

  if (mIsRoot) {
    nsIFrame* f = mScrolledFrame->PrincipalChildList().FirstChild();
    if (f && f->IsSVGOuterSVGFrame() &&
        static_cast<SVGOuterSVGFrame*>(f)->VerticalScrollbarNotNeeded()) {
      // Common SVG case - avoid a bad guess.
      return false;
    }
    // Assume that there will be a scrollbar; it seems to me
    // that 'most pages' do have a scrollbar, and anyway, it's cheaper
    // to do an extra reflow for the pages that *don't* need a
    // scrollbar (because on average they will have less content).
    return true;
  }

  // For non-viewports, just guess that we don't need a scrollbar.
  // XXX I wonder if statistically this is the right idea; I'm
  // basically guessing that there are a lot of overflow:auto DIVs
  // that get their intrinsic size and don't overflow
  return false;
}

bool nsHTMLScrollFrame::InInitialReflow() const {
  // We're in an initial reflow if NS_FRAME_FIRST_REFLOW is set, unless we're a
  // root scrollframe.  In that case we want to skip this clause altogether.
  // The guess here is that there are lots of overflow:auto divs out there that
  // end up auto-sizing so they don't overflow, and that the root basically
  // always needs a scrollbar if it did last time we loaded this page (good
  // assumption, because our initial reflow is no longer synchronous).
  return !mIsRoot && HasAnyStateBits(NS_FRAME_FIRST_REFLOW);
}

void nsHTMLScrollFrame::ReflowContents(ScrollReflowInput& aState,
                                       const ReflowOutput& aDesiredSize) {
  const WritingMode desiredWm = aDesiredSize.GetWritingMode();
  ReflowOutput kidDesiredSize(desiredWm);
  ReflowScrolledFrame(aState, GuessHScrollbarNeeded(aState),
                      GuessVScrollbarNeeded(aState), &kidDesiredSize);

  // There's an important special case ... if the child appears to fit
  // in the inside-border rect (but overflows the scrollport), we
  // should try laying it out without a vertical scrollbar. It will
  // usually fit because making the available-width wider will not
  // normally make the child taller. (The only situation I can think
  // of is when you have a line containing %-width inline replaced
  // elements whose percentages sum to more than 100%, so increasing
  // the available width makes the line break where it was fitting
  // before.) If we don't treat this case specially, then we will
  // decide that showing scrollbars is OK because the content
  // overflows when we're showing scrollbars and we won't try to
  // remove the vertical scrollbar.

  // Detecting when we enter this special case is important for when
  // people design layouts that exactly fit the container "most of the
  // time".

  // XXX Is this check really sufficient to catch all the incremental cases
  // where the ideal case doesn't have a scrollbar?
  if ((aState.mReflowedContentsWithHScrollbar ||
       aState.mReflowedContentsWithVScrollbar) &&
      aState.mVScrollbar != ShowScrollbar::Always &&
      aState.mHScrollbar != ShowScrollbar::Always) {
    nsSize kidSize = GetContainSizeAxes().ContainSize(
        kidDesiredSize.PhysicalSize(), *aState.mReflowInput.mFrame);
    nsSize insideBorderSize = ComputeInsideBorderSize(aState, kidSize);
    nsRect scrolledRect = GetUnsnappedScrolledRectInternal(
        kidDesiredSize.ScrollableOverflow(), insideBorderSize);
    if (nsRect(nsPoint(0, 0), insideBorderSize).Contains(scrolledRect)) {
      // Let's pretend we had no scrollbars coming in here
      kidDesiredSize.mOverflowAreas.Clear();
      ReflowScrolledFrame(aState, false, false, &kidDesiredSize);
    }
  }

  if (IsRootScrollFrameOfDocument()) {
    UpdateMinimumScaleSize(aState.mContentsOverflowAreas.ScrollableOverflow(),
                           kidDesiredSize.PhysicalSize());
  }

  // Try vertical scrollbar settings that leave the vertical scrollbar
  // unchanged. Do this first because changing the vertical scrollbar setting is
  // expensive, forcing a reflow always.

  // Try leaving the horizontal scrollbar unchanged first. This will be more
  // efficient.
  ROOT_SCROLLBAR_LOG("Trying layout1 with %d, %d\n",
                     aState.mReflowedContentsWithHScrollbar,
                     aState.mReflowedContentsWithVScrollbar);
  if (TryLayout(aState, &kidDesiredSize, aState.mReflowedContentsWithHScrollbar,
                aState.mReflowedContentsWithVScrollbar, false)) {
    return;
  }
  ROOT_SCROLLBAR_LOG("Trying layout2 with %d, %d\n",
                     !aState.mReflowedContentsWithHScrollbar,
                     aState.mReflowedContentsWithVScrollbar);
  if (TryLayout(aState, &kidDesiredSize,
                !aState.mReflowedContentsWithHScrollbar,
                aState.mReflowedContentsWithVScrollbar, false)) {
    return;
  }

  // OK, now try toggling the vertical scrollbar. The performance advantage
  // of trying the status-quo horizontal scrollbar state
  // does not exist here (we'll have to reflow due to the vertical scrollbar
  // change), so always try no horizontal scrollbar first.
  bool newVScrollbarState = !aState.mReflowedContentsWithVScrollbar;
  ROOT_SCROLLBAR_LOG("Trying layout3 with %d, %d\n", false, newVScrollbarState);
  if (TryLayout(aState, &kidDesiredSize, false, newVScrollbarState, false)) {
    return;
  }
  ROOT_SCROLLBAR_LOG("Trying layout4 with %d, %d\n", true, newVScrollbarState);
  if (TryLayout(aState, &kidDesiredSize, true, newVScrollbarState, false)) {
    return;
  }

  // OK, we're out of ideas. Try again enabling whatever scrollbars we can
  // enable and force the layout to stick even if it's inconsistent.
  // This just happens sometimes.
  ROOT_SCROLLBAR_LOG("Giving up, adding both scrollbars...\n");
  TryLayout(aState, &kidDesiredSize, aState.mHScrollbar != ShowScrollbar::Never,
            aState.mVScrollbar != ShowScrollbar::Never, true);
}

void nsHTMLScrollFrame::PlaceScrollArea(ScrollReflowInput& aState,
                                        const nsPoint& aScrollPosition) {
  // Set the x,y of the scrolled frame to the correct value
  mScrolledFrame->SetPosition(ScrollPort().TopLeft() - aScrollPosition);

  // Recompute our scrollable overflow, taking perspective children into
  // account. Note that this only recomputes the overflow areas stored on the
  // helper (which are used to compute scrollable length and scrollbar thumb
  // sizes) but not the overflow areas stored on the frame. This seems to work
  // for now, but it's possible that we may need to update both in the future.
  AdjustForPerspective(aState.mContentsOverflowAreas.ScrollableOverflow());

  // Preserve the width or height of empty rects
  const nsSize portSize = ScrollPort().Size();
  nsRect scrolledRect = GetUnsnappedScrolledRectInternal(
      aState.mContentsOverflowAreas.ScrollableOverflow(), portSize);
  nsRect scrolledArea =
      scrolledRect.UnionEdges(nsRect(nsPoint(0, 0), portSize));

  // Store the new overflow area. Note that this changes where an outline
  // of the scrolled frame would be painted, but scrolled frames can't have
  // outlines (the outline would go on this scrollframe instead).
  // Using FinishAndStoreOverflow is needed so the overflow rect gets set
  // correctly.  It also messes with the overflow rect in the 'clip' case, but
  // scrolled frames can't have 'overflow' either.
  // This needs to happen before SyncFrameViewAfterReflow so
  // HasOverflowRect() will return the correct value.
  OverflowAreas overflow(scrolledArea, scrolledArea);
  mScrolledFrame->FinishAndStoreOverflow(overflow, mScrolledFrame->GetSize());

  // Note that making the view *exactly* the size of the scrolled area
  // is critical, since the view scrolling code uses the size of the
  // scrolled view to clamp scroll requests.
  // Normally the mScrolledFrame won't have a view but in some cases it
  // might create its own.
  nsContainerFrame::SyncFrameViewAfterReflow(
      mScrolledFrame->PresContext(), mScrolledFrame, mScrolledFrame->GetView(),
      scrolledArea, ReflowChildFlags::Default);
}

nscoord nsHTMLScrollFrame::IntrinsicScrollbarGutterSizeAtInlineEdges() const {
  const auto wm = GetWritingMode();
  const LogicalMargin gutter(wm, IntrinsicScrollbarGutterSize());
  return gutter.IStartEnd(wm);
}

nsMargin nsHTMLScrollFrame::IntrinsicScrollbarGutterSize() const {
  if (PresContext()->UseOverlayScrollbars()) {
    // Overlay scrollbars do not consume space per spec.
    return {};
  }

  const auto* styleForScrollbar = nsLayoutUtils::StyleForScrollbar(this);
  const auto& styleScrollbarWidth =
      styleForScrollbar->StyleUIReset()->ScrollbarWidth();
  if (styleScrollbarWidth == StyleScrollbarWidth::None) {
    // Scrollbar shouldn't appear at all with "scrollbar-width: none".
    return {};
  }

  const auto& styleScrollbarGutter =
      styleForScrollbar->StyleDisplay()->mScrollbarGutter;
  nsMargin gutter =
      ComputeStableScrollbarGutter(styleScrollbarWidth, styleScrollbarGutter);
  if (gutter.LeftRight() == 0 || gutter.TopBottom() == 0) {
    // If there is no stable scrollbar-gutter at vertical or horizontal
    // dimension, check if a scrollbar is always shown at that dimension.
    ScrollStyles scrollStyles = GetScrollStyles();
    const nscoord scrollbarSize =
        GetNonOverlayScrollbarSize(PresContext(), styleScrollbarWidth);
    if (gutter.LeftRight() == 0 &&
        scrollStyles.mVertical == StyleOverflow::Scroll) {
      (IsScrollbarOnRight() ? gutter.right : gutter.left) = scrollbarSize;
    }
    if (gutter.TopBottom() == 0 &&
        scrollStyles.mHorizontal == StyleOverflow::Scroll) {
      // The horizontal scrollbar is always at the bottom side.
      gutter.bottom = scrollbarSize;
    }
  }
  return gutter;
}

nsMargin nsHTMLScrollFrame::ComputeStableScrollbarGutter(
    const StyleScrollbarWidth& aStyleScrollbarWidth,
    const StyleScrollbarGutter& aStyleScrollbarGutter) const {
  if (PresContext()->UseOverlayScrollbars()) {
    // Overlay scrollbars do not consume space per spec.
    return {};
  }

  if (aStyleScrollbarWidth == StyleScrollbarWidth::None) {
    // Scrollbar shouldn't appear at all with "scrollbar-width: none".
    return {};
  }

  if (aStyleScrollbarGutter == StyleScrollbarGutter::AUTO) {
    // Scrollbars create space depending on the 'overflow' property and whether
    // the content overflows. Callers need to check this scenario if they want
    // to consider the space created by the actual scrollbars.
    return {};
  }

  const bool bothEdges =
      bool(aStyleScrollbarGutter & StyleScrollbarGutter::BOTH_EDGES);
  const bool isVerticalWM = GetWritingMode().IsVertical();
  const nscoord scrollbarSize =
      GetNonOverlayScrollbarSize(PresContext(), aStyleScrollbarWidth);

  nsMargin scrollbarGutter;
  if (bothEdges) {
    if (isVerticalWM) {
      scrollbarGutter.top = scrollbarGutter.bottom = scrollbarSize;
    } else {
      scrollbarGutter.left = scrollbarGutter.right = scrollbarSize;
    }
  } else {
    MOZ_ASSERT(bool(aStyleScrollbarGutter & StyleScrollbarGutter::STABLE),
               "scrollbar-gutter value should be 'stable'!");
    if (isVerticalWM) {
      // The horizontal scrollbar-gutter is always at the bottom side.
      scrollbarGutter.bottom = scrollbarSize;
    } else if (IsScrollbarOnRight()) {
      scrollbarGutter.right = scrollbarSize;
    } else {
      scrollbarGutter.left = scrollbarSize;
    }
  }
  return scrollbarGutter;
}

// Legacy, this sucks!
static bool IsMarqueeScrollbox(const nsIFrame& aScrollFrame) {
  return HTMLMarqueeElement::FromNodeOrNull(aScrollFrame.GetContent());
}

/* virtual */
nscoord nsHTMLScrollFrame::GetMinISize(gfxContext* aRenderingContext) {
  nscoord result = [&] {
    if (const Maybe<nscoord> containISize = ContainIntrinsicISize()) {
      return *containISize;
    }
    if (MOZ_UNLIKELY(IsMarqueeScrollbox(*this))) {
      return 0;
    }
    return mScrolledFrame->GetMinISize(aRenderingContext);
  }();

  return result + IntrinsicScrollbarGutterSizeAtInlineEdges();
}

/* virtual */
nscoord nsHTMLScrollFrame::GetPrefISize(gfxContext* aRenderingContext) {
  const Maybe<nscoord> containISize = ContainIntrinsicISize();
  nscoord result = containISize
                       ? *containISize
                       : mScrolledFrame->GetPrefISize(aRenderingContext);
  return NSCoordSaturatingAdd(result,
                              IntrinsicScrollbarGutterSizeAtInlineEdges());
}

// When we have perspective set on the outer scroll frame, and transformed
// children (possibly with preserve-3d) then the effective transform on the
// child depends on the offset to the scroll frame, which changes as we scroll.
// This perspective transform can cause the element to move relative to the
// scrolled inner frame, which would cause the scrollable length changes during
// scrolling if we didn't account for it. Since we don't want scrollHeight/Width
// and the size of scrollbar thumbs to change during scrolling, we compute the
// scrollable overflow by determining the scroll position at which the child
// becomes completely visible within the scrollport rather than using the union
// of the overflow areas at their current position.
static void GetScrollableOverflowForPerspective(
    nsIFrame* aScrolledFrame, nsIFrame* aCurrentFrame, const nsRect aScrollPort,
    nsPoint aOffset, nsRect& aScrolledFrameOverflowArea) {
  // Iterate over all children except pop-ups.
  for (const auto& [list, listID] : aCurrentFrame->ChildLists()) {
    if (listID == FrameChildListID::Popup) {
      continue;
    }

    for (nsIFrame* child : list) {
      nsPoint offset = aOffset;

      // When we reach a direct child of the scroll, then we record the offset
      // to convert from that frame's coordinate into the scroll frame's
      // coordinates. Preserve-3d descendant frames use the same offset as their
      // ancestors, since TransformRect already converts us into the coordinate
      // space of the preserve-3d root.
      if (aScrolledFrame == aCurrentFrame) {
        offset = child->GetPosition();
      }

      if (child->Extend3DContext()) {
        // If we're a preserve-3d frame, then recurse and include our
        // descendants since overflow of preserve-3d frames is only included
        // in the post-transform overflow area of the preserve-3d root frame.
        GetScrollableOverflowForPerspective(aScrolledFrame, child, aScrollPort,
                                            offset, aScrolledFrameOverflowArea);
      }

      // If we're transformed, then we want to consider the possibility that
      // this frame might move relative to the scrolled frame when scrolling.
      // For preserve-3d, leaf frames have correct overflow rects relative to
      // themselves. preserve-3d 'nodes' (intermediate frames and the root) have
      // only their untransformed children included in their overflow relative
      // to self, which is what we want to include here.
      if (child->IsTransformed()) {
        // Compute the overflow rect for this leaf transform frame in the
        // coordinate space of the scrolled frame.
        nsPoint scrollPos = aScrolledFrame->GetPosition();
        nsRect preScroll, postScroll;
        {
          // TODO: Can we reuse the reference box?
          TransformReferenceBox refBox(child);
          preScroll = nsDisplayTransform::TransformRect(
              child->ScrollableOverflowRectRelativeToSelf(), child, refBox);
        }

        // Temporarily override the scroll position of the scrolled frame by
        // 10 CSS pixels, and then recompute what the overflow rect would be.
        // This scroll position may not be valid, but that shouldn't matter
        // for our calculations.
        {
          aScrolledFrame->SetPosition(scrollPos + nsPoint(600, 600));
          TransformReferenceBox refBox(child);
          postScroll = nsDisplayTransform::TransformRect(
              child->ScrollableOverflowRectRelativeToSelf(), child, refBox);
          aScrolledFrame->SetPosition(scrollPos);
        }

        // Compute how many app units the overflow rects moves by when we adjust
        // the scroll position by 1 app unit.
        double rightDelta =
            (postScroll.XMost() - preScroll.XMost() + 600.0) / 600.0;
        double bottomDelta =
            (postScroll.YMost() - preScroll.YMost() + 600.0) / 600.0;

        // We can't ever have negative scrolling.
        NS_ASSERTION(rightDelta > 0.0f && bottomDelta > 0.0f,
                     "Scrolling can't be reversed!");

        // Move preScroll into the coordinate space of the scrollport.
        preScroll += offset + scrollPos;

        // For each of the four edges of preScroll, figure out how far they
        // extend beyond the scrollport. Ignore negative values since that means
        // that side is already scrolled in to view and we don't need to add
        // overflow to account for it.
        nsMargin overhang(std::max(0, aScrollPort.Y() - preScroll.Y()),
                          std::max(0, preScroll.XMost() - aScrollPort.XMost()),
                          std::max(0, preScroll.YMost() - aScrollPort.YMost()),
                          std::max(0, aScrollPort.X() - preScroll.X()));

        // Scale according to rightDelta/bottomDelta to adjust for the different
        // scroll rates.
        overhang.top = NSCoordSaturatingMultiply(
            overhang.top, static_cast<float>(1 / bottomDelta));
        overhang.right = NSCoordSaturatingMultiply(
            overhang.right, static_cast<float>(1 / rightDelta));
        overhang.bottom = NSCoordSaturatingMultiply(
            overhang.bottom, static_cast<float>(1 / bottomDelta));
        overhang.left = NSCoordSaturatingMultiply(
            overhang.left, static_cast<float>(1 / rightDelta));

        // Take the minimum overflow rect that would allow the current scroll
        // position, using the size of the scroll port and offset by the
        // inverse of the scroll position.
        nsRect overflow = aScrollPort - scrollPos;

        // Expand it by our margins to get an overflow rect that would allow all
        // edges of our transformed content to be scrolled into view.
        overflow.Inflate(overhang);

        // Merge it with the combined overflow
        aScrolledFrameOverflowArea.UnionRect(aScrolledFrameOverflowArea,
                                             overflow);
      } else if (aCurrentFrame == aScrolledFrame) {
        aScrolledFrameOverflowArea.UnionRect(
            aScrolledFrameOverflowArea,
            child->ScrollableOverflowRectRelativeToParent());
      }
    }
  }
}

BaselineSharingGroup nsHTMLScrollFrame::GetDefaultBaselineSharingGroup() const {
  return mScrolledFrame->GetDefaultBaselineSharingGroup();
}

nscoord nsHTMLScrollFrame::SynthesizeFallbackBaseline(
    mozilla::WritingMode aWM, BaselineSharingGroup aBaselineGroup) const {
  // Marign-end even for central baselines.
  if (aWM.IsLineInverted()) {
    return -GetLogicalUsedMargin(aWM).BStart(aWM);
  }
  return aBaselineGroup == BaselineSharingGroup::First
             ? BSize(aWM) + GetLogicalUsedMargin(aWM).BEnd(aWM)
             : -GetLogicalUsedMargin(aWM).BEnd(aWM);
}

Maybe<nscoord> nsHTMLScrollFrame::GetNaturalBaselineBOffset(
    WritingMode aWM, BaselineSharingGroup aBaselineGroup,
    BaselineExportContext aExportContext) const {
  // Block containers that are scrollable always have a last baseline
  // that are synthesized from block-end margin edge.
  // Note(dshin): This behaviour is really only relevant to `inline-block`
  // alignment context. In the context of table/flex/grid alignment, first/last
  // baselines are calculated through `GetFirstLineBaseline`, which does
  // calculations of its own.
  // https://drafts.csswg.org/css-align/#baseline-export
  if (aExportContext == BaselineExportContext::LineLayout &&
      aBaselineGroup == BaselineSharingGroup::Last &&
      mScrolledFrame->IsBlockFrameOrSubclass()) {
    return Some(SynthesizeFallbackBaseline(aWM, aBaselineGroup));
  }

  if (StyleDisplay()->IsContainLayout()) {
    return Nothing{};
  }

  // OK, here's where we defer to our scrolled frame.
  return mScrolledFrame
      ->GetNaturalBaselineBOffset(aWM, aBaselineGroup, aExportContext)
      .map([this, aWM](nscoord aBaseline) {
        // We have to add our border BStart thickness to whatever it returns, to
        // produce an offset in our frame-rect's coordinate system. (We don't
        // have to add padding, because the scrolled frame handles our padding.)
        LogicalMargin border = GetLogicalUsedBorder(aWM);
        const auto bSize = GetLogicalSize(aWM).BSize(aWM);
        // Clamp the baseline to the border rect. See bug 1791069.
        return std::clamp(border.BStart(aWM) + aBaseline, 0, bSize);
      });
}

void nsHTMLScrollFrame::AdjustForPerspective(nsRect& aScrollableOverflow) {
  // If we have perspective that is being applied to our children, then
  // the effective transform on the child depends on the relative position
  // of the child to us and changes during scrolling.
  if (!ChildrenHavePerspective()) {
    return;
  }
  aScrollableOverflow.SetEmpty();
  GetScrollableOverflowForPerspective(mScrolledFrame, mScrolledFrame,
                                      ScrollPort(), nsPoint(),
                                      aScrollableOverflow);
}

void nsHTMLScrollFrame::Reflow(nsPresContext* aPresContext,
                               ReflowOutput& aDesiredSize,
                               const ReflowInput& aReflowInput,
                               nsReflowStatus& aStatus) {
  MarkInReflow();
  DO_GLOBAL_REFLOW_COUNT("nsHTMLScrollFrame");
  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");

  HandleScrollbarStyleSwitching();

  ScrollReflowInput state(this, aReflowInput);

  //------------ Handle Incremental Reflow -----------------
  bool reflowHScrollbar = true;
  bool reflowVScrollbar = true;
  bool reflowScrollCorner = true;
  if (!aReflowInput.ShouldReflowAllKids()) {
    auto NeedsReflow = [](const nsIFrame* aFrame) {
      return aFrame && aFrame->IsSubtreeDirty();
    };

    reflowHScrollbar = NeedsReflow(mHScrollbarBox);
    reflowVScrollbar = NeedsReflow(mVScrollbarBox);
    reflowScrollCorner =
        NeedsReflow(mScrollCornerBox) || NeedsReflow(mResizerBox);
  }

  if (mIsRoot) {
    reflowScrollCorner = false;
  }

  const nsRect oldScrollPort = ScrollPort();
  nsRect oldScrolledAreaBounds =
      mScrolledFrame->ScrollableOverflowRectRelativeToParent();
  nsPoint oldScrollPosition = GetScrollPosition();

  ReflowContents(state, aDesiredSize);

  nsSize layoutSize =
      mIsUsingMinimumScaleSize ? mMinimumScaleSize : state.mInsideBorderSize;
  aDesiredSize.Width() = layoutSize.width + state.mComputedBorder.LeftRight();
  aDesiredSize.Height() = layoutSize.height + state.mComputedBorder.TopBottom();

  // Set the size of the frame now since computing the perspective-correct
  // overflow (within PlaceScrollArea) can rely on it.
  SetSize(aDesiredSize.GetWritingMode(),
          aDesiredSize.Size(aDesiredSize.GetWritingMode()));

  // Restore the old scroll position, for now, even if that's not valid anymore
  // because we changed size. We'll fix it up in a post-reflow callback, because
  // our current size may only be temporary (e.g. we're compute XUL desired
  // sizes).
  PlaceScrollArea(state, oldScrollPosition);
  if (!mPostedReflowCallback) {
    // Make sure we'll try scrolling to restored position
    PresShell()->PostReflowCallback(this);
    mPostedReflowCallback = true;
  }

  bool didOnlyHScrollbar = mOnlyNeedHScrollbarToScrollVVInsideLV;
  bool didOnlyVScrollbar = mOnlyNeedVScrollbarToScrollVVInsideLV;
  mOnlyNeedHScrollbarToScrollVVInsideLV =
      state.mOnlyNeedHScrollbarToScrollVVInsideLV;
  mOnlyNeedVScrollbarToScrollVVInsideLV =
      state.mOnlyNeedVScrollbarToScrollVVInsideLV;

  bool didHaveHScrollbar = mHasHorizontalScrollbar;
  bool didHaveVScrollbar = mHasVerticalScrollbar;
  mHasHorizontalScrollbar = state.mShowHScrollbar;
  mHasVerticalScrollbar = state.mShowVScrollbar;
  const nsRect& newScrollPort = ScrollPort();
  nsRect newScrolledAreaBounds =
      mScrolledFrame->ScrollableOverflowRectRelativeToParent();
  if (mSkippedScrollbarLayout || reflowHScrollbar || reflowVScrollbar ||
      reflowScrollCorner || HasAnyStateBits(NS_FRAME_IS_DIRTY) ||
      didHaveHScrollbar != state.mShowHScrollbar ||
      didHaveVScrollbar != state.mShowVScrollbar ||
      didOnlyHScrollbar != mOnlyNeedHScrollbarToScrollVVInsideLV ||
      didOnlyVScrollbar != mOnlyNeedVScrollbarToScrollVVInsideLV ||
      !oldScrollPort.IsEqualEdges(newScrollPort) ||
      !oldScrolledAreaBounds.IsEqualEdges(newScrolledAreaBounds)) {
    if (!mSuppressScrollbarUpdate) {
      mSkippedScrollbarLayout = false;
      nsHTMLScrollFrame::SetScrollbarVisibility(mHScrollbarBox,
                                                state.mShowHScrollbar);
      nsHTMLScrollFrame::SetScrollbarVisibility(mVScrollbarBox,
                                                state.mShowVScrollbar);
      // place and reflow scrollbars
      const nsRect insideBorderArea(
          nsPoint(state.mComputedBorder.left, state.mComputedBorder.top),
          layoutSize);
      LayoutScrollbars(state, insideBorderArea, oldScrollPort);
    } else {
      mSkippedScrollbarLayout = true;
    }
  }
  if (mIsRoot) {
    if (RefPtr<MobileViewportManager> manager =
            PresShell()->GetMobileViewportManager()) {
      // Note that this runs during layout, and when we get here the root
      // scrollframe has already been laid out. It may have added or removed
      // scrollbars as a result of that layout, so we need to ensure the
      // visual viewport is updated to account for that before we read the
      // visual viewport size.
      manager->UpdateVisualViewportSizeForPotentialScrollbarChange();
    } else if (oldScrollPort.Size() != newScrollPort.Size()) {
      // We want to make sure to send a visual viewport resize event if the
      // scrollport changed sizes for root scroll frames. The
      // MobileViewportManager will do that, but if we don't have one (ie we
      // aren't a root content document for example) we have to send one
      // ourselves.
      if (auto* window = nsGlobalWindowInner::Cast(
              aPresContext->Document()->GetInnerWindow())) {
        window->VisualViewport()->PostResizeEvent();
      }
    }
  }

  // Note that we need to do this after the
  // UpdateVisualViewportSizeForPotentialScrollbarChange call above because that
  // is what updates the visual viewport size and we need it to be up to date.
  if (mIsRoot && !state.OverlayScrollbars() &&
      (didHaveHScrollbar != state.mShowHScrollbar ||
       didHaveVScrollbar != state.mShowVScrollbar ||
       didOnlyHScrollbar != mOnlyNeedHScrollbarToScrollVVInsideLV ||
       didOnlyVScrollbar != mOnlyNeedVScrollbarToScrollVVInsideLV) &&
      PresShell()->IsVisualViewportOffsetSet()) {
    // Removing layout/classic scrollbars can make a previously valid vvoffset
    // invalid. For example, if we are zoomed in on an overflow hidden document
    // and then zoom back out, when apz reaches the initial resolution (ie 1.0)
    // it won't know that we can remove the scrollbars, so the vvoffset can
    // validly be upto the width/height of the scrollbars. After we reflow and
    // remove the scrollbars the only valid vvoffset is (0,0). We could wait
    // until we send the new frame metrics to apz and then have it reply with
    // the new corrected vvoffset but having an inconsistent vvoffset causes
    // problems so trigger the vvoffset to be re-set and re-clamped in
    // ReflowFinished.
    mReclampVVOffsetInReflowFinished = true;
  }

  aDesiredSize.SetOverflowAreasToDesiredBounds();

  UpdateSticky();
  FinishReflowWithAbsoluteFrames(aPresContext, aDesiredSize, aReflowInput,
                                 aStatus);

  if (!InInitialReflow() && !mHadNonInitialReflow) {
    mHadNonInitialReflow = true;
  }

  if (mIsRoot && !oldScrolledAreaBounds.IsEqualEdges(newScrolledAreaBounds)) {
    PostScrolledAreaEvent();
  }

  UpdatePrevScrolledRect();

  aStatus.Reset();  // This type of frame can't be split.
  PostOverflowEvent();
}

void nsHTMLScrollFrame::DidReflow(nsPresContext* aPresContext,
                                  const ReflowInput* aReflowInput) {
  nsContainerFrame::DidReflow(aPresContext, aReflowInput);
  if (NeedsResnap()) {
    PostPendingResnap();
  } else {
    PresShell()->PostPendingScrollAnchorAdjustment(Anchor());
  }
}

////////////////////////////////////////////////////////////////////////////////

#ifdef DEBUG_FRAME_DUMP
nsresult nsHTMLScrollFrame::GetFrameName(nsAString& aResult) const {
  return MakeFrameName(u"HTMLScroll"_ns, aResult);
}
#endif

#ifdef ACCESSIBILITY
a11y::AccType nsHTMLScrollFrame::AccessibleType() {
  if (IsTableCaption()) {
    return GetRect().IsEmpty() ? a11y::eNoType : a11y::eHTMLCaptionType;
  }

  // Create an accessible regardless of focusable state because the state can be
  // changed during frame life cycle without any notifications to accessibility.
  if (mContent->IsRootOfNativeAnonymousSubtree() ||
      GetScrollStyles().IsHiddenInBothDirections()) {
    return a11y::eNoType;
  }

  return a11y::eHyperTextType;
}
#endif

NS_QUERYFRAME_HEAD(nsHTMLScrollFrame)
  NS_QUERYFRAME_ENTRY(nsIAnonymousContentCreator)
  NS_QUERYFRAME_ENTRY(nsIScrollableFrame)
  NS_QUERYFRAME_ENTRY(nsIStatefulFrame)
  NS_QUERYFRAME_ENTRY(nsIScrollbarMediator)
  NS_QUERYFRAME_ENTRY(nsHTMLScrollFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)

nsMargin nsHTMLScrollFrame::GetDesiredScrollbarSizes() const {
  nsPresContext* pc = PresContext();
  if (pc->UseOverlayScrollbars()) {
    return {};
  }

  const auto& style = *nsLayoutUtils::StyleForScrollbar(this);
  const auto scrollbarWidth = style.StyleUIReset()->ScrollbarWidth();
  if (scrollbarWidth == StyleScrollbarWidth::None) {
    return {};
  }

  ScrollStyles styles = GetScrollStyles();
  nsMargin result(0, 0, 0, 0);

  auto size = GetNonOverlayScrollbarSize(pc, scrollbarWidth);
  if (styles.mVertical != StyleOverflow::Hidden) {
    if (IsScrollbarOnRight()) {
      result.right = size;
    } else {
      result.left = size;
    }
  }

  if (styles.mHorizontal != StyleOverflow::Hidden) {
    // We don't currently support any scripts that would require a scrollbar
    // at the top. (Are there any?)
    result.bottom = size;
  }

  return result;
}

nscoord nsHTMLScrollFrame::GetNonOverlayScrollbarSize(
    const nsPresContext* aPc, StyleScrollbarWidth aScrollbarWidth) {
  const auto size = aPc->Theme()->GetScrollbarSize(aPc, aScrollbarWidth,
                                                   nsITheme::Overlay::No);
  return aPc->DevPixelsToAppUnits(size);
}

void nsHTMLScrollFrame::HandleScrollbarStyleSwitching() {
  // Check if we switched between scrollbar styles.
  if (mScrollbarActivity && !UsesOverlayScrollbars()) {
    mScrollbarActivity->Destroy();
    mScrollbarActivity = nullptr;
  } else if (!mScrollbarActivity && UsesOverlayScrollbars()) {
    mScrollbarActivity = new ScrollbarActivity(do_QueryFrame(this));
  }
}

#if defined(MOZ_WIDGET_ANDROID)
static bool IsFocused(nsIContent* aContent) {
  // Some content elements, like the GetContent() of a scroll frame
  // for a text input field, are inside anonymous subtrees, but the focus
  // manager always reports a non-anonymous element as the focused one, so
  // walk up the tree until we reach a non-anonymous element.
  while (aContent && aContent->IsInNativeAnonymousSubtree()) {
    aContent = aContent->GetParent();
  }

  return aContent ? nsContentUtils::IsFocusedContent(aContent) : false;
}
#endif

void nsHTMLScrollFrame::SetScrollableByAPZ(bool aScrollable) {
  mScrollableByAPZ = aScrollable;
}

void nsHTMLScrollFrame::SetZoomableByAPZ(bool aZoomable) {
  if (!nsLayoutUtils::UsesAsyncScrolling(this)) {
    // If APZ is disabled on this window, then we're never actually going to
    // do any zooming. So we don't need to do any of the setup for it. Note
    // that this function gets called from ZoomConstraintsClient even if APZ
    // is disabled to indicate the zoomability of content.
    aZoomable = false;
  }
  if (mZoomableByAPZ != aZoomable) {
    // We might be changing the result of DecideScrollableLayer() so schedule a
    // paint to make sure we pick up the result of that change.
    mZoomableByAPZ = aZoomable;
    SchedulePaint();
  }
}

void nsHTMLScrollFrame::SetHasOutOfFlowContentInsideFilter() {
  mHasOutOfFlowContentInsideFilter = true;
}

bool nsHTMLScrollFrame::WantAsyncScroll() const {
  ScrollStyles styles = GetScrollStyles();

  // First, as an optimization because getting the scrollrange is
  // relatively slow, check overflow hidden and not a zoomed scroll frame.
  if (styles.mHorizontal == StyleOverflow::Hidden &&
      styles.mVertical == StyleOverflow::Hidden) {
    if (!mIsRoot || GetVisualViewportSize() == mScrollPort.Size()) {
      return false;
    }
  }

  nscoord oneDevPixel =
      GetScrolledFrame()->PresContext()->AppUnitsPerDevPixel();
  nsRect scrollRange = GetLayoutScrollRange();

  bool isVScrollable = (scrollRange.height >= oneDevPixel) &&
                       (styles.mVertical != StyleOverflow::Hidden);
  bool isHScrollable = (scrollRange.width >= oneDevPixel) &&
                       (styles.mHorizontal != StyleOverflow::Hidden);

#if defined(MOZ_WIDGET_ANDROID)
  // Mobile platforms need focus to scroll text inputs.
  bool canScrollWithoutScrollbars =
      !IsForTextControlWithNoScrollbars() || IsFocused(GetContent());
#else
  bool canScrollWithoutScrollbars = true;
#endif

  // The check for scroll bars was added in bug 825692 to prevent layerization
  // of text inputs for performance reasons.
  bool isVAsyncScrollable =
      isVScrollable && (mVScrollbarBox || canScrollWithoutScrollbars);
  bool isHAsyncScrollable =
      isHScrollable && (mHScrollbarBox || canScrollWithoutScrollbars);
  if (isVAsyncScrollable || isHAsyncScrollable) {
    return true;
  }

  // If the page has a visual viewport size that's different from
  // the layout viewport size at the current zoom level, we need to be
  // able to scroll the visual viewport inside the layout viewport
  // even if the page is not zoomable.
  return mIsRoot && GetVisualViewportSize() != mScrollPort.Size() &&
         !GetVisualScrollRange().IsEqualInterior(scrollRange);
}

static nsRect GetOnePixelRangeAroundPoint(const nsPoint& aPoint,
                                          bool aIsHorizontal) {
  nsRect allowedRange(aPoint, nsSize());
  nscoord halfPixel = nsPresContext::CSSPixelsToAppUnits(0.5f);
  if (aIsHorizontal) {
    allowedRange.x = aPoint.x - halfPixel;
    allowedRange.width = halfPixel * 2 - 1;
  } else {
    allowedRange.y = aPoint.y - halfPixel;
    allowedRange.height = halfPixel * 2 - 1;
  }
  return allowedRange;
}

void nsHTMLScrollFrame::ScrollByPage(nsScrollbarFrame* aScrollbar,
                                     int32_t aDirection,
                                     ScrollSnapFlags aSnapFlags) {
  ScrollByUnit(aScrollbar, ScrollMode::Smooth, aDirection, ScrollUnit::PAGES,
               aSnapFlags);
}

void nsHTMLScrollFrame::ScrollByWhole(nsScrollbarFrame* aScrollbar,
                                      int32_t aDirection,
                                      ScrollSnapFlags aSnapFlags) {
  ScrollByUnit(aScrollbar, ScrollMode::Instant, aDirection, ScrollUnit::WHOLE,
               aSnapFlags);
}

void nsHTMLScrollFrame::ScrollByLine(nsScrollbarFrame* aScrollbar,
                                     int32_t aDirection,
                                     ScrollSnapFlags aSnapFlags) {
  bool isHorizontal = aScrollbar->IsHorizontal();
  nsIntPoint delta;
  if (isHorizontal) {
    const double kScrollMultiplier =
        StaticPrefs::toolkit_scrollbox_horizontalScrollDistance();
    delta.x = static_cast<int32_t>(aDirection * kScrollMultiplier);
    if (GetLineScrollAmount().width * delta.x > GetPageScrollAmount().width) {
      // The scroll frame is so small that the delta would be more
      // than an entire page.  Scroll by one page instead to maintain
      // context.
      ScrollByPage(aScrollbar, aDirection);
      return;
    }
  } else {
    const double kScrollMultiplier =
        StaticPrefs::toolkit_scrollbox_verticalScrollDistance();
    delta.y = static_cast<int32_t>(aDirection * kScrollMultiplier);
    if (GetLineScrollAmount().height * delta.y > GetPageScrollAmount().height) {
      // The scroll frame is so small that the delta would be more
      // than an entire page.  Scroll by one page instead to maintain
      // context.
      ScrollByPage(aScrollbar, aDirection);
      return;
    }
  }

  nsIntPoint overflow;
  ScrollBy(delta, ScrollUnit::LINES, ScrollMode::Smooth, &overflow,
           ScrollOrigin::Other, nsIScrollableFrame::NOT_MOMENTUM, aSnapFlags);
}

void nsHTMLScrollFrame::RepeatButtonScroll(nsScrollbarFrame* aScrollbar) {
  aScrollbar->MoveToNewPosition(nsScrollbarFrame::ImplementsScrollByUnit::Yes);
}

void nsHTMLScrollFrame::ThumbMoved(nsScrollbarFrame* aScrollbar,
                                   nscoord aOldPos, nscoord aNewPos) {
  MOZ_ASSERT(aScrollbar != nullptr);
  bool isHorizontal = aScrollbar->IsHorizontal();
  nsPoint current = GetScrollPosition();
  nsPoint dest = current;
  if (isHorizontal) {
    dest.x = IsPhysicalLTR() ? aNewPos : aNewPos - GetLayoutScrollRange().width;
  } else {
    dest.y = aNewPos;
  }
  nsRect allowedRange = GetOnePixelRangeAroundPoint(dest, isHorizontal);

  // Don't try to scroll if we're already at an acceptable place.
  // Don't call Contains here since Contains returns false when the point is
  // on the bottom or right edge of the rectangle.
  if (allowedRange.ClampPoint(current) == current) {
    return;
  }

  ScrollToWithOrigin(
      dest, &allowedRange,
      ScrollOperationParams{ScrollMode::Instant, ScrollOrigin::Other});
}

void nsHTMLScrollFrame::ScrollbarReleased(nsScrollbarFrame* aScrollbar) {
  // Scrollbar scrolling does not result in fling gestures, clear any
  // accumulated velocity
  mVelocityQueue.Reset();

  // Perform scroll snapping, if needed.  Scrollbar movement uses the same
  // smooth scrolling animation as keyboard scrolling.
  ScrollSnap(mDestination, ScrollMode::Smooth);
}

void nsHTMLScrollFrame::ScrollByUnit(nsScrollbarFrame* aScrollbar,
                                     ScrollMode aMode, int32_t aDirection,
                                     ScrollUnit aUnit,
                                     ScrollSnapFlags aSnapFlags) {
  MOZ_ASSERT(aScrollbar != nullptr);
  bool isHorizontal = aScrollbar->IsHorizontal();
  nsIntPoint delta;
  if (isHorizontal) {
    delta.x = aDirection;
  } else {
    delta.y = aDirection;
  }
  nsIntPoint overflow;
  ScrollBy(delta, aUnit, aMode, &overflow, ScrollOrigin::Other,
           nsIScrollableFrame::NOT_MOMENTUM, aSnapFlags);
}

//-------------------- Helper ----------------------

// AsyncSmoothMSDScroll has ref counting.
class nsHTMLScrollFrame::AsyncSmoothMSDScroll final
    : public nsARefreshObserver {
 public:
  AsyncSmoothMSDScroll(const nsPoint& aInitialPosition,
                       const nsPoint& aInitialDestination,
                       const nsSize& aInitialVelocity, const nsRect& aRange,
                       const mozilla::TimeStamp& aStartTime,
                       nsPresContext* aPresContext,
                       UniquePtr<ScrollSnapTargetIds> aSnapTargetIds,
                       ScrollTriggeredByScript aTriggeredByScript)
      : mXAxisModel(aInitialPosition.x, aInitialDestination.x,
                    aInitialVelocity.width,
                    StaticPrefs::layout_css_scroll_behavior_spring_constant(),
                    StaticPrefs::layout_css_scroll_behavior_damping_ratio()),
        mYAxisModel(aInitialPosition.y, aInitialDestination.y,
                    aInitialVelocity.height,
                    StaticPrefs::layout_css_scroll_behavior_spring_constant(),
                    StaticPrefs::layout_css_scroll_behavior_damping_ratio()),
        mRange(aRange),
        mStartPosition(aInitialPosition),
        mLastRefreshTime(aStartTime),
        mCallee(nullptr),
        mOneDevicePixelInAppUnits(aPresContext->DevPixelsToAppUnits(1)),
        mSnapTargetIds(std::move(aSnapTargetIds)),
        mTriggeredByScript(aTriggeredByScript) {
    Telemetry::SetHistogramRecordingEnabled(
        Telemetry::FX_REFRESH_DRIVER_SYNC_SCROLL_FRAME_DELAY_MS, true);
  }

  NS_INLINE_DECL_REFCOUNTING(AsyncSmoothMSDScroll, override)

  nsSize GetVelocity() {
    // In nscoords per second
    return nsSize(mXAxisModel.GetVelocity(), mYAxisModel.GetVelocity());
  }

  nsPoint GetPosition() {
    // In nscoords
    return nsPoint(NSToCoordRound(mXAxisModel.GetPosition()),
                   NSToCoordRound(mYAxisModel.GetPosition()));
  }

  void SetDestination(const nsPoint& aDestination,
                      ScrollTriggeredByScript aTriggeredByScript) {
    mXAxisModel.SetDestination(static_cast<int32_t>(aDestination.x));
    mYAxisModel.SetDestination(static_cast<int32_t>(aDestination.y));
    mTriggeredByScript = aTriggeredByScript;
  }

  void SetRange(const nsRect& aRange) { mRange = aRange; }

  nsRect GetRange() { return mRange; }

  nsPoint GetStartPosition() { return mStartPosition; }

  void Simulate(const TimeDuration& aDeltaTime) {
    mXAxisModel.Simulate(aDeltaTime);
    mYAxisModel.Simulate(aDeltaTime);

    nsPoint desired = GetPosition();
    nsPoint clamped = mRange.ClampPoint(desired);
    if (desired.x != clamped.x) {
      // The scroll has hit the "wall" at the left or right edge of the allowed
      // scroll range.
      // Absorb the impact to avoid bounceback effect.
      mXAxisModel.SetVelocity(0.0);
      mXAxisModel.SetPosition(clamped.x);
    }

    if (desired.y != clamped.y) {
      // The scroll has hit the "wall" at the left or right edge of the allowed
      // scroll range.
      // Absorb the impact to avoid bounceback effect.
      mYAxisModel.SetVelocity(0.0);
      mYAxisModel.SetPosition(clamped.y);
    }
  }

  bool IsFinished() {
    return mXAxisModel.IsFinished(mOneDevicePixelInAppUnits) &&
           mYAxisModel.IsFinished(mOneDevicePixelInAppUnits);
  }

  virtual void WillRefresh(mozilla::TimeStamp aTime) override {
    mozilla::TimeDuration deltaTime = aTime - mLastRefreshTime;
    mLastRefreshTime = aTime;

    // The callback may release "this".
    // We don't access members after returning, so no need for KungFuDeathGrip.
    nsHTMLScrollFrame::AsyncSmoothMSDScrollCallback(mCallee, deltaTime);
  }

  /*
   * Set a refresh observer for smooth scroll iterations (and start observing).
   * Should be used at most once during the lifetime of this object.
   */
  void SetRefreshObserver(nsHTMLScrollFrame* aCallee) {
    MOZ_ASSERT(aCallee,
               "AsyncSmoothMSDScroll::SetRefreshObserver needs "
               "a non-null aCallee in order to get a refresh driver");
    MOZ_RELEASE_ASSERT(!mCallee,
                       "AsyncSmoothMSDScroll::SetRefreshObserver "
                       "shouldn't be called if we're already registered with "
                       "a refresh driver, via a preexisting mCallee");

    RefreshDriver(aCallee)->AddRefreshObserver(this, FlushType::Style,
                                               "Smooth scroll (MSD) animation");
    mCallee = aCallee;
  }

  /**
   * The mCallee holds a strong ref to us since the refresh driver doesn't.
   * Our dtor and mCallee's Destroy() method both call RemoveObserver() -
   * whichever comes first removes us from the refresh driver.
   */
  void RemoveObserver() {
    if (mCallee) {
      RefreshDriver(mCallee)->RemoveRefreshObserver(this, FlushType::Style);
      mCallee = nullptr;
    }
  }

  UniquePtr<ScrollSnapTargetIds> TakeSnapTargetIds() {
    return std::move(mSnapTargetIds);
  }

  bool WasTriggeredByScript() const {
    return mTriggeredByScript == ScrollTriggeredByScript::Yes;
  }

 private:
  // Private destructor, to discourage deletion outside of Release():
  ~AsyncSmoothMSDScroll() {
    RemoveObserver();
    Telemetry::SetHistogramRecordingEnabled(
        Telemetry::FX_REFRESH_DRIVER_SYNC_SCROLL_FRAME_DELAY_MS, false);
  }

  nsRefreshDriver* RefreshDriver(nsHTMLScrollFrame* aCallee) {
    return aCallee->PresContext()->RefreshDriver();
  }

  mozilla::layers::AxisPhysicsMSDModel mXAxisModel, mYAxisModel;
  nsRect mRange;
  nsPoint mStartPosition;
  mozilla::TimeStamp mLastRefreshTime;
  nsHTMLScrollFrame* mCallee;
  nscoord mOneDevicePixelInAppUnits;
  UniquePtr<ScrollSnapTargetIds> mSnapTargetIds;
  ScrollTriggeredByScript mTriggeredByScript;
};

// AsyncScroll has ref counting.
class nsHTMLScrollFrame::AsyncScroll final : public nsARefreshObserver {
 public:
  typedef mozilla::TimeStamp TimeStamp;
  typedef mozilla::TimeDuration TimeDuration;

  explicit AsyncScroll(UniquePtr<ScrollSnapTargetIds> aSnapTargetIds,
                       ScrollTriggeredByScript aTriggeredByScript)
      : mOrigin(ScrollOrigin::NotSpecified),
        mCallee(nullptr),
        mSnapTargetIds(std::move(aSnapTargetIds)),
        mTriggeredByScript(aTriggeredByScript) {
    Telemetry::SetHistogramRecordingEnabled(
        Telemetry::FX_REFRESH_DRIVER_SYNC_SCROLL_FRAME_DELAY_MS, true);
  }

 private:
  // Private destructor, to discourage deletion outside of Release():
  ~AsyncScroll() {
    RemoveObserver();
    Telemetry::SetHistogramRecordingEnabled(
        Telemetry::FX_REFRESH_DRIVER_SYNC_SCROLL_FRAME_DELAY_MS, false);
  }

 public:
  void InitSmoothScroll(TimeStamp aTime, nsPoint aInitialPosition,
                        nsPoint aDestination, ScrollOrigin aOrigin,
                        const nsRect& aRange, const nsSize& aCurrentVelocity);
  void Init(nsPoint aInitialPosition, const nsRect& aRange) {
    mAnimationPhysics = nullptr;
    mRange = aRange;
    mStartPosition = aInitialPosition;
  }

  bool IsSmoothScroll() { return mAnimationPhysics != nullptr; }

  bool IsFinished(const TimeStamp& aTime) const {
    MOZ_RELEASE_ASSERT(mAnimationPhysics);
    return mAnimationPhysics->IsFinished(aTime);
  }

  nsPoint PositionAt(const TimeStamp& aTime) const {
    MOZ_RELEASE_ASSERT(mAnimationPhysics);
    return mAnimationPhysics->PositionAt(aTime);
  }

  nsSize VelocityAt(const TimeStamp& aTime) const {
    MOZ_RELEASE_ASSERT(mAnimationPhysics);
    return mAnimationPhysics->VelocityAt(aTime);
  }

  nsPoint GetStartPosition() const { return mStartPosition; }

  // Most recent scroll origin.
  ScrollOrigin mOrigin;

  // Allowed destination positions around mDestination
  nsRect mRange;

  // Initial position where the async scroll was triggered.
  nsPoint mStartPosition;

 private:
  void InitPreferences(TimeStamp aTime, nsAtom* aOrigin);

  UniquePtr<ScrollAnimationPhysics> mAnimationPhysics;

  // The next section is observer/callback management
  // Bodies of WillRefresh and RefreshDriver contain nsHTMLScrollFrame specific
  // code.
 public:
  NS_INLINE_DECL_REFCOUNTING(AsyncScroll, override)

  /*
   * Set a refresh observer for smooth scroll iterations (and start observing).
   * Should be used at most once during the lifetime of this object.
   */
  void SetRefreshObserver(nsHTMLScrollFrame* aCallee) {
    MOZ_ASSERT(aCallee,
               "AsyncScroll::SetRefreshObserver needs "
               "a non-null aCallee in order to get a refresh driver");
    MOZ_RELEASE_ASSERT(!mCallee,
                       "AsyncScroll::SetRefreshObserver "
                       "shouldn't be called if we're already registered with "
                       "a refresh driver, via a preexisting mCallee");

    RefreshDriver(aCallee)->AddRefreshObserver(this, FlushType::Style,
                                               "Smooth scroll animation");
    mCallee = aCallee;
    auto* presShell = mCallee->PresShell();
    MOZ_ASSERT(presShell);
    presShell->SuppressDisplayport(true);
  }

  virtual void WillRefresh(mozilla::TimeStamp aTime) override {
    // The callback may release "this".
    // We don't access members after returning, so no need for KungFuDeathGrip.
    nsHTMLScrollFrame::AsyncScrollCallback(mCallee, aTime);
  }

  /**
   * The mCallee holds a strong ref to us since the refresh driver doesn't.
   * Our dtor and mCallee's Destroy() method both call RemoveObserver() -
   * whichever comes first removes us from the refresh driver.
   */
  void RemoveObserver() {
    if (mCallee) {
      RefreshDriver(mCallee)->RemoveRefreshObserver(this, FlushType::Style);
      auto* presShell = mCallee->PresShell();
      MOZ_ASSERT(presShell);
      presShell->SuppressDisplayport(false);
      mCallee = nullptr;
    }
  }

  UniquePtr<ScrollSnapTargetIds> TakeSnapTargetIds() {
    return std::move(mSnapTargetIds);
  }

  bool WasTriggeredByScript() const {
    return mTriggeredByScript == ScrollTriggeredByScript::Yes;
  }

 private:
  nsHTMLScrollFrame* mCallee;
  UniquePtr<ScrollSnapTargetIds> mSnapTargetIds;
  ScrollTriggeredByScript mTriggeredByScript;

  nsRefreshDriver* RefreshDriver(nsHTMLScrollFrame* aCallee) {
    return aCallee->PresContext()->RefreshDriver();
  }
};

void nsHTMLScrollFrame::AsyncScroll::InitSmoothScroll(
    TimeStamp aTime, nsPoint aInitialPosition, nsPoint aDestination,
    ScrollOrigin aOrigin, const nsRect& aRange,
    const nsSize& aCurrentVelocity) {
  switch (aOrigin) {
    case ScrollOrigin::NotSpecified:
    case ScrollOrigin::Restore:
    case ScrollOrigin::Relative:
      // We don't have special prefs for "restore", just treat it as "other".
      // "restore" scrolls are (for now) always instant anyway so unless
      // something changes we should never have aOrigin ==
      // ScrollOrigin::Restore here.
      aOrigin = ScrollOrigin::Other;
      break;
    case ScrollOrigin::Apz:
      // Likewise we should never get APZ-triggered scrolls here, and if that
      // changes something is likely broken somewhere.
      MOZ_ASSERT(false);
      break;
    default:
      break;
  };

  // Read preferences only on first iteration or for a different event origin.
  if (!mAnimationPhysics || aOrigin != mOrigin) {
    mOrigin = aOrigin;
    if (StaticPrefs::general_smoothScroll_msdPhysics_enabled()) {
      mAnimationPhysics =
          MakeUnique<ScrollAnimationMSDPhysics>(aInitialPosition);
    } else {
      ScrollAnimationBezierPhysicsSettings settings =
          layers::apz::ComputeBezierAnimationSettingsForOrigin(mOrigin);
      mAnimationPhysics =
          MakeUnique<ScrollAnimationBezierPhysics>(aInitialPosition, settings);
    }
  }

  mStartPosition = aInitialPosition;
  mRange = aRange;

  mAnimationPhysics->Update(aTime, aDestination, aCurrentVelocity);
}

/*
 * Callback function from AsyncSmoothMSDScroll, used in
 * nsHTMLScrollFrame::ScrollTo
 */
void nsHTMLScrollFrame::AsyncSmoothMSDScrollCallback(
    nsHTMLScrollFrame* aInstance, mozilla::TimeDuration aDeltaTime) {
  NS_ASSERTION(aInstance != nullptr, "aInstance must not be null");
  NS_ASSERTION(aInstance->mAsyncSmoothMSDScroll,
               "Did not expect AsyncSmoothMSDScrollCallback without an active "
               "MSD scroll.");

  nsRect range = aInstance->mAsyncSmoothMSDScroll->GetRange();
  aInstance->mAsyncSmoothMSDScroll->Simulate(aDeltaTime);

  if (!aInstance->mAsyncSmoothMSDScroll->IsFinished()) {
    nsPoint destination = aInstance->mAsyncSmoothMSDScroll->GetPosition();
    // Allow this scroll operation to land on any pixel boundary within the
    // allowed scroll range for this frame.
    // If the MSD is under-dampened or the destination is changed rapidly,
    // it is expected (and desired) that the scrolling may overshoot.
    nsRect intermediateRange = nsRect(destination, nsSize()).UnionEdges(range);
    aInstance->ScrollToImpl(destination, intermediateRange);
    // 'aInstance' might be destroyed here
    return;
  }

  aInstance->CompleteAsyncScroll(
      aInstance->mAsyncSmoothMSDScroll->GetStartPosition(), range,
      aInstance->mAsyncSmoothMSDScroll->TakeSnapTargetIds());
}

/*
 * Callback function from AsyncScroll, used in nsHTMLScrollFrame::ScrollTo
 */
void nsHTMLScrollFrame::AsyncScrollCallback(nsHTMLScrollFrame* aInstance,
                                            mozilla::TimeStamp aTime) {
  MOZ_ASSERT(aInstance != nullptr, "aInstance must not be null");
  MOZ_ASSERT(
      aInstance->mAsyncScroll,
      "Did not expect AsyncScrollCallback without an active async scroll.");

  if (!aInstance || !aInstance->mAsyncScroll) {
    return;  // XXX wallpaper bug 1107353 for now.
  }

  nsRect range = aInstance->mAsyncScroll->mRange;
  if (aInstance->mAsyncScroll->IsSmoothScroll()) {
    if (!aInstance->mAsyncScroll->IsFinished(aTime)) {
      nsPoint destination = aInstance->mAsyncScroll->PositionAt(aTime);
      // Allow this scroll operation to land on any pixel boundary between the
      // current position and the final allowed range.  (We don't want
      // intermediate steps to be more constrained than the final step!)
      nsRect intermediateRange =
          nsRect(aInstance->GetScrollPosition(), nsSize()).UnionEdges(range);
      aInstance->ScrollToImpl(destination, intermediateRange);
      // 'aInstance' might be destroyed here
      return;
    }
  }

  aInstance->CompleteAsyncScroll(aInstance->mAsyncScroll->GetStartPosition(),
                                 range,
                                 aInstance->mAsyncScroll->TakeSnapTargetIds());
}

void nsHTMLScrollFrame::SetTransformingByAPZ(bool aTransforming) {
  if (mTransformingByAPZ && !aTransforming) {
    PostScrollEndEvent();
  }
  mTransformingByAPZ = aTransforming;
  if (!mozilla::css::TextOverflow::HasClippedTextOverflow(this) ||
      mozilla::css::TextOverflow::HasBlockEllipsis(mScrolledFrame)) {
    // If the block has some overflow marker stuff we should kick off a paint
    // because we have special behaviour for it when APZ scrolling is active.
    SchedulePaint();
  }
}

void nsHTMLScrollFrame::CompleteAsyncScroll(
    const nsPoint& aStartPosition, const nsRect& aRange,
    UniquePtr<ScrollSnapTargetIds> aSnapTargetIds, ScrollOrigin aOrigin) {
  SetLastSnapTargetIds(std::move(aSnapTargetIds));

  bool scrollPositionChanged = mDestination != aStartPosition;
  bool isNotHandledByApz =
      nsLayoutUtils::CanScrollOriginClobberApz(aOrigin) ||
      ScrollAnimationState().contains(AnimationState::MainThread);

  // Apply desired destination range since this is the last step of scrolling.
  RemoveObservers();
  AutoWeakFrame weakFrame(this);
  ScrollToImpl(mDestination, aRange, aOrigin);
  if (!weakFrame.IsAlive()) {
    return;
  }
  // We are done scrolling, set our destination to wherever we actually ended
  // up scrolling to.
  mDestination = GetScrollPosition();
  // Post a `scrollend` event for scrolling not handled by APZ, including:
  //
  //  - programmatic instant scrolls
  //  - the end of a smooth scroll animation running on the main thread
  //
  // For scrolling handled by APZ, the `scrollend` event is posted in
  // SetTransformingByAPZ() when the APZC is transitioning from a transforming
  // to a non-transforming state (e.g. a transition from PANNING to NOTHING).
  // The scrollend event should not be fired for a scroll that does not
  // result in a scroll position change.
  if (isNotHandledByApz && scrollPositionChanged) {
    PostScrollEndEvent();
  }
}

bool nsHTMLScrollFrame::HasBgAttachmentLocal() const {
  const nsStyleBackground* bg = StyleBackground();
  return bg->HasLocalBackground();
}

void nsHTMLScrollFrame::ScrollToInternal(
    nsPoint aScrollPosition, ScrollMode aMode, ScrollOrigin aOrigin,
    const nsRect* aRange, ScrollSnapFlags aSnapFlags,
    ScrollTriggeredByScript aTriggeredByScript) {
  if (aOrigin == ScrollOrigin::NotSpecified) {
    aOrigin = ScrollOrigin::Other;
  }
  ScrollToWithOrigin(
      aScrollPosition, aRange,
      ScrollOperationParams{aMode, aOrigin, aSnapFlags, aTriggeredByScript});
}

void nsHTMLScrollFrame::ScrollToCSSPixels(const CSSIntPoint& aScrollPosition,
                                          ScrollMode aMode) {
  CSSIntPoint currentCSSPixels = GetRoundedScrollPositionCSSPixels();
  // Transmogrify this scroll to a relative one if there's any on-going
  // animation in APZ triggered by __user__.
  // Bug 1740164: We will apply it for cases there's no animation in APZ.

  auto scrollAnimationState = ScrollAnimationState();
  bool isScrollAnimating =
      scrollAnimationState.contains(AnimationState::MainThread) ||
      scrollAnimationState.contains(AnimationState::APZPending) ||
      scrollAnimationState.contains(AnimationState::APZRequested);
  if (mCurrentAPZScrollAnimationType ==
          APZScrollAnimationType::TriggeredByUserInput &&
      !isScrollAnimating) {
    CSSIntPoint delta = aScrollPosition - currentCSSPixels;
    // This transmogrification need to be an intended end position scroll
    // operation.
    ScrollByCSSPixelsInternal(delta, aMode,
                              ScrollSnapFlags::IntendedEndPosition);
    return;
  }

  nscoord halfPixel = nsPresContext::CSSPixelsToAppUnits(0.5f);
  nsPoint pt = CSSPoint::ToAppUnits(aScrollPosition);
  nsRect range(pt.x - halfPixel, pt.y - halfPixel, 2 * halfPixel - 1,
               2 * halfPixel - 1);
  // XXX I don't think the following blocks are needed anymore, now that
  // ScrollToImpl simply tries to scroll an integer number of layer
  // pixels from the current position
  nsPoint current = GetScrollPosition();
  if (currentCSSPixels.x == aScrollPosition.x) {
    pt.x = current.x;
    range.x = pt.x;
    range.width = 0;
  }
  if (currentCSSPixels.y == aScrollPosition.y) {
    pt.y = current.y;
    range.y = pt.y;
    range.height = 0;
  }
  ScrollToWithOrigin(
      pt, &range,
      ScrollOperationParams{
          aMode, ScrollOrigin::Other,
          // This ScrollToCSSPixels is used for Element.scrollTo,
          // Element.scrollTop, Element.scrollLeft and for Window.scrollTo.
          ScrollSnapFlags::IntendedEndPosition, ScrollTriggeredByScript::Yes});
  // 'this' might be destroyed here
}

void nsHTMLScrollFrame::ScrollToCSSPixelsForApz(
    const CSSPoint& aScrollPosition, ScrollSnapTargetIds&& aLastSnapTargetIds) {
  nsPoint pt = CSSPoint::ToAppUnits(aScrollPosition);
  nscoord halfRange = nsPresContext::CSSPixelsToAppUnits(1000);
  nsRect range(pt.x - halfRange, pt.y - halfRange, 2 * halfRange - 1,
               2 * halfRange - 1);
  ScrollToWithOrigin(
      pt, &range,
      ScrollOperationParams{ScrollMode::Instant, ScrollOrigin::Apz,
                            std::move(aLastSnapTargetIds)});
  // 'this' might be destroyed here
}

CSSIntPoint nsHTMLScrollFrame::GetRoundedScrollPositionCSSPixels() {
  return CSSIntPoint::FromAppUnitsRounded(GetScrollPosition());
}

/*
 * this method wraps calls to ScrollToImpl(), either in one shot or
 * incrementally, based on the setting of the smoothness scroll pref
 */
void nsHTMLScrollFrame::ScrollToWithOrigin(nsPoint aScrollPosition,
                                           const nsRect* aRange,
                                           ScrollOperationParams&& aParams) {
  // None is never a valid scroll origin to be passed in.
  MOZ_ASSERT(aParams.mOrigin != ScrollOrigin::None);

  if (aParams.mOrigin != ScrollOrigin::Restore) {
    // If we're doing a non-restore scroll, we don't want to later
    // override it by restoring our saved scroll position.
    SCROLLRESTORE_LOG("%p: Clearing mRestorePos (cur=%s, dst=%s)\n", this,
                      ToString(GetScrollPosition()).c_str(),
                      ToString(aScrollPosition).c_str());
    mRestorePos.x = mRestorePos.y = -1;
  }

  Maybe<SnapDestination> snapDestination;
  if (!aParams.IsScrollSnapDisabled()) {
    snapDestination = GetSnapPointForDestination(ScrollUnit::DEVICE_PIXELS,
                                                 aParams.mSnapFlags,
                                                 mDestination, aScrollPosition);
    if (snapDestination) {
      aScrollPosition = snapDestination->mPosition;
    }
  }

  nsRect scrollRange = GetLayoutScrollRange();
  mDestination = scrollRange.ClampPoint(aScrollPosition);
  if (mDestination != aScrollPosition &&
      aParams.mOrigin == ScrollOrigin::Restore &&
      GetPageLoadingState() != LoadingState::Loading) {
    // If we're doing a restore but the scroll position is clamped, promote
    // the origin from one that APZ can clobber to one that it can't clobber.
    aParams.mOrigin = ScrollOrigin::Other;
  }

  nsRect range = aRange && snapDestination.isNothing()
                     ? *aRange
                     : nsRect(aScrollPosition, nsSize(0, 0));

  UniquePtr<ScrollSnapTargetIds> snapTargetIds;
  if (snapDestination) {
    snapTargetIds =
        MakeUnique<ScrollSnapTargetIds>(std::move(snapDestination->mTargetIds));
  } else {
    snapTargetIds =
        MakeUnique<ScrollSnapTargetIds>(std::move(aParams.mTargetIds));
  }
  if (aParams.IsInstant()) {
    // Asynchronous scrolling is not allowed, so we'll kill any existing
    // async-scrolling process and do an instant scroll.
    CompleteAsyncScroll(GetScrollPosition(), range, std::move(snapTargetIds),
                        aParams.mOrigin);
    mApzSmoothScrollDestination = Nothing();
    return;
  }

  if (!aParams.IsSmoothMsd()) {
    // If we get a non-smooth-scroll, reset the cached APZ scroll destination,
    // so that we know to process the next smooth-scroll destined for APZ.
    mApzSmoothScrollDestination = Nothing();
  }

  nsPresContext* presContext = PresContext();
  TimeStamp now =
      presContext->RefreshDriver()->IsTestControllingRefreshesEnabled()
          ? presContext->RefreshDriver()->MostRecentRefresh()
          : TimeStamp::Now();

  nsSize currentVelocity(0, 0);

  const bool canHandoffToApz =
      nsLayoutUtils::AsyncPanZoomEnabled(this) && WantAsyncScroll() &&
      CanApzScrollInTheseDirections(
          DirectionsInDelta(mDestination - GetScrollPosition()));

  if (aParams.IsSmoothMsd()) {
    mIgnoreMomentumScroll = true;
    if (!mAsyncSmoothMSDScroll) {
      nsPoint sv = mVelocityQueue.GetVelocity();
      currentVelocity.width = sv.x;
      currentVelocity.height = sv.y;
      if (mAsyncScroll) {
        if (mAsyncScroll->IsSmoothScroll()) {
          currentVelocity = mAsyncScroll->VelocityAt(now);
        }
        mAsyncScroll = nullptr;
      }

      if (canHandoffToApz) {
        ApzSmoothScrollTo(mDestination, ScrollMode::SmoothMsd, aParams.mOrigin,
                          aParams.mTriggeredByScript, std::move(snapTargetIds));
        return;
      }

      mAsyncSmoothMSDScroll = new AsyncSmoothMSDScroll(
          GetScrollPosition(), mDestination, currentVelocity,
          GetLayoutScrollRange(), now, presContext, std::move(snapTargetIds),
          aParams.mTriggeredByScript);

      mAsyncSmoothMSDScroll->SetRefreshObserver(this);
    } else {
      // A previous smooth MSD scroll is still in progress, so we just need to
      // update its range and destination.
      mAsyncSmoothMSDScroll->SetRange(GetLayoutScrollRange());
      mAsyncSmoothMSDScroll->SetDestination(mDestination,
                                            aParams.mTriggeredByScript);
    }

    return;
  }

  if (mAsyncSmoothMSDScroll) {
    currentVelocity = mAsyncSmoothMSDScroll->GetVelocity();
    mAsyncSmoothMSDScroll = nullptr;
  }

  const bool isSmoothScroll =
      aParams.IsSmooth() && nsLayoutUtils::IsSmoothScrollingEnabled();
  if (!mAsyncScroll) {
    if (isSmoothScroll && canHandoffToApz) {
      ApzSmoothScrollTo(mDestination, ScrollMode::Smooth, aParams.mOrigin,
                        aParams.mTriggeredByScript, std::move(snapTargetIds));
      return;
    }

    mAsyncScroll =
        new AsyncScroll(std::move(snapTargetIds), aParams.mTriggeredByScript);
    mAsyncScroll->SetRefreshObserver(this);
  }

  if (isSmoothScroll) {
    mAsyncScroll->InitSmoothScroll(now, GetScrollPosition(), mDestination,
                                   aParams.mOrigin, range, currentVelocity);
  } else {
    mAsyncScroll->Init(GetScrollPosition(), range);
  }
}

// We can't use nsContainerFrame::PositionChildViews here because
// we don't want to invalidate views that have moved.
static void AdjustViews(nsIFrame* aFrame) {
  nsView* view = aFrame->GetView();
  if (view) {
    nsPoint pt;
    aFrame->GetParent()->GetClosestView(&pt);
    pt += aFrame->GetPosition();
    view->SetPosition(pt.x, pt.y);

    return;
  }

  if (!aFrame->HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW)) {
    return;
  }

  // Call AdjustViews recursively for all child frames except the popup list as
  // the views for popups are not scrolled.
  for (const auto& [list, listID] : aFrame->ChildLists()) {
    if (listID == FrameChildListID::Popup) {
      continue;
    }
    for (nsIFrame* child : list) {
      AdjustViews(child);
    }
  }
}

void nsHTMLScrollFrame::MarkScrollbarsDirtyForReflow() const {
  auto* presShell = PresShell();
  if (mVScrollbarBox) {
    presShell->FrameNeedsReflow(mVScrollbarBox,
                                IntrinsicDirty::FrameAncestorsAndDescendants,
                                NS_FRAME_IS_DIRTY);
  }
  if (mHScrollbarBox) {
    presShell->FrameNeedsReflow(mHScrollbarBox,
                                IntrinsicDirty::FrameAncestorsAndDescendants,
                                NS_FRAME_IS_DIRTY);
  }
}

void nsHTMLScrollFrame::InvalidateScrollbars() const {
  if (mHScrollbarBox) {
    mHScrollbarBox->InvalidateFrameSubtree();
  }
  if (mVScrollbarBox) {
    mVScrollbarBox->InvalidateFrameSubtree();
  }
}

bool nsHTMLScrollFrame::IsAlwaysActive() const {
  if (nsDisplayItem::ForceActiveLayers()) {
    return true;
  }

  // Unless this is the root scrollframe for a non-chrome document
  // which is the direct child of a chrome document, we default to not
  // being "active".
  if (!(mIsRoot && PresContext()->IsRootContentDocumentCrossProcess())) {
    return false;
  }

  // If we have scrolled before, then we should stay active.
  if (mHasBeenScrolled) {
    return true;
  }

  // If we're overflow:hidden, then start as inactive until
  // we get scrolled manually.
  ScrollStyles styles = GetScrollStyles();
  return (styles.mHorizontal != StyleOverflow::Hidden &&
          styles.mVertical != StyleOverflow::Hidden);
}

static void RemoveDisplayPortCallback(nsITimer* aTimer, void* aClosure) {
  nsHTMLScrollFrame* sf = static_cast<nsHTMLScrollFrame*>(aClosure);

  // This function only ever gets called from the expiry timer, so it must
  // be non-null here. Set it to null here so that we don't keep resetting
  // it unnecessarily in MarkRecentlyScrolled().
  MOZ_ASSERT(sf->mDisplayPortExpiryTimer);
  sf->mDisplayPortExpiryTimer = nullptr;

  if (!sf->AllowDisplayPortExpiration() || sf->mIsParentToActiveScrollFrames) {
    // If this is a scroll parent for some other scrollable frame, don't
    // expire the displayport because it would break scroll handoff. Once the
    // descendant scrollframes have their displayports expired, they will
    // trigger the displayport expiration on this scrollframe as well, and
    // mIsParentToActiveScrollFrames will presumably be false when that kicks
    // in.
    return;
  }

  // Remove the displayport from this scrollframe if it's been a while
  // since it's scrolled, except if it needs to be always active. Note that
  // there is one scrollframe that doesn't fall under this general rule, and
  // that is the one that nsLayoutUtils::MaybeCreateDisplayPort decides to put
  // a displayport on (i.e. the first scrollframe that WantAsyncScroll()s).
  // If that scrollframe is this one, we remove the displayport anyway, and
  // as part of the next paint MaybeCreateDisplayPort will put another
  // displayport back on it. Although the displayport will "flicker" off and
  // back on, the layer itself should never disappear, because this all
  // happens between actual painting. If the displayport is reset to a
  // different position that's ok; this scrollframe hasn't been scrolled
  // recently and so the reset should be correct.

  nsIContent* content = sf->GetContent();

  if (nsHTMLScrollFrame::ShouldActivateAllScrollFrames()) {
    // If we are activating all scroll frames then we only want to remove the
    // regular display port and downgrade to a minimal display port.
    MOZ_ASSERT(!content->GetProperty(nsGkAtoms::MinimalDisplayPort));
    content->SetProperty(nsGkAtoms::MinimalDisplayPort,
                         reinterpret_cast<void*>(true));
  } else {
    content->RemoveProperty(nsGkAtoms::MinimalDisplayPort);
    DisplayPortUtils::RemoveDisplayPort(content);
    // Be conservative and unflag this this scrollframe as being scrollable by
    // APZ. If it is still scrollable this will get flipped back soon enough.
    sf->mScrollableByAPZ = false;
  }

  DisplayPortUtils::ExpireDisplayPortOnAsyncScrollableAncestor(sf);
  sf->SchedulePaint();
}

void nsHTMLScrollFrame::MarkEverScrolled() {
  // Mark this frame as having been scrolled. If this is the root
  // scroll frame of a content document, then IsAlwaysActive()
  // will return true from now on and MarkNotRecentlyScrolled() won't
  // have any effect.
  mHasBeenScrolled = true;
}

void nsHTMLScrollFrame::MarkNotRecentlyScrolled() {
  if (!mHasBeenScrolledRecently) return;

  mHasBeenScrolledRecently = false;
  SchedulePaint();
}

void nsHTMLScrollFrame::MarkRecentlyScrolled() {
  mHasBeenScrolledRecently = true;
  if (IsAlwaysActive()) {
    return;
  }

  if (mActivityExpirationState.IsTracked()) {
    gScrollFrameActivityTracker->MarkUsed(this);
  } else {
    if (!gScrollFrameActivityTracker) {
      gScrollFrameActivityTracker =
          new ScrollFrameActivityTracker(GetMainThreadSerialEventTarget());
    }
    gScrollFrameActivityTracker->AddObject(this);
  }

  // If we just scrolled and there's a displayport expiry timer in place,
  // reset the timer.
  ResetDisplayPortExpiryTimer();
}

void nsHTMLScrollFrame::ResetDisplayPortExpiryTimer() {
  if (mDisplayPortExpiryTimer) {
    mDisplayPortExpiryTimer->InitWithNamedFuncCallback(
        RemoveDisplayPortCallback, this,
        StaticPrefs::apz_displayport_expiry_ms(), nsITimer::TYPE_ONE_SHOT,
        "nsHTMLScrollFrame::ResetDisplayPortExpiryTimer");
  }
}

bool nsHTMLScrollFrame::AllowDisplayPortExpiration() {
  if (IsAlwaysActive()) {
    return false;
  }

  if (mIsRoot && PresContext()->IsRoot()) {
    return false;
  }

  // If this was the first scrollable frame found, this displayport should
  // not expire.
  if (IsFirstScrollableFrameSequenceNumber().isSome()) {
    return false;
  }

  if (ShouldActivateAllScrollFrames() &&
      GetContent()->GetProperty(nsGkAtoms::MinimalDisplayPort)) {
    return false;
  }
  return true;
}

void nsHTMLScrollFrame::TriggerDisplayPortExpiration() {
  if (!AllowDisplayPortExpiration()) {
    return;
  }

  if (!StaticPrefs::apz_displayport_expiry_ms()) {
    // a zero time disables the expiry
    return;
  }

  if (!mDisplayPortExpiryTimer) {
    mDisplayPortExpiryTimer = NS_NewTimer();
  }
  ResetDisplayPortExpiryTimer();
}

void nsHTMLScrollFrame::ScrollVisual() {
  MarkEverScrolled();

  AdjustViews(mScrolledFrame);
  // We need to call this after fixing up the view positions
  // to be consistent with the frame hierarchy.
  MarkRecentlyScrolled();
}

/**
 * Clamp desired scroll position aDesired and range [aDestLower, aDestUpper]
 * to [aBoundLower, aBoundUpper] and then select the appunit value from among
 * aBoundLower, aBoundUpper and those such that (aDesired - aCurrent) *
 * aRes/aAppUnitsPerPixel is an integer (or as close as we can get
 * modulo rounding to appunits) that is in [aDestLower, aDestUpper] and
 * closest to aDesired.  If no such value exists, return the nearest in
 * [aDestLower, aDestUpper].
 */
static nscoord ClampAndAlignWithPixels(nscoord aDesired, nscoord aBoundLower,
                                       nscoord aBoundUpper, nscoord aDestLower,
                                       nscoord aDestUpper,
                                       nscoord aAppUnitsPerPixel, double aRes,
                                       nscoord aCurrent) {
  // Intersect scroll range with allowed range, by clamping the ends
  // of aRange to be within bounds
  nscoord destLower = clamped(aDestLower, aBoundLower, aBoundUpper);
  nscoord destUpper = clamped(aDestUpper, aBoundLower, aBoundUpper);

  nscoord desired = clamped(aDesired, destLower, destUpper);
  if (StaticPrefs::layout_scroll_disable_pixel_alignment()) {
    return desired;
  }

  double currentLayerVal = (aRes * aCurrent) / aAppUnitsPerPixel;
  double desiredLayerVal = (aRes * desired) / aAppUnitsPerPixel;
  double delta = desiredLayerVal - currentLayerVal;
  double nearestLayerVal = NS_round(delta) + currentLayerVal;

  // Convert back from PaintedLayer space to appunits relative to the top-left
  // of the scrolled frame.
  nscoord aligned =
      aRes == 0.0
          ? 0.0
          : NSToCoordRoundWithClamp(nearestLayerVal * aAppUnitsPerPixel / aRes);

  // Use a bound if it is within the allowed range and closer to desired than
  // the nearest pixel-aligned value.
  if (aBoundUpper == destUpper &&
      static_cast<decltype(Abs(desired))>(aBoundUpper - desired) <
          Abs(desired - aligned)) {
    return aBoundUpper;
  }

  if (aBoundLower == destLower &&
      static_cast<decltype(Abs(desired))>(desired - aBoundLower) <
          Abs(aligned - desired)) {
    return aBoundLower;
  }

  // Accept the nearest pixel-aligned value if it is within the allowed range.
  if (aligned >= destLower && aligned <= destUpper) {
    return aligned;
  }

  // Check if opposite pixel boundary fits into allowed range.
  double oppositeLayerVal =
      nearestLayerVal + ((nearestLayerVal < desiredLayerVal) ? 1.0 : -1.0);
  nscoord opposite = aRes == 0.0
                         ? 0.0
                         : NSToCoordRoundWithClamp(oppositeLayerVal *
                                                   aAppUnitsPerPixel / aRes);
  if (opposite >= destLower && opposite <= destUpper) {
    return opposite;
  }

  // No alignment available.
  return desired;
}

/**
 * Clamp desired scroll position aPt to aBounds and then snap
 * it to the same layer pixel edges as aCurrent, keeping it within aRange
 * during snapping. aCurrent is the current scroll position.
 */
static nsPoint ClampAndAlignWithLayerPixels(const nsPoint& aPt,
                                            const nsRect& aBounds,
                                            const nsRect& aRange,
                                            const nsPoint& aCurrent,
                                            nscoord aAppUnitsPerPixel,
                                            const MatrixScales& aScale) {
  return nsPoint(
      ClampAndAlignWithPixels(aPt.x, aBounds.x, aBounds.XMost(), aRange.x,
                              aRange.XMost(), aAppUnitsPerPixel, aScale.xScale,
                              aCurrent.x),
      ClampAndAlignWithPixels(aPt.y, aBounds.y, aBounds.YMost(), aRange.y,
                              aRange.YMost(), aAppUnitsPerPixel, aScale.yScale,
                              aCurrent.y));
}

/* static */
void nsHTMLScrollFrame::ScrollActivityCallback(nsITimer* aTimer,
                                               void* anInstance) {
  nsHTMLScrollFrame* self = static_cast<nsHTMLScrollFrame*>(anInstance);

  // Fire the synth mouse move.
  self->mScrollActivityTimer->Cancel();
  self->mScrollActivityTimer = nullptr;
  self->PresShell()->SynthesizeMouseMove(true);
}

void nsHTMLScrollFrame::ScheduleSyntheticMouseMove() {
  if (!mScrollActivityTimer) {
    mScrollActivityTimer = NS_NewTimer(GetMainThreadSerialEventTarget());
    if (!mScrollActivityTimer) {
      return;
    }
  }

  mScrollActivityTimer->InitWithNamedFuncCallback(
      ScrollActivityCallback, this, 100, nsITimer::TYPE_ONE_SHOT,
      "nsHTMLScrollFrame::ScheduleSyntheticMouseMove");
}

void nsHTMLScrollFrame::NotifyApproximateFrameVisibilityUpdate(
    bool aIgnoreDisplayPort) {
  mLastUpdateFramesPos = GetScrollPosition();
  if (aIgnoreDisplayPort) {
    mHadDisplayPortAtLastFrameUpdate = false;
    mDisplayPortAtLastFrameUpdate = nsRect();
  } else {
    mHadDisplayPortAtLastFrameUpdate = DisplayPortUtils::GetDisplayPort(
        GetContent(), &mDisplayPortAtLastFrameUpdate);
  }
}

bool nsHTMLScrollFrame::GetDisplayPortAtLastApproximateFrameVisibilityUpdate(
    nsRect* aDisplayPort) {
  if (mHadDisplayPortAtLastFrameUpdate) {
    *aDisplayPort = mDisplayPortAtLastFrameUpdate;
  }
  return mHadDisplayPortAtLastFrameUpdate;
}

/* aIncludeCSSTransform controls if we include CSS transforms that are in this
 * process (the BrowserChild EffectsInfo mTransformToAncestorScale will include
 * CSS transforms in ancestor processes in all cases). */
MatrixScales GetPaintedLayerScaleForFrame(nsIFrame* aFrame,
                                          bool aIncludeCSSTransform) {
  MOZ_ASSERT(aFrame, "need a frame");

  nsPresContext* presCtx = aFrame->PresContext()->GetRootPresContext();

  if (!presCtx) {
    presCtx = aFrame->PresContext();
    MOZ_ASSERT(presCtx);
  }

  ParentLayerToScreenScale2D transformToAncestorScale;
  if (aIncludeCSSTransform) {
    transformToAncestorScale =
        nsLayoutUtils::GetTransformToAncestorScaleCrossProcessForFrameMetrics(
            aFrame);
  } else {
    if (BrowserChild* browserChild =
            BrowserChild::GetFrom(aFrame->PresShell())) {
      transformToAncestorScale =
          browserChild->GetEffectsInfo().mTransformToAncestorScale;
    }
  }
  transformToAncestorScale =
      ParentLayerToParentLayerScale(
          presCtx->PresShell()->GetCumulativeResolution()) *
      transformToAncestorScale;

  return transformToAncestorScale.ToUnknownScale();
}

void nsHTMLScrollFrame::ScrollToImpl(
    nsPoint aPt, const nsRect& aRange, ScrollOrigin aOrigin,
    ScrollTriggeredByScript aTriggeredByScript) {
  // None is never a valid scroll origin to be passed in.
  MOZ_ASSERT(aOrigin != ScrollOrigin::None);

  // Figure out the effective origin for this scroll request.
  if (aOrigin == ScrollOrigin::NotSpecified) {
    // If no origin was specified, we still want to set it to something that's
    // non-unknown, so that we can use eUnknown to distinguish if the frame was
    // scrolled at all. Default it to some generic placeholder.
    aOrigin = ScrollOrigin::Other;
  }

  // If this scroll is |relative|, but we've already had a user scroll that
  // was not relative, promote this origin to |other|. This ensures that we
  // may only transmit a relative update to APZ if all scrolls since the last
  // transaction or repaint request have been relative.
  if (aOrigin == ScrollOrigin::Relative &&
      (mLastScrollOrigin != ScrollOrigin::None &&
       mLastScrollOrigin != ScrollOrigin::NotSpecified &&
       mLastScrollOrigin != ScrollOrigin::Relative &&
       mLastScrollOrigin != ScrollOrigin::Apz)) {
    aOrigin = ScrollOrigin::Other;
  }

  // If the origin is a downgrade, and downgrades are allowed, process the
  // downgrade even if we're going to early-exit because we're already at
  // the correct scroll position. This ensures that if there wasn't a main-
  // thread scroll update pending before a frame reconstruction (as indicated
  // by mAllowScrollOriginDowngrade=true), then after the frame reconstruction
  // the origin is downgraded to "restore" even if the layout scroll offset to
  // be restored is (0,0) (which will take the early-exit below). This is
  // important so that restoration of a *visual* scroll offset (which might be
  // to something other than (0,0)) isn't clobbered.
  bool isScrollOriginDowngrade =
      nsLayoutUtils::CanScrollOriginClobberApz(mLastScrollOrigin) &&
      !nsLayoutUtils::CanScrollOriginClobberApz(aOrigin);
  bool allowScrollOriginChange =
      mAllowScrollOriginDowngrade && isScrollOriginDowngrade;

  if (allowScrollOriginChange) {
    mLastScrollOrigin = aOrigin;
    mAllowScrollOriginDowngrade = false;
  }

  nsPresContext* presContext = PresContext();
  nscoord appUnitsPerDevPixel = presContext->AppUnitsPerDevPixel();
  // 'scale' is our estimate of the scale factor that will be applied
  // when rendering the scrolled content to its own PaintedLayer.
  MatrixScales scale = GetPaintedLayerScaleForFrame(
      mScrolledFrame, /* aIncludeCSSTransform = */ true);
  nsPoint curPos = GetScrollPosition();

  // Try to align aPt with curPos so they have an integer number of layer
  // pixels between them. This gives us the best chance of scrolling without
  // having to invalidate due to changes in subpixel rendering.
  // Note that when we actually draw into a PaintedLayer, the coordinates
  // that get mapped onto the layer buffer pixels are from the display list,
  // which are relative to the display root frame's top-left increasing down,
  // whereas here our coordinates are scroll positions which increase upward
  // and are relative to the scrollport top-left. This difference doesn't
  // actually matter since all we are about is that there be an integer number
  // of layer pixels between pt and curPos.
  nsPoint pt = ClampAndAlignWithLayerPixels(aPt, GetLayoutScrollRange(), aRange,
                                            curPos, appUnitsPerDevPixel, scale);
  if (pt == curPos) {
    // Even if we are bailing out due to no-op main-thread scroll position
    // change, we might need to cancel an APZ smooth scroll that we already
    // kicked off. It might be reasonable to eventually remove the
    // mApzSmoothScrollDestination clause from this if statement, as that
    // may simplify this a bit and should be fine from the APZ side.
    if (mApzSmoothScrollDestination && aOrigin != ScrollOrigin::Clamp) {
      if (aOrigin == ScrollOrigin::Relative) {
        AppendScrollUpdate(
            ScrollPositionUpdate::NewRelativeScroll(mApzScrollPos, pt));
        mApzScrollPos = pt;
      } else if (aOrigin != ScrollOrigin::Apz) {
        ScrollOrigin origin =
            (mAllowScrollOriginDowngrade || !isScrollOriginDowngrade)
                ? aOrigin
                : mLastScrollOrigin;
        AppendScrollUpdate(ScrollPositionUpdate::NewScroll(origin, pt));
      }
    }
    return;
  }

  // If we are scrolling the RCD-RSF, and a visual scroll update is pending,
  // cancel it; otherwise, it will clobber this scroll.
  if (IsRootScrollFrameOfDocument() &&
      presContext->IsRootContentDocumentCrossProcess()) {
    auto* ps = presContext->GetPresShell();
    if (const auto& visualScrollUpdate = ps->GetPendingVisualScrollUpdate()) {
      if (visualScrollUpdate->mVisualScrollOffset != aPt) {
        // Only clobber if the scroll was originated by the main thread.
        // Respect the priority of origins (an "eRestore" layout scroll should
        // not clobber an "eMainThread" visual scroll.)
        bool shouldClobber =
            aOrigin == ScrollOrigin::Other ||
            (aOrigin == ScrollOrigin::Restore &&
             visualScrollUpdate->mUpdateType == FrameMetrics::eRestore);
        if (shouldClobber) {
          ps->AcknowledgePendingVisualScrollUpdate();
          ps->ClearPendingVisualScrollUpdate();
        }
      }
    }
  }

  bool needFrameVisibilityUpdate = mLastUpdateFramesPos == nsPoint(-1, -1);

  nsPoint dist(std::abs(pt.x - mLastUpdateFramesPos.x),
               std::abs(pt.y - mLastUpdateFramesPos.y));
  nsSize visualViewportSize = GetVisualViewportSize();
  nscoord horzAllowance = std::max(
      visualViewportSize.width /
          std::max(
              StaticPrefs::
                  layout_framevisibility_amountscrollbeforeupdatehorizontal(),
              1),
      AppUnitsPerCSSPixel());
  nscoord vertAllowance = std::max(
      visualViewportSize.height /
          std::max(
              StaticPrefs::
                  layout_framevisibility_amountscrollbeforeupdatevertical(),
              1),
      AppUnitsPerCSSPixel());
  if (dist.x >= horzAllowance || dist.y >= vertAllowance) {
    needFrameVisibilityUpdate = true;
  }

  // notify the listeners.
  for (uint32_t i = 0; i < mListeners.Length(); i++) {
    mListeners[i]->ScrollPositionWillChange(pt.x, pt.y);
  }

  nsRect oldDisplayPort;
  nsIContent* content = GetContent();
  DisplayPortUtils::GetDisplayPort(content, &oldDisplayPort);
  oldDisplayPort.MoveBy(-mScrolledFrame->GetPosition());

  // Update frame position for scrolling
  mScrolledFrame->SetPosition(mScrollPort.TopLeft() - pt);

  // If |mLastScrollOrigin| is already set to something that can clobber APZ's
  // scroll offset, then we don't want to change it to something that can't.
  // If we allowed this, then we could end up in a state where APZ ignores
  // legitimate scroll offset updates because the origin has been masked by
  // a later change within the same refresh driver tick.
  allowScrollOriginChange =
      (mAllowScrollOriginDowngrade || !isScrollOriginDowngrade);

  if (allowScrollOriginChange) {
    mLastScrollOrigin = aOrigin;
    mAllowScrollOriginDowngrade = false;
  }

  if (aOrigin == ScrollOrigin::Relative) {
    MOZ_ASSERT(!isScrollOriginDowngrade);
    MOZ_ASSERT(mLastScrollOrigin == ScrollOrigin::Relative);
    AppendScrollUpdate(
        ScrollPositionUpdate::NewRelativeScroll(mApzScrollPos, pt));
    mApzScrollPos = pt;
  } else if (aOrigin != ScrollOrigin::Apz) {
    AppendScrollUpdate(ScrollPositionUpdate::NewScroll(mLastScrollOrigin, pt));
  }

  if (mLastScrollOrigin == ScrollOrigin::Apz) {
    mApzScrollPos = GetScrollPosition();
  }

  ScrollVisual();
  mAnchor.UserScrolled();

  // Only report user-triggered scrolling interactions
  bool jsOnStack = nsContentUtils::GetCurrentJSContext() != nullptr;
  bool scrollingToAnchor = ScrollingInteractionContext::IsScrollingToAnchor();
  if (!jsOnStack && !scrollingToAnchor) {
    nsPoint distanceScrolled(std::abs(pt.x - curPos.x),
                             std::abs(pt.y - curPos.y));
    ScrollingMetrics::OnScrollingInteraction(
        CSSPoint::FromAppUnits(distanceScrolled).Length());
  }

  bool schedulePaint = true;
  if (nsLayoutUtils::AsyncPanZoomEnabled(this) &&
      !nsLayoutUtils::ShouldDisableApzForElement(content) &&
      !content->GetProperty(nsGkAtoms::MinimalDisplayPort) &&
      StaticPrefs::apz_paint_skipping_enabled()) {
    // If APZ is enabled with paint-skipping, there are certain conditions in
    // which we can skip paints:
    // 1) If APZ triggered this scroll, and the tile-aligned displayport is
    //    unchanged.
    // 2) If non-APZ triggered this scroll, but we can handle it by just asking
    //    APZ to update the scroll position. Again we make this conditional on
    //    the tile-aligned displayport being unchanged.
    // We do the displayport check first since it's common to all scenarios,
    // and then if the displayport is unchanged, we check if APZ triggered,
    // or can handle, this scroll. If so, we set schedulePaint to false and
    // skip the paint.
    // Because of bug 1264297, we also don't do paint-skipping for elements with
    // perspective, because the displayport may not have captured everything
    // that needs to be painted. So even if the final tile-aligned displayport
    // is the same, we force a repaint for these elements. Bug 1254260 tracks
    // fixing this properly.
    nsRect displayPort;
    bool usingDisplayPort =
        DisplayPortUtils::GetDisplayPort(content, &displayPort);
    displayPort.MoveBy(-mScrolledFrame->GetPosition());

    PAINT_SKIP_LOG(
        "New scrollpos %s usingDP %d dpEqual %d scrollableByApz "
        "%d perspective %d bglocal %d filter %d\n",
        ToString(CSSPoint::FromAppUnits(GetScrollPosition())).c_str(),
        usingDisplayPort, displayPort.IsEqualEdges(oldDisplayPort),
        mScrollableByAPZ, HasPerspective(), HasBgAttachmentLocal(),
        mHasOutOfFlowContentInsideFilter);
    if (usingDisplayPort && displayPort.IsEqualEdges(oldDisplayPort) &&
        !HasPerspective() && !HasBgAttachmentLocal() &&
        !mHasOutOfFlowContentInsideFilter) {
      bool haveScrollLinkedEffects =
          content->GetComposedDoc()->HasScrollLinkedEffect();
      bool apzDisabled = haveScrollLinkedEffects &&
                         StaticPrefs::apz_disable_for_scroll_linked_effects();
      if (!apzDisabled) {
        if (LastScrollOrigin() == ScrollOrigin::Apz) {
          schedulePaint = false;
          PAINT_SKIP_LOG("Skipping due to APZ scroll\n");
        } else if (mScrollableByAPZ) {
          nsIWidget* widget = presContext->GetNearestWidget();
          WindowRenderer* renderer =
              widget ? widget->GetWindowRenderer() : nullptr;
          if (renderer) {
            mozilla::layers::ScrollableLayerGuid::ViewID id;
            bool success = nsLayoutUtils::FindIDFor(content, &id);
            MOZ_ASSERT(success);  // we have a displayport, we better have an ID

            // Schedule an empty transaction to carry over the scroll offset
            // update, instead of a full transaction. This empty transaction
            // might still get squashed into a full transaction if something
            // happens to trigger one.
            MOZ_ASSERT(!mScrollUpdates.IsEmpty());
            success = renderer->AddPendingScrollUpdateForNextTransaction(
                id, mScrollUpdates.LastElement());
            if (success) {
              schedulePaint = false;
              SchedulePaint(nsIFrame::PAINT_COMPOSITE_ONLY);
              PAINT_SKIP_LOG(
                  "Skipping due to APZ-forwarded main-thread scroll\n");
            } else {
              PAINT_SKIP_LOG(
                  "Failed to set pending scroll update on layer manager\n");
            }
          }
        }
      }
    }
  }

  // If the new scroll offset is going to clobber APZ's scroll offset, for
  // the RCD-RSF this will have the effect of updating the visual viewport
  // offset in a way that keeps the relative offset between the layout and
  // visual viewports constant. This will cause APZ to send us a new visual
  // viewport offset, but instead of waiting for  that, just set the value
  // we expect APZ will set ourselves, to minimize the chances of
  // inconsistencies from querying a stale value.
  if (mIsRoot && nsLayoutUtils::CanScrollOriginClobberApz(aOrigin)) {
    AutoWeakFrame weakFrame(this);
    AutoScrollbarRepaintSuppression repaintSuppression(this, weakFrame,
                                                       !schedulePaint);

    nsPoint visualViewportOffset = curPos;
    if (presContext->PresShell()->IsVisualViewportOffsetSet()) {
      visualViewportOffset =
          presContext->PresShell()->GetVisualViewportOffset();
    }
    nsPoint relativeOffset = visualViewportOffset - curPos;

    presContext->PresShell()->SetVisualViewportOffset(pt + relativeOffset,
                                                      curPos);
    if (!weakFrame.IsAlive()) {
      return;
    }
  }

  if (schedulePaint) {
    SchedulePaint();

    if (needFrameVisibilityUpdate) {
      presContext->PresShell()->ScheduleApproximateFrameVisibilityUpdateNow();
    }
  }

  if (ChildrenHavePerspective()) {
    // The overflow areas of descendants may depend on the scroll position,
    // so ensure they get updated.

    // First we recompute the overflow areas of the transformed children
    // that use the perspective. FinishAndStoreOverflow only calls this
    // if the size changes, so we need to do it manually.
    RecomputePerspectiveChildrenOverflow(this);

    // Update the overflow for the scrolled frame to take any changes from the
    // children into account.
    mScrolledFrame->UpdateOverflow();

    // Update the overflow for the outer so that we recompute scrollbars.
    UpdateOverflow();
  }

  ScheduleSyntheticMouseMove();

  nsAutoScriptBlocker scriptBlocker;
  PresShell::AutoAssertNoFlush noFlush(*PresShell());

  {  // scope the AutoScrollbarRepaintSuppression
    AutoWeakFrame weakFrame(this);
    AutoScrollbarRepaintSuppression repaintSuppression(this, weakFrame,
                                                       !schedulePaint);
    UpdateScrollbarPosition();
    if (!weakFrame.IsAlive()) {
      return;
    }
  }

  presContext->RecordInteractionTime(
      nsPresContext::InteractionType::ScrollInteraction, TimeStamp::Now());

  PostScrollEvent();
  // If this is a viewport scroll, this could affect the relative offset
  // between layout and visual viewport, so we might have to fire a visual
  // viewport scroll event as well.
  if (mIsRoot) {
    if (auto* window = nsGlobalWindowInner::Cast(
            PresContext()->Document()->GetInnerWindow())) {
      window->VisualViewport()->PostScrollEvent(
          presContext->PresShell()->GetVisualViewportOffset(), curPos);
    }
  }

  // Schedule the scroll-timelines linked to its scrollable frame.
  // if `pt == curPos`, we early return, so the position must be changed at
  // this moment. Therefore, we can schedule scroll animations directly.
  ScheduleScrollAnimations();

  // notify the listeners.
  for (uint32_t i = 0; i < mListeners.Length(); i++) {
    mListeners[i]->ScrollPositionDidChange(pt.x, pt.y);
  }

  if (nsCOMPtr<nsIDocShell> docShell = presContext->GetDocShell()) {
    docShell->NotifyScrollObservers();
  }
}

// Finds the max z-index of the items in aList that meet the following
// conditions
//   1) have z-index auto or z-index >= 0, and
//   2) aFrame is a proper ancestor of the item's frame.
// Returns Nothing() if there is no such item.
static Maybe<int32_t> MaxZIndexInListOfItemsContainedInFrame(
    nsDisplayList* aList, nsIFrame* aFrame) {
  Maybe<int32_t> maxZIndex = Nothing();
  for (nsDisplayItem* item : *aList) {
    int32_t zIndex = item->ZIndex();
    if (zIndex < 0 ||
        !nsLayoutUtils::IsProperAncestorFrame(aFrame, item->Frame())) {
      continue;
    }
    if (!maxZIndex) {
      maxZIndex = Some(zIndex);
    } else {
      maxZIndex = Some(std::max(maxZIndex.value(), zIndex));
    }
  }
  return maxZIndex;
}

template <class T>
static void AppendInternalItemToTop(const nsDisplayListSet& aLists, T* aItem,
                                    const Maybe<int32_t>& aZIndex) {
  if (aZIndex) {
    aItem->SetOverrideZIndex(aZIndex.value());
    aLists.PositionedDescendants()->AppendToTop(aItem);
  } else {
    aLists.Content()->AppendToTop(aItem);
  }
}

static const uint32_t APPEND_OWN_LAYER = 0x1;
static const uint32_t APPEND_POSITIONED = 0x2;
static const uint32_t APPEND_SCROLLBAR_CONTAINER = 0x4;
static const uint32_t APPEND_OVERLAY = 0x8;
static const uint32_t APPEND_TOP = 0x10;

static void AppendToTop(nsDisplayListBuilder* aBuilder,
                        const nsDisplayListSet& aLists, nsDisplayList* aSource,
                        nsIFrame* aSourceFrame, nsIFrame* aScrollFrame,
                        uint32_t aFlags) {
  if (aSource->IsEmpty()) {
    return;
  }

  nsDisplayWrapList* newItem;
  const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();
  if (aFlags & APPEND_OWN_LAYER) {
    ScrollbarData scrollbarData;
    if (aFlags & APPEND_SCROLLBAR_CONTAINER) {
      scrollbarData = ScrollbarData::CreateForScrollbarContainer(
          aBuilder->GetCurrentScrollbarDirection(),
          aBuilder->GetCurrentScrollbarTarget());
      // Direction should be set
      MOZ_ASSERT(scrollbarData.mDirection.isSome());
    }

    newItem = MakeDisplayItemWithIndex<nsDisplayOwnLayer>(
        aBuilder, aSourceFrame,
        /* aIndex = */ nsDisplayOwnLayer::OwnLayerForScrollbar, aSource, asr,
        nsDisplayOwnLayerFlags::None, scrollbarData, true, false);
  } else {
    // Build the wrap list with an index of 1, since the scrollbar frame itself
    // might have already built an nsDisplayWrapList.
    newItem = MakeDisplayItemWithIndex<nsDisplayWrapper>(
        aBuilder, aSourceFrame, 1, aSource, asr, false);
  }
  if (!newItem) {
    return;
  }

  if (aFlags & APPEND_POSITIONED) {
    // We want overlay scrollbars to always be on top of the scrolled content,
    // but we don't want them to unnecessarily cover overlapping elements from
    // outside our scroll frame.
    Maybe<int32_t> zIndex = Nothing();
    if (aFlags & APPEND_TOP) {
      zIndex = Some(INT32_MAX);
    } else if (aFlags & APPEND_OVERLAY) {
      zIndex = MaxZIndexInListOfItemsContainedInFrame(
          aLists.PositionedDescendants(), aScrollFrame);
    } else if (aSourceFrame->StylePosition()->mZIndex.IsInteger()) {
      zIndex = Some(aSourceFrame->StylePosition()->mZIndex.integer._0);
    }
    AppendInternalItemToTop(aLists, newItem, zIndex);
  } else {
    aLists.BorderBackground()->AppendToTop(newItem);
  }
}

struct HoveredStateComparator {
  static bool Hovered(const nsIFrame* aFrame) {
    return aFrame->GetContent()->IsElement() &&
           aFrame->GetContent()->AsElement()->HasAttr(nsGkAtoms::hover);
  }

  bool Equals(nsIFrame* A, nsIFrame* B) const {
    return Hovered(A) == Hovered(B);
  }

  bool LessThan(nsIFrame* A, nsIFrame* B) const {
    return !Hovered(A) && Hovered(B);
  }
};

void nsHTMLScrollFrame::AppendScrollPartsTo(nsDisplayListBuilder* aBuilder,
                                            const nsDisplayListSet& aLists,
                                            bool aCreateLayer,
                                            bool aPositioned) {
  const bool overlayScrollbars = UsesOverlayScrollbars();

  AutoTArray<nsIFrame*, 3> scrollParts;
  for (nsIFrame* kid : PrincipalChildList()) {
    if (kid == mScrolledFrame ||
        (kid->IsAbsPosContainingBlock() || overlayScrollbars) != aPositioned) {
      continue;
    }

    scrollParts.AppendElement(kid);
  }
  if (scrollParts.IsEmpty()) {
    return;
  }

  // We can't check will-change budget during display list building phase.
  // This means that we will build scroll bar layers for out of budget
  // will-change: scroll position.
  const mozilla::layers::ScrollableLayerGuid::ViewID scrollTargetId =
      IsScrollingActive()
          ? nsLayoutUtils::FindOrCreateIDFor(mScrolledFrame->GetContent())
          : mozilla::layers::ScrollableLayerGuid::NULL_SCROLL_ID;

  scrollParts.Sort(HoveredStateComparator());

  DisplayListClipState::AutoSaveRestore clipState(aBuilder);
  // Don't let scrollparts extent outside our frame's border-box, if these are
  // viewport scrollbars. They would create layerization problems. This wouldn't
  // normally be an issue but themes can add overflow areas to scrollbar parts.
  if (mIsRoot) {
    nsRect scrollPartsClip(aBuilder->ToReferenceFrame(this),
                           TrueOuterSize(aBuilder));
    clipState.ClipContentDescendants(scrollPartsClip);
  }

  for (uint32_t i = 0; i < scrollParts.Length(); ++i) {
    MOZ_ASSERT(scrollParts[i]);
    Maybe<ScrollDirection> scrollDirection;
    uint32_t appendToTopFlags = 0;
    if (scrollParts[i] == mVScrollbarBox) {
      scrollDirection.emplace(ScrollDirection::eVertical);
      appendToTopFlags |= APPEND_SCROLLBAR_CONTAINER;
    }
    if (scrollParts[i] == mHScrollbarBox) {
      MOZ_ASSERT(!scrollDirection.isSome());
      scrollDirection.emplace(ScrollDirection::eHorizontal);
      appendToTopFlags |= APPEND_SCROLLBAR_CONTAINER;
    }

    // The display port doesn't necessarily include the scrollbars, so just
    // include all of the scrollbars if we are in a RCD-RSF. We only do
    // this for the root scrollframe of the root content document, which is
    // zoomable, and where the scrollbar sizes are bounded by the widget.
    const nsRect visible =
        mIsRoot && PresContext()->IsRootContentDocumentCrossProcess()
            ? scrollParts[i]->InkOverflowRectRelativeToParent()
            : aBuilder->GetVisibleRect();
    if (visible.IsEmpty()) {
      continue;
    }
    const nsRect dirty =
        mIsRoot && PresContext()->IsRootContentDocumentCrossProcess()
            ? scrollParts[i]->InkOverflowRectRelativeToParent()
            : aBuilder->GetDirtyRect();

    // Always create layers for overlay scrollbars so that we don't create a
    // giant layer covering the whole scrollport if both scrollbars are visible.
    const bool isOverlayScrollbar =
        scrollDirection.isSome() && overlayScrollbars;
    const bool createLayer =
        aCreateLayer || isOverlayScrollbar ||
        StaticPrefs::layout_scrollbars_always_layerize_track();

    nsDisplayListCollection partList(aBuilder);
    {
      nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
          aBuilder, this, visible, dirty);

      nsDisplayListBuilder::AutoCurrentScrollbarInfoSetter infoSetter(
          aBuilder, scrollTargetId, scrollDirection, createLayer);
      BuildDisplayListForChild(
          aBuilder, scrollParts[i], partList,
          nsIFrame::DisplayChildFlag::ForceStackingContext);
    }

    // DisplayChildFlag::ForceStackingContext put everything into
    // partList.PositionedDescendants().
    if (partList.PositionedDescendants()->IsEmpty()) {
      continue;
    }

    if (createLayer) {
      appendToTopFlags |= APPEND_OWN_LAYER;
    }
    if (aPositioned) {
      appendToTopFlags |= APPEND_POSITIONED;
    }

    if (isOverlayScrollbar || scrollParts[i] == mResizerBox) {
      if (isOverlayScrollbar && mIsRoot) {
        appendToTopFlags |= APPEND_TOP;
      } else {
        appendToTopFlags |= APPEND_OVERLAY;
        aBuilder->SetDisablePartialUpdates(true);
      }
    }

    {
      nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
          aBuilder, scrollParts[i], visible + GetOffsetTo(scrollParts[i]),
          dirty + GetOffsetTo(scrollParts[i]));
      if (scrollParts[i]->IsTransformed()) {
        nsPoint toOuterReferenceFrame;
        const nsIFrame* outerReferenceFrame = aBuilder->FindReferenceFrameFor(
            scrollParts[i]->GetParent(), &toOuterReferenceFrame);
        toOuterReferenceFrame += scrollParts[i]->GetPosition();

        buildingForChild.SetReferenceFrameAndCurrentOffset(
            outerReferenceFrame, toOuterReferenceFrame);
      }
      nsDisplayListBuilder::AutoCurrentScrollbarInfoSetter infoSetter(
          aBuilder, scrollTargetId, scrollDirection, createLayer);

      ::AppendToTop(aBuilder, aLists, partList.PositionedDescendants(),
                    scrollParts[i], this, appendToTopFlags);
    }
  }
}

nsRect nsHTMLScrollFrame::ExpandRectToNearlyVisible(const nsRect& aRect) const {
  // We don't want to expand a rect in a direction that we can't scroll, so we
  // check the scroll range.
  nsRect scrollRange = GetLayoutScrollRange();
  nsPoint scrollPos = GetScrollPosition();
  nsMargin expand(0, 0, 0, 0);

  nscoord vertShift =
      StaticPrefs::layout_framevisibility_numscrollportheights() * aRect.height;
  if (scrollRange.y < scrollPos.y) {
    expand.top = vertShift;
  }
  if (scrollPos.y < scrollRange.YMost()) {
    expand.bottom = vertShift;
  }

  nscoord horzShift =
      StaticPrefs::layout_framevisibility_numscrollportwidths() * aRect.width;
  if (scrollRange.x < scrollPos.x) {
    expand.left = horzShift;
  }
  if (scrollPos.x < scrollRange.XMost()) {
    expand.right = horzShift;
  }

  nsRect rect = aRect;
  rect.Inflate(expand);
  return rect;
}

static bool ShouldBeClippedByFrame(nsIFrame* aClipFrame,
                                   nsIFrame* aClippedFrame) {
  return nsLayoutUtils::IsProperAncestorFrame(aClipFrame, aClippedFrame);
}

static void ClipItemsExceptCaret(
    nsDisplayList* aList, nsDisplayListBuilder* aBuilder, nsIFrame* aClipFrame,
    const DisplayItemClipChain* aExtraClip,
    nsTHashMap<nsPtrHashKey<const DisplayItemClipChain>,
               const DisplayItemClipChain*>& aCache) {
  for (nsDisplayItem* i : *aList) {
    if (!ShouldBeClippedByFrame(aClipFrame, i->Frame())) {
      continue;
    }

    const DisplayItemType type = i->GetType();
    if (type != DisplayItemType::TYPE_CARET &&
        type != DisplayItemType::TYPE_CONTAINER) {
      const DisplayItemClipChain* clip = i->GetClipChain();
      const DisplayItemClipChain* intersection = nullptr;
      if (aCache.Get(clip, &intersection)) {
        i->SetClipChain(intersection, true);
      } else {
        i->IntersectClip(aBuilder, aExtraClip, true);
        aCache.InsertOrUpdate(clip, i->GetClipChain());
      }
    }
    nsDisplayList* children = i->GetSameCoordinateSystemChildren();
    if (children) {
      ClipItemsExceptCaret(children, aBuilder, aClipFrame, aExtraClip, aCache);
    }
  }
}

static void ClipListsExceptCaret(nsDisplayListCollection* aLists,
                                 nsDisplayListBuilder* aBuilder,
                                 nsIFrame* aClipFrame,
                                 const DisplayItemClipChain* aExtraClip) {
  nsTHashMap<nsPtrHashKey<const DisplayItemClipChain>,
             const DisplayItemClipChain*>
      cache;
  ClipItemsExceptCaret(aLists->BorderBackground(), aBuilder, aClipFrame,
                       aExtraClip, cache);
  ClipItemsExceptCaret(aLists->BlockBorderBackgrounds(), aBuilder, aClipFrame,
                       aExtraClip, cache);
  ClipItemsExceptCaret(aLists->Floats(), aBuilder, aClipFrame, aExtraClip,
                       cache);
  ClipItemsExceptCaret(aLists->PositionedDescendants(), aBuilder, aClipFrame,
                       aExtraClip, cache);
  ClipItemsExceptCaret(aLists->Outlines(), aBuilder, aClipFrame, aExtraClip,
                       cache);
  ClipItemsExceptCaret(aLists->Content(), aBuilder, aClipFrame, aExtraClip,
                       cache);
}

// This is similar to a "save-restore" RAII class for
// DisplayListBuilder::ContainsBlendMode(), with a slight enhancement.
// If this class is put on the stack and then unwound, the DL builder's
// ContainsBlendMode flag will be effectively the same as if this class wasn't
// put on the stack. However, if the CaptureContainsBlendMode method is called,
// there will be a difference - the blend mode in the descendant display lists
// will be "captured" and extracted.
// The main goal here is to allow conditionally capturing the flag that
// indicates whether or not a blend mode was encountered in the descendant part
// of the display list.
class MOZ_RAII AutoContainsBlendModeCapturer {
  nsDisplayListBuilder& mBuilder;
  bool mSavedContainsBlendMode;

 public:
  explicit AutoContainsBlendModeCapturer(nsDisplayListBuilder& aBuilder)
      : mBuilder(aBuilder),
        mSavedContainsBlendMode(aBuilder.ContainsBlendMode()) {
    mBuilder.SetContainsBlendMode(false);
  }

  bool CaptureContainsBlendMode() {
    // "Capture" the flag by extracting and clearing the ContainsBlendMode flag
    // on the builder.
    bool capturedBlendMode = mBuilder.ContainsBlendMode();
    mBuilder.SetContainsBlendMode(false);
    return capturedBlendMode;
  }

  ~AutoContainsBlendModeCapturer() {
    // If CaptureContainsBlendMode() was called, the descendant blend mode was
    // "captured" and so uncapturedContainsBlendMode will be false. If
    // CaptureContainsBlendMode() wasn't called, then no capture occurred, and
    // uncapturedContainsBlendMode may be true if there was a descendant blend
    // mode. In that case, we set the flag on the DL builder so that we restore
    // state to what it would have been without this RAII class on the stack.
    bool uncapturedContainsBlendMode = mBuilder.ContainsBlendMode();
    mBuilder.SetContainsBlendMode(mSavedContainsBlendMode ||
                                  uncapturedContainsBlendMode);
  }
};

void nsHTMLScrollFrame::MaybeCreateTopLayerAndWrapRootItems(
    nsDisplayListBuilder* aBuilder, nsDisplayListCollection& aSet,
    bool aCreateAsyncZoom,
    AutoContainsBlendModeCapturer* aAsyncZoomBlendCapture,
    const nsRect& aAsyncZoomClipRect, nscoord* aRadii) {
  if (!mIsRoot) {
    return;
  }

  // Create any required items for the 'top layer' and check if they'll be
  // opaque over the entire area of the viewport. If they are, then we can
  // skip building display items for the rest of the page.
  if (ViewportFrame* viewport = do_QueryFrame(GetParent())) {
    bool topLayerIsOpaque = false;
    if (nsDisplayWrapList* topLayerWrapList =
            viewport->BuildDisplayListForTopLayer(aBuilder,
                                                  &topLayerIsOpaque)) {
      // If the top layer content is opaque, and we're the root content document
      // in the process, we can drop the display items behind it. We only
      // support doing this for the root content document in the process, since
      // the top layer content might have fixed position items that have a
      // scrolltarget referencing the APZ data for the document. APZ builds this
      // data implicitly for the root content document in the process, but
      // subdocuments etc need their display items to generate it, so we can't
      // cull those.
      if (topLayerIsOpaque && PresContext()->IsRootContentDocumentInProcess()) {
        aSet.DeleteAll(aBuilder);
      }
      aSet.PositionedDescendants()->AppendToTop(topLayerWrapList);
    }
  }

  nsDisplayList rootResultList(aBuilder);

  bool serializedList = false;
  auto SerializeList = [&] {
    if (!serializedList) {
      serializedList = true;
      aSet.SerializeWithCorrectZOrder(&rootResultList, GetContent());
    }
  };

  if (nsIFrame* rootStyleFrame = GetFrameForStyle()) {
    bool usingBackdropFilter =
        rootStyleFrame->StyleEffects()->HasBackdropFilters() &&
        rootStyleFrame->IsVisibleForPainting();

    if (rootStyleFrame->StyleEffects()->HasFilters() &&
        !aBuilder->IsForGenerateGlyphMask()) {
      SerializeList();
      rootResultList.AppendNewToTop<nsDisplayFilters>(
          aBuilder, this, &rootResultList, rootStyleFrame, usingBackdropFilter);
    }

    if (usingBackdropFilter) {
      SerializeList();
      DisplayListClipState::AutoSaveRestore clipState(aBuilder);
      nsRect backdropRect =
          GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
      rootResultList.AppendNewToTop<nsDisplayBackdropFilters>(
          aBuilder, this, &rootResultList, backdropRect, rootStyleFrame);
    }
  }

  if (aCreateAsyncZoom) {
    MOZ_ASSERT(mIsRoot);

    // Wrap all our scrolled contents in an nsDisplayAsyncZoom. This will be
    // the layer that gets scaled for APZ zooming. It does not have the
    // scrolled ASR, but it does have the composition bounds clip applied to
    // it. The children have the layout viewport clip applied to them (above).
    // Effectively we are double clipping to the viewport, at potentially
    // different async scales.
    SerializeList();

    if (aAsyncZoomBlendCapture->CaptureContainsBlendMode()) {
      // The async zoom contents contain a mix-blend mode, so let's wrap all
      // those contents into a blend container, and then wrap the blend
      // container in the async zoom container. Otherwise the blend container
      // ends up outside the zoom container which results in blend failure for
      // WebRender.
      nsDisplayItem* blendContainer =
          nsDisplayBlendContainer::CreateForMixBlendMode(
              aBuilder, this, &rootResultList,
              aBuilder->CurrentActiveScrolledRoot());
      rootResultList.AppendToTop(blendContainer);

      // Blend containers can be created or omitted during partial updates
      // depending on the dirty rect. So we basically can't do partial updates
      // if there's a blend container involved. There is equivalent code to this
      // in the BuildDisplayListForStackingContext function as well, with a more
      // detailed comment explaining things better.
      if (aBuilder->IsRetainingDisplayList()) {
        if (aBuilder->IsPartialUpdate()) {
          aBuilder->SetPartialBuildFailed(true);
        } else {
          aBuilder->SetDisablePartialUpdates(true);
        }
      }
    }

    mozilla::layers::FrameMetrics::ViewID viewID =
        nsLayoutUtils::FindOrCreateIDFor(mScrolledFrame->GetContent());

    DisplayListClipState::AutoSaveRestore clipState(aBuilder);
    clipState.ClipContentDescendants(aAsyncZoomClipRect, aRadii);

    rootResultList.AppendNewToTop<nsDisplayAsyncZoom>(
        aBuilder, this, &rootResultList, aBuilder->CurrentActiveScrolledRoot(),
        viewID);
  }

  if (serializedList) {
    aSet.Content()->AppendToTop(&rootResultList);
  }
}

void nsHTMLScrollFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                         const nsDisplayListSet& aLists) {
  SetAndNullOnExit<const nsIFrame> tmpBuilder(
      mReferenceFrameDuringPainting, aBuilder->GetCurrentReferenceFrame());
  if (aBuilder->IsForFrameVisibility()) {
    NotifyApproximateFrameVisibilityUpdate(false);
  }

  DisplayBorderBackgroundOutline(aBuilder, aLists);

  const bool isRootContent =
      mIsRoot && PresContext()->IsRootContentDocumentCrossProcess();

  nsRect effectiveScrollPort = mScrollPort;
  if (isRootContent && PresContext()->HasDynamicToolbar()) {
    // Expand the scroll port to the size including the area covered by dynamic
    // toolbar in the case where the dynamic toolbar is being used since
    // position:fixed elements attached to this root scroller might be taller
    // than its scroll port (e.g 100vh). Even if the dynamic toolbar covers the
    // taller area, it doesn't mean the area is clipped by the toolbar because
    // the dynamic toolbar is laid out outside of our topmost window and it
    // transitions without changing our topmost window size.
    effectiveScrollPort.SizeTo(nsLayoutUtils::ExpandHeightForDynamicToolbar(
        PresContext(), effectiveScrollPort.Size()));
  }

  // It's safe to get this value before the DecideScrollableLayer call below
  // because that call cannot create a displayport for root scroll frames,
  // and hence it cannot create an ignore scroll frame.
  const bool ignoringThisScrollFrame = aBuilder->GetIgnoreScrollFrame() == this;

  // Overflow clipping can never clip frames outside our subtree, so there
  // is no need to worry about whether we are a moving frame that might clip
  // non-moving frames.
  // Not all our descendants will be clipped by overflow clipping, but all
  // the ones that aren't clipped will be out of flow frames that have already
  // had dirty rects saved for them by their parent frames calling
  // MarkOutOfFlowChildrenForDisplayList, so it's safe to restrict our
  // dirty rect here.
  nsRect visibleRect = aBuilder->GetVisibleRect();
  nsRect dirtyRect = aBuilder->GetDirtyRect();
  if (!ignoringThisScrollFrame) {
    visibleRect = visibleRect.Intersect(effectiveScrollPort);
    dirtyRect = dirtyRect.Intersect(effectiveScrollPort);
  }

  bool dirtyRectHasBeenOverriden = false;
  Unused << DecideScrollableLayer(aBuilder, &visibleRect, &dirtyRect,
                                  /* aSetBase = */ !mIsRoot,
                                  &dirtyRectHasBeenOverriden);

  if (aBuilder->IsForFrameVisibility()) {
    // We expand the dirty rect to catch frames just outside of the scroll port.
    // We use the dirty rect instead of the whole scroll port to prevent
    // too much expansion in the presence of very large (bigger than the
    // viewport) scroll ports.
    dirtyRect = ExpandRectToNearlyVisible(dirtyRect);
    visibleRect = dirtyRect;
  }

  // We put non-overlay scrollbars in their own layers when this is the root
  // scroll frame and we are a toplevel content document. In this situation,
  // the scrollbar(s) would normally be assigned their own layer anyway, since
  // they're not scrolled with the rest of the document. But when both
  // scrollbars are visible, the layer's visible rectangle would be the size
  // of the viewport, so most layer implementations would create a layer buffer
  // that's much larger than necessary. Creating independent layers for each
  // scrollbar works around the problem.
  const bool createLayersForScrollbars = isRootContent;

  nsDisplayListCollection set(aBuilder);

  if (ignoringThisScrollFrame) {
    // If we are a root scroll frame that has a display port we want to add
    // scrollbars, they will be children of the scrollable layer, but they get
    // adjusted by the APZC automatically.
    bool addScrollBars =
        mIsRoot && mWillBuildScrollableLayer && aBuilder->IsPaintingToWindow();

    if (addScrollBars) {
      // Add classic scrollbars.
      AppendScrollPartsTo(aBuilder, set, createLayersForScrollbars, false);
    }

    {
      nsDisplayListBuilder::AutoBuildingDisplayList building(
          aBuilder, this, visibleRect, dirtyRect);

      // Don't clip the scrolled child, and don't paint scrollbars/scrollcorner.
      // The scrolled frame shouldn't have its own background/border, so we
      // can just pass aLists directly.
      BuildDisplayListForChild(aBuilder, mScrolledFrame, set);
    }

    MaybeCreateTopLayerAndWrapRootItems(aBuilder, set,
                                        /* aCreateAsyncZoom = */ false, nullptr,
                                        nsRect(), nullptr);

    if (addScrollBars) {
      // Add overlay scrollbars.
      AppendScrollPartsTo(aBuilder, set, createLayersForScrollbars, true);
    }

    set.MoveTo(aLists);
    return;
  }

  // Whether we might want to build a scrollable layer for this scroll frame
  // at some point in the future. This controls whether we add the information
  // to the layer tree (a scroll info layer if necessary, and add the right
  // area to the dispatch to content layer event regions) necessary to activate
  // a scroll frame so it creates a scrollable layer.
  const bool couldBuildLayer = [&] {
    if (!aBuilder->IsPaintingToWindow()) {
      return false;
    }
    if (mWillBuildScrollableLayer) {
      return true;
    }
    return StyleVisibility()->IsVisible() &&
           nsLayoutUtils::AsyncPanZoomEnabled(this) && WantAsyncScroll();
  }();

  // Now display the scrollbars and scrollcorner. These parts are drawn
  // in the border-background layer, on top of our own background and
  // borders and underneath borders and backgrounds of later elements
  // in the tree.
  // Note that this does not apply for overlay scrollbars; those are drawn
  // in the positioned-elements layer on top of everything else by the call
  // to AppendScrollPartsTo(..., true) further down.
  AppendScrollPartsTo(aBuilder, aLists, createLayersForScrollbars, false);

  const nsStyleDisplay* disp = StyleDisplay();
  if (aBuilder->IsForPainting() &&
      disp->mWillChange.bits & StyleWillChangeBits::SCROLL) {
    aBuilder->AddToWillChangeBudget(this, GetVisualViewportSize());
  }

  mScrollParentID = aBuilder->GetCurrentScrollParentId();

  Maybe<nsRect> contentBoxClip;
  Maybe<const DisplayItemClipChain*> extraContentBoxClipForNonCaretContent;
  if (MOZ_UNLIKELY(
          disp->mOverflowClipBoxBlock == StyleOverflowClipBox::ContentBox ||
          disp->mOverflowClipBoxInline == StyleOverflowClipBox::ContentBox)) {
    WritingMode wm = mScrolledFrame->GetWritingMode();
    bool cbH = (wm.IsVertical() ? disp->mOverflowClipBoxBlock
                                : disp->mOverflowClipBoxInline) ==
               StyleOverflowClipBox::ContentBox;
    bool cbV = (wm.IsVertical() ? disp->mOverflowClipBoxInline
                                : disp->mOverflowClipBoxBlock) ==
               StyleOverflowClipBox::ContentBox;
    // We only clip if there is *scrollable* overflow, to avoid clipping
    // *ink* overflow unnecessarily.
    nsRect clipRect = effectiveScrollPort + aBuilder->ToReferenceFrame(this);
    nsMargin padding = GetUsedPadding();
    if (!cbH) {
      padding.left = padding.right = nscoord(0);
    }
    if (!cbV) {
      padding.top = padding.bottom = nscoord(0);
    }
    clipRect.Deflate(padding);

    nsRect so = mScrolledFrame->ScrollableOverflowRect();
    if ((cbH && (clipRect.width != so.width || so.x < 0)) ||
        (cbV && (clipRect.height != so.height || so.y < 0))) {
      // The non-inflated clip needs to be set on all non-caret items.
      // We prepare an extra DisplayItemClipChain here that will be intersected
      // with those items after they've been created.
      const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();

      DisplayItemClip newClip;
      newClip.SetTo(clipRect);

      const DisplayItemClipChain* extraClip =
          aBuilder->AllocateDisplayItemClipChain(newClip, asr, nullptr);

      extraContentBoxClipForNonCaretContent = Some(extraClip);

      nsIFrame* caretFrame = aBuilder->GetCaretFrame();
      // Avoid clipping it in a zero-height line box (heuristic only).
      if (caretFrame && caretFrame->GetRect().height != 0) {
        nsRect caretRect = aBuilder->GetCaretRect();
        // Allow the caret to stick out of the content box clip by half the
        // caret height on the top, and its full width on the right.
        nsRect inflatedClip = clipRect;
        inflatedClip.Inflate(
            nsMargin(caretRect.height / 2, caretRect.width, 0, 0));
        contentBoxClip = Some(inflatedClip);
      }
    }
  }

  AutoContainsBlendModeCapturer blendCapture(*aBuilder);

  const bool willBuildAsyncZoomContainer =
      mWillBuildScrollableLayer && aBuilder->ShouldBuildAsyncZoomContainer() &&
      isRootContent;

  nsRect scrollPortClip =
      effectiveScrollPort + aBuilder->ToReferenceFrame(this);
  nsRect clipRect = scrollPortClip;
  // Our override of GetBorderRadii ensures we never have a radius at
  // the corners where we have a scrollbar.
  nscoord radii[8];
  const bool haveRadii = GetPaddingBoxBorderRadii(radii);
  if (mIsRoot) {
    clipRect.SizeTo(nsLayoutUtils::CalculateCompositionSizeForFrame(
        this, true /* aSubtractScrollbars */,
        nullptr /* aOverrideScrollPortSize */,
        // With the dynamic toolbar, this CalculateCompositionSizeForFrame call
        // basically expands the region being covered up by the dynamic toolbar,
        // but if the root scroll container is not scrollable, e.g. the root
        // element has `overflow: hidden` or `position: fixed`, the function
        // doesn't expand the region since expanding the region in such cases
        // will prevent the content from restoring zooming to 1.0 zoom level
        // such as bug 1652190. That said, this `clipRect` which will be used
        // for the async zoom container needs to be expanded because zoomed-in
        // contents can be scrollable __visually__ so that the region under the
        // dynamic toolbar area will be revealed.
        nsLayoutUtils::IncludeDynamicToolbar::Force));

    // The composition size is essentially in visual coordinates.
    // If we are hit-testing in layout coordinates, transform the clip rect
    // to layout coordinates to match.
    if (aBuilder->IsRelativeToLayoutViewport() && isRootContent) {
      clipRect = ViewportUtils::VisualToLayout(clipRect, PresShell());
    }
  }

  {
    DisplayListClipState::AutoSaveRestore clipState(aBuilder);

    // If we're building an async zoom container, clip the contents inside
    // to the layout viewport (scrollPortClip). The composition bounds clip
    // (clipRect) will be applied to the zoom container itself in
    // MaybeCreateTopLayerAndWrapRootItems.
    nsRect clipRectForContents =
        willBuildAsyncZoomContainer ? scrollPortClip : clipRect;
    if (mIsRoot) {
      clipState.ClipContentDescendants(clipRectForContents,
                                       haveRadii ? radii : nullptr);
    } else {
      clipState.ClipContainingBlockDescendants(clipRectForContents,
                                               haveRadii ? radii : nullptr);
    }

    Maybe<DisplayListClipState::AutoSaveRestore> contentBoxClipState;
    if (contentBoxClip) {
      contentBoxClipState.emplace(aBuilder);
      if (mIsRoot) {
        contentBoxClipState->ClipContentDescendants(*contentBoxClip);
      } else {
        contentBoxClipState->ClipContainingBlockDescendants(*contentBoxClip);
      }
    }

    nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(
        aBuilder);

    if (mWillBuildScrollableLayer && aBuilder->IsPaintingToWindow()) {
      // If this scroll frame has a first scrollable frame sequence number,
      // ensure that it matches the current paint sequence number. If it does
      // not, reset it so that we can expire the displayport. The stored
      // sequence number will not match that of the current paint if the dom
      // was mutated in some way that alters the order of scroll frames.
      if (IsFirstScrollableFrameSequenceNumber().isSome() &&
          *IsFirstScrollableFrameSequenceNumber() !=
              nsDisplayListBuilder::GetPaintSequenceNumber()) {
        SetIsFirstScrollableFrameSequenceNumber(Nothing());
      }
      asrSetter.EnterScrollFrame(this);
    }

    if (couldBuildLayer && mScrolledFrame->GetContent()) {
      asrSetter.SetCurrentScrollParentId(
          nsLayoutUtils::FindOrCreateIDFor(mScrolledFrame->GetContent()));
    }

    if (mWillBuildScrollableLayer && aBuilder->BuildCompositorHitTestInfo()) {
      // Create a hit test info item for the scrolled content that's not
      // clipped to the displayport. This ensures that within the bounds
      // of the scroll frame, the scrolled content is always hit, even
      // if we are checkerboarding.
      CompositorHitTestInfo info =
          mScrolledFrame->GetCompositorHitTestInfo(aBuilder);

      if (info != CompositorHitTestInvisibleToHit) {
        auto* hitInfo =
            MakeDisplayItemWithIndex<nsDisplayCompositorHitTestInfo>(
                aBuilder, mScrolledFrame, 1);
        if (hitInfo) {
          aBuilder->SetCompositorHitTestInfo(info);
          set.BorderBackground()->AppendToTop(hitInfo);
        }
      }
    }

    {
      // Clip our contents to the unsnapped scrolled rect. This makes sure
      // that we don't have display items over the subpixel seam at the edge
      // of the scrolled area.
      DisplayListClipState::AutoSaveRestore scrolledRectClipState(aBuilder);
      nsRect scrolledRectClip =
          GetUnsnappedScrolledRectInternal(
              mScrolledFrame->ScrollableOverflowRect(), mScrollPort.Size()) +
          mScrolledFrame->GetPosition();
      bool clippedToDisplayPort = false;
      if (mWillBuildScrollableLayer && aBuilder->IsPaintingToWindow()) {
        // Clip the contents to the display port.
        // The dirty rect already acts kind of like a clip, in that
        // FrameLayerBuilder intersects item bounds and opaque regions with
        // it, but it doesn't have the consistent snapping behavior of a
        // true clip.
        // For a case where this makes a difference, imagine the following
        // scenario: The display port has an edge that falls on a fractional
        // layer pixel, and there's an opaque display item that covers the
        // whole display port up until that fractional edge, and there is a
        // transparent display item that overlaps the edge. We want to prevent
        // this transparent item from enlarging the scrolled layer's visible
        // region beyond its opaque region. The dirty rect doesn't do that -
        // it gets rounded out, whereas a true clip gets rounded to nearest
        // pixels.
        // If there is no display port, we don't need this because the clip
        // from the scroll port is still applied.
        scrolledRectClip = scrolledRectClip.Intersect(visibleRect);
        clippedToDisplayPort = scrolledRectClip.IsEqualEdges(visibleRect);
      }
      scrolledRectClipState.ClipContainingBlockDescendants(
          scrolledRectClip + aBuilder->ToReferenceFrame(this));
      if (clippedToDisplayPort) {
        // We have to do this after the ClipContainingBlockDescendants call
        // above, otherwise that call will clobber the flag set by this call
        // to SetClippedToDisplayPort.
        scrolledRectClipState.SetClippedToDisplayPort();
      }

      nsRect visibleRectForChildren = visibleRect;
      nsRect dirtyRectForChildren = dirtyRect;

      // If we are entering the RCD-RSF, we are crossing the async zoom
      // container boundary, and need to convert from visual to layout
      // coordinates.
      if (willBuildAsyncZoomContainer && aBuilder->IsForEventDelivery()) {
        MOZ_ASSERT(ViewportUtils::IsZoomedContentRoot(mScrolledFrame));
        visibleRectForChildren =
            ViewportUtils::VisualToLayout(visibleRectForChildren, PresShell());
        dirtyRectForChildren =
            ViewportUtils::VisualToLayout(dirtyRectForChildren, PresShell());
      }

      nsDisplayListBuilder::AutoBuildingDisplayList building(
          aBuilder, this, visibleRectForChildren, dirtyRectForChildren);

      BuildDisplayListForChild(aBuilder, mScrolledFrame, set);

      if (dirtyRectHasBeenOverriden &&
          StaticPrefs::layout_display_list_show_rebuild_area()) {
        nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
            aBuilder, this,
            dirtyRect + aBuilder->GetCurrentFrameOffsetToReferenceFrame(),
            NS_RGBA(0, 0, 255, 64), false);
        if (color) {
          color->SetOverrideZIndex(INT32_MAX);
          set.PositionedDescendants()->AppendToTop(color);
        }
      }
    }

    if (extraContentBoxClipForNonCaretContent) {
      // The items were built while the inflated content box clip was in
      // effect, so that the caret wasn't clipped unnecessarily. We apply
      // the non-inflated clip to the non-caret items now, by intersecting
      // it with their existing clip.
      ClipListsExceptCaret(&set, aBuilder, mScrolledFrame,
                           *extraContentBoxClipForNonCaretContent);
    }

    if (aBuilder->IsPaintingToWindow()) {
      mIsParentToActiveScrollFrames =
          ShouldActivateAllScrollFrames()
              ? asrSetter.GetContainsNonMinimalDisplayPort()
              : asrSetter.ShouldForceLayerForScrollParent();
    }

    if (asrSetter.ShouldForceLayerForScrollParent()) {
      // Note that forcing layerization of scroll parents follows the scroll
      // handoff chain which is subject to the out-of-flow-frames caveat noted
      // above (where the asrSetter variable is created).
      MOZ_ASSERT(couldBuildLayer && mScrolledFrame->GetContent() &&
                 aBuilder->IsPaintingToWindow());
      if (!mWillBuildScrollableLayer) {
        // Set a displayport so next paint we don't have to force layerization
        // after the fact. It's ok to pass DoNotRepaint here, since we've
        // already painted the change and we're just optimizing it to be
        // detected earlier. We also won't confuse RetainedDisplayLists
        // with the silent change, since we explicitly request partial updates
        // to be disabled on the next paint.
        DisplayPortUtils::SetDisplayPortMargins(
            GetContent(), PresShell(), DisplayPortMargins::Empty(GetContent()),
            DisplayPortUtils::ClearMinimalDisplayPortProperty::Yes, 0,
            DisplayPortUtils::RepaintMode::DoNotRepaint);
        // Call DecideScrollableLayer to recompute mWillBuildScrollableLayer
        // and recompute the current animated geometry root if needed. It's
        // too late to change the dirty rect so pass a copy.
        nsRect copyOfDirtyRect = dirtyRect;
        nsRect copyOfVisibleRect = visibleRect;
        Unused << DecideScrollableLayer(aBuilder, &copyOfVisibleRect,
                                        &copyOfDirtyRect,
                                        /* aSetBase = */ false, nullptr);
        if (mWillBuildScrollableLayer) {
#ifndef MOZ_WIDGET_ANDROID
          gfxCriticalNoteOnce << "inserted scroll frame";
#endif
          asrSetter.InsertScrollFrame(this);
          aBuilder->SetDisablePartialUpdates(true);
        }
      }
    }
  }

  if (mWillBuildScrollableLayer && aBuilder->IsPaintingToWindow()) {
    aBuilder->ForceLayerForScrollParent();
  }

  MaybeCreateTopLayerAndWrapRootItems(
      aBuilder, set, willBuildAsyncZoomContainer, &blendCapture, clipRect,
      haveRadii ? radii : nullptr);

  // We want to call SetContainsNonMinimalDisplayPort if
  // mWillBuildScrollableLayer is true for any reason other than having a
  // minimal display port.
  if (aBuilder->IsPaintingToWindow()) {
    if (DisplayPortUtils::HasNonMinimalDisplayPort(GetContent()) ||
        mZoomableByAPZ || nsContentUtils::HasScrollgrab(GetContent())) {
      aBuilder->SetContainsNonMinimalDisplayPort();
    }
  }

  if (couldBuildLayer) {
    CompositorHitTestInfo info(CompositorHitTestFlags::eVisibleToHitTest,
                               CompositorHitTestFlags::eInactiveScrollframe);
    // If the scroll frame has non-default overscroll-behavior, instruct
    // APZ to require a target confirmation before processing events that
    // hit this scroll frame (that is, to drop the events if a
    // confirmation does not arrive within the timeout period). Otherwise,
    // APZ's fallback behaviour of scrolling the enclosing scroll frame
    // would violate the specified overscroll-behavior.
    auto overscroll = GetOverscrollBehaviorInfo();
    if (overscroll.mBehaviorX != OverscrollBehavior::Auto ||
        overscroll.mBehaviorY != OverscrollBehavior::Auto) {
      info += CompositorHitTestFlags::eRequiresTargetConfirmation;
    }

    nsRect area = effectiveScrollPort + aBuilder->ToReferenceFrame(this);

    // Make sure that APZ will dispatch events back to content so we can
    // create a displayport for this frame. We'll add the item later on.
    if (!mWillBuildScrollableLayer && aBuilder->BuildCompositorHitTestInfo()) {
      // Make sure the z-index of the inactive item is at least zero.
      // Otherwise, it will end up behind non-positioned items in the scrolled
      // content.
      int32_t zIndex = MaxZIndexInListOfItemsContainedInFrame(
                           set.PositionedDescendants(), this)
                           .valueOr(0);
      if (aBuilder->IsPartialUpdate()) {
        for (nsDisplayItem* item : mScrolledFrame->DisplayItems()) {
          if (item->GetType() ==
              DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO) {
            auto* hitTestItem =
                static_cast<nsDisplayCompositorHitTestInfo*>(item);
            if (hitTestItem->GetHitTestInfo().Info().contains(
                    CompositorHitTestFlags::eInactiveScrollframe)) {
              zIndex = std::max(zIndex, hitTestItem->ZIndex());
              item->SetCantBeReused();
            }
          }
        }
      }
      nsDisplayCompositorHitTestInfo* hitInfo =
          MakeDisplayItemWithIndex<nsDisplayCompositorHitTestInfo>(
              aBuilder, mScrolledFrame, 1, area, info);
      if (hitInfo) {
        AppendInternalItemToTop(set, hitInfo, Some(zIndex));
        aBuilder->SetCompositorHitTestInfo(info);
      }
    }

    if (aBuilder->ShouldBuildScrollInfoItemsForHoisting()) {
      aBuilder->AppendNewScrollInfoItemForHoisting(
          MakeDisplayItem<nsDisplayScrollInfoLayer>(aBuilder, mScrolledFrame,
                                                    this, info, area));
    }
  }

  // Now display overlay scrollbars and the resizer, if we have one.
  AppendScrollPartsTo(aBuilder, set, createLayersForScrollbars, true);

  set.MoveTo(aLists);
}

nsRect nsHTMLScrollFrame::RestrictToRootDisplayPort(
    const nsRect& aDisplayportBase) {
  // This function clips aDisplayportBase so that it is no larger than the
  // root frame's displayport (or the root composition bounds, if we can't
  // obtain the root frame's displayport). This is useful for ensuring that
  // the displayport of a tall scrollframe doesn't gobble up all the memory.

  nsPresContext* pc = PresContext();
  const nsPresContext* rootPresContext =
      pc->GetInProcessRootContentDocumentPresContext();
  if (!rootPresContext) {
    rootPresContext = pc->GetRootPresContext();
  }
  if (!rootPresContext) {
    return aDisplayportBase;
  }
  const mozilla::PresShell* const rootPresShell = rootPresContext->PresShell();
  nsIFrame* rootFrame = rootPresShell->GetRootScrollFrame();
  if (!rootFrame) {
    rootFrame = rootPresShell->GetRootFrame();
  }
  if (!rootFrame) {
    return aDisplayportBase;
  }

  // Make sure we aren't trying to restrict to our own displayport, which is a
  // circular dependency.
  MOZ_ASSERT(!mIsRoot || rootPresContext != pc);

  nsRect rootDisplayPort;
  bool hasDisplayPort =
      rootFrame->GetContent() && DisplayPortUtils::GetDisplayPort(
                                     rootFrame->GetContent(), &rootDisplayPort);
  if (hasDisplayPort) {
    // The display port of the root frame already factors in it's callback
    // transform, so subtract it out here, the GetCumulativeApzCallbackTransform
    // call below will add it back.
    MOZ_LOG(sDisplayportLog, LogLevel::Verbose,
            ("RestrictToRootDisplayPort: Existing root displayport is %s\n",
             ToString(rootDisplayPort).c_str()));
    if (nsIContent* content = rootFrame->GetContent()) {
      if (void* property =
              content->GetProperty(nsGkAtoms::apzCallbackTransform)) {
        rootDisplayPort -=
            CSSPoint::ToAppUnits(*static_cast<CSSPoint*>(property));
      }
    }
  } else {
    // If we don't have a display port on the root frame let's fall back to
    // the root composition bounds instead.
    nsRect rootCompBounds =
        nsRect(nsPoint(0, 0),
               nsLayoutUtils::CalculateCompositionSizeForFrame(rootFrame));

    // If rootFrame is the RCD-RSF then
    // CalculateCompositionSizeForFrame did not take the document's
    // resolution into account, so we must.
    if (rootPresContext->IsRootContentDocumentCrossProcess() &&
        rootFrame == rootPresShell->GetRootScrollFrame()) {
      MOZ_LOG(
          sDisplayportLog, LogLevel::Verbose,
          ("RestrictToRootDisplayPort: Removing resolution %f from root "
           "composition bounds %s\n",
           rootPresShell->GetResolution(), ToString(rootCompBounds).c_str()));
      rootCompBounds =
          rootCompBounds.RemoveResolution(rootPresShell->GetResolution());
    }

    rootDisplayPort = rootCompBounds;
  }
  MOZ_LOG(sDisplayportLog, LogLevel::Verbose,
          ("RestrictToRootDisplayPort: Intermediate root displayport %s\n",
           ToString(rootDisplayPort).c_str()));

  // We want to convert the root display port from the
  // coordinate space of |rootFrame| to the coordinate space of
  // |this|. We do that with the TransformRect call below.
  // However, since we care about the root display port
  // relative to what the user is actually seeing, we also need to
  // incorporate the APZ callback transforms into this. Most of the
  // time those transforms are negligible, but in some cases (e.g.
  // when a zoom is applied on an overflow:hidden document) it is
  // not (see bug 1280013).
  // XXX: Eventually we may want to create a modified version of
  // TransformRect that includes the APZ callback transforms
  // directly.
  nsLayoutUtils::TransformRect(rootFrame, this, rootDisplayPort);
  MOZ_LOG(sDisplayportLog, LogLevel::Verbose,
          ("RestrictToRootDisplayPort: Transformed root displayport %s\n",
           ToString(rootDisplayPort).c_str()));
  rootDisplayPort += CSSPoint::ToAppUnits(
      nsLayoutUtils::GetCumulativeApzCallbackTransform(this));
  MOZ_LOG(sDisplayportLog, LogLevel::Verbose,
          ("RestrictToRootDisplayPort: Final root displayport %s\n",
           ToString(rootDisplayPort).c_str()));

  // We want to limit aDisplayportBase to be no larger than
  // rootDisplayPort on either axis, but we don't want to just
  // blindly intersect the two, because rootDisplayPort might be
  // offset from where aDisplayportBase is (see bug 1327095 comment
  // 8). Instead, we translate rootDisplayPort so as to maximize the
  // overlap with aDisplayportBase, and *then* do the intersection.
  if (rootDisplayPort.x > aDisplayportBase.x &&
      rootDisplayPort.XMost() > aDisplayportBase.XMost()) {
    // rootDisplayPort is at a greater x-position for both left and
    // right, so translate it such that the XMost() values are the
    // same. This will line up the right edge of the two rects, and
    // might mean that rootDisplayPort.x is smaller than
    // aDisplayportBase.x. We can avoid that by taking the min of the
    // x delta and XMost() delta, but it doesn't really matter
    // because the intersection between the two rects below will end
    // up the same.
    rootDisplayPort.x -= (rootDisplayPort.XMost() - aDisplayportBase.XMost());
  } else if (rootDisplayPort.x < aDisplayportBase.x &&
             rootDisplayPort.XMost() < aDisplayportBase.XMost()) {
    // Analaogous code for when the rootDisplayPort is at a smaller
    // x-position.
    rootDisplayPort.x = aDisplayportBase.x;
  }
  // Do the same for y-axis
  if (rootDisplayPort.y > aDisplayportBase.y &&
      rootDisplayPort.YMost() > aDisplayportBase.YMost()) {
    rootDisplayPort.y -= (rootDisplayPort.YMost() - aDisplayportBase.YMost());
  } else if (rootDisplayPort.y < aDisplayportBase.y &&
             rootDisplayPort.YMost() < aDisplayportBase.YMost()) {
    rootDisplayPort.y = aDisplayportBase.y;
  }
  MOZ_LOG(
      sDisplayportLog, LogLevel::Verbose,
      ("RestrictToRootDisplayPort: Root displayport translated to %s to "
       "better enclose %s\n",
       ToString(rootDisplayPort).c_str(), ToString(aDisplayportBase).c_str()));

  // Now we can do the intersection
  return aDisplayportBase.Intersect(rootDisplayPort);
}

/* static */ bool nsHTMLScrollFrame::ShouldActivateAllScrollFrames() {
  return (StaticPrefs::apz_wr_activate_all_scroll_frames() ||
          (StaticPrefs::apz_wr_activate_all_scroll_frames_when_fission() &&
           FissionAutostart()));
}

bool nsHTMLScrollFrame::DecideScrollableLayer(
    nsDisplayListBuilder* aBuilder, nsRect* aVisibleRect, nsRect* aDirtyRect,
    bool aSetBase, bool* aDirtyRectHasBeenOverriden) {
  nsIContent* content = GetContent();
  bool hasDisplayPort = DisplayPortUtils::HasDisplayPort(content);
  // For hit testing purposes with fission we want to create a
  // minimal display port for every scroll frame that could be active. (We only
  // do this when aSetBase is true because we only want to do this the first
  // time this function is called for the same scroll frame.)
  if (aSetBase && !hasDisplayPort && aBuilder->IsPaintingToWindow() &&
      ShouldActivateAllScrollFrames() &&
      nsLayoutUtils::AsyncPanZoomEnabled(this) && WantAsyncScroll()) {
    // SetDisplayPortMargins calls TriggerDisplayPortExpiration which starts a
    // display port expiry timer for display ports that do expire. However
    // minimal display ports do not expire, so the display port has to be
    // marked before the SetDisplayPortMargins call so the expiry timer
    // doesn't get started.
    content->SetProperty(nsGkAtoms::MinimalDisplayPort,
                         reinterpret_cast<void*>(true));

    DisplayPortUtils::SetDisplayPortMargins(
        content, PresShell(), DisplayPortMargins::Empty(content),
        DisplayPortUtils::ClearMinimalDisplayPortProperty::No, 0,
        DisplayPortUtils::RepaintMode::DoNotRepaint);
    hasDisplayPort = true;
  }

  if (aBuilder->IsPaintingToWindow()) {
    if (aSetBase) {
      nsRect displayportBase = *aVisibleRect;
      nsPresContext* pc = PresContext();

      bool isChromeRootDoc =
          !pc->Document()->IsContentDocument() && !pc->GetParentPresContext();

      if (mIsRoot &&
          (pc->IsRootContentDocumentCrossProcess() || isChromeRootDoc)) {
        displayportBase =
            nsRect(nsPoint(0, 0),
                   nsLayoutUtils::CalculateCompositionSizeForFrame(this));
      } else {
        // Make the displayport base equal to the visible rect restricted to
        // the scrollport and the root composition bounds, relative to the
        // scrollport.
        displayportBase = aVisibleRect->Intersect(mScrollPort);

        mozilla::layers::ScrollableLayerGuid::ViewID viewID =
            mozilla::layers::ScrollableLayerGuid::NULL_SCROLL_ID;
        if (MOZ_LOG_TEST(sDisplayportLog, LogLevel::Verbose)) {
          nsLayoutUtils::FindIDFor(GetContent(), &viewID);
          MOZ_LOG(
              sDisplayportLog, LogLevel::Verbose,
              ("Scroll id %" PRIu64 " has visible rect %s, scroll port %s\n",
               viewID, ToString(*aVisibleRect).c_str(),
               ToString(mScrollPort).c_str()));
        }

        // Only restrict to the root displayport bounds if necessary,
        // as the required coordinate transformation is expensive.
        // And don't call RestrictToRootDisplayPort if we would be trying to
        // restrict to our own display port, which doesn't make sense (ie if we
        // are a root scroll frame in a process root prescontext).
        if (hasDisplayPort && (!mIsRoot || pc->GetParentPresContext()) &&
            !DisplayPortUtils::WillUseEmptyDisplayPortMargins(content)) {
          displayportBase = RestrictToRootDisplayPort(displayportBase);
          MOZ_LOG(sDisplayportLog, LogLevel::Verbose,
                  ("Scroll id %" PRIu64 " has restricted base %s\n", viewID,
                   ToString(displayportBase).c_str()));
        }
        displayportBase -= mScrollPort.TopLeft();
      }

      DisplayPortUtils::SetDisplayPortBase(GetContent(), displayportBase);
    }

    // If we don't have aSetBase == true then should have already
    // been called with aSetBase == true which should have set a
    // displayport base.
    MOZ_ASSERT(content->GetProperty(nsGkAtoms::DisplayPortBase));
    nsRect displayPort;
    hasDisplayPort = DisplayPortUtils::GetDisplayPort(
        content, &displayPort,
        DisplayPortOptions().With(DisplayportRelativeTo::ScrollFrame));

    auto OverrideDirtyRect = [&](const nsRect& aRect) {
      *aDirtyRect = aRect;
      if (aDirtyRectHasBeenOverriden) {
        *aDirtyRectHasBeenOverriden = true;
      }
    };

    if (hasDisplayPort) {
      // Override the dirty rectangle if the displayport has been set.
      *aVisibleRect = displayPort;
      if (aBuilder->IsReusingStackingContextItems() ||
          !aBuilder->IsPartialUpdate() || aBuilder->InInvalidSubtree() ||
          IsFrameModified()) {
        OverrideDirtyRect(displayPort);
      } else if (HasOverrideDirtyRegion()) {
        nsRect* rect = GetProperty(
            nsDisplayListBuilder::DisplayListBuildingDisplayPortRect());
        if (rect) {
          OverrideDirtyRect(*rect);
        }
      }
    } else if (mIsRoot) {
      // The displayPort getter takes care of adjusting for resolution. So if
      // we have resolution but no displayPort then we need to adjust for
      // resolution here.
      auto* presShell = PresShell();
      *aVisibleRect =
          aVisibleRect->RemoveResolution(presShell->GetResolution());
      *aDirtyRect = aDirtyRect->RemoveResolution(presShell->GetResolution());
    }
  }

  // Since making new layers is expensive, only create a scrollable layer
  // for some scroll frames.
  // When a displayport is being used, force building of a layer so that
  // the compositor can find the scrollable layer for async scrolling.
  // If the element is marked 'scrollgrab', also force building of a layer
  // so that APZ can implement scroll grabbing.
  mWillBuildScrollableLayer = hasDisplayPort ||
                              nsContentUtils::HasScrollgrab(content) ||
                              mZoomableByAPZ;
  return mWillBuildScrollableLayer;
}

void nsHTMLScrollFrame::NotifyApzTransaction() {
  mAllowScrollOriginDowngrade = true;
  mApzScrollPos = GetScrollPosition();
  mApzAnimationRequested = IsLastScrollUpdateAnimating();
  mApzAnimationTriggeredByScriptRequested =
      IsLastScrollUpdateTriggeredByScriptAnimating();
  mScrollUpdates.Clear();
  if (mIsRoot) {
    PresShell()->SetResolutionUpdated(false);
  }
}

Maybe<ScrollMetadata> nsHTMLScrollFrame::ComputeScrollMetadata(
    WebRenderLayerManager* aLayerManager, const nsIFrame* aItemFrame,
    const nsPoint& aOffsetToReferenceFrame) const {
  if (!mWillBuildScrollableLayer) {
    return Nothing();
  }

  bool isRootContent =
      mIsRoot && PresContext()->IsRootContentDocumentCrossProcess();

  MOZ_ASSERT(mScrolledFrame->GetContent());

  return Some(nsLayoutUtils::ComputeScrollMetadata(
      mScrolledFrame, this, GetContent(), aItemFrame, aOffsetToReferenceFrame,
      aLayerManager, mScrollParentID, mScrollPort.Size(), isRootContent));
}

bool nsHTMLScrollFrame::IsRectNearlyVisible(const nsRect& aRect) const {
  // Use the right rect depending on if a display port is set.
  nsRect displayPort;
  bool usingDisplayport = DisplayPortUtils::GetDisplayPort(
      GetContent(), &displayPort,
      DisplayPortOptions().With(DisplayportRelativeTo::ScrollFrame));

  if (mIsRoot && !usingDisplayport &&
      PresContext()->IsRootContentDocumentInProcess() &&
      !PresContext()->IsRootContentDocumentCrossProcess()) {
    // In the case of the root scroller of OOP iframes, there are cases where
    // any display port value isn't set, e.g. the iframe element is out of view
    // in the parent document. In such cases we'd consider the iframe is not
    // visible.
    return false;
  }

  return aRect.Intersects(
      ExpandRectToNearlyVisible(usingDisplayport ? displayPort : mScrollPort));
}

OverscrollBehaviorInfo nsHTMLScrollFrame::GetOverscrollBehaviorInfo() const {
  nsIFrame* frame = GetFrameForStyle();
  if (!frame) {
    return {};
  }

  auto& disp = *frame->StyleDisplay();
  return OverscrollBehaviorInfo::FromStyleConstants(disp.mOverscrollBehaviorX,
                                                    disp.mOverscrollBehaviorY);
}

ScrollStyles nsHTMLScrollFrame::GetScrollStyles() const {
  nsPresContext* presContext = PresContext();
  if (!presContext->IsDynamic() &&
      !(mIsRoot && presContext->HasPaginatedScrolling())) {
    return ScrollStyles(StyleOverflow::Hidden, StyleOverflow::Hidden);
  }

  if (!mIsRoot) {
    return ScrollStyles(*StyleDisplay(),
                        ScrollStyles::MapOverflowToValidScrollStyle);
  }

  ScrollStyles result = presContext->GetViewportScrollStylesOverride();
  if (nsDocShell* ds = presContext->GetDocShell()) {
    switch (ds->ScrollbarPreference()) {
      case ScrollbarPreference::Auto:
        break;
      case ScrollbarPreference::Never:
        result.mHorizontal = result.mVertical = StyleOverflow::Hidden;
        break;
    }
  }
  return result;
}

nsRect nsHTMLScrollFrame::GetLayoutScrollRange() const {
  return GetScrollRange(mScrollPort.width, mScrollPort.height);
}

nsRect nsHTMLScrollFrame::GetScrollRange(nscoord aWidth,
                                         nscoord aHeight) const {
  nsRect range = GetScrolledRect();
  range.width = std::max(range.width - aWidth, 0);
  range.height = std::max(range.height - aHeight, 0);
  return range;
}

nsRect nsHTMLScrollFrame::GetVisualScrollRange() const {
  nsSize visualViewportSize = GetVisualViewportSize();
  return GetScrollRange(visualViewportSize.width, visualViewportSize.height);
}

nsSize nsHTMLScrollFrame::GetVisualViewportSize() const {
  auto* presShell = PresShell();
  if (mIsRoot && presShell->IsVisualViewportSizeSet()) {
    return presShell->GetVisualViewportSize();
  }
  return mScrollPort.Size();
}

nsPoint nsHTMLScrollFrame::GetVisualViewportOffset() const {
  if (mIsRoot) {
    auto* presShell = PresShell();
    if (auto pendingUpdate = presShell->GetPendingVisualScrollUpdate()) {
      // The pending visual scroll update on the PresShell contains a raw,
      // unclamped offset (basically, whatever was passed to ScrollToVisual()).
      // It will be clamped on the APZ side, but if we use it as the
      // main-thread's visual viewport offset we need to clamp it ourselves.
      // Use GetScrollRangeForUserInputEvents() to do the clamping because this
      // the scroll range that APZ will use.
      return GetScrollRangeForUserInputEvents().ClampPoint(
          pendingUpdate->mVisualScrollOffset);
    }
    return presShell->GetVisualViewportOffset();
  }
  return GetScrollPosition();
}

bool nsHTMLScrollFrame::SetVisualViewportOffset(const nsPoint& aOffset,
                                                bool aRepaint) {
  MOZ_ASSERT(mIsRoot);
  AutoWeakFrame weakFrame(this);
  AutoScrollbarRepaintSuppression repaintSuppression(this, weakFrame,
                                                     !aRepaint);

  bool retVal =
      PresShell()->SetVisualViewportOffset(aOffset, GetScrollPosition());
  if (!weakFrame.IsAlive()) {
    return false;
  }
  return retVal;
}

nsRect nsHTMLScrollFrame::GetVisualOptimalViewingRect() const {
  auto* presShell = PresShell();
  nsRect rect = mScrollPort;
  if (mIsRoot && presShell->IsVisualViewportSizeSet() &&
      presShell->IsVisualViewportOffsetSet()) {
    rect = nsRect(mScrollPort.TopLeft() - GetScrollPosition() +
                      presShell->GetVisualViewportOffset(),
                  presShell->GetVisualViewportSize());
  }
  // NOTE: We intentionally resolve scroll-padding percentages against the
  // scrollport even when the visual viewport is set, see
  // https://github.com/w3c/csswg-drafts/issues/4393.
  rect.Deflate(GetScrollPadding());
  return rect;
}

static void AdjustDestinationForWholeDelta(const nsIntPoint& aDelta,
                                           const nsRect& aScrollRange,
                                           nsPoint& aPoint) {
  if (aDelta.x < 0) {
    aPoint.x = aScrollRange.X();
  } else if (aDelta.x > 0) {
    aPoint.x = aScrollRange.XMost();
  }
  if (aDelta.y < 0) {
    aPoint.y = aScrollRange.Y();
  } else if (aDelta.y > 0) {
    aPoint.y = aScrollRange.YMost();
  }
}

/**
 * Calculate lower/upper scrollBy range in given direction.
 * @param aDelta specifies scrollBy direction, if 0 then range will be 0 size
 * @param aPos desired destination in AppUnits
 * @param aNeg/PosTolerance defines relative range distance
 *   below and above of aPos point
 * @param aMultiplier used for conversion of tolerance into appUnis
 */
static void CalcRangeForScrollBy(int32_t aDelta, nscoord aPos,
                                 float aNegTolerance, float aPosTolerance,
                                 nscoord aMultiplier, nscoord* aLower,
                                 nscoord* aUpper) {
  if (!aDelta) {
    *aLower = *aUpper = aPos;
    return;
  }
  *aLower = aPos - NSToCoordRound(aMultiplier *
                                  (aDelta > 0 ? aNegTolerance : aPosTolerance));
  *aUpper = aPos + NSToCoordRound(aMultiplier *
                                  (aDelta > 0 ? aPosTolerance : aNegTolerance));
}

void nsHTMLScrollFrame::ScrollBy(nsIntPoint aDelta, ScrollUnit aUnit,
                                 ScrollMode aMode, nsIntPoint* aOverflow,
                                 ScrollOrigin aOrigin,
                                 nsIScrollableFrame::ScrollMomentum aMomentum,
                                 ScrollSnapFlags aSnapFlags) {
  // When a smooth scroll is being processed on a frame, mouse wheel and
  // trackpad momentum scroll event updates must notcancel the SMOOTH or
  // SMOOTH_MSD scroll animations, enabling Javascript that depends on them to
  // be responsive without forcing the user to wait for the fling animations to
  // completely stop.
  switch (aMomentum) {
    case nsIScrollableFrame::NOT_MOMENTUM:
      mIgnoreMomentumScroll = false;
      break;
    case nsIScrollableFrame::SYNTHESIZED_MOMENTUM_EVENT:
      if (mIgnoreMomentumScroll) {
        return;
      }
      break;
  }

  if (mAsyncSmoothMSDScroll != nullptr) {
    // When CSSOM-View scroll-behavior smooth scrolling is interrupted,
    // the scroll is not completed to avoid non-smooth snapping to the
    // prior smooth scroll's destination.
    mDestination = GetScrollPosition();
  }

  nsSize deltaMultiplier;
  float negativeTolerance;
  float positiveTolerance;
  if (aOrigin == ScrollOrigin::NotSpecified) {
    aOrigin = ScrollOrigin::Other;
  }
  bool isGenericOrigin = (aOrigin == ScrollOrigin::Other);

  bool askApzToDoTheScroll = false;
  if ((aSnapFlags == ScrollSnapFlags::Disabled || !NeedsScrollSnap()) &&
      gfxPlatform::UseDesktopZoomingScrollbars() &&
      nsLayoutUtils::AsyncPanZoomEnabled(this) &&
      !nsLayoutUtils::ShouldDisableApzForElement(GetContent()) &&
      (WantAsyncScroll() || mZoomableByAPZ) &&
      CanApzScrollInTheseDirections(DirectionsInDelta(aDelta))) {
    askApzToDoTheScroll = true;
  }

  switch (aUnit) {
    case ScrollUnit::DEVICE_PIXELS: {
      nscoord appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
      deltaMultiplier = nsSize(appUnitsPerDevPixel, appUnitsPerDevPixel);
      if (isGenericOrigin) {
        aOrigin = ScrollOrigin::Pixels;
      }
      negativeTolerance = positiveTolerance = 0.5f;
      break;
    }
    case ScrollUnit::LINES: {
      deltaMultiplier = GetLineScrollAmount();
      if (isGenericOrigin) {
        aOrigin = ScrollOrigin::Lines;
      }
      negativeTolerance = positiveTolerance = 0.1f;
      break;
    }
    case ScrollUnit::PAGES: {
      deltaMultiplier = GetPageScrollAmount();
      if (isGenericOrigin) {
        aOrigin = ScrollOrigin::Pages;
      }
      negativeTolerance = 0.05f;
      positiveTolerance = 0;
      break;
    }
    case ScrollUnit::WHOLE: {
      if (askApzToDoTheScroll) {
        MOZ_ASSERT(aDelta.x >= -1 && aDelta.x <= 1 && aDelta.y >= -1 &&
                   aDelta.y <= 1);
        deltaMultiplier = GetScrollRangeForUserInputEvents().Size();
        break;
      } else {
        nsPoint pos = GetScrollPosition();
        AdjustDestinationForWholeDelta(aDelta, GetLayoutScrollRange(), pos);
        ScrollToWithOrigin(
            pos, nullptr /* range */,
            ScrollOperationParams{aMode, ScrollOrigin::Other, aSnapFlags,
                                  ScrollTriggeredByScript::No});
        // 'this' might be destroyed here
        if (aOverflow) {
          *aOverflow = nsIntPoint(0, 0);
        }
        return;
      }
    }
    default:
      NS_ERROR("Invalid scroll mode");
      return;
  }

  if (askApzToDoTheScroll) {
    nsPoint delta(
        NSCoordSaturatingNonnegativeMultiply(aDelta.x, deltaMultiplier.width),
        NSCoordSaturatingNonnegativeMultiply(aDelta.y, deltaMultiplier.height));

    AppendScrollUpdate(
        ScrollPositionUpdate::NewPureRelativeScroll(aOrigin, aMode, delta));

    nsIContent* content = GetContent();
    if (!DisplayPortUtils::HasNonMinimalNonZeroDisplayPort(content)) {
      if (MOZ_LOG_TEST(sDisplayportLog, LogLevel::Debug)) {
        mozilla::layers::ScrollableLayerGuid::ViewID viewID =
            mozilla::layers::ScrollableLayerGuid::NULL_SCROLL_ID;
        nsLayoutUtils::FindIDFor(content, &viewID);
        MOZ_LOG(
            sDisplayportLog, LogLevel::Debug,
            ("ScrollBy setting displayport on scrollId=%" PRIu64 "\n", viewID));
      }

      DisplayPortUtils::CalculateAndSetDisplayPortMargins(
          GetScrollTargetFrame(), DisplayPortUtils::RepaintMode::Repaint);
      nsIFrame* frame = do_QueryFrame(GetScrollTargetFrame());
      DisplayPortUtils::SetZeroMarginDisplayPortOnAsyncScrollableAncestors(
          frame);
    }

    SchedulePaint();
    return;
  }

  nsPoint newPos(NSCoordSaturatingAdd(mDestination.x,
                                      NSCoordSaturatingNonnegativeMultiply(
                                          aDelta.x, deltaMultiplier.width)),
                 NSCoordSaturatingAdd(mDestination.y,
                                      NSCoordSaturatingNonnegativeMultiply(
                                          aDelta.y, deltaMultiplier.height)));

  Maybe<SnapDestination> snapDestination;
  if (aSnapFlags != ScrollSnapFlags::Disabled) {
    if (NeedsScrollSnap()) {
      nscoord appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
      deltaMultiplier = nsSize(appUnitsPerDevPixel, appUnitsPerDevPixel);
      negativeTolerance = 0.1f;
      positiveTolerance = 0;
      ScrollUnit snapUnit = aUnit;
      if (aOrigin == ScrollOrigin::MouseWheel) {
        // When using a clicky scroll wheel, snap point selection works the same
        // as keyboard up/down/left/right navigation, but with varying amounts
        // of scroll delta.
        snapUnit = ScrollUnit::LINES;
      }
      snapDestination = GetSnapPointForDestination(snapUnit, aSnapFlags,
                                                   mDestination, newPos);
      if (snapDestination) {
        newPos = snapDestination->mPosition;
      }
    }
  }

  // Calculate desired range values.
  nscoord rangeLowerX, rangeUpperX, rangeLowerY, rangeUpperY;
  CalcRangeForScrollBy(aDelta.x, newPos.x, negativeTolerance, positiveTolerance,
                       deltaMultiplier.width, &rangeLowerX, &rangeUpperX);
  CalcRangeForScrollBy(aDelta.y, newPos.y, negativeTolerance, positiveTolerance,
                       deltaMultiplier.height, &rangeLowerY, &rangeUpperY);
  nsRect range(rangeLowerX, rangeLowerY, rangeUpperX - rangeLowerX,
               rangeUpperY - rangeLowerY);
  AutoWeakFrame weakFrame(this);
  ScrollToWithOrigin(
      newPos, &range,
      snapDestination
          ? ScrollOperationParams{aMode, aOrigin,
                                  std::move(snapDestination->mTargetIds)}
          : ScrollOperationParams{aMode, aOrigin});
  if (!weakFrame.IsAlive()) {
    return;
  }

  if (aOverflow) {
    nsPoint clampAmount = newPos - mDestination;
    float appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
    *aOverflow =
        nsIntPoint(NSAppUnitsToIntPixels(clampAmount.x, appUnitsPerDevPixel),
                   NSAppUnitsToIntPixels(clampAmount.y, appUnitsPerDevPixel));
  }

  if (aUnit == ScrollUnit::DEVICE_PIXELS &&
      !nsLayoutUtils::AsyncPanZoomEnabled(this)) {
    // When APZ is disabled, we must track the velocity
    // on the main thread; otherwise, the APZC will manage this.
    mVelocityQueue.Sample(GetScrollPosition());
  }
}

void nsHTMLScrollFrame::ScrollByCSSPixelsInternal(const CSSIntPoint& aDelta,
                                                  ScrollMode aMode,
                                                  ScrollSnapFlags aSnapFlags) {
  nsPoint current = GetScrollPosition();
  // `current` value above might be a value which was aligned to in
  // layer-pixels, so starting from such points will make the difference between
  // the given position in script (e.g. scrollTo) and the aligned position
  // larger, in the worst case the difference can be observed in CSS pixels.
  // To avoid it, we use the current position in CSS pixels as the start
  // position.  Hopefully it exactly matches the position where it was given by
  // the previous scrolling operation, but there may be some edge cases where
  // the current position in CSS pixels differs from the given position, the
  // cases should be fixed in bug 1556685.
  CSSPoint currentCSSPixels;
  if (StaticPrefs::layout_scroll_disable_pixel_alignment()) {
    currentCSSPixels = GetScrollPositionCSSPixels();
  } else {
    currentCSSPixels = GetRoundedScrollPositionCSSPixels();
  }
  nsPoint pt = CSSPoint::ToAppUnits(currentCSSPixels + aDelta);

  nscoord halfPixel = nsPresContext::CSSPixelsToAppUnits(0.5f);
  nsRect range(pt.x - halfPixel, pt.y - halfPixel, 2 * halfPixel - 1,
               2 * halfPixel - 1);
  // XXX I don't think the following blocks are needed anymore, now that
  // ScrollToImpl simply tries to scroll an integer number of layer
  // pixels from the current position
  if (aDelta.x == 0.0f) {
    pt.x = current.x;
    range.x = pt.x;
    range.width = 0;
  }
  if (aDelta.y == 0.0f) {
    pt.y = current.y;
    range.y = pt.y;
    range.height = 0;
  }
  ScrollToWithOrigin(
      pt, &range,
      ScrollOperationParams{aMode, ScrollOrigin::Relative, aSnapFlags,
                            ScrollTriggeredByScript::Yes});
  // 'this' might be destroyed here
}

void nsHTMLScrollFrame::ScrollSnap(ScrollMode aMode) {
  float flingSensitivity =
      StaticPrefs::layout_css_scroll_snap_prediction_sensitivity();
  int maxVelocity =
      StaticPrefs::layout_css_scroll_snap_prediction_max_velocity();
  maxVelocity = nsPresContext::CSSPixelsToAppUnits(maxVelocity);
  int maxOffset = maxVelocity * flingSensitivity;
  nsPoint velocity = mVelocityQueue.GetVelocity();
  // Multiply each component individually to avoid integer multiply
  nsPoint predictedOffset =
      nsPoint(velocity.x * flingSensitivity, velocity.y * flingSensitivity);
  predictedOffset.Clamp(maxOffset);
  nsPoint pos = GetScrollPosition();
  nsPoint destinationPos = pos + predictedOffset;
  ScrollSnap(destinationPos, aMode);
}

void nsHTMLScrollFrame::ScrollSnap(const nsPoint& aDestination,
                                   ScrollMode aMode) {
  nsRect scrollRange = GetLayoutScrollRange();
  nsPoint pos = GetScrollPosition();
  nsPoint destination = scrollRange.ClampPoint(aDestination);
  ScrollSnapFlags snapFlags = ScrollSnapFlags::IntendedEndPosition;
  if (mVelocityQueue.GetVelocity() != nsPoint()) {
    snapFlags |= ScrollSnapFlags::IntendedDirection;
  }

  // Bug 1776624 : Consider using mDestination as |aStartPos| argument for this
  // GetSnapPointForDestination call, this function call is the only one call
  // site using `GetScrollPosition()` as |aStartPos|.
  if (auto snapDestination = GetSnapPointForDestination(
          ScrollUnit::DEVICE_PIXELS, snapFlags, pos, destination)) {
    destination = snapDestination->mPosition;
    ScrollToWithOrigin(
        destination, nullptr /* range */,
        ScrollOperationParams{aMode, ScrollOrigin::Other,
                              std::move(snapDestination->mTargetIds)});
  }
}

nsSize nsHTMLScrollFrame::GetLineScrollAmount() const {
  RefPtr<nsFontMetrics> fm =
      nsLayoutUtils::GetInflatedFontMetricsForFrame(this);
  NS_ASSERTION(fm, "FontMetrics is null, assuming fontHeight == 1 appunit");
  int32_t appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
  nscoord minScrollAmountInAppUnits =
      std::max(1, StaticPrefs::mousewheel_min_line_scroll_amount()) *
      appUnitsPerDevPixel;
  nscoord horizontalAmount = fm ? fm->AveCharWidth() : 0;
  nscoord verticalAmount = fm ? fm->MaxHeight() : 0;
  return nsSize(std::max(horizontalAmount, minScrollAmountInAppUnits),
                std::max(verticalAmount, minScrollAmountInAppUnits));
}

/**
 * Compute the scrollport size excluding any fixed-pos and sticky-pos (that are
 * stuck) headers and footers. A header or footer is an box that spans that
 * entire width of the viewport and touches the top (or bottom, respectively) of
 * the viewport. We also want to consider fixed/sticky elements that stack or
 * overlap to effectively create a larger header or footer. Headers and footers
 * that cover more than a third of the the viewport are ignored since they
 * probably aren't true headers and footers and we don't want to restrict
 * scrolling too much in such cases. This is a bit conservative --- some
 * pages use elements as headers or footers that don't span the entire width
 * of the viewport --- but it should be a good start.
 *
 * If aViewportFrame is non-null then the scroll frame is the root scroll
 * frame and we should consider fixed-pos items.
 */
struct TopAndBottom {
  TopAndBottom(nscoord aTop, nscoord aBottom) : top(aTop), bottom(aBottom) {}

  nscoord top, bottom;
};
struct TopComparator {
  bool Equals(const TopAndBottom& A, const TopAndBottom& B) const {
    return A.top == B.top;
  }
  bool LessThan(const TopAndBottom& A, const TopAndBottom& B) const {
    return A.top < B.top;
  }
};
struct ReverseBottomComparator {
  bool Equals(const TopAndBottom& A, const TopAndBottom& B) const {
    return A.bottom == B.bottom;
  }
  bool LessThan(const TopAndBottom& A, const TopAndBottom& B) const {
    return A.bottom > B.bottom;
  }
};

static void AddToListIfHeaderFooter(nsIFrame* aFrame,
                                    nsIFrame* aScrollPortFrame,
                                    const nsRect& aScrollPort,
                                    nsTArray<TopAndBottom>& aList) {
  nsRect r = aFrame->GetRectRelativeToSelf();
  r = nsLayoutUtils::TransformFrameRectToAncestor(aFrame, r, aScrollPortFrame);
  r = r.Intersect(aScrollPort);
  if ((r.width >= aScrollPort.width / 2 ||
       r.width >= NSIntPixelsToAppUnits(800, AppUnitsPerCSSPixel())) &&
      r.height <= aScrollPort.height / 3) {
    aList.AppendElement(TopAndBottom(r.y, r.YMost()));
  }
}

static nsSize GetScrollPortSizeExcludingHeadersAndFooters(
    nsIFrame* aScrollFrame, nsIFrame* aViewportFrame,
    const nsRect& aScrollPort) {
  AutoTArray<TopAndBottom, 10> list;
  if (aViewportFrame) {
    for (nsIFrame* f : aViewportFrame->GetChildList(FrameChildListID::Fixed)) {
      AddToListIfHeaderFooter(f, aViewportFrame, aScrollPort, list);
    }
  }

  // Add sticky frames that are currently in "fixed" positions
  StickyScrollContainer* ssc =
      StickyScrollContainer::GetStickyScrollContainerForScrollFrame(
          aScrollFrame);
  if (ssc) {
    const nsTArray<nsIFrame*>& stickyFrames = ssc->GetFrames();
    for (nsIFrame* f : stickyFrames) {
      // If it's acting like fixed position.
      if (ssc->IsStuckInYDirection(f)) {
        AddToListIfHeaderFooter(f, aScrollFrame, aScrollPort, list);
      }
    }
  }

  list.Sort(TopComparator());
  nscoord headerBottom = 0;
  for (uint32_t i = 0; i < list.Length(); ++i) {
    if (list[i].top <= headerBottom) {
      headerBottom = std::max(headerBottom, list[i].bottom);
    }
  }

  list.Sort(ReverseBottomComparator());
  nscoord footerTop = aScrollPort.height;
  for (uint32_t i = 0; i < list.Length(); ++i) {
    if (list[i].bottom >= footerTop) {
      footerTop = std::min(footerTop, list[i].top);
    }
  }

  headerBottom = std::min(aScrollPort.height / 3, headerBottom);
  footerTop = std::max(aScrollPort.height - aScrollPort.height / 3, footerTop);

  return nsSize(aScrollPort.width, footerTop - headerBottom);
}

nsSize nsHTMLScrollFrame::GetPageScrollAmount() const {
  nsSize effectiveScrollPortSize;

  if (GetVisualViewportSize() != mScrollPort.Size()) {
    // We want to use the visual viewport size if one is set.
    // The headers/footers adjustment is too complicated to do if there is a
    // visual viewport that differs from the layout viewport, this is probably
    // okay.
    effectiveScrollPortSize = GetVisualViewportSize();
  } else {
    // Reduce effective scrollport height by the height of any
    // fixed-pos/sticky-pos headers or footers
    effectiveScrollPortSize = GetScrollPortSizeExcludingHeadersAndFooters(
        const_cast<nsHTMLScrollFrame*>(this),
        mIsRoot ? PresShell()->GetRootFrame() : nullptr, mScrollPort);
  }

  nsSize lineScrollAmount = GetLineScrollAmount();
  const int32_t maxOverlapPercent = std::clamp(
      StaticPrefs::toolkit_scrollbox_pagescroll_maxOverlapPercent(), 0, 80);
  const int32_t maxOverlapLines =
      std::max(StaticPrefs::toolkit_scrollbox_pagescroll_maxOverlapLines(), 0);

  // The page increment is the size of the page, minus some overlap.
  return nsSize(
      effectiveScrollPortSize.width -
          std::min(effectiveScrollPortSize.width * maxOverlapPercent / 100,
                   maxOverlapLines * lineScrollAmount.width),
      effectiveScrollPortSize.height -
          std::min(effectiveScrollPortSize.height * maxOverlapPercent / 100,
                   maxOverlapLines * lineScrollAmount.height));
}

/**
 * this code is resposible for restoring the scroll position back to some
 * saved position. if the user has not moved the scroll position manually
 * we keep scrolling down until we get to our original position. keep in
 * mind that content could incrementally be coming in. we only want to stop
 * when we reach our new position.
 */
void nsHTMLScrollFrame::ScrollToRestoredPosition() {
  if (mRestorePos.y == -1 || mLastPos.x == -1 || mLastPos.y == -1) {
    return;
  }
  // make sure our scroll position did not change for where we last put
  // it. if it does then the user must have moved it, and we no longer
  // need to restore.
  //
  // In the RTL case, we check whether the scroll position changed using the
  // logical scroll position, but we scroll to the physical scroll position in
  // all cases

  // The layout offset we want to restore is the same as the visual offset
  // (for now, may change in bug 1499210), but clamped to the layout scroll
  // range (which can be a subset of the visual scroll range).
  // Note that we can't do the clamping when initializing mRestorePos in
  // RestoreState(), since the scrollable rect (which the clamping depends
  // on) can change over the course of the restoration process.
  nsPoint layoutRestorePos = GetLayoutScrollRange().ClampPoint(mRestorePos);
  nsPoint visualRestorePos = GetVisualScrollRange().ClampPoint(mRestorePos);

  // Continue restoring until both the layout and visual scroll positions
  // reach the destination. (Note that the two can only be different for
  // the root content document's root scroll frame, and when zoomed in).
  // This is necessary to avoid situations where the two offsets get stuck
  // at different values and nothing reconciles them (see bug 1519621 comment
  // 8).
  nsPoint logicalLayoutScrollPos = GetLogicalScrollPosition();

  SCROLLRESTORE_LOG(
      "%p: ScrollToRestoredPosition (mRestorePos=%s, mLastPos=%s, "
      "layoutRestorePos=%s, visualRestorePos=%s, "
      "logicalLayoutScrollPos=%s, "
      "GetLogicalVisualViewportOffset()=%s)\n",
      this, ToString(mRestorePos).c_str(), ToString(mLastPos).c_str(),
      ToString(layoutRestorePos).c_str(), ToString(visualRestorePos).c_str(),
      ToString(logicalLayoutScrollPos).c_str(),
      ToString(GetLogicalVisualViewportOffset()).c_str());

  // if we didn't move, we still need to restore
  if (GetLogicalVisualViewportOffset() == mLastPos ||
      logicalLayoutScrollPos == mLastPos) {
    // if our desired position is different to the scroll position, scroll.
    // remember that we could be incrementally loading so we may enter
    // and scroll many times.
    if (mRestorePos != mLastPos /* GetLogicalVisualViewportOffset() */ ||
        layoutRestorePos != logicalLayoutScrollPos) {
      LoadingState state = GetPageLoadingState();
      if (state == LoadingState::Stopped && !IsSubtreeDirty()) {
        return;
      }
      nsPoint visualScrollToPos = visualRestorePos;
      nsPoint layoutScrollToPos = layoutRestorePos;
      if (!IsPhysicalLTR()) {
        // convert from logical to physical scroll position
        visualScrollToPos.x -=
            (GetVisualViewportSize().width - mScrolledFrame->GetRect().width);
        layoutScrollToPos.x -=
            (GetVisualViewportSize().width - mScrolledFrame->GetRect().width);
      }
      AutoWeakFrame weakFrame(this);
      // It's very important to pass ScrollOrigin::Restore here, so
      // ScrollToWithOrigin won't clear out mRestorePos.
      ScrollToWithOrigin(
          layoutScrollToPos, nullptr,
          ScrollOperationParams{ScrollMode::Instant, ScrollOrigin::Restore});
      if (!weakFrame.IsAlive()) {
        return;
      }
      if (mIsRoot) {
        PresShell()->ScrollToVisual(visualScrollToPos, FrameMetrics::eRestore,
                                    ScrollMode::Instant);
      }
      if (state == LoadingState::Loading || IsSubtreeDirty()) {
        // If we're trying to do a history scroll restore, then we want to
        // keep trying this until we succeed, because the page can be loading
        // incrementally. So re-get the scroll position for the next iteration,
        // it might not be exactly equal to mRestorePos due to rounding and
        // clamping.
        mLastPos = GetLogicalVisualViewportOffset();
        return;
      }
    }
    // If we get here, either we reached the desired position (mLastPos ==
    // mRestorePos) or we're not trying to do a history scroll restore, so
    // we can stop after the scroll attempt above.
    mRestorePos.y = -1;
    mLastPos.x = -1;
    mLastPos.y = -1;
  } else {
    // user moved the position, so we won't need to restore
    mLastPos.x = -1;
    mLastPos.y = -1;
  }
}

auto nsHTMLScrollFrame::GetPageLoadingState() -> LoadingState {
  bool loadCompleted = false, stopped = false;
  nsCOMPtr<nsIDocShell> ds = GetContent()->GetComposedDoc()->GetDocShell();
  if (ds) {
    nsCOMPtr<nsIDocumentViewer> viewer;
    ds->GetDocViewer(getter_AddRefs(viewer));
    if (viewer) {
      loadCompleted = viewer->GetLoadCompleted();
      stopped = viewer->GetIsStopped();
    }
  }
  return loadCompleted
             ? (stopped ? LoadingState::Stopped : LoadingState::Loaded)
             : LoadingState::Loading;
}

nsHTMLScrollFrame::OverflowState nsHTMLScrollFrame::GetOverflowState() const {
  nsSize scrollportSize = mScrollPort.Size();
  nsSize childSize = GetScrolledRect().Size();

  OverflowState result = OverflowState::None;

  if (childSize.height > scrollportSize.height) {
    result |= OverflowState::Vertical;
  }

  if (childSize.width > scrollportSize.width) {
    result |= OverflowState::Horizontal;
  }

  return result;
}

nsresult nsHTMLScrollFrame::FireScrollPortEvent() {
  mAsyncScrollPortEvent.Forget();

  // TODO(emilio): why do we need the whole WillPaintObserver infrastructure and
  // can't use AddScriptRunner & co? I guess it made sense when we used
  // WillPaintObserver for scroll events too, or when this used to flush.
  //
  // Should we remove this?

  OverflowState overflowState = GetOverflowState();

  bool newVerticalOverflow = !!(overflowState & OverflowState::Vertical);
  bool vertChanged = mVerticalOverflow != newVerticalOverflow;

  bool newHorizontalOverflow = !!(overflowState & OverflowState::Horizontal);
  bool horizChanged = mHorizontalOverflow != newHorizontalOverflow;

  if (!vertChanged && !horizChanged) {
    return NS_OK;
  }

  // If both either overflowed or underflowed then we dispatch only one
  // DOM event.
  bool both = vertChanged && horizChanged &&
              newVerticalOverflow == newHorizontalOverflow;
  InternalScrollPortEvent::OrientType orient;
  if (both) {
    orient = InternalScrollPortEvent::eBoth;
    mHorizontalOverflow = newHorizontalOverflow;
    mVerticalOverflow = newVerticalOverflow;
  } else if (vertChanged) {
    orient = InternalScrollPortEvent::eVertical;
    mVerticalOverflow = newVerticalOverflow;
    if (horizChanged) {
      // We need to dispatch a separate horizontal DOM event. Do that the next
      // time around since dispatching the vertical DOM event might destroy
      // the frame.
      PostOverflowEvent();
    }
  } else {
    orient = InternalScrollPortEvent::eHorizontal;
    mHorizontalOverflow = newHorizontalOverflow;
  }

  InternalScrollPortEvent event(
      true,
      (orient == InternalScrollPortEvent::eHorizontal ? mHorizontalOverflow
                                                      : mVerticalOverflow)
          ? eScrollPortOverflow
          : eScrollPortUnderflow,
      nullptr);
  event.mOrient = orient;

  RefPtr<nsIContent> content = GetContent();
  RefPtr<nsPresContext> presContext = PresContext();
  return EventDispatcher::Dispatch(content, presContext, &event);
}

void nsHTMLScrollFrame::PostScrollEndEvent(bool aDelayed) {
  if (mScrollEndEvent) {
    return;
  }

  // The ScrollEndEvent constructor registers itself with the refresh driver.
  mScrollEndEvent = new ScrollEndEvent(this, aDelayed);
}

void nsHTMLScrollFrame::FireScrollEndEvent() {
  RefPtr<nsIContent> content = GetContent();
  MOZ_ASSERT(content);

  MOZ_ASSERT(mScrollEndEvent);
  mScrollEndEvent->Revoke();
  mScrollEndEvent = nullptr;

  if (content->GetComposedDoc() &&
      content->GetComposedDoc()->EventHandlingSuppressed()) {
    content->GetComposedDoc()->SetHasDelayedRefreshEvent();
    PostScrollEndEvent(/* aDelayed = */ true);
    return;
  }

  RefPtr<nsPresContext> presContext = PresContext();
  nsEventStatus status = nsEventStatus_eIgnore;
  WidgetGUIEvent event(true, eScrollend, nullptr);
  event.mFlags.mBubbles = mIsRoot;
  event.mFlags.mCancelable = false;
  RefPtr<nsINode> target =
      mIsRoot ? static_cast<nsINode*>(presContext->Document()) : GetContent();
  EventDispatcher::Dispatch(target, presContext, &event, nullptr, &status);
}

void nsHTMLScrollFrame::ReloadChildFrames() {
  mScrolledFrame = nullptr;
  mHScrollbarBox = nullptr;
  mVScrollbarBox = nullptr;
  mScrollCornerBox = nullptr;
  mResizerBox = nullptr;

  for (nsIFrame* frame : PrincipalChildList()) {
    nsIContent* content = frame->GetContent();
    if (content == GetContent()) {
      NS_ASSERTION(!mScrolledFrame, "Already found the scrolled frame");
      mScrolledFrame = frame;
    } else {
      nsAutoString value;
      if (content->IsElement()) {
        content->AsElement()->GetAttr(nsGkAtoms::orient, value);
      }
      if (!value.IsEmpty()) {
        // probably a scrollbar then
        if (value.LowerCaseEqualsLiteral("horizontal")) {
          NS_ASSERTION(!mHScrollbarBox,
                       "Found multiple horizontal scrollbars?");
          mHScrollbarBox = do_QueryFrame(frame);
          MOZ_ASSERT(mHScrollbarBox, "Not a scrollbar?");
        } else {
          NS_ASSERTION(!mVScrollbarBox, "Found multiple vertical scrollbars?");
          mVScrollbarBox = do_QueryFrame(frame);
          MOZ_ASSERT(mVScrollbarBox, "Not a scrollbar?");
        }
      } else if (content->IsXULElement(nsGkAtoms::resizer)) {
        NS_ASSERTION(!mResizerBox, "Found multiple resizers");
        mResizerBox = frame;
      } else if (content->IsXULElement(nsGkAtoms::scrollcorner)) {
        // probably a scrollcorner
        NS_ASSERTION(!mScrollCornerBox, "Found multiple scrollcorners");
        mScrollCornerBox = frame;
      }
    }
  }
}

already_AddRefed<Element> nsHTMLScrollFrame::MakeScrollbar(
    NodeInfo* aNodeInfo, bool aVertical, AnonymousContentKey& aKey) {
  MOZ_ASSERT(aNodeInfo);
  MOZ_ASSERT(
      aNodeInfo->Equals(nsGkAtoms::scrollbar, nullptr, kNameSpaceID_XUL));

  static constexpr nsLiteralString kOrientValues[2] = {
      u"horizontal"_ns,
      u"vertical"_ns,
  };

  aKey = AnonymousContentKey::Type_Scrollbar;
  if (aVertical) {
    aKey |= AnonymousContentKey::Flag_Vertical;
  }

  RefPtr<Element> e;
  NS_TrustedNewXULElement(getter_AddRefs(e), do_AddRef(aNodeInfo));

#ifdef DEBUG
  // Scrollbars can get restyled by theme changes.  Whether such a restyle
  // will actually reconstruct them correctly if it involves a frame
  // reconstruct... I don't know.  :(
  e->SetProperty(nsGkAtoms::restylableAnonymousNode,
                 reinterpret_cast<void*>(true));
#endif  // DEBUG

  e->SetAttr(kNameSpaceID_None, nsGkAtoms::orient, kOrientValues[aVertical],
             false);

  if (mIsRoot) {
    e->SetProperty(nsGkAtoms::docLevelNativeAnonymousContent,
                   reinterpret_cast<void*>(true));
    e->SetAttr(kNameSpaceID_None, nsGkAtoms::root_, u"true"_ns, false);

    // Don't bother making style caching take [root="true"] styles into account.
    aKey = AnonymousContentKey::None;
  }

  return e.forget();
}

bool nsHTMLScrollFrame::IsForTextControlWithNoScrollbars() const {
  // FIXME(emilio): we should probably make the scroller inside <input> an
  // internal pseudo-element, and then this would be simpler.
  //
  // Also, this could just use scrollbar-width these days.
  auto* content = GetContent();
  if (!content) {
    return false;
  }
  auto* input = content->GetClosestNativeAnonymousSubtreeRootParentOrHost();
  return input && input->IsHTMLElement(nsGkAtoms::input);
}

auto nsHTMLScrollFrame::GetCurrentAnonymousContent() const
    -> EnumSet<AnonymousContentType> {
  EnumSet<AnonymousContentType> result;
  if (mHScrollbarContent) {
    result += AnonymousContentType::HorizontalScrollbar;
  }
  if (mVScrollbarContent) {
    result += AnonymousContentType::VerticalScrollbar;
  }
  if (mResizerContent) {
    result += AnonymousContentType::Resizer;
  }
  return result;
}

auto nsHTMLScrollFrame::GetNeededAnonymousContent() const
    -> EnumSet<AnonymousContentType> {
  nsPresContext* pc = PresContext();

  // Don't create scrollbars if we're an SVG document being used as an image,
  // or if we're printing/print previewing.
  // (In the printing case, we allow scrollbars if this is the child of the
  // viewport & paginated scrolling is enabled, because then we must be the
  // scroll frame for the print preview window, & that does need scrollbars.)
  if (pc->Document()->IsBeingUsedAsImage() ||
      (!pc->IsDynamic() && !(mIsRoot && pc->HasPaginatedScrolling()))) {
    return {};
  }

  if (IsForTextControlWithNoScrollbars()) {
    return {};
  }

  EnumSet<AnonymousContentType> result;
  // If we're the scrollframe for the root, then we want to construct our
  // scrollbar frames no matter what.  That way later dynamic changes to
  // propagated overflow styles will show or hide scrollbars on the viewport
  // without requiring frame reconstruction of the viewport (good!).
  //
  // TODO(emilio): Figure out if we can remove this special-case now that we
  // have more targeted optimizations.
  if (mIsRoot) {
    result += AnonymousContentType::HorizontalScrollbar;
    result += AnonymousContentType::VerticalScrollbar;
    // If scrollbar-width is none, don't generate scrollbars.
  } else if (StyleUIReset()->ScrollbarWidth() != StyleScrollbarWidth::None) {
    ScrollStyles styles = GetScrollStyles();
    if (styles.mHorizontal != StyleOverflow::Hidden) {
      result += AnonymousContentType::HorizontalScrollbar;
    }
    if (styles.mVertical != StyleOverflow::Hidden) {
      result += AnonymousContentType::VerticalScrollbar;
    }
  }

  // Check if the frame is resizable. Note:
  // "The effect of the resize property on generated content is undefined.
  //  Implementations should not apply the resize property to generated
  //  content." [1]
  // For info on what is generated content, see [2].
  // [1]: https://drafts.csswg.org/css-ui/#resize
  // [2]: https://www.w3.org/TR/CSS2/generate.html#content
  auto resizeStyle = StyleDisplay()->mResize;
  if (resizeStyle != StyleResize::None &&
      !HasAnyStateBits(NS_FRAME_GENERATED_CONTENT)) {
    result += AnonymousContentType::Resizer;
  }

  return result;
}

nsresult nsHTMLScrollFrame::CreateAnonymousContent(
    nsTArray<nsIAnonymousContentCreator::ContentInfo>& aElements) {
  typedef nsIAnonymousContentCreator::ContentInfo ContentInfo;

  nsPresContext* presContext = PresContext();
  nsNodeInfoManager* nodeInfoManager =
      presContext->Document()->NodeInfoManager();

  auto neededAnonContent = GetNeededAnonymousContent();
  if (neededAnonContent.isEmpty()) {
    return NS_OK;
  }

  {
    RefPtr<NodeInfo> nodeInfo = nodeInfoManager->GetNodeInfo(
        nsGkAtoms::scrollbar, nullptr, kNameSpaceID_XUL, nsINode::ELEMENT_NODE);
    NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);

    if (neededAnonContent.contains(AnonymousContentType::HorizontalScrollbar)) {
      AnonymousContentKey key;
      mHScrollbarContent = MakeScrollbar(nodeInfo, /* aVertical */ false, key);
      aElements.AppendElement(ContentInfo(mHScrollbarContent, key));
    }

    if (neededAnonContent.contains(AnonymousContentType::VerticalScrollbar)) {
      AnonymousContentKey key;
      mVScrollbarContent = MakeScrollbar(nodeInfo, /* aVertical */ true, key);
      aElements.AppendElement(ContentInfo(mVScrollbarContent, key));
    }
  }

  if (neededAnonContent.contains(AnonymousContentType::Resizer)) {
    MOZ_ASSERT(!mIsRoot, "Root scroll frame shouldn't be resizable");

    RefPtr<NodeInfo> nodeInfo;
    nodeInfo = nodeInfoManager->GetNodeInfo(
        nsGkAtoms::resizer, nullptr, kNameSpaceID_XUL, nsINode::ELEMENT_NODE);
    NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);

    NS_TrustedNewXULElement(getter_AddRefs(mResizerContent), nodeInfo.forget());

    nsAutoString dir;
    switch (StyleDisplay()->mResize) {
      case StyleResize::Horizontal:
        if (IsScrollbarOnRight()) {
          dir.AssignLiteral("right");
        } else {
          dir.AssignLiteral("left");
        }
        break;
      case StyleResize::Vertical:
        dir.AssignLiteral("bottom");
        if (!IsScrollbarOnRight()) {
          mResizerContent->SetAttr(kNameSpaceID_None, nsGkAtoms::flip, u""_ns,
                                   false);
        }
        break;
      case StyleResize::Both:
        if (IsScrollbarOnRight()) {
          dir.AssignLiteral("bottomright");
        } else {
          dir.AssignLiteral("bottomleft");
        }
        break;
      default:
        NS_WARNING("only resizable types should have resizers");
    }
    mResizerContent->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, dir, false);
    aElements.AppendElement(mResizerContent);
  }

  if (neededAnonContent.contains(AnonymousContentType::HorizontalScrollbar) &&
      neededAnonContent.contains(AnonymousContentType::VerticalScrollbar)) {
    AnonymousContentKey key = AnonymousContentKey::Type_ScrollCorner;

    RefPtr<NodeInfo> nodeInfo =
        nodeInfoManager->GetNodeInfo(nsGkAtoms::scrollcorner, nullptr,
                                     kNameSpaceID_XUL, nsINode::ELEMENT_NODE);
    NS_TrustedNewXULElement(getter_AddRefs(mScrollCornerContent),
                            nodeInfo.forget());
    if (mIsRoot) {
      mScrollCornerContent->SetProperty(
          nsGkAtoms::docLevelNativeAnonymousContent,
          reinterpret_cast<void*>(true));
      mScrollCornerContent->SetAttr(kNameSpaceID_None, nsGkAtoms::root_,
                                    u"true"_ns, false);

      // Don't bother making style caching take [root="true"] styles into
      // account.
      key = AnonymousContentKey::None;
    }
    aElements.AppendElement(ContentInfo(mScrollCornerContent, key));
  }

  // Don't cache styles if we are a child of a <select> element, since we have
  // some UA style sheet rules that depend on the <select>'s attributes.
  if (GetContent()->IsHTMLElement(nsGkAtoms::select)) {
    for (auto& info : aElements) {
      info.mKey = AnonymousContentKey::None;
    }
  }

  return NS_OK;
}

void nsHTMLScrollFrame::AppendAnonymousContentTo(
    nsTArray<nsIContent*>& aElements, uint32_t aFilter) {
  if (mHScrollbarContent) {
    aElements.AppendElement(mHScrollbarContent);
  }

  if (mVScrollbarContent) {
    aElements.AppendElement(mVScrollbarContent);
  }

  if (mScrollCornerContent) {
    aElements.AppendElement(mScrollCornerContent);
  }

  if (mResizerContent) {
    aElements.AppendElement(mResizerContent);
  }
}

void nsHTMLScrollFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
  nsContainerFrame::DidSetComputedStyle(aOldComputedStyle);
  if (aOldComputedStyle && !mIsRoot &&
      StyleDisplay()->mScrollSnapType !=
          aOldComputedStyle->StyleDisplay()->mScrollSnapType) {
    PostPendingResnap();
  }
}

void nsHTMLScrollFrame::RemoveObservers() {
  if (mAsyncScroll) {
    mAsyncScroll->RemoveObserver();
    mAsyncScroll = nullptr;
  }
  if (mAsyncSmoothMSDScroll) {
    mAsyncSmoothMSDScroll->RemoveObserver();
    mAsyncSmoothMSDScroll = nullptr;
  }
}

/**
 * Called when we want to update the scrollbar position, either because
 * scrolling happened or the user moved the scrollbar position and we need to
 * undo that (e.g., when the user clicks to scroll and we're using smooth
 * scrolling, so we need to put the thumb back to its initial position for the
 * start of the smooth sequence).
 */
void nsHTMLScrollFrame::UpdateScrollbarPosition() {
  AutoWeakFrame weakFrame(this);
  mFrameIsUpdatingScrollbar = true;

  nsPoint pt = GetScrollPosition();
  nsRect scrollRange = GetVisualScrollRange();

  if (gfxPlatform::UseDesktopZoomingScrollbars()) {
    pt = GetVisualViewportOffset();
    scrollRange = GetScrollRangeForUserInputEvents();
  }

  if (mVScrollbarBox) {
    SetCoordAttribute(mVScrollbarBox->GetContent()->AsElement(),
                      nsGkAtoms::curpos, pt.y - scrollRange.y);
    if (!weakFrame.IsAlive()) {
      return;
    }
  }
  if (mHScrollbarBox) {
    SetCoordAttribute(mHScrollbarBox->GetContent()->AsElement(),
                      nsGkAtoms::curpos, pt.x - scrollRange.x);
    if (!weakFrame.IsAlive()) {
      return;
    }
  }

  mFrameIsUpdatingScrollbar = false;
}

void nsHTMLScrollFrame::CurPosAttributeChangedInternal(nsIContent* aContent,
                                                       bool aDoScroll) {
  NS_ASSERTION(aContent, "aContent must not be null");
  NS_ASSERTION((mHScrollbarBox && mHScrollbarBox->GetContent() == aContent) ||
                   (mVScrollbarBox && mVScrollbarBox->GetContent() == aContent),
               "unexpected child");
  MOZ_ASSERT(aContent->IsElement());

  // Attribute changes on the scrollbars happen in one of three ways:
  // 1) The scrollbar changed the attribute in response to some user event
  // 2) We changed the attribute in response to a ScrollPositionDidChange
  // callback from the scrolling view
  // 3) We changed the attribute to adjust the scrollbars for the start
  // of a smooth scroll operation
  //
  // In cases 2 and 3 we do not need to scroll because we're just
  // updating our scrollbar.
  if (mFrameIsUpdatingScrollbar) {
    return;
  }

  nsRect scrollRange = GetVisualScrollRange();

  nsPoint current = GetScrollPosition() - scrollRange.TopLeft();

  if (gfxPlatform::UseDesktopZoomingScrollbars()) {
    scrollRange = GetScrollRangeForUserInputEvents();
    current = GetVisualViewportOffset() - scrollRange.TopLeft();
  }

  nsPoint dest;
  nsRect allowedRange;
  dest.x = GetCoordAttribute(mHScrollbarBox, nsGkAtoms::curpos, current.x,
                             &allowedRange.x, &allowedRange.width);
  dest.y = GetCoordAttribute(mVScrollbarBox, nsGkAtoms::curpos, current.y,
                             &allowedRange.y, &allowedRange.height);
  current += scrollRange.TopLeft();
  dest += scrollRange.TopLeft();
  allowedRange += scrollRange.TopLeft();

  // Don't try to scroll if we're already at an acceptable place.
  // Don't call Contains here since Contains returns false when the point is
  // on the bottom or right edge of the rectangle.
  if (allowedRange.ClampPoint(current) == current) {
    return;
  }

  if (mScrollbarActivity &&
      (mHasHorizontalScrollbar || mHasVerticalScrollbar)) {
    RefPtr<ScrollbarActivity> scrollbarActivity(mScrollbarActivity);
    scrollbarActivity->ActivityOccurred();
  }

  const bool isSmooth = aContent->AsElement()->HasAttr(nsGkAtoms::smooth);
  if (isSmooth) {
    // Make sure an attribute-setting callback occurs even if the view
    // didn't actually move yet.  We need to make sure other listeners
    // see that the scroll position is not (yet) what they thought it
    // was.
    AutoWeakFrame weakFrame(this);
    UpdateScrollbarPosition();
    if (!weakFrame.IsAlive()) {
      return;
    }
  }

  if (aDoScroll) {
    ScrollToWithOrigin(dest, &allowedRange,
                       ScrollOperationParams{
                           isSmooth ? ScrollMode::Smooth : ScrollMode::Instant,
                           ScrollOrigin::Scrollbars});
  }
  // 'this' might be destroyed here
}

/* ============= Scroll events ========== */

nsHTMLScrollFrame::ScrollEvent::ScrollEvent(nsHTMLScrollFrame* aHelper,
                                            bool aDelayed)
    : Runnable("nsHTMLScrollFrame::ScrollEvent"), mHelper(aHelper) {
  mHelper->PresContext()->RefreshDriver()->PostScrollEvent(this, aDelayed);
}

// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP
nsHTMLScrollFrame::ScrollEvent::Run() {
  if (mHelper) {
    mHelper->FireScrollEvent();
  }
  return NS_OK;
}

nsHTMLScrollFrame::ScrollEndEvent::ScrollEndEvent(nsHTMLScrollFrame* aHelper,
                                                  bool aDelayed)
    : Runnable("nsHTMLScrollFrame::ScrollEndEvent"), mHelper(aHelper) {
  mHelper->PresContext()->RefreshDriver()->PostScrollEvent(this, aDelayed);
}

MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP
nsHTMLScrollFrame::ScrollEndEvent::Run() {
  if (mHelper) {
    mHelper->FireScrollEndEvent();
  }
  return NS_OK;
}

void nsHTMLScrollFrame::FireScrollEvent() {
  RefPtr<nsIContent> content = GetContent();
  RefPtr<nsPresContext> presContext = PresContext();
  AUTO_PROFILER_TRACING_MARKER_DOCSHELL("Paint", "FireScrollEvent", GRAPHICS,
                                        presContext->GetDocShell());

  MOZ_ASSERT(mScrollEvent);
  mScrollEvent->Revoke();
  mScrollEvent = nullptr;

  // If event handling is suppressed, keep posting the scroll event to the
  // refresh driver until it is unsuppressed. The event is marked as delayed so
  // that the refresh driver does not continue ticking.
  if (content->GetComposedDoc() &&
      content->GetComposedDoc()->EventHandlingSuppressed()) {
    content->GetComposedDoc()->SetHasDelayedRefreshEvent();
    PostScrollEvent(/* aDelayed = */ true);
    return;
  }

  bool oldProcessing = mProcessingScrollEvent;
  AutoWeakFrame weakFrame(this);
  auto RestoreProcessingScrollEvent = mozilla::MakeScopeExit([&] {
    if (weakFrame.IsAlive()) {  // Otherwise `this` will be dead too.
      mProcessingScrollEvent = oldProcessing;
    }
  });

  mProcessingScrollEvent = true;

  WidgetGUIEvent event(true, eScroll, nullptr);
  nsEventStatus status = nsEventStatus_eIgnore;
  // Fire viewport scroll events at the document (where they
  // will bubble to the window)
  mozilla::layers::ScrollLinkedEffectDetector detector(
      content->GetComposedDoc(),
      presContext->RefreshDriver()->MostRecentRefresh());
  if (mIsRoot) {
    if (RefPtr<Document> doc = content->GetUncomposedDoc()) {
      EventDispatcher::Dispatch(doc, presContext, &event, nullptr, &status);
    }
  } else {
    // scroll events fired at elements don't bubble (although scroll events
    // fired at documents do, to the window)
    event.mFlags.mBubbles = false;
    EventDispatcher::Dispatch(content, presContext, &event, nullptr, &status);
  }
}

void nsHTMLScrollFrame::PostScrollEvent(bool aDelayed) {
  if (mScrollEvent) {
    return;
  }

  // The ScrollEvent constructor registers itself with the refresh driver.
  mScrollEvent = new ScrollEvent(this, aDelayed);
}

// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP
nsHTMLScrollFrame::AsyncScrollPortEvent::Run() {
  return mHelper ? mHelper->FireScrollPortEvent() : NS_OK;
}

void nsHTMLScrollFrame::PostOverflowEvent() {
  if (mAsyncScrollPortEvent.IsPending()) {
    return;
  }

  OverflowState overflowState = GetOverflowState();

  bool newVerticalOverflow = !!(overflowState & OverflowState::Vertical);
  bool vertChanged = mVerticalOverflow != newVerticalOverflow;

  bool newHorizontalOverflow = !!(overflowState & OverflowState::Horizontal);
  bool horizChanged = mHorizontalOverflow != newHorizontalOverflow;

  if (!vertChanged && !horizChanged) {
    return;
  }

  nsRootPresContext* rpc = PresContext()->GetRootPresContext();
  if (!rpc) {
    return;
  }

  mAsyncScrollPortEvent = new AsyncScrollPortEvent(this);
  rpc->AddWillPaintObserver(mAsyncScrollPortEvent.get());
}

nsIFrame* nsHTMLScrollFrame::GetFrameForStyle() const {
  nsIFrame* styleFrame = nullptr;
  if (mIsRoot) {
    if (const Element* rootElement =
            PresContext()->Document()->GetRootElement()) {
      styleFrame = rootElement->GetPrimaryFrame();
    }
  } else {
    styleFrame = const_cast<nsHTMLScrollFrame*>(this);
  }

  return styleFrame;
}

bool nsHTMLScrollFrame::NeedsScrollSnap() const {
  nsIFrame* scrollSnapFrame = GetFrameForStyle();
  if (!scrollSnapFrame) {
    return false;
  }
  return scrollSnapFrame->StyleDisplay()->mScrollSnapType.strictness !=
         StyleScrollSnapStrictness::None;
}

nsSize nsHTMLScrollFrame::GetSnapportSize() const {
  nsRect snapport = GetScrollPortRect();
  nsMargin scrollPadding = GetScrollPadding();
  snapport.Deflate(scrollPadding);
  return snapport.Size();
}

bool nsHTMLScrollFrame::IsScrollbarOnRight() const {
  // The position of the scrollbar in top-level windows depends on the pref
  // layout.scrollbar.side. For non-top-level elements, it depends only on the
  // directionaliy of the element (equivalent to a value of "1" for the pref).
  if (!mIsRoot) {
    return IsPhysicalLTR();
  }
  switch (StaticPrefs::layout_scrollbar_side()) {
    default:
    case 0:  // UI directionality
      return StaticPrefs::bidi_direction() == IBMBIDI_TEXTDIRECTION_LTR;
    case 1:  // Document / content directionality
      return IsPhysicalLTR();
    case 2:  // Always right
      return true;
    case 3:  // Always left
      return false;
  }
}

bool nsHTMLScrollFrame::IsScrollingActive() const {
  const nsStyleDisplay* disp = StyleDisplay();
  if (disp->mWillChange.bits & StyleWillChangeBits::SCROLL) {
    return true;
  }

  nsIContent* content = GetContent();
  return mHasBeenScrolledRecently || IsAlwaysActive() ||
         DisplayPortUtils::HasDisplayPort(content) ||
         nsContentUtils::HasScrollgrab(content);
}

void nsHTMLScrollFrame::FinishReflowForScrollbar(Element* aElement,
                                                 nscoord aMinXY, nscoord aMaxXY,
                                                 nscoord aCurPosXY,
                                                 nscoord aPageIncrement,
                                                 nscoord aIncrement) {
  // Scrollbars assume zero is the minimum position, so translate for them.
  SetCoordAttribute(aElement, nsGkAtoms::curpos, aCurPosXY - aMinXY);
  SetScrollbarEnabled(aElement, aMaxXY - aMinXY);
  SetCoordAttribute(aElement, nsGkAtoms::maxpos, aMaxXY - aMinXY);
  SetCoordAttribute(aElement, nsGkAtoms::pageincrement, aPageIncrement);
  SetCoordAttribute(aElement, nsGkAtoms::increment, aIncrement);
}

class MOZ_RAII AutoMinimumScaleSizeChangeDetector final {
 public:
  explicit AutoMinimumScaleSizeChangeDetector(
      nsHTMLScrollFrame* ansHTMLScrollFrame)
      : mHelper(ansHTMLScrollFrame) {
    MOZ_ASSERT(mHelper);
    MOZ_ASSERT(mHelper->mIsRoot);

    mPreviousMinimumScaleSize = ansHTMLScrollFrame->mMinimumScaleSize;
    mPreviousIsUsingMinimumScaleSize =
        ansHTMLScrollFrame->mIsUsingMinimumScaleSize;
  }
  ~AutoMinimumScaleSizeChangeDetector() {
    if (mPreviousMinimumScaleSize != mHelper->mMinimumScaleSize ||
        mPreviousIsUsingMinimumScaleSize != mHelper->mIsUsingMinimumScaleSize) {
      mHelper->mMinimumScaleSizeChanged = true;
    }
  }

 private:
  nsHTMLScrollFrame* mHelper;

  nsSize mPreviousMinimumScaleSize;
  bool mPreviousIsUsingMinimumScaleSize;
};

nsSize nsHTMLScrollFrame::TrueOuterSize(nsDisplayListBuilder* aBuilder) const {
  if (!PresShell()->UsesMobileViewportSizing()) {
    return GetSize();
  }

  RefPtr<MobileViewportManager> manager =
      PresShell()->GetMobileViewportManager();
  MOZ_ASSERT(manager);

  LayoutDeviceIntSize displaySize = manager->DisplaySize();

  MOZ_ASSERT(aBuilder);
  // In case of WebRender, we expand the outer size to include the dynamic
  // toolbar area here.
  // In case of non WebRender, we expand the size dynamically in
  // MoveScrollbarForLayerMargin in AsyncCompositionManager.cpp.
  WebRenderLayerManager* layerManager = aBuilder->GetWidgetLayerManager();
  if (layerManager) {
    displaySize.height += ViewAs<LayoutDevicePixel>(
        PresContext()->GetDynamicToolbarMaxHeight(),
        PixelCastJustification::LayoutDeviceIsScreenForBounds);
  }

  return LayoutDeviceSize::ToAppUnits(displaySize,
                                      PresContext()->AppUnitsPerDevPixel());
}

void nsHTMLScrollFrame::UpdateMinimumScaleSize(
    const nsRect& aScrollableOverflow, const nsSize& aICBSize) {
  MOZ_ASSERT(mIsRoot);

  AutoMinimumScaleSizeChangeDetector minimumScaleSizeChangeDetector(this);

  mIsUsingMinimumScaleSize = false;

  if (!PresShell()->UsesMobileViewportSizing()) {
    return;
  }

  nsPresContext* pc = PresContext();
  MOZ_ASSERT(pc->IsRootContentDocumentCrossProcess(),
             "The pres context should be for the root content document");

  RefPtr<MobileViewportManager> manager =
      PresShell()->GetMobileViewportManager();
  MOZ_ASSERT(manager);

  ScreenIntSize displaySize = ViewAs<ScreenPixel>(
      manager->DisplaySize(),
      PixelCastJustification::LayoutDeviceIsScreenForBounds);
  if (displaySize.width == 0 || displaySize.height == 0) {
    return;
  }
  if (aScrollableOverflow.IsEmpty()) {
    // Bail if the scrollable overflow rect is empty, as we're going to be
    // dividing by it.
    return;
  }

  Document* doc = pc->Document();
  MOZ_ASSERT(doc, "The document should be valid");
  if (doc->GetFullscreenElement()) {
    // Don't use the minimum scale size in the case of fullscreen state.
    // FIXME: 1508177: We will no longer need this.
    return;
  }

  nsViewportInfo viewportInfo = doc->GetViewportInfo(displaySize);
  if (!viewportInfo.IsZoomAllowed()) {
    // Don't apply the minimum scale size if user-scalable=no is specified.
    return;
  }

  // The intrinsic minimum scale is the scale that fits the entire content
  // width into the visual viewport.
  CSSToScreenScale intrinsicMinScale(
      displaySize.width / CSSRect::FromAppUnits(aScrollableOverflow).XMost());

  // The scale used to compute the minimum-scale size is the larger of the
  // intrinsic minimum and the min-scale from the meta viewport tag.
  CSSToScreenScale minScale =
      std::max(intrinsicMinScale, viewportInfo.GetMinZoom());

  // The minimum-scale size is the size of the visual viewport when zoomed
  // to be the minimum scale.
  mMinimumScaleSize = CSSSize::ToAppUnits(ScreenSize(displaySize) / minScale);

  // Ensure the minimum-scale size is never smaller than the ICB size.
  // That could happen if a page has a meta viewport tag with large explicitly
  // specified viewport dimensions (making the ICB large) and also a large
  // minimum scale (making the min-scale size small).
  mMinimumScaleSize = Max(aICBSize, mMinimumScaleSize);

  mIsUsingMinimumScaleSize = true;
}

bool nsHTMLScrollFrame::ReflowFinished() {
  mPostedReflowCallback = false;

  TryScheduleScrollAnimations();

  if (mIsRoot) {
    if (mMinimumScaleSizeChanged && PresShell()->UsesMobileViewportSizing() &&
        !PresShell()->IsResolutionUpdatedByApz()) {
      RefPtr<MobileViewportManager> manager =
          PresShell()->GetMobileViewportManager();
      MOZ_ASSERT(manager);

      manager->ShrinkToDisplaySizeIfNeeded();
      mMinimumScaleSizeChanged = false;
    }

    if (!UsesOverlayScrollbars()) {
      // Layout scrollbars may have added or removed during reflow, so let's
      // update the visual viewport accordingly. Note that this may be a no-op
      // because we might have recomputed the visual viewport size during the
      // reflow itself, just before laying out the fixed-pos items. But there
      // might be cases where that code doesn't run, so this is a sort of
      // backstop to ensure we do that recomputation.
      if (RefPtr<MobileViewportManager> manager =
              PresShell()->GetMobileViewportManager()) {
        manager->UpdateVisualViewportSizeForPotentialScrollbarChange();
      }
    }

#if defined(MOZ_WIDGET_ANDROID)
    const bool hasVerticalOverflow =
        GetOverflowState() & OverflowState::Vertical &&
        GetScrollStyles().mVertical != StyleOverflow::Hidden;
    if (!mFirstReflow && mHasVerticalOverflowForDynamicToolbar &&
        !hasVerticalOverflow) {
      PresShell()->MaybeNotifyShowDynamicToolbar();
    }
    mHasVerticalOverflowForDynamicToolbar = hasVerticalOverflow;
#endif  // defined(MOZ_WIDGET_ANDROID)
  }

  bool doScroll = true;
  if (IsSubtreeDirty()) {
    // We will get another call after the next reflow and scrolling
    // later is less janky.
    doScroll = false;
  }

  if (mFirstReflow) {
    nsPoint currentScrollPos = GetScrollPosition();
    if (!mScrollUpdates.IsEmpty() &&
        mScrollUpdates.LastElement().GetOrigin() == ScrollOrigin::None &&
        currentScrollPos != nsPoint()) {
      // With frame reconstructions, the reconstructed frame may have a nonzero
      // scroll position by the end of the reflow, but without going through
      // RestoreState. In particular this can happen with RTL XUL scrollframes,
      // see https://bugzilla.mozilla.org/show_bug.cgi?id=1664638#c14.
      // Upon construction, the nsHTMLScrollFrame constructor will have inserted
      // a ScrollPositionUpdate into mScrollUpdates with origin None and a zero
      // scroll position, but here we update that to hold the correct scroll
      // position. Otherwise APZ may end up resetting the scroll position to
      // zero incorrectly. If we ever hit this codepath, it must be on a reflow
      // immediately following the scrollframe construction, so there should be
      // exactly one ScrollPositionUpdate in mScrollUpdates.
      MOZ_ASSERT(mScrollUpdates.Length() == 1);
      MOZ_ASSERT(mScrollUpdates.LastElement().GetGeneration() ==
                 mScrollGeneration);
      MOZ_ASSERT(mScrollUpdates.LastElement().GetDestination() == CSSPoint());
      SCROLLRESTORE_LOG("%p: updating initial SPU to pos %s\n", this,
                        ToString(currentScrollPos).c_str());
      mScrollUpdates.Clear();
      AppendScrollUpdate(
          ScrollPositionUpdate::NewScrollframe(currentScrollPos));
    }

    mFirstReflow = false;
  }

  nsAutoScriptBlocker scriptBlocker;

  if (mReclampVVOffsetInReflowFinished) {
    MOZ_ASSERT(mIsRoot && PresShell()->IsVisualViewportOffsetSet());
    mReclampVVOffsetInReflowFinished = false;
    AutoWeakFrame weakFrame(this);
    PresShell()->SetVisualViewportOffset(PresShell()->GetVisualViewportOffset(),
                                         GetScrollPosition());
    NS_ENSURE_TRUE(weakFrame.IsAlive(), false);
  }

  if (doScroll) {
    ScrollToRestoredPosition();

    // Clamp current scroll position to new bounds. Normally this won't
    // do anything.
    nsPoint currentScrollPos = GetScrollPosition();
    ScrollToImpl(currentScrollPos, nsRect(currentScrollPos, nsSize(0, 0)),
                 ScrollOrigin::Clamp);
    if (ScrollAnimationState().isEmpty()) {
      // We need to have mDestination track the current scroll position,
      // in case it falls outside the new reflow area. mDestination is used
      // by ScrollBy as its starting position.
      mDestination = GetScrollPosition();
    }
  }

  if (!mUpdateScrollbarAttributes) {
    return false;
  }
  mUpdateScrollbarAttributes = false;

  // Update scrollbar attributes.
  if (mMayHaveDirtyFixedChildren) {
    mMayHaveDirtyFixedChildren = false;
    nsIFrame* parentFrame = GetParent();
    for (nsIFrame* fixedChild =
             parentFrame->GetChildList(FrameChildListID::Fixed).FirstChild();
         fixedChild; fixedChild = fixedChild->GetNextSibling()) {
      // force a reflow of the fixed child
      PresShell()->FrameNeedsReflow(fixedChild, IntrinsicDirty::None,
                                    NS_FRAME_HAS_DIRTY_CHILDREN);
    }
  }

  // Suppress handling of the curpos attribute changes we make here.
  NS_ASSERTION(!mFrameIsUpdatingScrollbar, "We shouldn't be reentering here");
  mFrameIsUpdatingScrollbar = true;

  // FIXME(emilio): Why this instead of mHScrollbarContent / mVScrollbarContent?
  RefPtr<Element> vScroll =
      mVScrollbarBox ? mVScrollbarBox->GetContent()->AsElement() : nullptr;
  RefPtr<Element> hScroll =
      mHScrollbarBox ? mHScrollbarBox->GetContent()->AsElement() : nullptr;

  // Note, in some cases this may get deleted while finishing reflow
  // for scrollbars. XXXmats is this still true now that we have a script
  // blocker in this scope? (if not, remove the weak frame checks below).
  if (vScroll || hScroll) {
    nsSize visualViewportSize = GetVisualViewportSize();
    nsRect scrollRange = GetVisualScrollRange();
    nsPoint scrollPos = GetScrollPosition();
    nsSize lineScrollAmount = GetLineScrollAmount();

    if (gfxPlatform::UseDesktopZoomingScrollbars()) {
      scrollRange = GetScrollRangeForUserInputEvents();
      scrollPos = GetVisualViewportOffset();
    }

    // If modifying the logic here, be sure to modify the corresponding
    // compositor-side calculation in ScrollThumbUtils::ApplyTransformForAxis().
    AutoWeakFrame weakFrame(this);
    if (vScroll) {
      const double kScrollMultiplier =
          StaticPrefs::toolkit_scrollbox_verticalScrollDistance();
      nscoord increment = lineScrollAmount.height * kScrollMultiplier;
      // We normally use (visualViewportSize.height - increment) for height of
      // page scrolling.  However, it is too small when increment is very large.
      // (If increment is larger than visualViewportSize.height, direction of
      // scrolling will be opposite). To avoid it, we use
      // (float(visualViewportSize.height) * 0.8) as lower bound value of height
      // of page scrolling. (bug 383267)
      // XXX shouldn't we use GetPageScrollAmount here?
      nscoord pageincrement = nscoord(visualViewportSize.height - increment);
      nscoord pageincrementMin =
          nscoord(float(visualViewportSize.height) * 0.8);
      FinishReflowForScrollbar(
          vScroll, scrollRange.y, scrollRange.YMost(), scrollPos.y,
          std::max(pageincrement, pageincrementMin), increment);
    }
    if (hScroll) {
      const double kScrollMultiplier =
          StaticPrefs::toolkit_scrollbox_horizontalScrollDistance();
      nscoord increment = lineScrollAmount.width * kScrollMultiplier;
      FinishReflowForScrollbar(
          hScroll, scrollRange.x, scrollRange.XMost(), scrollPos.x,
          nscoord(float(visualViewportSize.width) * 0.8), increment);
    }
    NS_ENSURE_TRUE(weakFrame.IsAlive(), false);
  }

  mFrameIsUpdatingScrollbar = false;
  // We used to rely on the curpos attribute changes above to scroll the
  // view.  However, for scrolling to the left of the viewport, we
  // rescale the curpos attribute, which means that operations like
  // resizing the window while it is scrolled all the way to the left
  // hold the curpos attribute constant at 0 while still requiring
  // scrolling.  So we suppress the effect of the changes above with
  // mFrameIsUpdatingScrollbar and call CurPosAttributeChanged here.
  // (It actually even works some of the time without this, thanks to
  // nsSliderFrame::AttributeChanged's handling of maxpos, but not when
  // we hide the scrollbar on a large size change, such as
  // maximization.)
  if (!mHScrollbarBox && !mVScrollbarBox) {
    return false;
  }
  CurPosAttributeChangedInternal(
      mVScrollbarBox ? mVScrollbarBox->GetContent()->AsElement()
                     : mHScrollbarBox->GetContent()->AsElement(),
      doScroll);
  return doScroll;
}

void nsHTMLScrollFrame::ReflowCallbackCanceled() {
  mPostedReflowCallback = false;
}

bool nsHTMLScrollFrame::ComputeCustomOverflow(OverflowAreas& aOverflowAreas) {
  ScrollStyles ss = GetScrollStyles();

  // Reflow when the change in overflow leads to one of our scrollbars
  // changing or might require repositioning the scrolled content due to
  // reduced extents.
  nsRect scrolledRect = GetScrolledRect();
  ScrollDirections overflowChange =
      GetOverflowChange(scrolledRect, mPrevScrolledRect);
  mPrevScrolledRect = scrolledRect;

  bool needReflow = false;
  nsPoint scrollPosition = GetScrollPosition();
  if (overflowChange.contains(ScrollDirection::eHorizontal)) {
    if (ss.mHorizontal != StyleOverflow::Hidden || scrollPosition.x) {
      needReflow = true;
    }
  }
  if (overflowChange.contains(ScrollDirection::eVertical)) {
    if (ss.mVertical != StyleOverflow::Hidden || scrollPosition.y) {
      needReflow = true;
    }
  }

  if (needReflow) {
    // If there are scrollbars, or we're not at the beginning of the pane,
    // the scroll position may change. In this case, mark the frame as
    // needing reflow. Don't use NS_FRAME_IS_DIRTY as dirty as that means
    // we have to reflow the frame and all its descendants, and we don't
    // have to do that here. Only this frame needs to be reflowed.
    PresShell()->FrameNeedsReflow(this, IntrinsicDirty::None,
                                  NS_FRAME_HAS_DIRTY_CHILDREN);
    // Ensure that next time nsHTMLScrollFrame::Reflow runs, we don't skip
    // updating the scrollbars. (Because the overflow area of the scrolled
    // frame has probably just been updated, Reflow won't see it change.)
    mSkippedScrollbarLayout = true;
    return false;  // reflowing will update overflow
  }
  PostOverflowEvent();
  return nsContainerFrame::ComputeCustomOverflow(aOverflowAreas);
}

void nsHTMLScrollFrame::UpdateSticky() {
  StickyScrollContainer* ssc =
      StickyScrollContainer::GetStickyScrollContainerForScrollFrame(this);
  if (ssc) {
    ssc->UpdatePositions(GetScrollPosition(), this);
  }
}

void nsHTMLScrollFrame::UpdatePrevScrolledRect() {
  // The layout scroll range is determinated by the scrolled rect and the scroll
  // port, so if the scrolled rect is updated, we may have to schedule the
  // associated scroll-driven animations' restyles.
  nsRect currScrolledRect = GetScrolledRect();
  if (!currScrolledRect.IsEqualEdges(mPrevScrolledRect)) {
    mMayScheduleScrollAnimations = true;
  }
  mPrevScrolledRect = currScrolledRect;
}

void nsHTMLScrollFrame::AdjustScrollbarRectForResizer(
    nsIFrame* aFrame, nsPresContext* aPresContext, nsRect& aRect,
    bool aHasResizer, ScrollDirection aDirection) {
  if ((aDirection == ScrollDirection::eVertical ? aRect.width : aRect.height) ==
      0) {
    return;
  }

  // if a content resizer is present, use its size. Otherwise, check if the
  // widget has a resizer.
  nsRect resizerRect;
  if (aHasResizer) {
    resizerRect = mResizerBox->GetRect();
  } else {
    nsPoint offset;
    nsIWidget* widget = aFrame->GetNearestWidget(offset);
    LayoutDeviceIntRect widgetRect;
    if (!widget || !widget->ShowsResizeIndicator(&widgetRect)) {
      return;
    }

    resizerRect =
        nsRect(aPresContext->DevPixelsToAppUnits(widgetRect.x) - offset.x,
               aPresContext->DevPixelsToAppUnits(widgetRect.y) - offset.y,
               aPresContext->DevPixelsToAppUnits(widgetRect.width),
               aPresContext->DevPixelsToAppUnits(widgetRect.height));
  }

  if (resizerRect.Contains(aRect.BottomRight() - nsPoint(1, 1))) {
    switch (aDirection) {
      case ScrollDirection::eVertical:
        aRect.height = std::max(0, resizerRect.y - aRect.y);
        break;
      case ScrollDirection::eHorizontal:
        aRect.width = std::max(0, resizerRect.x - aRect.x);
        break;
    }
  } else if (resizerRect.Contains(aRect.BottomLeft() + nsPoint(1, -1))) {
    switch (aDirection) {
      case ScrollDirection::eVertical:
        aRect.height = std::max(0, resizerRect.y - aRect.y);
        break;
      case ScrollDirection::eHorizontal: {
        nscoord xmost = aRect.XMost();
        aRect.x = std::max(aRect.x, resizerRect.XMost());
        aRect.width = xmost - aRect.x;
        break;
      }
    }
  }
}

static void AdjustOverlappingScrollbars(nsRect& aVRect, nsRect& aHRect) {
  if (aVRect.IsEmpty() || aHRect.IsEmpty()) return;

  const nsRect oldVRect = aVRect;
  const nsRect oldHRect = aHRect;
  if (oldVRect.Contains(oldHRect.BottomRight() - nsPoint(1, 1))) {
    aHRect.width = std::max(0, oldVRect.x - oldHRect.x);
  } else if (oldVRect.Contains(oldHRect.BottomLeft() - nsPoint(0, 1))) {
    nscoord overlap = std::min(oldHRect.width, oldVRect.XMost() - oldHRect.x);
    aHRect.x += overlap;
    aHRect.width -= overlap;
  }
  if (oldHRect.Contains(oldVRect.BottomRight() - nsPoint(1, 1))) {
    aVRect.height = std::max(0, oldHRect.y - oldVRect.y);
  }
}

void nsHTMLScrollFrame::LayoutScrollbarPartAtRect(
    const ScrollReflowInput& aState, ReflowInput& aKidReflowInput,
    const nsRect& aRect) {
  nsPresContext* pc = PresContext();
  nsIFrame* kid = aKidReflowInput.mFrame;
  const auto wm = kid->GetWritingMode();
  ReflowOutput desiredSize(wm);
  MOZ_ASSERT(!wm.IsVertical(),
             "Scrollbar parts should have writing-mode: initial");
  MOZ_ASSERT(!wm.IsInlineReversed(),
             "Scrollbar parts should have writing-mode: initial");
  // XXX Maybe get a meaningful container size or something. Shouldn't matter
  // given our asserts above.
  const nsSize containerSize;
  aKidReflowInput.SetComputedISize(aRect.Width());
  aKidReflowInput.SetComputedBSize(aRect.Height());

  const LogicalPoint pos(wm, aRect.TopLeft(), containerSize);
  const auto flags = ReflowChildFlags::Default;
  nsReflowStatus status;
  ReflowOutput kidDesiredSize(wm);
  ReflowChild(kid, pc, kidDesiredSize, aKidReflowInput, wm, pos, containerSize,
              flags, status);
  FinishReflowChild(kid, pc, kidDesiredSize, &aKidReflowInput, wm, pos,
                    containerSize, flags);
}

void nsHTMLScrollFrame::LayoutScrollbars(ScrollReflowInput& aState,
                                         const nsRect& aInsideBorderArea,
                                         const nsRect& aOldScrollPort) {
  NS_ASSERTION(!mSuppressScrollbarUpdate, "This should have been suppressed");

  const bool scrollbarOnLeft = !IsScrollbarOnRight();
  const bool overlayScrollbars = UsesOverlayScrollbars();
  const bool overlayScrollBarsOnRoot = overlayScrollbars && mIsRoot;
  const bool showVScrollbar = mVScrollbarBox && mHasVerticalScrollbar;
  const bool showHScrollbar = mHScrollbarBox && mHasHorizontalScrollbar;

  nsSize compositionSize = mScrollPort.Size();
  if (overlayScrollBarsOnRoot) {
    compositionSize = nsLayoutUtils::CalculateCompositionSizeForFrame(
        this, false, &compositionSize);
  }

  nsPresContext* presContext = mScrolledFrame->PresContext();
  nsRect vRect;
  if (showVScrollbar) {
    vRect.height =
        overlayScrollBarsOnRoot ? compositionSize.height : mScrollPort.height;
    vRect.y = mScrollPort.y;
    if (scrollbarOnLeft) {
      vRect.width = mScrollPort.x - aInsideBorderArea.x;
      vRect.x = aInsideBorderArea.x;
    } else {
      vRect.width = aInsideBorderArea.XMost() - mScrollPort.XMost();
      vRect.x = mScrollPort.x + compositionSize.width;
    }
    if (overlayScrollbars || mOnlyNeedVScrollbarToScrollVVInsideLV) {
      const nscoord width = aState.VScrollbarPrefWidth();
      // There is no space reserved for the layout scrollbar, it is currently
      // not visible because it is positioned just outside the scrollport. But
      // we know that it needs to be made visible so we shift it back in.
      vRect.width += width;
      if (!scrollbarOnLeft) {
        vRect.x -= width;
      }
    }
  }

  nsRect hRect;
  if (showHScrollbar) {
    hRect.width =
        overlayScrollBarsOnRoot ? compositionSize.width : mScrollPort.width;
    hRect.x = mScrollPort.x;
    hRect.height = aInsideBorderArea.YMost() - mScrollPort.YMost();
    hRect.y = mScrollPort.y + compositionSize.height;

    if (overlayScrollbars || mOnlyNeedHScrollbarToScrollVVInsideLV) {
      const nscoord height = aState.HScrollbarPrefHeight();
      hRect.height += height;
      // There is no space reserved for the layout scrollbar, it is currently
      // not visible because it is positioned just outside the scrollport. But
      // we know that it needs to be made visible so we shift it back in.
      hRect.y -= height;
    }
  }

  const bool hasVisualOnlyScrollbarsOnBothDirections =
      !overlayScrollbars && showHScrollbar &&
      mOnlyNeedHScrollbarToScrollVVInsideLV && showVScrollbar &&
      mOnlyNeedVScrollbarToScrollVVInsideLV;
  nsPresContext* pc = PresContext();

  // place the scrollcorner
  if (mScrollCornerBox) {
    nsRect r(0, 0, 0, 0);
    if (scrollbarOnLeft) {
      // scrollbar (if any) on left
      r.width = showVScrollbar ? mScrollPort.x - aInsideBorderArea.x : 0;
      r.x = aInsideBorderArea.x;
    } else {
      // scrollbar (if any) on right
      r.width =
          showVScrollbar ? aInsideBorderArea.XMost() - mScrollPort.XMost() : 0;
      r.x = aInsideBorderArea.XMost() - r.width;
    }
    NS_ASSERTION(r.width >= 0, "Scroll area should be inside client rect");

    if (showHScrollbar) {
      // scrollbar (if any) on bottom
      // Note we don't support the horizontal scrollbar at the top side.
      r.height = aInsideBorderArea.YMost() - mScrollPort.YMost();
      NS_ASSERTION(r.height >= 0, "Scroll area should be inside client rect");
    }
    r.y = aInsideBorderArea.YMost() - r.height;

    // If we have layout scrollbars and both scrollbars are present and both are
    // only needed to scroll the VV inside the LV then we need a scrollcorner
    // but the above calculation will result in an empty rect, so adjust it.
    if (r.IsEmpty() && hasVisualOnlyScrollbarsOnBothDirections) {
      r.width = vRect.width;
      r.height = hRect.height;
      r.x = scrollbarOnLeft ? mScrollPort.x : mScrollPort.XMost() - r.width;
      r.y = mScrollPort.YMost() - r.height;
    }

    ReflowInput scrollCornerRI(
        pc, aState.mReflowInput, mScrollCornerBox,
        LogicalSize(mScrollCornerBox->GetWritingMode(), r.Size()));
    LayoutScrollbarPartAtRect(aState, scrollCornerRI, r);
  }

  if (mResizerBox) {
    // If a resizer is present, get its size.
    //
    // TODO(emilio): Should this really account for scrollbar-width?
    auto scrollbarWidth = nsLayoutUtils::StyleForScrollbar(this)
                              ->StyleUIReset()
                              ->ScrollbarWidth();
    const nscoord scrollbarSize =
        GetNonOverlayScrollbarSize(pc, scrollbarWidth);
    ReflowInput resizerRI(pc, aState.mReflowInput, mResizerBox,
                          LogicalSize(mResizerBox->GetWritingMode()));
    nsSize resizerMinSize = {resizerRI.ComputedMinWidth(),
                             resizerRI.ComputedMinHeight()};

    nsRect r;
    r.width = std::max(std::max(r.width, scrollbarSize), resizerMinSize.width);
    r.x = scrollbarOnLeft ? aInsideBorderArea.x
                          : aInsideBorderArea.XMost() - r.width;
    r.height =
        std::max(std::max(r.height, scrollbarSize), resizerMinSize.height);
    r.y = aInsideBorderArea.YMost() - r.height;

    LayoutScrollbarPartAtRect(aState, resizerRI, r);
  }

  // Note that AdjustScrollbarRectForResizer has to be called after the
  // resizer has been laid out immediately above this because it gets the rect
  // of the resizer frame.
  if (mVScrollbarBox) {
    AdjustScrollbarRectForResizer(this, presContext, vRect, mResizerBox,
                                  ScrollDirection::eVertical);
  }
  if (mHScrollbarBox) {
    AdjustScrollbarRectForResizer(this, presContext, hRect, mResizerBox,
                                  ScrollDirection::eHorizontal);
  }

  // Layout scrollbars can overlap at this point if they are both present and
  // both only needed to scroll the VV inside the LV.
  if (!LookAndFeel::GetInt(LookAndFeel::IntID::AllowOverlayScrollbarsOverlap) ||
      hasVisualOnlyScrollbarsOnBothDirections) {
    AdjustOverlappingScrollbars(vRect, hRect);
  }
  if (mVScrollbarBox) {
    ReflowInput vScrollbarRI(
        pc, aState.mReflowInput, mVScrollbarBox,
        LogicalSize(mVScrollbarBox->GetWritingMode(), vRect.Size()));
    LayoutScrollbarPartAtRect(aState, vScrollbarRI, vRect);
  }
  if (mHScrollbarBox) {
    ReflowInput hScrollbarRI(
        pc, aState.mReflowInput, mHScrollbarBox,
        LogicalSize(mHScrollbarBox->GetWritingMode(), hRect.Size()));
    LayoutScrollbarPartAtRect(aState, hScrollbarRI, hRect);
  }

  // may need to update fixed position children of the viewport,
  // if the client area changed size because of an incremental
  // reflow of a descendant.  (If the outer frame is dirty, the fixed
  // children will be re-laid out anyway)
  if (aOldScrollPort.Size() != mScrollPort.Size() &&
      !HasAnyStateBits(NS_FRAME_IS_DIRTY) && mIsRoot) {
    mMayHaveDirtyFixedChildren = true;
  }

  // post reflow callback to modify scrollbar attributes
  mUpdateScrollbarAttributes = true;
  if (!mPostedReflowCallback) {
    PresShell()->PostReflowCallback(this);
    mPostedReflowCallback = true;
  }
}

#if DEBUG
static bool ShellIsAlive(nsWeakPtr& aWeakPtr) {
  RefPtr<PresShell> presShell = do_QueryReferent(aWeakPtr);
  return !!presShell;
}
#endif

void nsHTMLScrollFrame::SetScrollbarEnabled(Element* aElement,
                                            nscoord aMaxPos) {
  DebugOnly<nsWeakPtr> weakShell(do_GetWeakReference(PresShell()));
  if (aMaxPos) {
    aElement->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled, true);
  } else {
    aElement->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, u"true"_ns, true);
  }
  MOZ_ASSERT(ShellIsAlive(weakShell), "pres shell was destroyed by scrolling");
}

void nsHTMLScrollFrame::SetCoordAttribute(Element* aElement, nsAtom* aAtom,
                                          nscoord aSize) {
  DebugOnly<nsWeakPtr> weakShell(do_GetWeakReference(PresShell()));
  // convert to pixels
  int32_t pixelSize = nsPresContext::AppUnitsToIntCSSPixels(aSize);

  // only set the attribute if it changed.

  nsAutoString newValue;
  newValue.AppendInt(pixelSize);

  if (aElement->AttrValueIs(kNameSpaceID_None, aAtom, newValue, eCaseMatters)) {
    return;
  }

  AutoWeakFrame weakFrame(this);
  RefPtr<Element> kungFuDeathGrip = aElement;
  aElement->SetAttr(kNameSpaceID_None, aAtom, newValue, true);
  MOZ_ASSERT(ShellIsAlive(weakShell), "pres shell was destroyed by scrolling");
  if (!weakFrame.IsAlive()) {
    return;
  }

  if (mScrollbarActivity &&
      (mHasHorizontalScrollbar || mHasVerticalScrollbar)) {
    RefPtr<ScrollbarActivity> scrollbarActivity(mScrollbarActivity);
    scrollbarActivity->ActivityOccurred();
  }
}

static void ReduceRadii(nscoord aXBorder, nscoord aYBorder, nscoord& aXRadius,
                        nscoord& aYRadius) {
  // In order to ensure that the inside edge of the border has no
  // curvature, we need at least one of its radii to be zero.
  if (aXRadius <= aXBorder || aYRadius <= aYBorder) return;

  // For any corner where we reduce the radii, preserve the corner's shape.
  double ratio =
      std::max(double(aXBorder) / aXRadius, double(aYBorder) / aYRadius);
  aXRadius *= ratio;
  aYRadius *= ratio;
}

/**
 * Implement an override for nsIFrame::GetBorderRadii to ensure that
 * the clipping region for the border radius does not clip the scrollbars.
 *
 * In other words, we require that the border radius be reduced until the
 * inner border radius at the inner edge of the border is 0 wherever we
 * have scrollbars.
 */
bool nsHTMLScrollFrame::GetBorderRadii(const nsSize& aFrameSize,
                                       const nsSize& aBorderArea,
                                       Sides aSkipSides,
                                       nscoord aRadii[8]) const {
  if (!nsContainerFrame::GetBorderRadii(aFrameSize, aBorderArea, aSkipSides,
                                        aRadii)) {
    return false;
  }

  // Since we can use GetActualScrollbarSizes (rather than
  // GetDesiredScrollbarSizes) since this doesn't affect reflow, we
  // probably should.
  nsMargin sb = GetActualScrollbarSizes();
  nsMargin border = GetUsedBorder();

  if (sb.left > 0 || sb.top > 0) {
    ReduceRadii(border.left, border.top, aRadii[eCornerTopLeftX],
                aRadii[eCornerTopLeftY]);
  }

  if (sb.top > 0 || sb.right > 0) {
    ReduceRadii(border.right, border.top, aRadii[eCornerTopRightX],
                aRadii[eCornerTopRightY]);
  }

  if (sb.right > 0 || sb.bottom > 0) {
    ReduceRadii(border.right, border.bottom, aRadii[eCornerBottomRightX],
                aRadii[eCornerBottomRightY]);
  }

  if (sb.bottom > 0 || sb.left > 0) {
    ReduceRadii(border.left, border.bottom, aRadii[eCornerBottomLeftX],
                aRadii[eCornerBottomLeftY]);
  }

  return true;
}

static nscoord SnapCoord(nscoord aCoord, double aRes,
                         nscoord aAppUnitsPerPixel) {
  if (StaticPrefs::layout_scroll_disable_pixel_alignment()) {
    return aCoord;
  }
  double snappedToLayerPixels = NS_round((aRes * aCoord) / aAppUnitsPerPixel);
  return NSToCoordRoundWithClamp(snappedToLayerPixels * aAppUnitsPerPixel /
                                 aRes);
}

nsRect nsHTMLScrollFrame::GetScrolledRect() const {
  nsRect result = GetUnsnappedScrolledRectInternal(
      mScrolledFrame->ScrollableOverflowRect(), mScrollPort.Size());

#if 0
  // This happens often enough.
  if (result.width < mScrollPort.width || result.height < mScrollPort.height) {
    NS_WARNING("Scrolled rect smaller than scrollport?");
  }
#endif

  // Expand / contract the result by up to half a layer pixel so that scrolling
  // to the right / bottom edge does not change the layer pixel alignment of
  // the scrolled contents.

  if (result.x == 0 && result.y == 0 && result.width == mScrollPort.width &&
      result.height == mScrollPort.height) {
    // The edges that we would snap are already aligned with the scroll port,
    // so we can skip all the work below.
    return result;
  }

  // For that, we first convert the scroll port and the scrolled rect to rects
  // relative to the reference frame, since that's the space where painting does
  // snapping.
  nsSize visualViewportSize = GetVisualViewportSize();
  const nsIFrame* referenceFrame =
      mReferenceFrameDuringPainting ? mReferenceFrameDuringPainting
                                    : nsLayoutUtils::GetReferenceFrame(
                                          const_cast<nsHTMLScrollFrame*>(this));
  nsPoint toReferenceFrame = GetOffsetToCrossDoc(referenceFrame);
  nsRect scrollPort(mScrollPort.TopLeft() + toReferenceFrame,
                    visualViewportSize);
  nsRect scrolledRect = result + scrollPort.TopLeft();

  if (scrollPort.Overflows() || scrolledRect.Overflows()) {
    return result;
  }

  // Now, snap the bottom right corner of both of these rects.
  // We snap to layer pixels, so we need to respect the layer's scale.
  nscoord appUnitsPerDevPixel =
      mScrolledFrame->PresContext()->AppUnitsPerDevPixel();
  MatrixScales scale = GetPaintedLayerScaleForFrame(
      mScrolledFrame, /* aIncludeCSSTransform = */ false);
  if (scale.xScale == 0 || scale.yScale == 0) {
    scale = MatrixScales();
  }

  // Compute bounds for the scroll position, and computed the snapped scrolled
  // rect from the scroll position bounds.
  nscoord snappedScrolledAreaBottom =
      SnapCoord(scrolledRect.YMost(), scale.yScale, appUnitsPerDevPixel);
  nscoord snappedScrollPortBottom =
      SnapCoord(scrollPort.YMost(), scale.yScale, appUnitsPerDevPixel);
  nscoord maximumScrollOffsetY =
      snappedScrolledAreaBottom - snappedScrollPortBottom;
  result.SetBottomEdge(scrollPort.height + maximumScrollOffsetY);

  if (GetScrolledFrameDir() == StyleDirection::Ltr) {
    nscoord snappedScrolledAreaRight =
        SnapCoord(scrolledRect.XMost(), scale.xScale, appUnitsPerDevPixel);
    nscoord snappedScrollPortRight =
        SnapCoord(scrollPort.XMost(), scale.xScale, appUnitsPerDevPixel);
    nscoord maximumScrollOffsetX =
        snappedScrolledAreaRight - snappedScrollPortRight;
    result.SetRightEdge(scrollPort.width + maximumScrollOffsetX);
  } else {
    // In RTL, the scrolled area's right edge is at scrollPort.XMost(),
    // and the scrolled area's x position is zero or negative. We want
    // the right edge to stay flush with the scroll port, so we snap the
    // left edge.
    nscoord snappedScrolledAreaLeft =
        SnapCoord(scrolledRect.x, scale.xScale, appUnitsPerDevPixel);
    nscoord snappedScrollPortLeft =
        SnapCoord(scrollPort.x, scale.xScale, appUnitsPerDevPixel);
    nscoord minimumScrollOffsetX =
        snappedScrolledAreaLeft - snappedScrollPortLeft;
    result.SetLeftEdge(minimumScrollOffsetX);
  }

  return result;
}

StyleDirection nsHTMLScrollFrame::GetScrolledFrameDir() const {
  // If the scrolled frame has unicode-bidi: plaintext, the paragraph
  // direction set by the text content overrides the direction of the frame
  if (mScrolledFrame->StyleTextReset()->mUnicodeBidi ==
      StyleUnicodeBidi::Plaintext) {
    if (nsIFrame* child = mScrolledFrame->PrincipalChildList().FirstChild()) {
      return nsBidiPresUtils::ParagraphDirection(child) ==
                     mozilla::intl::BidiDirection::LTR
                 ? StyleDirection::Ltr
                 : StyleDirection::Rtl;
    }
  }
  return IsBidiLTR() ? StyleDirection::Ltr : StyleDirection::Rtl;
}

nsRect nsHTMLScrollFrame::GetUnsnappedScrolledRectInternal(
    const nsRect& aScrolledOverflowArea, const nsSize& aScrollPortSize) const {
  return nsLayoutUtils::GetScrolledRect(mScrolledFrame, aScrolledOverflowArea,
                                        aScrollPortSize, GetScrolledFrameDir());
}

nsMargin nsHTMLScrollFrame::GetActualScrollbarSizes(
    nsIScrollableFrame::ScrollbarSizesOptions
        aOptions /* = nsIScrollableFrame::ScrollbarSizesOptions::NONE */)
    const {
  nsRect r = GetPaddingRectRelativeToSelf();

  nsMargin m(mScrollPort.y - r.y, r.XMost() - mScrollPort.XMost(),
             r.YMost() - mScrollPort.YMost(), mScrollPort.x - r.x);

  if (aOptions == nsIScrollableFrame::ScrollbarSizesOptions::
                      INCLUDE_VISUAL_VIEWPORT_SCROLLBARS &&
      !UsesOverlayScrollbars()) {
    // If we are using layout scrollbars and they only exist to scroll the
    // visual viewport then they do not take up any layout space (so the
    // scrollport is the same as the padding rect) but they do cover everything
    // below them so some callers may want to include this special type of
    // scrollbars in the returned value.
    if (mHScrollbarBox && mHasHorizontalScrollbar &&
        mOnlyNeedHScrollbarToScrollVVInsideLV) {
      m.bottom += mHScrollbarBox->GetRect().height;
    }
    if (mVScrollbarBox && mHasVerticalScrollbar &&
        mOnlyNeedVScrollbarToScrollVVInsideLV) {
      if (IsScrollbarOnRight()) {
        m.right += mVScrollbarBox->GetRect().width;
      } else {
        m.left += mVScrollbarBox->GetRect().width;
      }
    }
  }

  return m;
}

void nsHTMLScrollFrame::SetScrollbarVisibility(nsIFrame* aScrollbar,
                                               bool aVisible) {
  nsScrollbarFrame* scrollbar = do_QueryFrame(aScrollbar);
  if (scrollbar) {
    // See if we have a mediator.
    nsIScrollbarMediator* mediator = scrollbar->GetScrollbarMediator();
    if (mediator) {
      // Inform the mediator of the visibility change.
      mediator->VisibilityChanged(aVisible);
    }
  }
}

nscoord nsHTMLScrollFrame::GetCoordAttribute(nsIFrame* aBox, nsAtom* aAtom,
                                             nscoord aDefaultValue,
                                             nscoord* aRangeStart,
                                             nscoord* aRangeLength) {
  if (aBox) {
    nsIContent* content = aBox->GetContent();

    nsAutoString value;
    if (content->IsElement()) {
      content->AsElement()->GetAttr(aAtom, value);
    }
    if (!value.IsEmpty()) {
      nsresult error;
      // convert it to appunits
      nscoord result =
          nsPresContext::CSSPixelsToAppUnits(value.ToInteger(&error));
      nscoord halfPixel = nsPresContext::CSSPixelsToAppUnits(0.5f);
      // Any nscoord value that would round to the attribute value when
      // converted to CSS pixels is allowed.
      *aRangeStart = result - halfPixel;
      *aRangeLength = halfPixel * 2 - 1;
      return result;
    }
  }

  // Only this exact default value is allowed.
  *aRangeStart = aDefaultValue;
  *aRangeLength = 0;
  return aDefaultValue;
}

bool nsHTMLScrollFrame::IsLastScrollUpdateAnimating() const {
  if (!mScrollUpdates.IsEmpty()) {
    switch (mScrollUpdates.LastElement().GetMode()) {
      case ScrollMode::Smooth:
      case ScrollMode::SmoothMsd:
        return true;
      case ScrollMode::Instant:
      case ScrollMode::Normal:
        break;
    }
  }
  return false;
}

bool nsHTMLScrollFrame::IsLastScrollUpdateTriggeredByScriptAnimating() const {
  if (!mScrollUpdates.IsEmpty()) {
    const ScrollPositionUpdate& lastUpdate = mScrollUpdates.LastElement();
    if (lastUpdate.WasTriggeredByScript() &&
        (mScrollUpdates.LastElement().GetMode() == ScrollMode::Smooth ||
         mScrollUpdates.LastElement().GetMode() == ScrollMode::SmoothMsd)) {
      return true;
    }
  }
  return false;
}

using AnimationState = nsIScrollableFrame::AnimationState;
EnumSet<AnimationState> nsHTMLScrollFrame::ScrollAnimationState() const {
  EnumSet<AnimationState> retval;
  if (IsApzAnimationInProgress()) {
    retval += AnimationState::APZInProgress;
    if (mCurrentAPZScrollAnimationType ==
        APZScrollAnimationType::TriggeredByScript) {
      retval += AnimationState::TriggeredByScript;
    }
  }

  if (mApzAnimationRequested) {
    retval += AnimationState::APZRequested;
    if (mApzAnimationTriggeredByScriptRequested) {
      retval += AnimationState::TriggeredByScript;
    }
  }

  if (IsLastScrollUpdateAnimating()) {
    retval += AnimationState::APZPending;
    if (IsLastScrollUpdateTriggeredByScriptAnimating()) {
      retval += AnimationState::TriggeredByScript;
    }
  }
  if (mAsyncScroll) {
    retval += AnimationState::MainThread;
    if (mAsyncScroll->WasTriggeredByScript()) {
      retval += AnimationState::TriggeredByScript;
    }
  }

  if (mAsyncSmoothMSDScroll) {
    retval += AnimationState::MainThread;
    if (mAsyncSmoothMSDScroll->WasTriggeredByScript()) {
      retval += AnimationState::TriggeredByScript;
    }
  }
  return retval;
}

void nsHTMLScrollFrame::ResetScrollInfoIfNeeded(
    const MainThreadScrollGeneration& aGeneration,
    const APZScrollGeneration& aGenerationOnApz,
    APZScrollAnimationType aAPZScrollAnimationType,
    InScrollingGesture aInScrollingGesture) {
  if (aGeneration == mScrollGeneration) {
    mLastScrollOrigin = ScrollOrigin::None;
    mApzAnimationRequested = false;
    mApzAnimationTriggeredByScriptRequested = false;
  }

  mScrollGenerationOnApz = aGenerationOnApz;
  // We can reset this regardless of scroll generation, as this is only set
  // here, as a response to APZ requesting a repaint.
  mCurrentAPZScrollAnimationType = aAPZScrollAnimationType;

  mInScrollingGesture = aInScrollingGesture;
}

UniquePtr<PresState> nsHTMLScrollFrame::SaveState() {
  nsIScrollbarMediator* mediator = do_QueryFrame(GetScrolledFrame());
  if (mediator) {
    // child handles its own scroll state, so don't bother saving state here
    return nullptr;
  }

  // Don't store a scroll state if we never have been scrolled or restored
  // a previous scroll state, and we're not in the middle of a smooth scroll.
  auto scrollAnimationState = ScrollAnimationState();
  bool isScrollAnimating =
      scrollAnimationState.contains(AnimationState::MainThread) ||
      scrollAnimationState.contains(AnimationState::APZPending) ||
      scrollAnimationState.contains(AnimationState::APZRequested);
  if (!mHasBeenScrolled && !mDidHistoryRestore && !isScrollAnimating) {
    return nullptr;
  }

  UniquePtr<PresState> state = NewPresState();
  bool allowScrollOriginDowngrade =
      !nsLayoutUtils::CanScrollOriginClobberApz(mLastScrollOrigin) ||
      mAllowScrollOriginDowngrade;
  // Save mRestorePos instead of our actual current scroll position, if it's
  // valid and we haven't moved since the last update of mLastPos (same check
  // that ScrollToRestoredPosition uses). This ensures if a reframe occurs
  // while we're in the process of loading content to scroll to a restored
  // position, we'll keep trying after the reframe. Similarly, if we're in the
  // middle of a smooth scroll, store the destination so that when we restore
  // we'll jump straight to the end of the scroll animation, rather than
  // effectively dropping it. Note that the mRestorePos will override the
  // smooth scroll destination if both are present.
  nsPoint pt = GetLogicalVisualViewportOffset();
  if (isScrollAnimating) {
    pt = mDestination;
    allowScrollOriginDowngrade = false;
  }
  SCROLLRESTORE_LOG("%p: SaveState, pt=%s, mLastPos=%s, mRestorePos=%s\n", this,
                    ToString(pt).c_str(), ToString(mLastPos).c_str(),
                    ToString(mRestorePos).c_str());
  if (mRestorePos.y != -1 && pt == mLastPos) {
    pt = mRestorePos;
  }
  state->scrollState() = pt;
  state->allowScrollOriginDowngrade() = allowScrollOriginDowngrade;
  if (mIsRoot) {
    // Only save resolution properties for root scroll frames
    state->resolution() = PresShell()->GetResolution();
  }
  return state;
}

NS_IMETHODIMP nsHTMLScrollFrame::RestoreState(PresState* aState) {
  mRestorePos = aState->scrollState();
  MOZ_ASSERT(mLastScrollOrigin == ScrollOrigin::None);
  mAllowScrollOriginDowngrade = aState->allowScrollOriginDowngrade();
  // When restoring state, we promote mLastScrollOrigin to a stronger value
  // from the default of eNone, to restore the behaviour that existed when
  // the state was saved. If mLastScrollOrigin was a weaker value previously,
  // then mAllowScrollOriginDowngrade will be true, and so the combination of
  // mAllowScrollOriginDowngrade and the stronger mLastScrollOrigin will allow
  // the same types of scrolls as before. It might be possible to also just
  // save and restore the mAllowScrollOriginDowngrade and mLastScrollOrigin
  // values directly without this sort of fiddling. Something to try in the
  // future or if we tinker with this code more.
  mLastScrollOrigin = ScrollOrigin::Other;
  mDidHistoryRestore = true;
  mLastPos = mScrolledFrame ? GetLogicalVisualViewportOffset() : nsPoint(0, 0);
  SCROLLRESTORE_LOG("%p: RestoreState, set mRestorePos=%s mLastPos=%s\n", this,
                    ToString(mRestorePos).c_str(), ToString(mLastPos).c_str());

  // Resolution properties should only exist on root scroll frames.
  MOZ_ASSERT(mIsRoot || aState->resolution() == 1.0);

  if (mIsRoot) {
    PresShell()->SetResolutionAndScaleTo(
        aState->resolution(), ResolutionChangeOrigin::MainThreadRestore);
  }
  return NS_OK;
}

void nsHTMLScrollFrame::PostScrolledAreaEvent() {
  if (mScrolledAreaEvent.IsPending()) {
    return;
  }
  mScrolledAreaEvent = new ScrolledAreaEvent(this);
  nsContentUtils::AddScriptRunner(mScrolledAreaEvent.get());
}

////////////////////////////////////////////////////////////////////////////////
// ScrolledArea change event dispatch

// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP
nsHTMLScrollFrame::ScrolledAreaEvent::Run() {
  if (mHelper) {
    mHelper->FireScrolledAreaEvent();
  }
  return NS_OK;
}

void nsHTMLScrollFrame::FireScrolledAreaEvent() {
  mScrolledAreaEvent.Forget();

  InternalScrollAreaEvent event(true, eScrolledAreaChanged, nullptr);
  RefPtr<nsPresContext> presContext = PresContext();
  nsIContent* content = GetContent();

  event.mArea = mScrolledFrame->ScrollableOverflowRectRelativeToParent();
  if (RefPtr<Document> doc = content->GetUncomposedDoc()) {
    EventDispatcher::Dispatch(doc, presContext, &event, nullptr);
  }
}

ScrollDirections nsIScrollableFrame::GetAvailableScrollingDirections() const {
  nscoord oneDevPixel =
      GetScrolledFrame()->PresContext()->AppUnitsPerDevPixel();
  ScrollDirections directions;
  nsRect scrollRange = GetScrollRange();
  if (scrollRange.width >= oneDevPixel) {
    directions += ScrollDirection::eHorizontal;
  }
  if (scrollRange.height >= oneDevPixel) {
    directions += ScrollDirection::eVertical;
  }
  return directions;
}

nsRect nsHTMLScrollFrame::GetScrollRangeForUserInputEvents() const {
  // This function computes a scroll range based on a scrolled rect and scroll
  // port defined as follows:
  //   scrollable rect = overflow:hidden ? layout viewport : scrollable rect
  //   scroll port = have visual viewport ? visual viewport : layout viewport
  // The results in the same notion of scroll range that APZ uses (the combined
  // effect of FrameMetrics::CalculateScrollRange() and
  // nsLayoutUtils::CalculateScrollableRectForFrame).

  ScrollStyles ss = GetScrollStyles();

  nsPoint scrollPos = GetScrollPosition();

  nsRect scrolledRect = GetScrolledRect();
  if (StyleOverflow::Hidden == ss.mHorizontal) {
    scrolledRect.width = mScrollPort.width;
    scrolledRect.x = scrollPos.x;
  }
  if (StyleOverflow::Hidden == ss.mVertical) {
    scrolledRect.height = mScrollPort.height;
    scrolledRect.y = scrollPos.y;
  }

  nsSize scrollPort = GetVisualViewportSize();

  nsRect scrollRange = scrolledRect;
  scrollRange.width = std::max(scrolledRect.width - scrollPort.width, 0);
  scrollRange.height = std::max(scrolledRect.height - scrollPort.height, 0);

  return scrollRange;
}

ScrollDirections
nsHTMLScrollFrame::GetAvailableScrollingDirectionsForUserInputEvents() const {
  nsRect scrollRange = GetScrollRangeForUserInputEvents();

  // We check if there is at least one half of a screen pixel of scroll range to
  // roughly match what apz does when it checks if the change in scroll position
  // in screen pixels round to zero or not.
  // (https://searchfox.org/mozilla-central/rev/2f09184ec781a2667feec87499d4b81b32b6c48e/gfx/layers/apz/src/AsyncPanZoomController.cpp#3210)
  // This isn't quite half a screen pixel, it doesn't take into account CSS
  // transforms, but should be good enough.
  float halfScreenPixel =
      GetScrolledFrame()->PresContext()->AppUnitsPerDevPixel() /
      (PresShell()->GetCumulativeResolution() * 2.f);
  ScrollDirections directions;
  if (scrollRange.width >= halfScreenPixel) {
    directions += ScrollDirection::eHorizontal;
  }
  if (scrollRange.height >= halfScreenPixel) {
    directions += ScrollDirection::eVertical;
  }
  return directions;
}

/**
 * Append scroll positions for valid snap positions into |aSnapInfo| if
 * applicable.
 */
static void AppendScrollPositionsForSnap(
    const nsIFrame* aFrame, const nsIFrame* aScrolledFrame,
    const nsRect& aScrolledRect, const nsMargin& aScrollPadding,
    const nsRect& aScrollRange, WritingMode aWritingModeOnScroller,
    ScrollSnapInfo& aSnapInfo, nsHTMLScrollFrame::SnapTargetSet* aSnapTargets) {
  ScrollSnapTargetId targetId = ScrollSnapUtils::GetTargetIdFor(aFrame);

  nsRect snapArea =
      ScrollSnapUtils::GetSnapAreaFor(aFrame, aScrolledFrame, aScrolledRect);
  // Use the writing-mode on the target element if the snap area is larger than
  // the snapport.
  // https://drafts.csswg.org/css-scroll-snap/#snap-scope
  WritingMode writingMode = ScrollSnapUtils::NeedsToRespectTargetWritingMode(
                                snapArea.Size(), aSnapInfo.mSnapportSize)
                                ? aFrame->GetWritingMode()
                                : aWritingModeOnScroller;

  // These snap range shouldn't be involved with scroll-margin since we just
  // need the visible range of the target element.
  if (snapArea.width > aSnapInfo.mSnapportSize.width) {
    aSnapInfo.mXRangeWiderThanSnapport.AppendElement(
        ScrollSnapInfo::ScrollSnapRange(snapArea, ScrollDirection::eHorizontal,
                                        targetId));
  }
  if (snapArea.height > aSnapInfo.mSnapportSize.height) {
    aSnapInfo.mYRangeWiderThanSnapport.AppendElement(
        ScrollSnapInfo::ScrollSnapRange(snapArea, ScrollDirection::eVertical,
                                        targetId));
  }

  // Shift target rect position by the scroll padding to get the padded
  // position thus we don't need to take account scroll-padding values in
  // ScrollSnapUtils::GetSnapPointForDestination() when it gets called from
  // the compositor thread.
  snapArea.y -= aScrollPadding.top;
  snapArea.x -= aScrollPadding.left;

  LogicalRect logicalTargetRect(writingMode, snapArea, aSnapInfo.mSnapportSize);
  LogicalSize logicalSnapportRect(writingMode, aSnapInfo.mSnapportSize);
  LogicalRect logicalScrollRange(aWritingModeOnScroller, aScrollRange,
                                 // The origin of this logical coordinate system
                                 // what we need here is (0, 0), so we use an
                                 // empty size.
                                 nsSize());

  Maybe<nscoord> blockDirectionPosition;
  const nsStyleDisplay* styleDisplay = aFrame->StyleDisplay();
  nscoord containerBSize = logicalSnapportRect.BSize(writingMode);
  switch (styleDisplay->mScrollSnapAlign.block) {
    case StyleScrollSnapAlignKeyword::None:
      break;
    case StyleScrollSnapAlignKeyword::Start:
      blockDirectionPosition.emplace(
          writingMode.IsVerticalRL() ? -logicalTargetRect.BStart(writingMode)
                                     : logicalTargetRect.BStart(writingMode));
      break;
    case StyleScrollSnapAlignKeyword::End: {
      nscoord candidate = std::clamp(
          // What we need here is the scroll position instead of the snap
          // position itself, so we need, for example, the top edge of the
          // scroll port on horizontal-tb when the frame is positioned at
          // the bottom edge of the scroll port. For this reason we subtract
          // containerBSize from BEnd of the target and clamp it inside the
          // scrollable range.
          logicalTargetRect.BEnd(writingMode) - containerBSize,
          logicalScrollRange.BStart(writingMode),
          logicalScrollRange.BEnd(writingMode));
      blockDirectionPosition.emplace(writingMode.IsVerticalRL() ? -candidate
                                                                : candidate);
      break;
    }
    case StyleScrollSnapAlignKeyword::Center: {
      nscoord targetCenter = (logicalTargetRect.BStart(writingMode) +
                              logicalTargetRect.BEnd(writingMode)) /
                             2;
      nscoord halfSnapportSize = containerBSize / 2;
      // Get the center of the target to align with the center of the snapport
      // depending on direction.
      nscoord candidate = std::clamp(targetCenter - halfSnapportSize,
                                     logicalScrollRange.BStart(writingMode),
                                     logicalScrollRange.BEnd(writingMode));
      blockDirectionPosition.emplace(writingMode.IsVerticalRL() ? -candidate
                                                                : candidate);
      break;
    }
  }

  Maybe<nscoord> inlineDirectionPosition;
  nscoord containerISize = logicalSnapportRect.ISize(writingMode);
  switch (styleDisplay->mScrollSnapAlign.inline_) {
    case StyleScrollSnapAlignKeyword::None:
      break;
    case StyleScrollSnapAlignKeyword::Start:
      inlineDirectionPosition.emplace(
          writingMode.IsInlineReversed()
              ? -logicalTargetRect.IStart(writingMode)
              : logicalTargetRect.IStart(writingMode));
      break;
    case StyleScrollSnapAlignKeyword::End: {
      nscoord candidate = std::clamp(
          // Same as above BEnd case, we subtract containerISize.
          //
          // Note that the logical scroll range is mapped to [0, x] range even
          // if it's in RTL contents. So for example, if the physical range is
          // [-200, 0], it's mapped to [0, 200], i.e. IStart() is 0, IEnd() is
          // 200. So we can just use std::clamp with the same arguments in both
          // RTL/LTR cases.
          logicalTargetRect.IEnd(writingMode) - containerISize,
          logicalScrollRange.IStart(writingMode),
          logicalScrollRange.IEnd(writingMode));
      inlineDirectionPosition.emplace(
          writingMode.IsInlineReversed() ? -candidate : candidate);
      break;
    }
    case StyleScrollSnapAlignKeyword::Center: {
      nscoord targetCenter = (logicalTargetRect.IStart(writingMode) +
                              logicalTargetRect.IEnd(writingMode)) /
                             2;
      nscoord halfSnapportSize = containerISize / 2;
      // Get the center of the target to align with the center of the snapport
      // depending on direction.
      nscoord candidate = std::clamp(targetCenter - halfSnapportSize,
                                     logicalScrollRange.IStart(writingMode),
                                     logicalScrollRange.IEnd(writingMode));
      inlineDirectionPosition.emplace(
          writingMode.IsInlineReversed() ? -candidate : candidate);
      break;
    }
  }

  if (blockDirectionPosition || inlineDirectionPosition) {
    aSnapInfo.mSnapTargets.AppendElement(
        writingMode.IsVertical()
            ? ScrollSnapInfo::SnapTarget(
                  std::move(blockDirectionPosition),
                  std::move(inlineDirectionPosition), std::move(snapArea),
                  styleDisplay->mScrollSnapStop, targetId)
            : ScrollSnapInfo::SnapTarget(
                  std::move(inlineDirectionPosition),
                  std::move(blockDirectionPosition), std::move(snapArea),
                  styleDisplay->mScrollSnapStop, targetId));
    if (aSnapTargets) {
      aSnapTargets->EnsureInserted(aFrame->GetContent());
    }
  }
}

/**
 * Collect the scroll positions corresponding to snap positions of frames in the
 * subtree rooted at |aFrame|, relative to |aScrolledFrame|, into |aSnapInfo|.
 */
static void CollectScrollPositionsForSnap(
    nsIFrame* aFrame, nsIFrame* aScrolledFrame, const nsRect& aScrolledRect,
    const nsMargin& aScrollPadding, const nsRect& aScrollRange,
    WritingMode aWritingModeOnScroller, ScrollSnapInfo& aSnapInfo,
    nsHTMLScrollFrame::SnapTargetSet* aSnapTargets) {
  // Snap positions only affect the nearest ancestor scroll container on the
  // element's containing block chain.
  nsIScrollableFrame* sf = do_QueryFrame(aFrame);
  if (sf) {
    return;
  }

  for (const auto& childList : aFrame->ChildLists()) {
    for (nsIFrame* f : childList.mList) {
      const nsStyleDisplay* styleDisplay = f->StyleDisplay();
      if (styleDisplay->mScrollSnapAlign.inline_ !=
              StyleScrollSnapAlignKeyword::None ||
          styleDisplay->mScrollSnapAlign.block !=
              StyleScrollSnapAlignKeyword::None) {
        AppendScrollPositionsForSnap(
            f, aScrolledFrame, aScrolledRect, aScrollPadding, aScrollRange,
            aWritingModeOnScroller, aSnapInfo, aSnapTargets);
      }
      CollectScrollPositionsForSnap(
          f, aScrolledFrame, aScrolledRect, aScrollPadding, aScrollRange,
          aWritingModeOnScroller, aSnapInfo, aSnapTargets);
    }
  }
}

static nscoord ResolveScrollPaddingStyleValue(
    const StyleRect<mozilla::NonNegativeLengthPercentageOrAuto>&
        aScrollPaddingStyle,
    Side aSide, const nsSize& aScrollPortSize) {
  if (aScrollPaddingStyle.Get(aSide).IsAuto()) {
    // https://drafts.csswg.org/css-scroll-snap-1/#valdef-scroll-padding-auto
    return 0;
  }

  nscoord percentageBasis;
  switch (aSide) {
    case eSideTop:
    case eSideBottom:
      percentageBasis = aScrollPortSize.height;
      break;
    case eSideLeft:
    case eSideRight:
      percentageBasis = aScrollPortSize.width;
      break;
  }

  return aScrollPaddingStyle.Get(aSide).AsLengthPercentage().Resolve(
      percentageBasis);
}

static nsMargin ResolveScrollPaddingStyle(
    const StyleRect<mozilla::NonNegativeLengthPercentageOrAuto>&
        aScrollPaddingStyle,
    const nsSize& aScrollPortSize) {
  return nsMargin(ResolveScrollPaddingStyleValue(aScrollPaddingStyle, eSideTop,
                                                 aScrollPortSize),
                  ResolveScrollPaddingStyleValue(aScrollPaddingStyle,
                                                 eSideRight, aScrollPortSize),
                  ResolveScrollPaddingStyleValue(aScrollPaddingStyle,
                                                 eSideBottom, aScrollPortSize),
                  ResolveScrollPaddingStyleValue(aScrollPaddingStyle, eSideLeft,
                                                 aScrollPortSize));
}

nsMargin nsHTMLScrollFrame::GetScrollPadding() const {
  nsIFrame* styleFrame = GetFrameForStyle();
  if (!styleFrame) {
    return nsMargin();
  }

  // The spec says percentage values are relative to the scroll port size.
  // https://drafts.csswg.org/css-scroll-snap-1/#scroll-padding
  return ResolveScrollPaddingStyle(styleFrame->StylePadding()->mScrollPadding,
                                   GetScrollPortRect().Size());
}

ScrollSnapInfo nsHTMLScrollFrame::ComputeScrollSnapInfo() {
  ScrollSnapInfo result;

  nsIFrame* scrollSnapFrame = GetFrameForStyle();
  if (!scrollSnapFrame) {
    return result;
  }

  const nsStyleDisplay* disp = scrollSnapFrame->StyleDisplay();
  if (disp->mScrollSnapType.strictness == StyleScrollSnapStrictness::None) {
    // We won't be snapping, short-circuit the computation.
    return result;
  }

  WritingMode writingMode = GetWritingMode();
  result.InitializeScrollSnapStrictness(writingMode, disp);

  result.mSnapportSize = GetSnapportSize();
  CollectScrollPositionsForSnap(
      mScrolledFrame, mScrolledFrame, GetScrolledRect(), GetScrollPadding(),
      GetLayoutScrollRange(), writingMode, result, &mSnapTargets);
  return result;
}

ScrollSnapInfo nsHTMLScrollFrame::GetScrollSnapInfo() {
  // TODO(botond): Should we cache it?
  return ComputeScrollSnapInfo();
}

Maybe<SnapDestination> nsHTMLScrollFrame::GetSnapPointForDestination(
    ScrollUnit aUnit, ScrollSnapFlags aFlags, const nsPoint& aStartPos,
    const nsPoint& aDestination) {
  // We can release the strong references for the previous snap target
  // elements here since calling this ComputeScrollSnapInfo means we are going
  // to evaluate new snap points, thus there's no chance to generating
  // nsIContent instances in between this function call and the function call
  // for the (re-)evaluation.
  mSnapTargets.Clear();
  return ScrollSnapUtils::GetSnapPointForDestination(
      ComputeScrollSnapInfo(), aUnit, aFlags, GetLayoutScrollRange(), aStartPos,
      aDestination);
}

Maybe<SnapDestination> nsHTMLScrollFrame::GetSnapPointForResnap() {
  // Same as in GetSnapPointForDestination, We can release the strong references
  // for the previous snap targets here.
  mSnapTargets.Clear();
  nsIContent* focusedContent =
      GetContent()->GetComposedDoc()->GetUnretargetedFocusedContent();
  return ScrollSnapUtils::GetSnapPointForResnap(
      ComputeScrollSnapInfo(), GetLayoutScrollRange(), GetScrollPosition(),
      mLastSnapTargetIds, focusedContent);
}

bool nsHTMLScrollFrame::NeedsResnap() {
  nsIContent* focusedContent =
      GetContent()->GetComposedDoc()->GetUnretargetedFocusedContent();
  return ScrollSnapUtils::GetSnapPointForResnap(
             ComputeScrollSnapInfo(), GetLayoutScrollRange(),
             GetScrollPosition(), mLastSnapTargetIds, focusedContent)
      .isSome();
}

void nsHTMLScrollFrame::SetLastSnapTargetIds(
    UniquePtr<ScrollSnapTargetIds> aIds) {
  if (!aIds) {
    mLastSnapTargetIds = nullptr;
    return;
  }

  // This SetLastSnapTargetIds gets called asynchronously so that there's a race
  // condition something like;
  // 1) an async scroll operation triggered snapping to a point on an element
  // 2) during the async scroll operation, the element got removed from this
  //    scroll container
  // 3) re-snapping triggered
  // 4) this SetLastSnapTargetIds got called
  // In such case |aIds| are stale, we shouldn't use it.
  for (const auto* idList : {&aIds->mIdsOnX, &aIds->mIdsOnY}) {
    for (const auto id : *idList) {
      if (!mSnapTargets.Contains(reinterpret_cast<nsIContent*>(id))) {
        mLastSnapTargetIds = nullptr;
        return;
      }
    }
  }

  mLastSnapTargetIds = std::move(aIds);
}

bool nsHTMLScrollFrame::IsLastSnappedTarget(const nsIFrame* aFrame) const {
  ScrollSnapTargetId id = ScrollSnapUtils::GetTargetIdFor(aFrame);
  MOZ_ASSERT(id != ScrollSnapTargetId::None,
             "This function is supposed to be called for contents");

  if (!mLastSnapTargetIds) {
    return false;
  }

  return mLastSnapTargetIds->mIdsOnX.Contains(id) ||
         mLastSnapTargetIds->mIdsOnY.Contains(id);
}

void nsHTMLScrollFrame::TryResnap() {
  // If there's any async scroll is running or we are processing pan/touch
  // gestures or scroll thumb dragging,  don't clobber the scroll.
  if (!ScrollAnimationState().isEmpty() ||
      mInScrollingGesture == InScrollingGesture::Yes) {
    return;
  }

  if (auto snapDestination = GetSnapPointForResnap()) {
    // We are going to re-snap so that we need to clobber scroll anchoring.
    mAnchor.UserScrolled();

    // Snap to the nearest snap position if exists.
    ScrollToWithOrigin(
        snapDestination->mPosition, nullptr /* range */,
        ScrollOperationParams{
            IsSmoothScroll(ScrollBehavior::Auto) ? ScrollMode::SmoothMsd
                                                 : ScrollMode::Instant,
            ScrollOrigin::Other, std::move(snapDestination->mTargetIds)});
  }
}

void nsHTMLScrollFrame::PostPendingResnapIfNeeded(const nsIFrame* aFrame) {
  if (!IsLastSnappedTarget(aFrame)) {
    return;
  }

  PostPendingResnap();
}

void nsHTMLScrollFrame::PostPendingResnap() {
  PresShell()->PostPendingScrollResnap(this);
}

nsIScrollableFrame::PhysicalScrollSnapAlign
nsHTMLScrollFrame::GetScrollSnapAlignFor(const nsIFrame* aFrame) const {
  StyleScrollSnapAlignKeyword alignForY = StyleScrollSnapAlignKeyword::None;
  StyleScrollSnapAlignKeyword alignForX = StyleScrollSnapAlignKeyword::None;

  nsIFrame* styleFrame = GetFrameForStyle();
  if (!styleFrame) {
    return {alignForX, alignForY};
  }

  if (styleFrame->StyleDisplay()->mScrollSnapType.strictness ==
      StyleScrollSnapStrictness::None) {
    return {alignForX, alignForY};
  }

  const nsStyleDisplay* styleDisplay = aFrame->StyleDisplay();
  if (styleDisplay->mScrollSnapAlign.inline_ ==
          StyleScrollSnapAlignKeyword::None &&
      styleDisplay->mScrollSnapAlign.block ==
          StyleScrollSnapAlignKeyword::None) {
    return {alignForX, alignForY};
  }

  nsSize snapAreaSize =
      ScrollSnapUtils::GetSnapAreaFor(aFrame, mScrolledFrame, GetScrolledRect())
          .Size();
  const WritingMode writingMode =
      ScrollSnapUtils::NeedsToRespectTargetWritingMode(snapAreaSize,
                                                       GetSnapportSize())
          ? aFrame->GetWritingMode()
          : styleFrame->GetWritingMode();

  switch (styleFrame->StyleDisplay()->mScrollSnapType.axis) {
    case StyleScrollSnapAxis::X:
      alignForX = writingMode.IsVertical()
                      ? styleDisplay->mScrollSnapAlign.block
                      : styleDisplay->mScrollSnapAlign.inline_;
      break;
    case StyleScrollSnapAxis::Y:
      alignForY = writingMode.IsVertical()
                      ? styleDisplay->mScrollSnapAlign.inline_
                      : styleDisplay->mScrollSnapAlign.block;
      break;
    case StyleScrollSnapAxis::Block:
      if (writingMode.IsVertical()) {
        alignForX = styleDisplay->mScrollSnapAlign.block;
      } else {
        alignForY = styleDisplay->mScrollSnapAlign.block;
      }
      break;
    case StyleScrollSnapAxis::Inline:
      if (writingMode.IsVertical()) {
        alignForY = styleDisplay->mScrollSnapAlign.inline_;
      } else {
        alignForX = styleDisplay->mScrollSnapAlign.inline_;
      }
      break;
    case StyleScrollSnapAxis::Both:
      if (writingMode.IsVertical()) {
        alignForX = styleDisplay->mScrollSnapAlign.block;
        alignForY = styleDisplay->mScrollSnapAlign.inline_;
      } else {
        alignForX = styleDisplay->mScrollSnapAlign.inline_;
        alignForY = styleDisplay->mScrollSnapAlign.block;
      }
      break;
  }

  return {alignForX, alignForY};
}

bool nsHTMLScrollFrame::UsesOverlayScrollbars() const {
  return PresContext()->UseOverlayScrollbars();
}

bool nsHTMLScrollFrame::DragScroll(WidgetEvent* aEvent) {
  // Dragging is allowed while within a 20 pixel border. Note that device pixels
  // are used so that the same margin is used even when zoomed in or out.
  nscoord margin = 20 * PresContext()->AppUnitsPerDevPixel();

  // Don't drag scroll for small scrollareas.
  if (mScrollPort.width < margin * 2 || mScrollPort.height < margin * 2) {
    return false;
  }

  // If willScroll is computed as false, then the frame is already scrolled as
  // far as it can go in both directions. Return false so that an ancestor
  // scrollframe can scroll instead.
  bool willScroll = false;
  nsPoint pnt =
      nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, RelativeTo{this});
  nsPoint scrollPoint = GetScrollPosition();
  nsRect rangeRect = GetLayoutScrollRange();

  // Only drag scroll when a scrollbar is present.
  nsPoint offset;
  if (mHasHorizontalScrollbar) {
    if (pnt.x >= mScrollPort.x && pnt.x <= mScrollPort.x + margin) {
      offset.x = -margin;
      if (scrollPoint.x > 0) {
        willScroll = true;
      }
    } else if (pnt.x >= mScrollPort.XMost() - margin &&
               pnt.x <= mScrollPort.XMost()) {
      offset.x = margin;
      if (scrollPoint.x < rangeRect.width) {
        willScroll = true;
      }
    }
  }

  if (mHasVerticalScrollbar) {
    if (pnt.y >= mScrollPort.y && pnt.y <= mScrollPort.y + margin) {
      offset.y = -margin;
      if (scrollPoint.y > 0) {
        willScroll = true;
      }
    } else if (pnt.y >= mScrollPort.YMost() - margin &&
               pnt.y <= mScrollPort.YMost()) {
      offset.y = margin;
      if (scrollPoint.y < rangeRect.height) {
        willScroll = true;
      }
    }
  }

  if (offset.x || offset.y) {
    ScrollToWithOrigin(
        GetScrollPosition() + offset, nullptr /* range */,
        ScrollOperationParams{ScrollMode::Normal, ScrollOrigin::Other});
  }

  return willScroll;
}

static nsSliderFrame* GetSliderFrame(nsIFrame* aScrollbarFrame) {
  if (!aScrollbarFrame) {
    return nullptr;
  }

  for (const auto& childList : aScrollbarFrame->ChildLists()) {
    for (nsIFrame* frame : childList.mList) {
      if (nsSliderFrame* sliderFrame = do_QueryFrame(frame)) {
        return sliderFrame;
      }
    }
  }
  return nullptr;
}

static void AsyncScrollbarDragInitiated(uint64_t aDragBlockId,
                                        nsIFrame* aScrollbar) {
  if (nsSliderFrame* sliderFrame = GetSliderFrame(aScrollbar)) {
    sliderFrame->AsyncScrollbarDragInitiated(aDragBlockId);
  }
}

void nsHTMLScrollFrame::AsyncScrollbarDragInitiated(
    uint64_t aDragBlockId, ScrollDirection aDirection) {
  switch (aDirection) {
    case ScrollDirection::eVertical:
      ::AsyncScrollbarDragInitiated(aDragBlockId, mVScrollbarBox);
      break;
    case ScrollDirection::eHorizontal:
      ::AsyncScrollbarDragInitiated(aDragBlockId, mHScrollbarBox);
      break;
  }
}

static void AsyncScrollbarDragRejected(nsIFrame* aScrollbar) {
  if (nsSliderFrame* sliderFrame = GetSliderFrame(aScrollbar)) {
    sliderFrame->AsyncScrollbarDragRejected();
  }
}

void nsHTMLScrollFrame::AsyncScrollbarDragRejected() {
  // We don't get told which scrollbar requested the async drag,
  // so we notify both.
  ::AsyncScrollbarDragRejected(mHScrollbarBox);
  ::AsyncScrollbarDragRejected(mVScrollbarBox);
}

void nsHTMLScrollFrame::ApzSmoothScrollTo(
    const nsPoint& aDestination, ScrollMode aMode, ScrollOrigin aOrigin,
    ScrollTriggeredByScript aTriggeredByScript,
    UniquePtr<ScrollSnapTargetIds> aSnapTargetIds) {
  if (mApzSmoothScrollDestination == Some(aDestination)) {
    // If we already sent APZ a smooth-scroll request to this
    // destination (i.e. it was the last request
    // we sent), then don't send another one because it is redundant.
    // This is to avoid a scenario where pages do repeated scrollBy
    // calls, incrementing the generation counter, and blocking APZ from
    // syncing the scroll offset back to the main thread.
    // Note that if we get two smooth-scroll requests to the same
    // destination with some other scroll in between,
    // mApzSmoothScrollDestination will get reset to Nothing() and so
    // we shouldn't have the problem where this check discards a
    // legitimate smooth-scroll.
    return;
  }

  // The animation will be handled in the compositor, pass the
  // information needed to start the animation and skip the main-thread
  // animation for this scroll.
  MOZ_ASSERT(aOrigin != ScrollOrigin::None);
  mApzSmoothScrollDestination = Some(aDestination);
  AppendScrollUpdate(ScrollPositionUpdate::NewSmoothScroll(
      aMode, aOrigin, aDestination, aTriggeredByScript,
      std::move(aSnapTargetIds)));

  nsIContent* content = GetContent();
  if (!DisplayPortUtils::HasNonMinimalNonZeroDisplayPort(content)) {
    // If this frame doesn't have a displayport then there won't be an
    // APZC instance for it and so there won't be anything to process
    // this smooth scroll request. We should set a displayport on this
    // frame to force an APZC which can handle the request.
    if (MOZ_LOG_TEST(sDisplayportLog, LogLevel::Debug)) {
      mozilla::layers::ScrollableLayerGuid::ViewID viewID =
          mozilla::layers::ScrollableLayerGuid::NULL_SCROLL_ID;
      nsLayoutUtils::FindIDFor(content, &viewID);
      MOZ_LOG(
          sDisplayportLog, LogLevel::Debug,
          ("ApzSmoothScrollTo setting displayport on scrollId=%" PRIu64 "\n",
           viewID));
    }

    DisplayPortUtils::CalculateAndSetDisplayPortMargins(
        GetScrollTargetFrame(), DisplayPortUtils::RepaintMode::Repaint);
    nsIFrame* frame = do_QueryFrame(GetScrollTargetFrame());
    DisplayPortUtils::SetZeroMarginDisplayPortOnAsyncScrollableAncestors(frame);
  }

  // Schedule a paint to ensure that the frame metrics get updated on
  // the compositor thread.
  SchedulePaint();
}

bool nsHTMLScrollFrame::CanApzScrollInTheseDirections(
    ScrollDirections aDirections) {
  ScrollStyles styles = GetScrollStyles();
  if (aDirections.contains(ScrollDirection::eHorizontal) &&
      styles.mHorizontal == StyleOverflow::Hidden)
    return false;
  if (aDirections.contains(ScrollDirection::eVertical) &&
      styles.mVertical == StyleOverflow::Hidden)
    return false;
  return true;
}

bool nsHTMLScrollFrame::SmoothScrollVisual(
    const nsPoint& aVisualViewportOffset,
    FrameMetrics::ScrollOffsetUpdateType aUpdateType) {
  bool canDoApzSmoothScroll =
      nsLayoutUtils::AsyncPanZoomEnabled(this) && WantAsyncScroll();
  if (!canDoApzSmoothScroll) {
    return false;
  }

  // Clamp the destination to the visual scroll range.
  // There is a potential issue here, where |mDestination| is usually
  // clamped to the layout scroll range, and so e.g. a subsequent
  // window.scrollBy() may have an undesired effect. However, as this function
  // is only called internally, this should not be a problem in practice.
  // If it turns out to be, the fix would be:
  //   - add a new "destination" field that doesn't have to be clamped to
  //     the layout scroll range
  //   - clamp mDestination to the layout scroll range here
  //   - make sure ComputeScrollMetadata() picks up the former as the
  //     smooth scroll destination to send to APZ.
  mDestination = GetVisualScrollRange().ClampPoint(aVisualViewportOffset);

  UniquePtr<ScrollSnapTargetIds> snapTargetIds;
  // Perform the scroll.
  ApzSmoothScrollTo(mDestination, ScrollMode::SmoothMsd,
                    aUpdateType == FrameMetrics::eRestore
                        ? ScrollOrigin::Restore
                        : ScrollOrigin::Other,
                    ScrollTriggeredByScript::No, std::move(snapTargetIds));
  return true;
}

bool nsHTMLScrollFrame::IsSmoothScroll(dom::ScrollBehavior aBehavior) const {
  if (aBehavior == dom::ScrollBehavior::Instant) {
    return false;
  }

  // The user smooth scrolling preference should be honored for any requested
  // smooth scrolls. A requested smooth scroll when smooth scrolling is
  // disabled should be equivalent to an instant scroll. This is not enforced
  // for the <scrollbox> XUL element to allow for the browser chrome to
  // override this behavior when toolkit.scrollbox.smoothScroll is enabled.
  if (!GetContent()->IsXULElement(nsGkAtoms::scrollbox)) {
    if (!nsLayoutUtils::IsSmoothScrollingEnabled()) {
      return false;
    }
  } else {
    if (!StaticPrefs::toolkit_scrollbox_smoothScroll()) {
      return false;
    }
  }

  if (aBehavior == dom::ScrollBehavior::Smooth) {
    return true;
  }

  nsIFrame* styleFrame = GetFrameForStyle();
  if (!styleFrame) {
    return false;
  }
  return (aBehavior == dom::ScrollBehavior::Auto &&
          styleFrame->StyleDisplay()->mScrollBehavior ==
              StyleScrollBehavior::Smooth);
}

nsTArray<ScrollPositionUpdate> nsHTMLScrollFrame::GetScrollUpdates() const {
  return mScrollUpdates.Clone();
}

void nsHTMLScrollFrame::AppendScrollUpdate(
    const ScrollPositionUpdate& aUpdate) {
  mScrollGeneration = aUpdate.GetGeneration();
  mScrollUpdates.AppendElement(aUpdate);
}

void nsHTMLScrollFrame::ScheduleScrollAnimations() {
  nsIContent* content = GetContent();
  MOZ_ASSERT(content && content->IsElement(),
             "The nsIScrollableFrame should have the element.");

  const Element* elementOrPseudo = content->AsElement();
  PseudoStyleType pseudo = elementOrPseudo->GetPseudoElementType();
  if (pseudo != PseudoStyleType::NotPseudo &&
      !AnimationUtils::IsSupportedPseudoForAnimations(pseudo)) {
    // This is not an animatable pseudo element, and so we don't generate
    // scroll-timeline for it.
    return;
  }

  const auto [element, type] =
      AnimationUtils::GetElementPseudoPair(elementOrPseudo);
  const auto* scheduler = ProgressTimelineScheduler::Get(element, type);
  if (!scheduler) {
    // We don't have scroll timelines associated with this frame.
    return;
  }

  scheduler->ScheduleAnimations();
}