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
|
/* -*- 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/. */
#include "AsyncPanZoomController.h" // for AsyncPanZoomController, etc
#include <math.h> // for fabsf, fabs, atan2
#include <stdint.h> // for uint32_t, uint64_t
#include <sys/types.h> // for int32_t
#include <algorithm> // for max, min
#include "APZCTreeManager.h" // for APZCTreeManager
#include "AsyncPanZoomAnimation.h" // for AsyncPanZoomAnimation
#include "AutoDirWheelDeltaAdjuster.h" // for APZAutoDirWheelDeltaAdjuster
#include "AutoscrollAnimation.h" // for AutoscrollAnimation
#include "Axis.h" // for AxisX, AxisY, Axis, etc
#include "CheckerboardEvent.h" // for CheckerboardEvent
#include "Compositor.h" // for Compositor
#include "DesktopFlingPhysics.h" // for DesktopFlingPhysics
#include "FrameMetrics.h" // for FrameMetrics, etc
#include "GenericFlingAnimation.h" // for GenericFlingAnimation
#include "GestureEventListener.h" // for GestureEventListener
#include "HitTestingTreeNode.h" // for HitTestingTreeNode
#include "InputData.h" // for MultiTouchInput, etc
#include "InputBlockState.h" // for InputBlockState, TouchBlockState
#include "InputQueue.h" // for InputQueue
#include "Overscroll.h" // for OverscrollAnimation
#include "OverscrollHandoffState.h" // for OverscrollHandoffState
#include "SimpleVelocityTracker.h" // for SimpleVelocityTracker
#include "Units.h" // for CSSRect, CSSPoint, etc
#include "UnitTransforms.h" // for TransformTo
#include "base/message_loop.h" // for MessageLoop
#include "base/task.h" // for NewRunnableMethod, etc
#include "gfxTypes.h" // for gfxFloat
#include "mozilla/Assertions.h" // for MOZ_ASSERT, etc
#include "mozilla/BasicEvents.h" // for Modifiers, MODIFIER_*
#include "mozilla/ClearOnShutdown.h" // for ClearOnShutdown
#include "mozilla/ComputedTimingFunction.h" // for ComputedTimingFunction
#include "mozilla/EventForwards.h" // for nsEventStatus_*
#include "mozilla/EventStateManager.h" // for EventStateManager
#include "mozilla/MouseEvents.h" // for WidgetWheelEvent
#include "mozilla/Preferences.h" // for Preferences
#include "mozilla/RecursiveMutex.h" // for RecursiveMutexAutoLock, etc
#include "mozilla/RefPtr.h" // for RefPtr
#include "mozilla/ScrollTypes.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_general.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_mousewheel.h"
#include "mozilla/StaticPrefs_layers.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_slider.h"
#include "mozilla/StaticPrefs_test.h"
#include "mozilla/StaticPrefs_toolkit.h"
#include "mozilla/Telemetry.h" // for Telemetry
#include "mozilla/TimeStamp.h" // for TimeDuration, TimeStamp
#include "mozilla/dom/CheckerboardReportService.h" // for CheckerboardEventStorage
// note: CheckerboardReportService.h actually lives in gfx/layers/apz/util/
#include "mozilla/dom/Touch.h" // for Touch
#include "mozilla/gfx/gfxVars.h" // for gfxVars
#include "mozilla/gfx/BasePoint.h" // for BasePoint
#include "mozilla/gfx/BaseRect.h" // for BaseRect
#include "mozilla/gfx/Point.h" // for Point, RoundedToInt, etc
#include "mozilla/gfx/Rect.h" // for RoundedIn
#include "mozilla/gfx/ScaleFactor.h" // for ScaleFactor
#include "mozilla/layers/APZThreadUtils.h" // for AssertOnControllerThread, etc
#include "mozilla/layers/APZUtils.h" // for AsyncTransform
#include "mozilla/layers/CompositorController.h" // for CompositorController
#include "mozilla/layers/DirectionUtils.h" // for GetAxis{Start,End,Length,Scale}
#include "mozilla/layers/LayerTransactionParent.h" // for LayerTransactionParent
#include "mozilla/layers/MetricsSharingController.h" // for MetricsSharingController
#include "mozilla/layers/ScrollInputMethods.h" // for ScrollInputMethod
#include "mozilla/mozalloc.h" // for operator new, etc
#include "mozilla/Unused.h" // for unused
#include "mozilla/FloatingPoint.h" // for FuzzyEquals*
#include "nsAlgorithm.h" // for clamped
#include "nsCOMPtr.h" // for already_AddRefed
#include "nsDebug.h" // for NS_WARNING
#include "nsLayoutUtils.h"
#include "nsMathUtils.h" // for NS_hypot
#include "nsPoint.h" // for nsIntPoint
#include "nsStyleConsts.h"
#include "nsTimingFunction.h"
#include "nsTArray.h" // for nsTArray, nsTArray_Impl, etc
#include "nsThreadUtils.h" // for NS_IsMainThread
#include "nsViewportInfo.h" // for kViewportMinScale, kViewportMaxScale
#include "prsystem.h" // for PR_GetPhysicalMemorySize
#include "SharedMemoryBasic.h" // for SharedMemoryBasic
#include "ScrollSnap.h" // for ScrollSnapUtils
#include "ScrollAnimationPhysics.h" // for ComputeAcceleratedWheelDelta
#include "SmoothMsdScrollAnimation.h"
#include "SmoothScrollAnimation.h"
#include "WheelScrollAnimation.h"
#if defined(MOZ_WIDGET_ANDROID)
# include "AndroidAPZ.h"
#endif // defined(MOZ_WIDGET_ANDROID)
static mozilla::LazyLogModule sApzCtlLog("apz.controller");
#define APZC_LOG(...) MOZ_LOG(sApzCtlLog, LogLevel::Debug, (__VA_ARGS__))
#define APZC_LOGV(...) MOZ_LOG(sApzCtlLog, LogLevel::Verbose, (__VA_ARGS__))
#define APZC_LOG_FM_COMMON(fm, prefix, level, ...) \
if (MOZ_LOG_TEST(sApzCtlLog, level)) { \
std::stringstream ss; \
ss << nsPrintfCString(prefix, __VA_ARGS__).get() << ":" << fm; \
MOZ_LOG(sApzCtlLog, level, ("%s\n", ss.str().c_str())); \
}
#define APZC_LOG_FM(fm, prefix, ...) \
APZC_LOG_FM_COMMON(fm, prefix, LogLevel::Debug, __VA_ARGS__)
#define APZC_LOGV_FM(fm, prefix, ...) \
APZC_LOG_FM_COMMON(fm, prefix, LogLevel::Verbose, __VA_ARGS__)
namespace mozilla {
namespace layers {
typedef mozilla::layers::AllowedTouchBehavior AllowedTouchBehavior;
typedef GeckoContentController::APZStateChange APZStateChange;
typedef GeckoContentController::TapType TapType;
typedef mozilla::gfx::Point Point;
typedef mozilla::gfx::Matrix4x4 Matrix4x4;
// Choose between platform-specific implementations.
#ifdef MOZ_WIDGET_ANDROID
typedef WidgetOverscrollEffect OverscrollEffect;
typedef AndroidSpecificState PlatformSpecificState;
#else
typedef GenericOverscrollEffect OverscrollEffect;
typedef PlatformSpecificStateBase
PlatformSpecificState; // no extra state, just use the base class
#endif
/**
* \page APZCPrefs APZ preferences
*
* The following prefs are used to control the behaviour of the APZC.
* The default values are provided in StaticPrefList.yaml.
*
* \li\b apz.allow_double_tap_zooming
* Pref that allows or disallows double tap to zoom
*
* \li\b apz.allow_immediate_handoff
* If set to true, scroll can be handed off from one APZC to another within
* a single input block. If set to false, a single input block can only
* scroll one APZC.
*
* \li\b apz.allow_zooming_out
* If set to true, APZ will allow zooming out past the initial scale on
* desktop. This is false by default to match Chrome's behaviour.
*
* \li\b apz.android.chrome_fling_physics.friction
* A tunable parameter for Chrome fling physics on Android that governs
* how quickly a fling animation slows down due to friction (and therefore
* also how far it reaches). Should be in the range [0-1].
*
* \li\b apz.android.chrome_fling_physics.inflexion
* A tunable parameter for Chrome fling physics on Android that governs
* the shape of the fling curve. Should be in the range [0-1].
*
* \li\b apz.android.chrome_fling_physics.stop_threshold
* A tunable parameter for Chrome fling physics on Android that governs
* how close the fling animation has to get to its target destination
* before it stops.
* Units: ParentLayer pixels
*
* \li\b apz.autoscroll.enabled
* If set to true, autoscrolling is driven by APZ rather than the content
* process main thread.
*
* \li\b apz.axis_lock.mode
* The preferred axis locking style. See AxisLockMode for possible values.
*
* \li\b apz.axis_lock.lock_angle
* Angle from axis within which we stay axis-locked.\n
* Units: radians
*
* \li\b apz.axis_lock.breakout_threshold
* Distance in inches the user must pan before axis lock can be broken.\n
* Units: (real-world, i.e. screen) inches
*
* \li\b apz.axis_lock.breakout_angle
* Angle at which axis lock can be broken.\n
* Units: radians
*
* \li\b apz.axis_lock.direct_pan_angle
* If the angle from an axis to the line drawn by a pan move is less than
* this value, we can assume that panning can be done in the allowed direction
* (horizontal or vertical).\n
* Currently used only for touch-action css property stuff and was addded to
* keep behaviour consistent with IE.\n
* Units: radians
*
* \li\b apz.content_response_timeout
* Amount of time before we timeout response from content. For example, if
* content is being unruly/slow and we don't get a response back within this
* time, we will just pretend that content did not preventDefault any touch
* events we dispatched to it.\n
* Units: milliseconds
*
* \li\b apz.danger_zone_x
* \li\b apz.danger_zone_y
* When drawing high-res tiles, we drop down to drawing low-res tiles
* when we know we can't keep up with the scrolling. The way we determine
* this is by checking if we are entering the "danger zone", which is the
* boundary of the painted content. For example, if the painted content
* goes from y=0...1000 and the visible portion is y=250...750 then
* we're far from checkerboarding. If we get to y=490...990 though then we're
* only 10 pixels away from showing checkerboarding so we are probably in
* a state where we can't keep up with scrolling. The danger zone prefs specify
* how wide this margin is; in the above example a y-axis danger zone of 10
* pixels would make us drop to low-res at y=490...990.\n
* This value is in layer pixels.
*
* \li\b apz.disable_for_scroll_linked_effects
* Setting this pref to true will disable APZ scrolling on documents where
* scroll-linked effects are detected. A scroll linked effect is detected if
* positioning or transform properties are updated inside a scroll event
* dispatch; we assume that such an update is in response to the scroll event
* and is therefore a scroll-linked effect which will be laggy with APZ
* scrolling.
*
* \li\b apz.displayport_expiry_ms
* While a scrollable frame is scrolling async, we set a displayport on it
* to make sure it is layerized. However this takes up memory, so once the
* scrolling stops we want to remove the displayport. This pref controls how
* long after scrolling stops the displayport is removed. A value of 0 will
* disable the expiry behavior entirely.
* Units: milliseconds
*
* \li\b apz.drag.enabled
* Setting this pref to true will cause APZ to handle mouse-dragging of
* scrollbar thumbs.
*
* \li\b apz.drag.initial.enabled
* Setting this pref to true will cause APZ to try to handle mouse-dragging
* of scrollbar thumbs without an initial round-trip to content to start it
* if possible. Only has an effect if apz.drag.enabled is also true.
*
* \li\b apz.drag.touch.enabled
* Setting this pref to true will cause APZ to handle touch-dragging of
* scrollbar thumbs. Only has an effect if apz.drag.enabled is also true.
*
* \li\b apz.enlarge_displayport_when_clipped
* Pref that enables enlarging of the displayport along one axis when the
* generated displayport's size is beyond that of the scrollable rect on the
* opposite axis.
*
* \li\b apz.fling_accel_min_fling_velocity
* The minimum velocity of the second fling, and the minimum velocity of the
* previous fling animation at the point of interruption, for the new fling to
* be considered for fling acceleration.
* Units: screen pixels per milliseconds
*
* \li\b apz.fling_accel_min_pan_velocity
* The minimum velocity during the pan gesture that causes a fling for that
* fling to be considered for fling acceleration.
* Units: screen pixels per milliseconds
*
* \li\b apz.fling_accel_max_pause_interval_ms
* The maximum time that is allowed to elapse between the touch start event that
* interrupts the previous fling, and the touch move that initiates panning for
* the current fling, for that fling to be considered for fling acceleration.
* Units: milliseconds
*
* \li\b apz.fling_accel_base_mult
* \li\b apz.fling_accel_supplemental_mult
* When applying an acceleration on a fling, the new computed velocity is
* (new_fling_velocity * base_mult) + (old_velocity * supplemental_mult).
* The base_mult and supplemental_mult multiplier values are controlled by
* these prefs. Note that "old_velocity" here is the initial velocity of the
* previous fling _after_ acceleration was applied to it (if applicable).
*
* \li\b apz.fling_curve_function_x1
* \li\b apz.fling_curve_function_y1
* \li\b apz.fling_curve_function_x2
* \li\b apz.fling_curve_function_y2
* \li\b apz.fling_curve_threshold_inches_per_ms
* These five parameters define a Bezier curve function and threshold used to
* increase the actual velocity relative to the user's finger velocity. When the
* finger velocity is below the threshold (or if the threshold is not positive),
* the velocity is used as-is. If the finger velocity exceeds the threshold
* velocity, then the function defined by the curve is applied on the part of
* the velocity that exceeds the threshold. Note that the upper bound of the
* velocity is still specified by the \b apz.max_velocity_inches_per_ms pref,
* and the function will smoothly curve the velocity from the threshold to the
* max. In general the function parameters chosen should define an ease-out
* curve in order to increase the velocity in this range, or an ease-in curve to
* decrease the velocity. A straight-line curve is equivalent to disabling the
* curve entirely by setting the threshold to -1. The max velocity pref must
* also be set in order for the curving to take effect, as it defines the upper
* bound of the velocity curve.\n
* The points (x1, y1) and (x2, y2) used as the two intermediate control points
* in the cubic bezier curve; the first and last points are (0,0) and (1,1).\n
* Some example values for these prefs can be found at\n
* https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/dom/animation/ComputedTimingFunction.cpp#27-33
*
* \li\b apz.fling_friction
* Amount of friction applied during flings. This is used in the following
* formula: v(t1) = v(t0) * (1 - f)^(t1 - t0), where v(t1) is the velocity
* for a new sample, v(t0) is the velocity at the previous sample, f is the
* value of this pref, and (t1 - t0) is the amount of time, in milliseconds,
* that has elapsed between the two samples.\n
* NOTE: Not currently used in Android fling calculations.
*
* \li\b apz.fling_min_velocity_threshold
* Minimum velocity for a fling to actually kick off. If the user pans and lifts
* their finger such that the velocity is smaller than or equal to this amount,
* no fling is initiated.\n
* Units: screen pixels per millisecond
*
* \li\b apz.fling_stop_on_tap_threshold
* When flinging, if the velocity is above this number, then a tap on the
* screen will stop the fling without dispatching a tap to content. If the
* velocity is below this threshold a tap will also be dispatched.
* Note: when modifying this pref be sure to run the APZC gtests as some of
* them depend on the value of this pref.\n
* Units: screen pixels per millisecond
*
* \li\b apz.fling_stopped_threshold
* When flinging, if the velocity goes below this number, we just stop the
* animation completely. This is to prevent asymptotically approaching 0
* velocity and rerendering unnecessarily.\n
* Units: screen pixels per millisecond.\n
* NOTE: Should not be set to anything
* other than 0.0 for Android except for tests to disable flings.
*
* \li\b apz.keyboard.enabled
* Determines whether scrolling with the keyboard will be allowed to be handled
* by APZ.
*
* \li\b apz.keyboard.passive-listeners
* When enabled, APZ will interpret the passive event listener flag to mean
* that the event listener won't change the focused element or selection of
* the page. With this, web content can use passive key listeners and not have
* keyboard APZ disabled.
*
* \li\b apz.max_tap_time
* Maximum time for a touch on the screen and corresponding lift of the finger
* to be considered a tap. This also applies to double taps, except that it is
* used both for the interval between the first touchdown and first touchup,
* and for the interval between the first touchup and the second touchdown.\n
* Units: milliseconds.
*
* \li\b apz.max_velocity_inches_per_ms
* Maximum velocity. Velocity will be capped at this value if a faster fling
* occurs. Negative values indicate unlimited velocity.\n
* Units: (real-world, i.e. screen) inches per millisecond
*
* \li\b apz.max_velocity_queue_size
* Maximum size of velocity queue. The queue contains last N velocity records.
* On touch end we calculate the average velocity in order to compensate
* touch/mouse drivers misbehaviour.
*
* \li\b apz.min_skate_speed
* Minimum amount of speed along an axis before we switch to "skate" multipliers
* rather than using the "stationary" multipliers.\n
* Units: CSS pixels per millisecond
*
* \li\b apz.one_touch_pinch.enabled
* Whether or not the "one-touch-pinch" gesture (for zooming with one finger)
* is enabled or not.
*
* \li\b apz.overscroll.enabled
* Pref that enables overscrolling. If this is disabled, excess scroll that
* cannot be handed off is discarded.
*
* \li\b apz.overscroll.min_pan_distance_ratio
* The minimum ratio of the pan distance along one axis to the pan distance
* along the other axis needed to initiate overscroll along the first axis
* during panning.
*
* \li\b apz.overscroll.stretch_factor
* How much overscrolling can stretch content along an axis.
* The maximum stretch along an axis is a factor of (1 + kStretchFactor).
* (So if kStretchFactor is 0, you can't stretch at all; if kStretchFactor
* is 1, you can stretch at most by a factor of 2).
*
* \li\b apz.overscroll.stop_distance_threshold
* \li\b apz.overscroll.stop_velocity_threshold
* Thresholds for stopping the overscroll animation. When both the distance
* and the velocity fall below their thresholds, we stop oscillating.\n
* Units: screen pixels (for distance)
* screen pixels per millisecond (for velocity)
*
* \li\b apz.paint_skipping.enabled
* When APZ is scrolling and sending repaint requests to the main thread, often
* the main thread doesn't actually need to do a repaint. This pref allows the
* main thread to skip doing those repaints in cases where it doesn't need to.
*
* \li\b apz.pinch_lock.mode
* The preferred pinch locking style. See PinchLockMode for possible values.
*
* \li\b apz.pinch_lock.scroll_lock_threshold
* Pinch locking is triggered if the user scrolls more than this distance
* and pinches less than apz.pinch_lock.span_lock_threshold.\n
* Units: (real-world, i.e. screen) inches
*
* \li\b apz.pinch_lock.span_breakout_threshold
* Distance in inches the user must pinch before lock can be broken.\n
* Units: (real-world, i.e. screen) inches measured between two touch points
*
* \li\b apz.pinch_lock.span_lock_threshold
* Pinch locking is triggered if the user pinches less than this distance
* and scrolls more than apz.pinch_lock.scroll_lock_threshold.\n
* Units: (real-world, i.e. screen) inches measured between two touch points
*
* \li\b apz.pinch_lock.buffer_max_age
* To ensure that pinch locking threshold calculations are not affected by
* variations in touch screen sensitivity, calculations draw from a buffer of
* recent events. This preference specifies the maximum time that events are
* held in this buffer.
* Units: milliseconds
*
* \li\b apz.popups.enabled
* Determines whether APZ is used for XUL popup widgets with remote content.
* Ideally, this should always be true, but it is currently not well tested, and
* has known issues, so needs to be prefable.
*
* \li\b apz.record_checkerboarding
* Whether or not to record detailed info on checkerboarding events.
*
* \li\b apz.second_tap_tolerance
* Constant describing the tolerance in distance we use, multiplied by the
* device DPI, within which a second tap is counted as part of a gesture
* continuing from the first tap. Making this larger allows the user more
* distance between the first and second taps in a "double tap" or "one touch
* pinch" gesture.\n
* Units: (real-world, i.e. screen) inches
*
* \li\b apz.test.logging_enabled
* Enable logging of APZ test data (see bug 961289).
*
* \li\b apz.touch_move_tolerance
* See the description for apz.touch_start_tolerance below. This is a similar
* threshold, except it is used to suppress touchmove events from being
* delivered to content for NON-scrollable frames (or more precisely, for APZCs
* where ArePointerEventsConsumable returns false).\n Units: (real-world, i.e.
* screen) inches
*
* \li\b apz.touch_start_tolerance
* Constant describing the tolerance in distance we use, multiplied by the
* device DPI, before we start panning the screen. This is to prevent us from
* accidentally processing taps as touch moves, and from very short/accidental
* touches moving the screen. touchmove events are also not delivered to content
* within this distance on scrollable frames.\n
* Units: (real-world, i.e. screen) inches
*
* \li\b apz.velocity_bias
* How much to adjust the displayport in the direction of scrolling. This value
* is multiplied by the velocity and added to the displayport offset.
*
* \li\b apz.velocity_relevance_time_ms
* When computing a fling velocity from the most recently stored velocity
* information, only velocities within the most X milliseconds are used.
* This pref controls the value of X.\n
* Units: ms
*
* \li\b apz.x_skate_size_multiplier
* \li\b apz.y_skate_size_multiplier
* The multiplier we apply to the displayport size if it is skating (current
* velocity is above \b apz.min_skate_speed). We prefer to increase the size of
* the Y axis because it is more natural in the case that a user is reading a
* page page that scrolls up/down. Note that one, both or neither of these may
* be used at any instant.\n In general we want \b
* apz.[xy]_skate_size_multiplier to be smaller than the corresponding
* stationary size multiplier because when panning fast we would like to paint
* less and get faster, more predictable paint times. When panning slowly we
* can afford to paint more even though it's slower.
*
* \li\b apz.x_stationary_size_multiplier
* \li\b apz.y_stationary_size_multiplier
* The multiplier we apply to the displayport size if it is not skating (see
* documentation for the skate size multipliers above).
*
* \li\b apz.x_skate_highmem_adjust
* \li\b apz.y_skate_highmem_adjust
* On high memory systems, we adjust the displayport during skating
* to be larger so we can reduce checkerboarding.
*
* \li\b apz.zoom_animation_duration_ms
* This controls how long the zoom-to-rect animation takes.\n
* Units: ms
*
* \li\b apz.scale_repaint_delay_ms
* How long to delay between repaint requests during a scale.
* A negative number prevents repaint requests during a scale.\n
* Units: ms
*/
/**
* Computed time function used for sampling frames of a zoom to animation.
*/
StaticAutoPtr<ComputedTimingFunction> gZoomAnimationFunction;
/**
* Computed time function used for curving up velocity when it gets high.
*/
StaticAutoPtr<ComputedTimingFunction> gVelocityCurveFunction;
/**
* The estimated duration of a paint for the purposes of calculating a new
* displayport, in milliseconds.
*/
static const double kDefaultEstimatedPaintDurationMs = 50;
/**
* Returns true if this is a high memory system and we can use
* extra memory for a larger displayport to reduce checkerboarding.
*/
static bool gIsHighMemSystem = false;
static bool IsHighMemSystem() { return gIsHighMemSystem; }
// Counter used to give each APZC a unique id
static uint32_t sAsyncPanZoomControllerCount = 0;
AsyncPanZoomAnimation* PlatformSpecificStateBase::CreateFlingAnimation(
AsyncPanZoomController& aApzc, const FlingHandoffState& aHandoffState,
float aPLPPI) {
return new GenericFlingAnimation<DesktopFlingPhysics>(aApzc, aHandoffState,
aPLPPI);
}
UniquePtr<VelocityTracker> PlatformSpecificStateBase::CreateVelocityTracker(
Axis* aAxis) {
return MakeUnique<SimpleVelocityTracker>(aAxis);
}
SampleTime AsyncPanZoomController::GetFrameTime() const {
APZCTreeManager* treeManagerLocal = GetApzcTreeManager();
return treeManagerLocal ? treeManagerLocal->GetFrameTime()
: SampleTime::FromNow();
}
class MOZ_STACK_CLASS StateChangeNotificationBlocker final {
public:
explicit StateChangeNotificationBlocker(AsyncPanZoomController* aApzc)
: mApzc(aApzc) {
RecursiveMutexAutoLock lock(mApzc->mRecursiveMutex);
mInitialState = mApzc->mState;
mApzc->mNotificationBlockers++;
}
~StateChangeNotificationBlocker() {
AsyncPanZoomController::PanZoomState newState;
{
RecursiveMutexAutoLock lock(mApzc->mRecursiveMutex);
mApzc->mNotificationBlockers--;
newState = mApzc->mState;
}
mApzc->DispatchStateChangeNotification(mInitialState, newState);
}
private:
AsyncPanZoomController* mApzc;
AsyncPanZoomController::PanZoomState mInitialState;
};
/**
* An RAII class to temporarily apply async test attributes to the provided
* AsyncPanZoomController.
*
* This class should be used in the implementation of any AsyncPanZoomController
* method that queries the async scroll offset or async zoom (this includes
* the async layout viewport offset, since modifying the async scroll offset
* may result in the layout viewport moving as well).
*/
class MOZ_RAII AutoApplyAsyncTestAttributes final {
public:
explicit AutoApplyAsyncTestAttributes(
const AsyncPanZoomController*,
const RecursiveMutexAutoLock& aProofOfLock);
~AutoApplyAsyncTestAttributes();
private:
AsyncPanZoomController* mApzc;
FrameMetrics mPrevFrameMetrics;
const RecursiveMutexAutoLock& mProofOfLock;
};
AutoApplyAsyncTestAttributes::AutoApplyAsyncTestAttributes(
const AsyncPanZoomController* aApzc,
const RecursiveMutexAutoLock& aProofOfLock)
// Having to use const_cast here seems less ugly than the alternatives
// of making several members of AsyncPanZoomController that
// ApplyAsyncTestAttributes() modifies |mutable|, or several methods that
// query the async transforms non-const.
: mApzc(const_cast<AsyncPanZoomController*>(aApzc)),
mPrevFrameMetrics(aApzc->Metrics()),
mProofOfLock(aProofOfLock) {
mApzc->ApplyAsyncTestAttributes(aProofOfLock);
}
AutoApplyAsyncTestAttributes::~AutoApplyAsyncTestAttributes() {
mApzc->UnapplyAsyncTestAttributes(mProofOfLock, mPrevFrameMetrics);
}
class ZoomAnimation : public AsyncPanZoomAnimation {
public:
ZoomAnimation(AsyncPanZoomController& aApzc, const CSSPoint& aStartOffset,
const CSSToParentLayerScale2D& aStartZoom,
const CSSPoint& aEndOffset,
const CSSToParentLayerScale2D& aEndZoom)
: mApzc(aApzc),
mTotalDuration(TimeDuration::FromMilliseconds(
StaticPrefs::apz_zoom_animation_duration_ms())),
mStartOffset(aStartOffset),
mStartZoom(aStartZoom),
mEndOffset(aEndOffset),
mEndZoom(aEndZoom) {}
virtual bool DoSample(FrameMetrics& aFrameMetrics,
const TimeDuration& aDelta) override {
mDuration += aDelta;
double animPosition = mDuration / mTotalDuration;
if (animPosition >= 1.0) {
aFrameMetrics.SetZoom(mEndZoom);
mApzc.SetVisualScrollOffset(mEndOffset);
return false;
}
// Sample the zoom at the current time point. The sampled zoom
// will affect the final computed resolution.
float sampledPosition = gZoomAnimationFunction->GetValue(
animPosition, ComputedTimingFunction::BeforeFlag::Unset);
// We scale the scrollOffset linearly with sampledPosition, so the zoom
// needs to scale inversely to match.
if (mStartZoom == CSSToParentLayerScale2D(0, 0) ||
mEndZoom == CSSToParentLayerScale2D(0, 0)) {
return false;
}
aFrameMetrics.SetZoom(CSSToParentLayerScale2D(
1 / (sampledPosition / mEndZoom.xScale +
(1 - sampledPosition) / mStartZoom.xScale),
1 / (sampledPosition / mEndZoom.yScale +
(1 - sampledPosition) / mStartZoom.yScale)));
mApzc.SetVisualScrollOffset(CSSPoint::FromUnknownPoint(gfx::Point(
mEndOffset.x * sampledPosition + mStartOffset.x * (1 - sampledPosition),
mEndOffset.y * sampledPosition +
mStartOffset.y * (1 - sampledPosition))));
return true;
}
virtual bool WantsRepaints() override { return false; }
private:
AsyncPanZoomController& mApzc;
TimeDuration mDuration;
const TimeDuration mTotalDuration;
// Old metrics from before we started a zoom animation. This is only valid
// when we are in the "ANIMATED_ZOOM" state. This is used so that we can
// interpolate between the start and end frames. We only use the
// |mViewportScrollOffset| and |mResolution| fields on this.
CSSPoint mStartOffset;
CSSToParentLayerScale2D mStartZoom;
// Target metrics for a zoom to animation. This is only valid when we are in
// the "ANIMATED_ZOOM" state. We only use the |mViewportScrollOffset| and
// |mResolution| fields on this.
CSSPoint mEndOffset;
CSSToParentLayerScale2D mEndZoom;
};
/*static*/
void AsyncPanZoomController::InitializeGlobalState() {
static bool sInitialized = false;
if (sInitialized) return;
sInitialized = true;
MOZ_ASSERT(NS_IsMainThread());
gZoomAnimationFunction =
new ComputedTimingFunction(nsTimingFunction(StyleTimingKeyword::Ease));
ClearOnShutdown(&gZoomAnimationFunction);
gVelocityCurveFunction = new ComputedTimingFunction(
nsTimingFunction(StaticPrefs::apz_fling_curve_function_x1_AtStartup(),
StaticPrefs::apz_fling_curve_function_y1_AtStartup(),
StaticPrefs::apz_fling_curve_function_x2_AtStartup(),
StaticPrefs::apz_fling_curve_function_y2_AtStartup()));
ClearOnShutdown(&gVelocityCurveFunction);
uint64_t sysmem = PR_GetPhysicalMemorySize();
uint64_t threshold = 1LL << 32; // 4 GB in bytes
gIsHighMemSystem = sysmem >= threshold;
PlatformSpecificState::InitializeGlobalState();
}
AsyncPanZoomController::AsyncPanZoomController(
LayersId aLayersId, APZCTreeManager* aTreeManager,
const RefPtr<InputQueue>& aInputQueue,
GeckoContentController* aGeckoContentController, GestureBehavior aGestures)
: mLayersId(aLayersId),
mGeckoContentController(aGeckoContentController),
mRefPtrMonitor("RefPtrMonitor"),
// mTreeManager must be initialized before GetFrameTime() is called
mTreeManager(aTreeManager),
mRecursiveMutex("AsyncPanZoomController"),
mLastContentPaintMetrics(mLastContentPaintMetadata.GetMetrics()),
mX(this),
mY(this),
mPanDirRestricted(false),
mPinchLocked(false),
mPinchEventBuffer(TimeDuration::FromMilliseconds(
StaticPrefs::apz_pinch_lock_buffer_max_age_AtStartup())),
mZoomConstraints(false, false,
mScrollMetadata.GetMetrics().GetDevPixelsPerCSSPixel() *
kViewportMinScale / ParentLayerToScreenScale(1),
mScrollMetadata.GetMetrics().GetDevPixelsPerCSSPixel() *
kViewportMaxScale / ParentLayerToScreenScale(1)),
mLastSampleTime(GetFrameTime()),
mLastCheckerboardReport(GetFrameTime()),
mOverscrollEffect(MakeUnique<OverscrollEffect>(*this)),
mState(NOTHING),
mNotificationBlockers(0),
mInputQueue(aInputQueue),
mPinchPaintTimerSet(false),
mAPZCId(sAsyncPanZoomControllerCount++),
mSharedLock(nullptr),
mTestAttributeAppliers(0),
mAsyncTransformAppliedToContent(false),
mTestHasAsyncKeyScrolled(false),
mCheckerboardEventLock("APZCBELock") {
if (aGestures == USE_GESTURE_DETECTOR) {
mGestureEventListener = new GestureEventListener(this);
}
// Put one default-constructed sampled state in the queue.
RecursiveMutexAutoLock lock(mRecursiveMutex);
mSampledState.emplace_back();
}
AsyncPanZoomController::~AsyncPanZoomController() { MOZ_ASSERT(IsDestroyed()); }
PlatformSpecificStateBase* AsyncPanZoomController::GetPlatformSpecificState() {
if (!mPlatformSpecificState) {
mPlatformSpecificState = MakeUnique<PlatformSpecificState>();
}
return mPlatformSpecificState.get();
}
already_AddRefed<GeckoContentController>
AsyncPanZoomController::GetGeckoContentController() const {
MonitorAutoLock lock(mRefPtrMonitor);
RefPtr<GeckoContentController> controller = mGeckoContentController;
return controller.forget();
}
already_AddRefed<GestureEventListener>
AsyncPanZoomController::GetGestureEventListener() const {
MonitorAutoLock lock(mRefPtrMonitor);
RefPtr<GestureEventListener> listener = mGestureEventListener;
return listener.forget();
}
const RefPtr<InputQueue>& AsyncPanZoomController::GetInputQueue() const {
return mInputQueue;
}
void AsyncPanZoomController::Destroy() {
AssertOnUpdaterThread();
CancelAnimation(CancelAnimationFlags::ScrollSnap);
{ // scope the lock
MonitorAutoLock lock(mRefPtrMonitor);
mGeckoContentController = nullptr;
mGestureEventListener = nullptr;
}
mParent = nullptr;
mTreeManager = nullptr;
// Only send the release message if the SharedFrameMetrics has been created.
if (mMetricsSharingController && mSharedFrameMetricsBuffer) {
Unused << mMetricsSharingController->StopSharingMetrics(GetScrollId(),
mAPZCId);
}
{ // scope the lock
RecursiveMutexAutoLock lock(mRecursiveMutex);
mSharedFrameMetricsBuffer = nullptr;
delete mSharedLock;
mSharedLock = nullptr;
}
}
bool AsyncPanZoomController::IsDestroyed() const {
return mTreeManager == nullptr;
}
float AsyncPanZoomController::GetDPI() const {
if (APZCTreeManager* localPtr = mTreeManager) {
return localPtr->GetDPI();
}
// If this APZC has been destroyed then this value is not going to be
// used for anything that the user will end up seeing, so we can just
// return 0.
return 0.0;
}
ScreenCoord AsyncPanZoomController::GetTouchStartTolerance() const {
return (StaticPrefs::apz_touch_start_tolerance() * GetDPI());
}
ScreenCoord AsyncPanZoomController::GetTouchMoveTolerance() const {
return (StaticPrefs::apz_touch_move_tolerance() * GetDPI());
}
ScreenCoord AsyncPanZoomController::GetSecondTapTolerance() const {
return (StaticPrefs::apz_second_tap_tolerance() * GetDPI());
}
/* static */ AsyncPanZoomController::AxisLockMode
AsyncPanZoomController::GetAxisLockMode() {
return static_cast<AxisLockMode>(StaticPrefs::apz_axis_lock_mode());
}
/* static */ AsyncPanZoomController::PinchLockMode
AsyncPanZoomController::GetPinchLockMode() {
return static_cast<PinchLockMode>(StaticPrefs::apz_pinch_lock_mode());
}
bool AsyncPanZoomController::ArePointerEventsConsumable(
TouchBlockState* aBlock, const MultiTouchInput& aInput) {
uint32_t touchPoints = aInput.mTouches.Length();
if (touchPoints == 0) {
// Cant' do anything with zero touch points
return false;
}
// This logic is simplified, erring on the side of returning true if we're
// not sure. It's safer to pretend that we can consume the event and then
// not be able to than vice-versa. But at the same time, we should try hard
// to return an accurate result, because returning true can trigger a
// pointercancel event to web content, which can break certain features
// that are using touch-action and handling the pointermove events.
//
// Note that in particular this function can return true if APZ is waiting on
// the main thread for touch-action information. In this scenario, the
// APZEventState::MainThreadAgreesEventsAreConsumableByAPZ() function tries
// to use the main-thread touch-action information to filter out false
// positives.
//
// We could probably enhance this logic to determine things like "we're
// not pannable, so we can only zoom in, and the zoom is already maxed
// out, so we're not zoomable either" but no need for that at this point.
bool pannableX = aBlock->TouchActionAllowsPanningX() &&
aBlock->GetOverscrollHandoffChain()->CanScrollInDirection(
this, ScrollDirection::eHorizontal);
bool pannableY =
(aBlock->TouchActionAllowsPanningY() &&
(aBlock->GetOverscrollHandoffChain()->CanScrollInDirection(
this, ScrollDirection::eVertical) ||
// In the case of the root APZC with any dynamic toolbar, it
// shoule be pannable if there is room moving the dynamic
// toolbar.
(IsRootContent() && CanScrollDownwardsWithDynamicToolbar())));
bool pannable;
Maybe<ScrollDirection> panDirection =
aBlock->GetBestGuessPanDirection(aInput);
if (panDirection == Some(ScrollDirection::eVertical)) {
pannable = pannableY;
} else if (panDirection == Some(ScrollDirection::eHorizontal)) {
pannable = pannableX;
} else {
// If we don't have a guessed pan direction, err on the side of returning
// true.
pannable = pannableX || pannableY;
}
if (touchPoints == 1) {
return pannable;
}
bool zoomable = mZoomConstraints.mAllowZoom;
zoomable &= (aBlock->TouchActionAllowsPinchZoom());
return pannable || zoomable;
}
nsEventStatus AsyncPanZoomController::HandleDragEvent(
const MouseInput& aEvent, const AsyncDragMetrics& aDragMetrics,
CSSCoord aInitialThumbPos) {
// RDM is a special case where touch events will be synthesized in response
// to mouse events, and APZ will receive both even though RDM prevent-defaults
// the mouse events. This is because mouse events don't opt into APZ waiting
// to check if the event has been prevent-defaulted and are still processed
// as a result. To handle this, have APZ ignore mouse events when RDM and
// touch simulation are active.
bool isRDMTouchSimulationActive = false;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
isRDMTouchSimulationActive =
mScrollMetadata.GetIsRDMTouchSimulationActive();
}
if (!StaticPrefs::apz_drag_enabled() || isRDMTouchSimulationActive) {
return nsEventStatus_eIgnore;
}
if (!GetApzcTreeManager()) {
return nsEventStatus_eConsumeNoDefault;
}
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (aEvent.mType == MouseInput::MouseType::MOUSE_UP &&
mState == SCROLLBAR_DRAG) {
APZC_LOG("%p ending drag\n", this);
SetState(NOTHING);
ScrollSnap();
return nsEventStatus_eConsumeNoDefault;
}
}
HitTestingTreeNodeAutoLock node;
GetApzcTreeManager()->FindScrollThumbNode(aDragMetrics, node);
if (!node) {
APZC_LOG("%p unable to find scrollthumb node with viewid %" PRIu64 "\n",
this, aDragMetrics.mViewId);
return nsEventStatus_eConsumeNoDefault;
}
if (aEvent.mType == MouseInput::MouseType::MOUSE_DOWN) {
APZC_LOG("%p starting scrollbar drag\n", this);
SetState(SCROLLBAR_DRAG);
mozilla::Telemetry::Accumulate(
mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethod::ApzScrollbarDrag);
}
if (aEvent.mType != MouseInput::MouseType::MOUSE_MOVE) {
APZC_LOG("%p discarding event of type %d\n", this, aEvent.mType);
return nsEventStatus_eConsumeNoDefault;
}
const ScrollbarData& scrollbarData = node->GetScrollbarData();
MOZ_ASSERT(scrollbarData.mScrollbarLayerType ==
layers::ScrollbarLayerType::Thumb);
MOZ_ASSERT(scrollbarData.mDirection.isSome());
ScrollDirection direction = *scrollbarData.mDirection;
bool isMouseAwayFromThumb = false;
if (int snapMultiplier = StaticPrefs::slider_snapMultiplier_AtStartup()) {
// It's fine to ignore the async component of the thumb's transform,
// because any async transform of the thumb will be in the direction of
// scrolling, but here we're interested in the other direction.
ParentLayerRect thumbRect =
(node->GetTransform() * AsyncTransformMatrix())
.TransformBounds(LayerRect(node->GetVisibleRegion().GetBounds()));
ScrollDirection otherDirection = GetPerpendicularDirection(direction);
ParentLayerCoord distance =
GetAxisStart(otherDirection, thumbRect.DistanceTo(aEvent.mLocalOrigin));
ParentLayerCoord thumbWidth = GetAxisLength(otherDirection, thumbRect);
// Avoid triggering this condition spuriously when the thumb is
// offscreen and its visible region is therefore empty.
if (thumbWidth > 0 && thumbWidth * snapMultiplier < distance) {
isMouseAwayFromThumb = true;
APZC_LOG("%p determined mouse is away from thumb, will snap\n", this);
}
}
RecursiveMutexAutoLock lock(mRecursiveMutex);
CSSCoord thumbPosition;
if (isMouseAwayFromThumb) {
thumbPosition = aInitialThumbPos;
} else {
thumbPosition = ConvertScrollbarPoint(aEvent.mLocalOrigin, scrollbarData) -
aDragMetrics.mScrollbarDragOffset;
}
CSSCoord maxThumbPos = scrollbarData.mScrollTrackLength;
maxThumbPos -= scrollbarData.mThumbLength;
float scrollPercent =
maxThumbPos.value == 0.0f ? 0.0f : (float)(thumbPosition / maxThumbPos);
APZC_LOG("%p scrollbar dragged to %f percent\n", this, scrollPercent);
CSSCoord minScrollPosition =
GetAxisStart(direction, Metrics().GetScrollableRect().TopLeft());
CSSCoord maxScrollPosition =
GetAxisStart(direction, Metrics().GetScrollableRect().BottomRight()) -
GetAxisLength(direction, Metrics().CalculateCompositedSizeInCssPixels());
CSSCoord scrollPosition =
minScrollPosition +
(scrollPercent * (maxScrollPosition - minScrollPosition));
scrollPosition = std::max(scrollPosition, minScrollPosition);
scrollPosition = std::min(scrollPosition, maxScrollPosition);
CSSPoint scrollOffset = Metrics().GetVisualScrollOffset();
if (direction == ScrollDirection::eHorizontal) {
scrollOffset.x = scrollPosition;
} else {
scrollOffset.y = scrollPosition;
}
APZC_LOG("%p set scroll offset to %s from scrollbar drag\n", this,
ToString(scrollOffset).c_str());
SetVisualScrollOffset(scrollOffset);
ScheduleCompositeAndMaybeRepaint();
UpdateSharedCompositorFrameMetrics();
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::HandleInputEvent(
const InputData& aEvent,
const ScreenToParentLayerMatrix4x4& aTransformToApzc) {
APZThreadUtils::AssertOnControllerThread();
nsEventStatus rv = nsEventStatus_eIgnore;
switch (aEvent.mInputType) {
case MULTITOUCH_INPUT: {
MultiTouchInput multiTouchInput = aEvent.AsMultiTouchInput();
RefPtr<GestureEventListener> listener = GetGestureEventListener();
if (listener) {
// We only care about screen coordinates in the gesture listener,
// so we don't bother transforming the event to parent layer coordinates
rv = listener->HandleInputEvent(multiTouchInput);
if (rv == nsEventStatus_eConsumeNoDefault) {
return rv;
}
}
if (!multiTouchInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
switch (multiTouchInput.mType) {
case MultiTouchInput::MULTITOUCH_START:
rv = OnTouchStart(multiTouchInput);
break;
case MultiTouchInput::MULTITOUCH_MOVE:
rv = OnTouchMove(multiTouchInput);
break;
case MultiTouchInput::MULTITOUCH_END:
rv = OnTouchEnd(multiTouchInput);
break;
case MultiTouchInput::MULTITOUCH_CANCEL:
rv = OnTouchCancel(multiTouchInput);
break;
}
break;
}
case PANGESTURE_INPUT: {
PanGestureInput panGestureInput = aEvent.AsPanGestureInput();
if (!panGestureInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
switch (panGestureInput.mType) {
case PanGestureInput::PANGESTURE_MAYSTART:
rv = OnPanMayBegin(panGestureInput);
break;
case PanGestureInput::PANGESTURE_CANCELLED:
rv = OnPanCancelled(panGestureInput);
break;
case PanGestureInput::PANGESTURE_START:
rv = OnPanBegin(panGestureInput);
break;
case PanGestureInput::PANGESTURE_PAN:
rv = OnPan(panGestureInput, true);
break;
case PanGestureInput::PANGESTURE_END:
rv = OnPanEnd(panGestureInput);
break;
case PanGestureInput::PANGESTURE_MOMENTUMSTART:
rv = OnPanMomentumStart(panGestureInput);
break;
case PanGestureInput::PANGESTURE_MOMENTUMPAN:
rv = OnPan(panGestureInput, false);
break;
case PanGestureInput::PANGESTURE_MOMENTUMEND:
rv = OnPanMomentumEnd(panGestureInput);
break;
}
break;
}
case MOUSE_INPUT: {
MouseInput mouseInput = aEvent.AsMouseInput();
if (!mouseInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
break;
}
case SCROLLWHEEL_INPUT: {
ScrollWheelInput scrollInput = aEvent.AsScrollWheelInput();
if (!scrollInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
rv = OnScrollWheel(scrollInput);
break;
}
case PINCHGESTURE_INPUT: {
// The APZCTreeManager should take care of ensuring that only root-content
// APZCs get pinch inputs.
MOZ_ASSERT(IsRootContent());
PinchGestureInput pinchInput = aEvent.AsPinchGestureInput();
if (!pinchInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
rv = HandleGestureEvent(pinchInput);
break;
}
case TAPGESTURE_INPUT: {
TapGestureInput tapInput = aEvent.AsTapGestureInput();
if (!tapInput.TransformToLocal(aTransformToApzc)) {
return rv;
}
rv = HandleGestureEvent(tapInput);
break;
}
case KEYBOARD_INPUT: {
const KeyboardInput& keyInput = aEvent.AsKeyboardInput();
rv = OnKeyboard(keyInput);
break;
}
}
return rv;
}
nsEventStatus AsyncPanZoomController::HandleGestureEvent(
const InputData& aEvent) {
APZThreadUtils::AssertOnControllerThread();
nsEventStatus rv = nsEventStatus_eIgnore;
switch (aEvent.mInputType) {
case PINCHGESTURE_INPUT: {
// This may be invoked via a one-touch-pinch gesture from
// GestureEventListener. In that case we want redirect it to the enclosing
// root-content APZC.
if (!IsRootContent()) {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
if (RefPtr<AsyncPanZoomController> root =
treeManagerLocal->FindZoomableApzc(this)) {
rv = root->HandleGestureEvent(aEvent);
}
}
break;
}
PinchGestureInput pinchGestureInput = aEvent.AsPinchGestureInput();
pinchGestureInput.TransformToLocal(GetTransformToThis());
switch (pinchGestureInput.mType) {
case PinchGestureInput::PINCHGESTURE_START:
rv = OnScaleBegin(pinchGestureInput);
break;
case PinchGestureInput::PINCHGESTURE_SCALE:
rv = OnScale(pinchGestureInput);
break;
case PinchGestureInput::PINCHGESTURE_FINGERLIFTED:
case PinchGestureInput::PINCHGESTURE_END:
rv = OnScaleEnd(pinchGestureInput);
break;
}
break;
}
case TAPGESTURE_INPUT: {
TapGestureInput tapGestureInput = aEvent.AsTapGestureInput();
tapGestureInput.TransformToLocal(GetTransformToThis());
switch (tapGestureInput.mType) {
case TapGestureInput::TAPGESTURE_LONG:
rv = OnLongPress(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_LONG_UP:
rv = OnLongPressUp(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_UP:
rv = OnSingleTapUp(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_CONFIRMED:
rv = OnSingleTapConfirmed(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_DOUBLE:
rv = OnDoubleTap(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_SECOND:
rv = OnSecondTap(tapGestureInput);
break;
case TapGestureInput::TAPGESTURE_CANCEL:
rv = OnCancelTap(tapGestureInput);
break;
}
break;
}
default:
MOZ_ASSERT_UNREACHABLE("Unhandled input event");
break;
}
return rv;
}
void AsyncPanZoomController::StartAutoscroll(const ScreenPoint& aPoint) {
// Cancel any existing animation.
CancelAnimation();
Telemetry::Accumulate(Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethod::ApzAutoscrolling);
SetState(AUTOSCROLL);
StartAnimation(new AutoscrollAnimation(*this, aPoint));
}
void AsyncPanZoomController::StopAutoscroll() {
if (mState == AUTOSCROLL) {
CancelAnimation(TriggeredExternally);
}
}
nsEventStatus AsyncPanZoomController::OnTouchStart(
const MultiTouchInput& aEvent) {
APZC_LOG("%p got a touch-start in state %d\n", this, mState);
mPanDirRestricted = false;
switch (mState) {
case FLING:
case ANIMATING_ZOOM:
case SMOOTH_SCROLL:
case SMOOTHMSD_SCROLL:
case OVERSCROLL_ANIMATION:
case WHEEL_SCROLL:
case KEYBOARD_SCROLL:
case PAN_MOMENTUM:
case AUTOSCROLL:
MOZ_ASSERT(GetCurrentTouchBlock());
GetCurrentTouchBlock()->GetOverscrollHandoffChain()->CancelAnimations(
ExcludeOverscroll);
[[fallthrough]];
case SCROLLBAR_DRAG:
case NOTHING: {
ParentLayerPoint point = GetFirstTouchPoint(aEvent);
mStartTouch = GetFirstExternalTouchPoint(aEvent);
StartTouch(point, aEvent.mTimeStamp);
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
MOZ_ASSERT(GetCurrentTouchBlock());
controller->NotifyAPZStateChange(
GetGuid(), APZStateChange::eStartTouch,
GetCurrentTouchBlock()->GetOverscrollHandoffChain()->CanBePanned(
this));
}
mTouchStartTime = aEvent.mTimeStamp;
SetState(TOUCHING);
break;
}
case TOUCHING:
case PANNING:
case PANNING_LOCKED_X:
case PANNING_LOCKED_Y:
case PINCHING:
NS_WARNING("Received impossible touch in OnTouchStart");
break;
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnTouchMove(
const MultiTouchInput& aEvent) {
APZC_LOG("%p got a touch-move in state %d\n", this, mState);
switch (mState) {
case FLING:
case SMOOTHMSD_SCROLL:
case NOTHING:
case ANIMATING_ZOOM:
// May happen if the user double-taps and drags without lifting after the
// second tap. Ignore the move if this happens.
return nsEventStatus_eIgnore;
case TOUCHING: {
ScreenCoord panThreshold = GetTouchStartTolerance();
ExternalPoint extPoint = GetFirstExternalTouchPoint(aEvent);
// We intentionally skip the UpdateWithTouchAtDevicePoint call when the
// panThreshold is zero. This ensures more deterministic behaviour during
// testing. If we call that, Axis::mPos gets updated to the point of this
// touchmove event, but we "consume" the move to overcome the
// panThreshold, so it's hard to pan a specific amount reliably from a
// mochitest.
if (panThreshold > 0.0f) {
UpdateWithTouchAtDevicePoint(aEvent);
if (PanVector(extPoint).Length() < panThreshold) {
return nsEventStatus_eIgnore;
}
}
MOZ_ASSERT(GetCurrentTouchBlock());
if (StaticPrefs::layout_css_touch_action_enabled() &&
GetCurrentTouchBlock()->TouchActionAllowsPanningXY()) {
// User tries to trigger a touch behavior. If allowed touch behavior is
// vertical pan
// + horizontal pan (touch-action value is equal to AUTO) we can return
// ConsumeNoDefault status immediately to trigger cancel event further.
// It should happen independent of the parent type (whether it is
// scrolling or not).
StartPanning(extPoint, aEvent.mTimeStamp);
return nsEventStatus_eConsumeNoDefault;
}
return StartPanning(extPoint, aEvent.mTimeStamp);
}
case PANNING:
case PANNING_LOCKED_X:
case PANNING_LOCKED_Y:
case PAN_MOMENTUM:
TrackTouch(aEvent);
return nsEventStatus_eConsumeNoDefault;
case PINCHING:
// The scale gesture listener should have handled this.
NS_WARNING(
"Gesture listener should have handled pinching in OnTouchMove.");
return nsEventStatus_eIgnore;
case SMOOTH_SCROLL:
case WHEEL_SCROLL:
case KEYBOARD_SCROLL:
case OVERSCROLL_ANIMATION:
case AUTOSCROLL:
case SCROLLBAR_DRAG:
// Should not receive a touch-move in the OVERSCROLL_ANIMATION state
// as touch blocks that begin in an overscrolled state cancel the
// animation. The same is true for wheel scroll animations.
NS_WARNING("Received impossible touch in OnTouchMove");
break;
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnTouchEnd(
const MultiTouchInput& aEvent) {
APZC_LOG("%p got a touch-end in state %d\n", this, mState);
OnTouchEndOrCancel();
// In case no touch behavior triggered previously we can avoid sending
// scroll events or requesting content repaint. This condition is added
// to make tests consistent - in case touch-action is NONE (and therefore
// no pans/zooms can be performed) we expected neither scroll or repaint
// events.
if (mState != NOTHING) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
}
switch (mState) {
case FLING:
// Should never happen.
NS_WARNING("Received impossible touch end in OnTouchEnd.");
[[fallthrough]];
case ANIMATING_ZOOM:
case SMOOTHMSD_SCROLL:
case NOTHING:
// May happen if the user double-taps and drags without lifting after the
// second tap. Ignore if this happens.
return nsEventStatus_eIgnore;
case TOUCHING:
// We may have some velocity stored on the axis from move events
// that were not big enough to trigger scrolling. Clear that out.
SetVelocityVector(ParentLayerPoint(0, 0));
MOZ_ASSERT(GetCurrentTouchBlock());
APZC_LOG("%p still has %u touch points active\n", this,
GetCurrentTouchBlock()->GetActiveTouchCount());
// In cases where the user is panning, then taps the second finger without
// entering a pinch, we will arrive here when the second finger is lifted.
// However the first finger is still down so we want to remain in state
// TOUCHING.
if (GetCurrentTouchBlock()->GetActiveTouchCount() == 0) {
// It's possible we may be overscrolled if the user tapped during a
// previous overscroll pan. Make sure to snap back in this situation.
// An ancestor APZC could be overscrolled instead of this APZC, so
// walk the handoff chain as well.
GetCurrentTouchBlock()
->GetOverscrollHandoffChain()
->SnapBackOverscrolledApzc(this);
mFlingAccelerator.Reset();
// SnapBackOverscrolledApzc() will put any APZC it causes to snap back
// into the OVERSCROLL_ANIMATION state. If that's not us, since we're
// done TOUCHING enter the NOTHING state.
if (mState != OVERSCROLL_ANIMATION) {
SetState(NOTHING);
}
}
return nsEventStatus_eIgnore;
case PANNING:
case PANNING_LOCKED_X:
case PANNING_LOCKED_Y:
case PAN_MOMENTUM: {
MOZ_ASSERT(GetCurrentTouchBlock());
EndTouch(aEvent.mTimeStamp);
return HandleEndOfPan();
}
case PINCHING:
SetState(NOTHING);
// Scale gesture listener should have handled this.
NS_WARNING(
"Gesture listener should have handled pinching in OnTouchEnd.");
return nsEventStatus_eIgnore;
case SMOOTH_SCROLL:
case WHEEL_SCROLL:
case KEYBOARD_SCROLL:
case OVERSCROLL_ANIMATION:
case AUTOSCROLL:
case SCROLLBAR_DRAG:
// Should not receive a touch-end in the OVERSCROLL_ANIMATION state
// as touch blocks that begin in an overscrolled state cancel the
// animation. The same is true for WHEEL_SCROLL.
NS_WARNING("Received impossible touch in OnTouchEnd");
break;
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnTouchCancel(
const MultiTouchInput& aEvent) {
APZC_LOG("%p got a touch-cancel in state %d\n", this, mState);
OnTouchEndOrCancel();
CancelAnimationAndGestureState();
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnScaleBegin(
const PinchGestureInput& aEvent) {
APZC_LOG("%p got a scale-begin in state %d\n", this, mState);
mPinchLocked = false;
mPinchPaintTimerSet = false;
// Note that there may not be a touch block at this point, if we received the
// PinchGestureEvent directly from widget code without any touch events.
if (HasReadyTouchBlock() &&
!GetCurrentTouchBlock()->TouchActionAllowsPinchZoom()) {
return nsEventStatus_eIgnore;
}
// If zooming is not allowed, this is a two-finger pan.
// Start tracking panning distance and velocity.
if (!mZoomConstraints.mAllowZoom) {
StartTouch(aEvent.mLocalFocusPoint, aEvent.mTimeStamp);
}
// For platforms that don't support APZ zooming, dispatch a message to the
// content controller, it may want to do something else with this gesture.
// FIXME: bug 1525793 -- this may need to handle zooming or not on a
// per-document basis.
if (!StaticPrefs::apz_allow_zooming()) {
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
APZC_LOG("%p notifying controller of pinch gesture start\n", this);
controller->NotifyPinchGesture(
aEvent.mType, GetGuid(),
ViewAs<LayoutDevicePixel>(
aEvent.mFocusPoint,
PixelCastJustification::
LayoutDeviceIsScreenForUntransformedEvent),
0, aEvent.modifiers);
}
}
SetState(PINCHING);
Telemetry::Accumulate(Telemetry::APZ_ZOOM_PINCHSOURCE, (int)aEvent.mSource);
SetVelocityVector(ParentLayerPoint(0, 0));
RecursiveMutexAutoLock lock(mRecursiveMutex);
mLastZoomFocus =
aEvent.mLocalFocusPoint - Metrics().GetCompositionBounds().TopLeft();
mPinchEventBuffer.push(aEvent);
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnScale(const PinchGestureInput& aEvent) {
APZC_LOG("%p got a scale in state %d\n", this, mState);
if (HasReadyTouchBlock() &&
!GetCurrentTouchBlock()->TouchActionAllowsPinchZoom()) {
return nsEventStatus_eIgnore;
}
if (mState != PINCHING) {
return nsEventStatus_eConsumeNoDefault;
}
mPinchEventBuffer.push(aEvent);
HandlePinchLocking(aEvent);
bool allowZoom = mZoomConstraints.mAllowZoom && !mPinchLocked;
// If zooming is not allowed, this is a two-finger pan.
// Tracking panning distance and velocity.
// UpdateWithTouchAtDevicePoint() acquires the tree lock, so
// it cannot be called while the mRecursiveMutex lock is held.
if (!allowZoom) {
mX.UpdateWithTouchAtDevicePoint(aEvent.mLocalFocusPoint.x,
aEvent.mTimeStamp);
mY.UpdateWithTouchAtDevicePoint(aEvent.mLocalFocusPoint.y,
aEvent.mTimeStamp);
}
// FIXME: bug 1525793 -- this may need to handle zooming or not on a
// per-document basis.
if (!StaticPrefs::apz_allow_zooming()) {
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
APZC_LOG("%p notifying controller of pinch gesture\n", this);
controller->NotifyPinchGesture(
aEvent.mType, GetGuid(),
ViewAs<LayoutDevicePixel>(
aEvent.mFocusPoint,
PixelCastJustification::
LayoutDeviceIsScreenForUntransformedEvent),
ViewAs<LayoutDevicePixel>(
aEvent.mCurrentSpan - aEvent.mPreviousSpan,
PixelCastJustification::
LayoutDeviceIsScreenForUntransformedEvent),
aEvent.modifiers);
}
}
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
// Only the root APZC is zoomable, and the root APZC is not allowed to have
// different x and y scales. If it did, the calculations in this function
// would have to be adjusted (as e.g. it would no longer be valid to take
// the minimum or maximum of the ratios of the widths and heights of the
// page rect and the composition bounds).
MOZ_ASSERT(Metrics().IsRootContent());
MOZ_ASSERT(Metrics().GetZoom().AreScalesSame());
CSSToParentLayerScale userZoom = Metrics().GetZoom().ToScaleFactor();
ParentLayerPoint focusPoint =
aEvent.mLocalFocusPoint - Metrics().GetCompositionBounds().TopLeft();
CSSPoint cssFocusPoint;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
cssFocusPoint = focusPoint / Metrics().GetZoom();
}
ParentLayerPoint focusChange = mLastZoomFocus - focusPoint;
mLastZoomFocus = focusPoint;
// If displacing by the change in focus point will take us off page bounds,
// then reduce the displacement such that it doesn't.
focusChange.x -= mX.DisplacementWillOverscrollAmount(focusChange.x);
focusChange.y -= mY.DisplacementWillOverscrollAmount(focusChange.y);
if (userZoom != CSSToParentLayerScale(0)) {
ScrollBy(focusChange / userZoom);
}
// If the span is zero or close to it, we don't want to process this zoom
// change because we're going to get wonky numbers for the spanRatio. So
// let's bail out here. Note that we do this after the focus-change-scroll
// above, so that if we have a pinch with zero span but changing focus,
// such as generated by some Synaptics touchpads on Windows, we still
// scroll properly.
float prevSpan = aEvent.mPreviousSpan;
if (fabsf(prevSpan) <= EPSILON || fabsf(aEvent.mCurrentSpan) <= EPSILON) {
// We might have done a nonzero ScrollBy above, so update metrics and
// repaint/recomposite
ScheduleCompositeAndMaybeRepaint();
UpdateSharedCompositorFrameMetrics();
return nsEventStatus_eConsumeNoDefault;
}
float spanRatio = aEvent.mCurrentSpan / aEvent.mPreviousSpan;
// When we zoom in with focus, we can zoom too much towards the boundaries
// that we actually go over them. These are the needed displacements along
// either axis such that we don't overscroll the boundaries when zooming.
CSSPoint neededDisplacement;
CSSToParentLayerScale realMinZoom = mZoomConstraints.mMinZoom;
CSSToParentLayerScale realMaxZoom = mZoomConstraints.mMaxZoom;
realMinZoom.scale =
std::max(realMinZoom.scale, Metrics().GetCompositionBounds().Width() /
Metrics().GetScrollableRect().Width());
realMinZoom.scale =
std::max(realMinZoom.scale, Metrics().GetCompositionBounds().Height() /
Metrics().GetScrollableRect().Height());
if (realMaxZoom < realMinZoom) {
realMaxZoom = realMinZoom;
}
bool doScale = allowZoom && ((spanRatio > 1.0 && userZoom < realMaxZoom) ||
(spanRatio < 1.0 && userZoom > realMinZoom));
if (doScale) {
spanRatio = clamped(spanRatio, realMinZoom.scale / userZoom.scale,
realMaxZoom.scale / userZoom.scale);
// Note that the spanRatio here should never put us into OVERSCROLL_BOTH
// because up above we clamped it.
neededDisplacement.x =
-mX.ScaleWillOverscrollAmount(spanRatio, cssFocusPoint.x);
neededDisplacement.y =
-mY.ScaleWillOverscrollAmount(spanRatio, cssFocusPoint.y);
ScaleWithFocus(spanRatio, cssFocusPoint);
if (neededDisplacement != CSSPoint()) {
ScrollBy(neededDisplacement);
}
// We don't want to redraw on every scale, so throttle it.
if (!mPinchPaintTimerSet) {
const int delay = StaticPrefs::apz_scale_repaint_delay_ms();
if (delay >= 0) {
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
mPinchPaintTimerSet = true;
controller->PostDelayedTask(
NewRunnableMethod(
"layers::AsyncPanZoomController::"
"DoDelayedRequestContentRepaint",
this,
&AsyncPanZoomController::DoDelayedRequestContentRepaint),
delay);
}
}
} else if (apz::AboutToCheckerboard(mLastContentPaintMetrics,
Metrics())) {
// If we already scheduled a throttled repaint request but are also
// in danger of checkerboarding soon, trigger the repaint request to
// go out immediately. This should reduce the amount of time we spend
// checkerboarding.
//
// Note that if we remain in this "about to
// checkerboard" state over a period of time with multiple pinch input
// events (which is quite likely), then we will flip-flop between taking
// the above branch (!mPinchPaintTimerSet) and this branch (which will
// flush the repaint request and reset mPinchPaintTimerSet to false).
// This is sort of desirable because it halves the number of repaint
// requests we send, and therefore reduces IPC traffic.
// Keep in mind that many of these repaint requests will be ignored on
// the main-thread anyway due to the resolution mismatch - the first
// repaint request will be honored because APZ's notion of the painted
// resolution matches the actual main thread resolution, but that first
// repaint request will change the resolution on the main thread.
// Subsequent repaint requests will be ignored in APZCCallbackHelper, at
// https://searchfox.org/mozilla-central/rev/e0eb861a187f0bb6d994228f2e0e49b2c9ee455e/gfx/layers/apz/util/APZCCallbackHelper.cpp#331-338,
// until we receive a NotifyLayersUpdated call that re-syncs APZ's
// notion of the painted resolution to the main thread. These ignored
// repaint requests are contributing to IPC traffic needlessly, and so
// halving the number of repaint requests (as mentioned above) seems
// desirable.
DoDelayedRequestContentRepaint();
}
UpdateSharedCompositorFrameMetrics();
} else {
// Trigger a repaint request after scrolling.
RequestContentRepaint();
}
// We did a ScrollBy call above even if we didn't do a scale, so we
// should composite for that.
ScheduleComposite();
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnScaleEnd(
const PinchGestureInput& aEvent) {
APZC_LOG("%p got a scale-end in state %d\n", this, mState);
mPinchPaintTimerSet = false;
if (HasReadyTouchBlock() &&
!GetCurrentTouchBlock()->TouchActionAllowsPinchZoom()) {
return nsEventStatus_eIgnore;
}
// FIXME: bug 1525793 -- this may need to handle zooming or not on a
// per-document basis.
if (!StaticPrefs::apz_allow_zooming()) {
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
controller->NotifyPinchGesture(
aEvent.mType, GetGuid(),
ViewAs<LayoutDevicePixel>(
aEvent.mFocusPoint,
PixelCastJustification::
LayoutDeviceIsScreenForUntransformedEvent),
0, aEvent.modifiers);
}
}
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
ScheduleComposite();
RequestContentRepaint();
UpdateSharedCompositorFrameMetrics();
}
mPinchEventBuffer.clear();
if (aEvent.mType == PinchGestureInput::PINCHGESTURE_FINGERLIFTED) {
// One finger is still down, so transition to a TOUCHING state
if (mZoomConstraints.mAllowZoom) {
mPanDirRestricted = false;
StartTouch(aEvent.mLocalFocusPoint, aEvent.mTimeStamp);
SetState(TOUCHING);
} else {
// If zooming isn't allowed, StartTouch() was already called
// in OnScaleBegin().
StartPanning(ToExternalPoint(aEvent.mScreenOffset, aEvent.mFocusPoint),
aEvent.mTimeStamp);
}
} else {
// Otherwise, handle the gesture being completely done.
// Some of the code paths below, like ScrollSnap() or HandleEndOfPan(),
// may start an animation, but otherwise we want to end up in the NOTHING
// state. To avoid state change notification churn, we use a
// notification blocker.
bool stateWasPinching = (mState == PINCHING);
StateChangeNotificationBlocker blocker(this);
SetState(NOTHING);
if (mZoomConstraints.mAllowZoom) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
// We can get into a situation where we are overscrolled at the end of a
// pinch if we go into overscroll with a two-finger pan, and then turn
// that into a pinch by increasing the span sufficiently. In such a case,
// there is no snap-back animation to get us out of overscroll, so we need
// to get out of it somehow.
// Moreover, in cases of scroll handoff, the overscroll can be on an APZC
// further up in the handoff chain rather than on the current APZC, so
// we need to clear overscroll along the entire handoff chain.
if (HasReadyTouchBlock()) {
GetCurrentTouchBlock()->GetOverscrollHandoffChain()->ClearOverscroll();
} else {
ClearOverscroll();
}
// Along with clearing the overscroll, we also want to snap to the nearest
// snap point as appropriate.
ScrollSnap();
} else {
// when zoom is not allowed
EndTouch(aEvent.mTimeStamp);
if (stateWasPinching) {
// still pinching
if (HasReadyTouchBlock()) {
return HandleEndOfPan();
}
}
}
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::HandleEndOfPan() {
MOZ_ASSERT(GetCurrentTouchBlock() || GetCurrentPanGestureBlock());
GetCurrentInputBlock()->GetOverscrollHandoffChain()->FlushRepaints();
ParentLayerPoint flingVelocity = GetVelocityVector();
// Clear our velocities; if DispatchFling() gives the fling to us,
// the fling velocity gets *added* to our existing velocity in
// AcceptFling().
SetVelocityVector(ParentLayerPoint(0, 0));
// Clear our state so that we don't stay in the PANNING state
// if DispatchFling() gives the fling to somone else. However,
// don't send the state change notification until we've determined
// what our final state is to avoid notification churn.
StateChangeNotificationBlocker blocker(this);
SetState(NOTHING);
APZC_LOG("%p starting a fling animation if %f > %f\n", this,
flingVelocity.Length().value,
StaticPrefs::apz_fling_min_velocity_threshold());
if (flingVelocity.Length() <=
StaticPrefs::apz_fling_min_velocity_threshold()) {
// Relieve overscroll now if needed, since we will not transition to a fling
// animation and then an overscroll animation, and relieve it then.
GetCurrentInputBlock()
->GetOverscrollHandoffChain()
->SnapBackOverscrolledApzc(this);
mFlingAccelerator.Reset();
return nsEventStatus_eConsumeNoDefault;
}
// Make a local copy of the tree manager pointer and check that it's not
// null before calling DispatchFling(). This is necessary because Destroy(),
// which nulls out mTreeManager, could be called concurrently.
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
const FlingHandoffState handoffState{
flingVelocity,
GetCurrentInputBlock()->GetOverscrollHandoffChain(),
Some(mTouchStartRestingTimeBeforePan),
mMinimumVelocityDuringPan.valueOr(0),
false /* not handoff */,
GetCurrentInputBlock()->GetScrolledApzc()};
treeManagerLocal->DispatchFling(this, handoffState);
}
return nsEventStatus_eConsumeNoDefault;
}
Maybe<LayoutDevicePoint> AsyncPanZoomController::ConvertToGecko(
const ScreenIntPoint& aPoint) {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
if (Maybe<ScreenIntPoint> layoutPoint =
treeManagerLocal->ConvertToGecko(aPoint, this)) {
return Some(LayoutDevicePoint(ViewAs<LayoutDevicePixel>(
*layoutPoint,
PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent)));
}
}
return Nothing();
}
CSSCoord AsyncPanZoomController::ConvertScrollbarPoint(
const ParentLayerPoint& aScrollbarPoint,
const ScrollbarData& aThumbData) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
CSSPoint scrollbarPoint;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
// First, get it into the right coordinate space.
scrollbarPoint = aScrollbarPoint / Metrics().GetZoom();
}
// The scrollbar can be transformed with the frame but the pres shell
// resolution is only applied to the scroll frame.
scrollbarPoint = scrollbarPoint * Metrics().GetPresShellResolution();
// Now, get it to be relative to the beginning of the scroll track.
CSSRect cssCompositionBound =
Metrics().CalculateCompositionBoundsInCssPixelsOfSurroundingContent();
return GetAxisStart(*aThumbData.mDirection, scrollbarPoint) -
GetAxisStart(*aThumbData.mDirection, cssCompositionBound) -
aThumbData.mScrollTrackStart;
}
static bool AllowsScrollingMoreThanOnePage(double aMultiplier) {
const int32_t kMinAllowPageScroll =
EventStateManager::MIN_MULTIPLIER_VALUE_ALLOWING_OVER_ONE_PAGE_SCROLL;
return Abs(aMultiplier) >= kMinAllowPageScroll;
}
ParentLayerPoint AsyncPanZoomController::GetScrollWheelDelta(
const ScrollWheelInput& aEvent) const {
return GetScrollWheelDelta(aEvent, aEvent.mDeltaX, aEvent.mDeltaY,
aEvent.mUserDeltaMultiplierX,
aEvent.mUserDeltaMultiplierY);
}
ParentLayerPoint AsyncPanZoomController::GetScrollWheelDelta(
const ScrollWheelInput& aEvent, double aDeltaX, double aDeltaY,
double aMultiplierX, double aMultiplierY) const {
ParentLayerSize scrollAmount;
ParentLayerSize pageScrollSize;
{
// Grab the lock to access the frame metrics.
RecursiveMutexAutoLock lock(mRecursiveMutex);
LayoutDeviceIntSize scrollAmountLD = mScrollMetadata.GetLineScrollAmount();
LayoutDeviceIntSize pageScrollSizeLD =
mScrollMetadata.GetPageScrollAmount();
scrollAmount = scrollAmountLD / Metrics().GetDevPixelsPerCSSPixel() *
Metrics().GetZoom();
pageScrollSize = pageScrollSizeLD / Metrics().GetDevPixelsPerCSSPixel() *
Metrics().GetZoom();
}
ParentLayerPoint delta;
switch (aEvent.mDeltaType) {
case ScrollWheelInput::SCROLLDELTA_LINE: {
delta.x = aDeltaX * scrollAmount.width;
delta.y = aDeltaY * scrollAmount.height;
break;
}
case ScrollWheelInput::SCROLLDELTA_PAGE: {
delta.x = aDeltaX * pageScrollSize.width;
delta.y = aDeltaY * pageScrollSize.height;
break;
}
case ScrollWheelInput::SCROLLDELTA_PIXEL: {
delta = ToParentLayerCoordinates(ScreenPoint(aDeltaX, aDeltaY),
aEvent.mOrigin);
break;
}
}
// Apply user-set multipliers.
delta.x *= aMultiplierX;
delta.y *= aMultiplierY;
// For the conditions under which we allow system scroll overrides, see
// EventStateManager::DeltaAccumulator::ComputeScrollAmountForDefaultAction
// and WheelTransaction::OverrideSystemScrollSpeed. Note that we do *not*
// restrict this to the root content, see bug 1217715 for discussion on this.
if (StaticPrefs::
mousewheel_system_scroll_override_on_root_content_enabled() &&
!aEvent.IsCustomizedByUserPrefs() &&
aEvent.mDeltaType == ScrollWheelInput::SCROLLDELTA_LINE &&
aEvent.mAllowToOverrideSystemScrollSpeed) {
delta.x = WidgetWheelEvent::ComputeOverriddenDelta(delta.x, false);
delta.y = WidgetWheelEvent::ComputeOverriddenDelta(delta.y, true);
}
// If this is a line scroll, and this event was part of a scroll series, then
// it might need extra acceleration. See WheelHandlingHelper.cpp.
if (aEvent.mDeltaType == ScrollWheelInput::SCROLLDELTA_LINE &&
aEvent.mScrollSeriesNumber > 0) {
int32_t start = StaticPrefs::mousewheel_acceleration_start();
if (start >= 0 && aEvent.mScrollSeriesNumber >= uint32_t(start)) {
int32_t factor = StaticPrefs::mousewheel_acceleration_factor();
if (factor > 0) {
delta.x = ComputeAcceleratedWheelDelta(
delta.x, aEvent.mScrollSeriesNumber, factor);
delta.y = ComputeAcceleratedWheelDelta(
delta.y, aEvent.mScrollSeriesNumber, factor);
}
}
}
// We shouldn't scroll more than one page at once except when the
// user preference is large.
if (!AllowsScrollingMoreThanOnePage(aMultiplierX) &&
Abs(delta.x) > pageScrollSize.width) {
delta.x = (delta.x >= 0) ? pageScrollSize.width : -pageScrollSize.width;
}
if (!AllowsScrollingMoreThanOnePage(aMultiplierY) &&
Abs(delta.y) > pageScrollSize.height) {
delta.y = (delta.y >= 0) ? pageScrollSize.height : -pageScrollSize.height;
}
return delta;
}
static void ReportKeyboardScrollAction(const KeyboardScrollAction& aAction) {
ScrollInputMethod scrollMethod;
switch (aAction.mType) {
case KeyboardScrollAction::eScrollLine: {
scrollMethod = ScrollInputMethod::ApzScrollLine;
break;
}
case KeyboardScrollAction::eScrollCharacter: {
scrollMethod = ScrollInputMethod::ApzScrollCharacter;
break;
}
case KeyboardScrollAction::eScrollPage: {
scrollMethod = ScrollInputMethod::ApzScrollPage;
break;
}
case KeyboardScrollAction::eScrollComplete: {
scrollMethod = ScrollInputMethod::ApzCompleteScroll;
break;
}
}
mozilla::Telemetry::Accumulate(mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)scrollMethod);
}
nsEventStatus AsyncPanZoomController::OnKeyboard(const KeyboardInput& aEvent) {
// Report the type of scroll action to telemetry
ReportKeyboardScrollAction(aEvent.mAction);
// Mark that this APZC has async key scrolled
mTestHasAsyncKeyScrolled = true;
// Calculate the destination for this keyboard scroll action
CSSPoint destination = GetKeyboardDestination(aEvent.mAction);
bool scrollSnapped =
MaybeAdjustDestinationForScrollSnapping(aEvent, destination);
RecordScrollPayload(aEvent.mTimeStamp);
// If smooth scrolling is disabled, then scroll immediately to the destination
if (!StaticPrefs::general_smoothScroll()) {
CancelAnimation();
ParentLayerPoint startPoint, endPoint;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
// CallDispatchScroll interprets the start and end points as the start and
// end of a touch scroll so they need to be reversed.
startPoint = destination * Metrics().GetZoom();
endPoint = Metrics().GetVisualScrollOffset() * Metrics().GetZoom();
}
ParentLayerPoint delta = endPoint - startPoint;
ScreenPoint distance = ToScreenCoordinates(
ParentLayerPoint(fabs(delta.x), fabs(delta.y)), startPoint);
OverscrollHandoffState handoffState(
*mInputQueue->GetCurrentKeyboardBlock()->GetOverscrollHandoffChain(),
distance, ScrollSource::Keyboard);
CallDispatchScroll(startPoint, endPoint, handoffState);
SetState(NOTHING);
return nsEventStatus_eConsumeDoDefault;
}
// The lock must be held across the entire update operation, so the
// compositor doesn't end the animation before we get a chance to
// update it.
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (scrollSnapped) {
// If we're scroll snapping, use a smooth scroll animation to get
// the desired physics. Note that SmoothMsdScrollTo() will re-use an
// existing smooth scroll animation if there is one.
APZC_LOG("%p keyboard scrolling to snap point %s\n", this,
ToString(destination).c_str());
SmoothMsdScrollTo(destination);
return nsEventStatus_eConsumeDoDefault;
}
// Use a keyboard scroll animation to scroll, reusing an existing one if it
// exists
if (mState != KEYBOARD_SCROLL) {
CancelAnimation();
SetState(KEYBOARD_SCROLL);
nsPoint initialPosition =
CSSPoint::ToAppUnits(Metrics().GetVisualScrollOffset());
StartAnimation(new SmoothScrollAnimation(
*this, initialPosition,
SmoothScrollAnimation::GetScrollOriginForAction(aEvent.mAction.mType)));
}
// Convert velocity from ParentLayerPoints/ms to ParentLayerPoints/s and then
// to appunits/second.
nsPoint velocity;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
velocity =
CSSPoint::ToAppUnits(ParentLayerPoint(mX.GetVelocity() * 1000.0f,
mY.GetVelocity() * 1000.0f) /
Metrics().GetZoom());
}
SmoothScrollAnimation* animation = mAnimation->AsSmoothScrollAnimation();
MOZ_ASSERT(animation);
animation->UpdateDestination(aEvent.mTimeStamp,
CSSPixel::ToAppUnits(destination),
nsSize(velocity.x, velocity.y));
return nsEventStatus_eConsumeDoDefault;
}
CSSPoint AsyncPanZoomController::GetKeyboardDestination(
const KeyboardScrollAction& aAction) const {
CSSSize lineScrollSize;
CSSSize pageScrollSize;
CSSPoint scrollOffset;
CSSRect scrollRect;
{
// Grab the lock to access the frame metrics.
RecursiveMutexAutoLock lock(mRecursiveMutex);
lineScrollSize = mScrollMetadata.GetLineScrollAmount() /
Metrics().GetDevPixelsPerCSSPixel();
pageScrollSize = mScrollMetadata.GetPageScrollAmount() /
Metrics().GetDevPixelsPerCSSPixel();
scrollOffset = GetCurrentAnimationDestination(lock).valueOr(
Metrics().GetVisualScrollOffset());
scrollRect = Metrics().GetScrollableRect();
}
// Calculate the scroll destination based off of the scroll type and direction
CSSPoint scrollDestination = scrollOffset;
switch (aAction.mType) {
case KeyboardScrollAction::eScrollCharacter: {
int32_t scrollDistance =
StaticPrefs::toolkit_scrollbox_horizontalScrollDistance();
if (aAction.mForward) {
scrollDestination.x += scrollDistance * lineScrollSize.width;
} else {
scrollDestination.x -= scrollDistance * lineScrollSize.width;
}
break;
}
case KeyboardScrollAction::eScrollLine: {
int32_t scrollDistance =
StaticPrefs::toolkit_scrollbox_verticalScrollDistance();
if (aAction.mForward) {
scrollDestination.y += scrollDistance * lineScrollSize.height;
} else {
scrollDestination.y -= scrollDistance * lineScrollSize.height;
}
break;
}
case KeyboardScrollAction::eScrollPage: {
if (aAction.mForward) {
scrollDestination.y += pageScrollSize.height;
} else {
scrollDestination.y -= pageScrollSize.height;
}
break;
}
case KeyboardScrollAction::eScrollComplete: {
if (aAction.mForward) {
scrollDestination.y = scrollRect.YMost();
} else {
scrollDestination.y = scrollRect.Y();
}
break;
}
}
return scrollDestination;
}
ParentLayerPoint AsyncPanZoomController::GetDeltaForEvent(
const InputData& aEvent) const {
ParentLayerPoint delta;
if (aEvent.mInputType == SCROLLWHEEL_INPUT) {
delta = GetScrollWheelDelta(aEvent.AsScrollWheelInput());
} else if (aEvent.mInputType == PANGESTURE_INPUT) {
const PanGestureInput& panInput = aEvent.AsPanGestureInput();
delta = ToParentLayerCoordinates(panInput.UserMultipliedPanDisplacement(),
panInput.mPanStartPoint);
}
return delta;
}
// Return whether or not the underlying layer can be scrolled on either axis.
bool AsyncPanZoomController::CanScroll(const InputData& aEvent) const {
ParentLayerPoint delta = GetDeltaForEvent(aEvent);
if (!delta.x && !delta.y) {
return false;
}
if (SCROLLWHEEL_INPUT == aEvent.mInputType) {
const ScrollWheelInput& scrollWheelInput = aEvent.AsScrollWheelInput();
// If it's a wheel scroll, we first check if it is an auto-dir scroll.
// 1. For an auto-dir scroll, check if it's delta should be adjusted, if it
// is, then we can conclude it must be scrollable; otherwise, fall back
// to checking if it is scrollable without adjusting its delta.
// 2. For a non-auto-dir scroll, simply check if it is scrollable without
// adjusting its delta.
if (scrollWheelInput.IsAutoDir()) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
auto deltaX = scrollWheelInput.mDeltaX;
auto deltaY = scrollWheelInput.mDeltaY;
bool isRTL =
IsContentOfHonouredTargetRightToLeft(scrollWheelInput.HonoursRoot());
APZAutoDirWheelDeltaAdjuster adjuster(deltaX, deltaY, mX, mY, isRTL);
if (adjuster.ShouldBeAdjusted()) {
// If we detect that the delta values should be adjusted for an auto-dir
// wheel scroll, then it is impossible to be an unscrollable scroll.
return true;
}
}
return CanScrollWithWheel(delta);
}
return CanScroll(delta);
}
ScrollDirections AsyncPanZoomController::GetAllowedHandoffDirections() const {
ScrollDirections result;
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (mX.OverscrollBehaviorAllowsHandoff()) {
result += ScrollDirection::eHorizontal;
}
if (mY.OverscrollBehaviorAllowsHandoff()) {
result += ScrollDirection::eVertical;
}
return result;
}
bool AsyncPanZoomController::CanScroll(const ParentLayerPoint& aDelta) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return mX.CanScroll(aDelta.x) || mY.CanScroll(aDelta.y);
}
bool AsyncPanZoomController::CanScrollWithWheel(
const ParentLayerPoint& aDelta) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
// For more details about the concept of a disregarded direction, refer to the
// code in struct ScrollMetadata which defines mDisregardedDirection.
Maybe<ScrollDirection> disregardedDirection =
mScrollMetadata.GetDisregardedDirection();
if (mX.CanScroll(aDelta.x) &&
disregardedDirection != Some(ScrollDirection::eHorizontal)) {
return true;
}
if (mY.CanScroll(aDelta.y) &&
disregardedDirection != Some(ScrollDirection::eVertical)) {
return true;
}
return false;
}
bool AsyncPanZoomController::CanScroll(ScrollDirection aDirection) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
switch (aDirection) {
case ScrollDirection::eHorizontal:
return mX.CanScroll();
case ScrollDirection::eVertical:
return mY.CanScroll();
}
MOZ_ASSERT_UNREACHABLE("Invalid value");
return false;
}
bool AsyncPanZoomController::CanScrollDownwardsWithDynamicToolbar() const {
MOZ_ASSERT(IsRootContent());
RecursiveMutexAutoLock lock(mRecursiveMutex);
return mY.CanScrollDownwardsWithDynamicToolbar();
}
bool AsyncPanZoomController::CanScrollDownwards() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return mY.CanScrollTo(eSideBottom);
}
bool AsyncPanZoomController::IsContentOfHonouredTargetRightToLeft(
bool aHonoursRoot) const {
if (aHonoursRoot) {
return mScrollMetadata.IsAutoDirRootContentRTL();
}
RecursiveMutexAutoLock lock(mRecursiveMutex);
return Metrics().IsHorizontalContentRightToLeft();
}
bool AsyncPanZoomController::AllowScrollHandoffInCurrentBlock() const {
bool result = mInputQueue->AllowScrollHandoff();
if (!StaticPrefs::apz_allow_immediate_handoff()) {
if (InputBlockState* currentBlock = GetCurrentInputBlock()) {
// Do not allow handoff beyond the first APZC to scroll.
if (currentBlock->GetScrolledApzc() == this) {
result = false;
APZC_LOG("%p dropping handoff; AllowImmediateHandoff=false\n", this);
}
}
}
return result;
}
void AsyncPanZoomController::DoDelayedRequestContentRepaint() {
if (!IsDestroyed() && mPinchPaintTimerSet) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
RequestContentRepaint();
}
mPinchPaintTimerSet = false;
}
static ScrollInputMethod ScrollInputMethodForWheelDeltaType(
ScrollWheelInput::ScrollDeltaType aDeltaType) {
switch (aDeltaType) {
case ScrollWheelInput::SCROLLDELTA_LINE: {
return ScrollInputMethod::ApzWheelLine;
}
case ScrollWheelInput::SCROLLDELTA_PAGE: {
return ScrollInputMethod::ApzWheelPage;
}
case ScrollWheelInput::SCROLLDELTA_PIXEL: {
return ScrollInputMethod::ApzWheelPixel;
}
}
MOZ_ASSERT_UNREACHABLE("Invalid value");
return ScrollInputMethod::ApzWheelLine;
}
static void AdjustDeltaForAllowedScrollDirections(
ParentLayerPoint& aDelta,
const ScrollDirections& aAllowedScrollDirections) {
if (!aAllowedScrollDirections.contains(ScrollDirection::eHorizontal)) {
aDelta.x = 0;
}
if (!aAllowedScrollDirections.contains(ScrollDirection::eVertical)) {
aDelta.y = 0;
}
}
nsEventStatus AsyncPanZoomController::OnScrollWheel(
const ScrollWheelInput& aEvent) {
// Get the scroll wheel's delta values in parent-layer pixels. But before
// getting the values, we need to check if it is an auto-dir scroll and if it
// should be adjusted, if both answers are yes, let's adjust X and Y values
// first, and then get the delta values in parent-layer pixels based on the
// adjusted values.
bool adjustedByAutoDir = false;
auto deltaX = aEvent.mDeltaX;
auto deltaY = aEvent.mDeltaY;
ParentLayerPoint delta;
if (aEvent.IsAutoDir()) {
// It's an auto-dir scroll, so check if its delta should be adjusted, if so,
// adjust it.
RecursiveMutexAutoLock lock(mRecursiveMutex);
bool isRTL = IsContentOfHonouredTargetRightToLeft(aEvent.HonoursRoot());
APZAutoDirWheelDeltaAdjuster adjuster(deltaX, deltaY, mX, mY, isRTL);
if (adjuster.ShouldBeAdjusted()) {
adjuster.Adjust();
adjustedByAutoDir = true;
}
}
// Ensure the calls to GetScrollWheelDelta are outside the mRecursiveMutex
// lock since these calls may acquire the APZ tree lock. Holding
// mRecursiveMutex while acquiring the APZ tree lock is lock ordering
// violation.
if (adjustedByAutoDir) {
// If the original delta values have been adjusted, we pass them to
// replace the original delta values in |aEvent| so that the delta values
// in parent-layer pixels are caculated based on the adjusted values, not
// the original ones.
// Pay special attention to the last two parameters. They are in a swaped
// order so that they still correspond to their delta after adjustment.
delta = GetScrollWheelDelta(aEvent, deltaX, deltaY,
aEvent.mUserDeltaMultiplierY,
aEvent.mUserDeltaMultiplierX);
} else {
// If the original delta values haven't been adjusted by auto-dir, just pass
// the |aEvent| and caculate the delta values in parent-layer pixels based
// on the original delta values from |aEvent|.
delta = GetScrollWheelDelta(aEvent);
}
APZC_LOG("%p got a scroll-wheel with delta in parent-layer pixels: %s\n",
this, ToString(delta).c_str());
if (adjustedByAutoDir) {
MOZ_ASSERT(delta.x || delta.y,
"Adjusted auto-dir delta values can never be all-zero.");
APZC_LOG("%p got a scroll-wheel with adjusted auto-dir delta values\n",
this);
} else if ((delta.x || delta.y) && !CanScrollWithWheel(delta)) {
// We can't scroll this apz anymore, so we simply drop the event.
if (mInputQueue->GetActiveWheelTransaction() &&
StaticPrefs::test_mousescroll()) {
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
controller->NotifyMozMouseScrollEvent(GetScrollId(),
u"MozMouseScrollFailed"_ns);
}
}
return nsEventStatus_eConsumeNoDefault;
}
MOZ_ASSERT(mInputQueue->GetCurrentWheelBlock());
AdjustDeltaForAllowedScrollDirections(
delta, mInputQueue->GetCurrentWheelBlock()->GetAllowedScrollDirections());
if (delta.x == 0 && delta.y == 0) {
// Avoid spurious state changes and unnecessary work
return nsEventStatus_eIgnore;
}
mozilla::Telemetry::Accumulate(
mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethodForWheelDeltaType(aEvent.mDeltaType));
switch (aEvent.mScrollMode) {
case ScrollWheelInput::SCROLLMODE_INSTANT: {
// Wheel events from "clicky" mouse wheels trigger scroll snapping to the
// next snap point. Check for this, and adjust the delta to take into
// account the snap point.
CSSPoint startPosition;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
startPosition = Metrics().GetVisualScrollOffset();
}
MaybeAdjustDeltaForScrollSnappingOnWheelInput(aEvent, delta,
startPosition);
ScreenPoint distance = ToScreenCoordinates(
ParentLayerPoint(fabs(delta.x), fabs(delta.y)), aEvent.mLocalOrigin);
CancelAnimation();
OverscrollHandoffState handoffState(
*mInputQueue->GetCurrentWheelBlock()->GetOverscrollHandoffChain(),
distance, ScrollSource::Wheel);
ParentLayerPoint startPoint = aEvent.mLocalOrigin;
ParentLayerPoint endPoint = aEvent.mLocalOrigin - delta;
RecordScrollPayload(aEvent.mTimeStamp);
CallDispatchScroll(startPoint, endPoint, handoffState);
SetState(NOTHING);
// The calls above handle their own locking; moreover,
// ToScreenCoordinates() and CallDispatchScroll() can grab the tree lock.
RecursiveMutexAutoLock lock(mRecursiveMutex);
RequestContentRepaint();
break;
}
case ScrollWheelInput::SCROLLMODE_SMOOTH: {
// The lock must be held across the entire update operation, so the
// compositor doesn't end the animation before we get a chance to
// update it.
RecursiveMutexAutoLock lock(mRecursiveMutex);
RecordScrollPayload(aEvent.mTimeStamp);
// Perform scroll snapping if appropriate.
// If we're already in a wheel scroll or smooth scroll animation,
// the delta is applied to its destination, not to the current
// scroll position. Take this into account when finding a snap point.
CSSPoint startPosition = GetCurrentAnimationDestination(lock).valueOr(
Metrics().GetVisualScrollOffset());
if (MaybeAdjustDeltaForScrollSnappingOnWheelInput(aEvent, delta,
startPosition)) {
// If we're scroll snapping, use a smooth scroll animation to get
// the desired physics. Note that SmoothMsdScrollTo() will re-use an
// existing smooth scroll animation if there is one.
APZC_LOG("%p wheel scrolling to snap point %s\n", this,
ToString(startPosition).c_str());
SmoothMsdScrollTo(startPosition);
break;
}
// Otherwise, use a wheel scroll animation, also reusing one if possible.
if (mState != WHEEL_SCROLL) {
CancelAnimation();
SetState(WHEEL_SCROLL);
nsPoint initialPosition =
CSSPoint::ToAppUnits(Metrics().GetVisualScrollOffset());
StartAnimation(new WheelScrollAnimation(*this, initialPosition,
aEvent.mDeltaType));
}
// Convert velocity from ParentLayerPoints/ms to ParentLayerPoints/s and
// then to appunits/second.
nsPoint deltaInAppUnits;
nsPoint velocity;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
deltaInAppUnits = CSSPoint::ToAppUnits(delta / Metrics().GetZoom());
velocity =
CSSPoint::ToAppUnits(ParentLayerPoint(mX.GetVelocity() * 1000.0f,
mY.GetVelocity() * 1000.0f) /
Metrics().GetZoom());
}
WheelScrollAnimation* animation = mAnimation->AsWheelScrollAnimation();
animation->UpdateDelta(aEvent.mTimeStamp, deltaInAppUnits,
nsSize(velocity.x, velocity.y));
break;
}
}
return nsEventStatus_eConsumeNoDefault;
}
void AsyncPanZoomController::NotifyMozMouseScrollEvent(
const nsString& aString) const {
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (!controller) {
return;
}
controller->NotifyMozMouseScrollEvent(GetScrollId(), aString);
}
nsEventStatus AsyncPanZoomController::OnPanMayBegin(
const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-maybegin in state %d\n", this, mState);
StartTouch(aEvent.mLocalPanStartPoint, aEvent.mTimeStamp);
MOZ_ASSERT(GetCurrentPanGestureBlock());
GetCurrentPanGestureBlock()->GetOverscrollHandoffChain()->CancelAnimations();
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPanCancelled(
const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-cancelled in state %d\n", this, mState);
mX.CancelGesture();
mY.CancelGesture();
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPanBegin(
const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-begin in state %d\n", this, mState);
if (mState == SMOOTHMSD_SCROLL) {
// SMOOTHMSD_SCROLL scrolls are cancelled by pan gestures.
CancelAnimation();
}
StartTouch(aEvent.mLocalPanStartPoint, aEvent.mTimeStamp);
mozilla::Telemetry::Accumulate(mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethod::ApzPanGesture);
if (GetAxisLockMode() == FREE) {
SetState(PANNING);
return nsEventStatus_eConsumeNoDefault;
}
float dx = aEvent.mPanDisplacement.x, dy = aEvent.mPanDisplacement.y;
if (dx || dy) {
double angle = atan2(dy, dx); // range [-pi, pi]
angle = fabs(angle); // range [0, pi]
HandlePanning(angle);
} else {
SetState(PANNING);
}
// Call into OnPan in order to process any delta included in this event.
OnPan(aEvent, true);
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPan(const PanGestureInput& aEvent,
bool aFingersOnTouchpad) {
APZC_LOG("%p got a pan-pan in state %d\n", this, mState);
if (mState == SMOOTHMSD_SCROLL) {
if (!aFingersOnTouchpad) {
// When a SMOOTHMSD_SCROLL scroll is being processed on a frame, mouse
// wheel and trackpad momentum scroll position updates will not cancel the
// SMOOTHMSD_SCROLL scroll animations, enabling scripts that depend on
// them to be responsive without forcing the user to wait for the momentum
// scrolling to completely stop.
return nsEventStatus_eConsumeNoDefault;
}
// SMOOTHMSD_SCROLL scrolls are cancelled by pan gestures.
CancelAnimation();
}
if (mState == NOTHING) {
// This event block was interrupted by something else. If the user's fingers
// are still on on the touchpad we want to resume scrolling, otherwise we
// ignore the rest of the scroll gesture.
if (!aFingersOnTouchpad) {
return nsEventStatus_eConsumeNoDefault;
}
// Resume / restart the pan.
// PanBegin will call back into this function with mState == PANNING.
return OnPanBegin(aEvent);
}
// Note that there is a multiplier that applies onto the "physical" pan
// displacement (how much the user's fingers moved) that produces the
// "logical" pan displacement (how much the page should move). For some of the
// code below it makes more sense to use the physical displacement rather than
// the logical displacement, and vice-versa.
ScreenPoint physicalPanDisplacement = aEvent.mPanDisplacement;
ParentLayerPoint logicalPanDisplacement =
aEvent.UserMultipliedLocalPanDisplacement();
if (aEvent.mDeltaType == PanGestureInput::PANDELTA_PAGE) {
// Pan events with page units are used by Gtk, so this replicates Gtk:
// https://gitlab.gnome.org/GNOME/gtk/blob/c734c7e9188b56f56c3a504abee05fa40c5475ac/gtk/gtkrange.c#L3065-3073
CSSSize pageScrollSize;
CSSToParentLayerScale2D zoom;
{
// Grab the lock to access the frame metrics.
RecursiveMutexAutoLock lock(mRecursiveMutex);
pageScrollSize = mScrollMetadata.GetPageScrollAmount() /
Metrics().GetDevPixelsPerCSSPixel();
zoom = Metrics().GetZoom();
}
// scrollUnit* is in units of "ParentLayer pixels per page proportion"...
auto scrollUnitWidth = std::min(std::pow(pageScrollSize.width, 2.0 / 3.0),
pageScrollSize.width / 2.0) *
zoom.xScale;
auto scrollUnitHeight = std::min(std::pow(pageScrollSize.height, 2.0 / 3.0),
pageScrollSize.height / 2.0) *
zoom.yScale;
// ... and pan displacements are in units of "page proportion count"
// here, so the products of them and scrollUnit* are in ParentLayer pixels
ParentLayerPoint physicalPanDisplacementPL(
physicalPanDisplacement.x * scrollUnitWidth,
physicalPanDisplacement.y * scrollUnitHeight);
physicalPanDisplacement = ToScreenCoordinates(physicalPanDisplacementPL,
aEvent.mLocalPanStartPoint);
logicalPanDisplacement.x *= scrollUnitWidth;
logicalPanDisplacement.y *= scrollUnitHeight;
// Accelerate (decelerate) any pans by raising it to a user configurable
// power (apz.touch_acceleration_factor_x, apz.touch_acceleration_factor_y)
//
// Confine input for pow() to greater than or equal to 0 to avoid domain
// errors with non-integer exponents
if (mX.GetVelocity() != 0) {
float absVelocity = std::abs(mX.GetVelocity());
logicalPanDisplacement.x *=
std::pow(absVelocity,
StaticPrefs::apz_touch_acceleration_factor_x()) /
absVelocity;
}
if (mY.GetVelocity() != 0) {
float absVelocity = std::abs(mY.GetVelocity());
logicalPanDisplacement.y *=
std::pow(absVelocity,
StaticPrefs::apz_touch_acceleration_factor_y()) /
absVelocity;
}
}
MOZ_ASSERT(GetCurrentPanGestureBlock());
AdjustDeltaForAllowedScrollDirections(
logicalPanDisplacement,
GetCurrentPanGestureBlock()->GetAllowedScrollDirections());
// We need to update the axis velocity in order to get a useful display port
// size and position. We need to do so even if this is a momentum pan (i.e.
// aFingersOnTouchpad == false); in that case the "with touch" part is not
// really appropriate, so we may want to rethink this at some point.
// Note that we have to make all simulated positions relative to
// Axis::GetPos(), because the current position is an invented position, and
// because resetting the position to the mouse position (e.g.
// aEvent.mLocalStartPoint) would mess up velocity calculation. (This is
// the only caller of UpdateWithTouchAtDevicePoint() for pan events, so
// there is no risk of other calls resetting the position.)
mX.UpdateWithTouchAtDevicePoint(mX.GetPos() - logicalPanDisplacement.x,
aEvent.mTimeStamp);
mY.UpdateWithTouchAtDevicePoint(mY.GetPos() - logicalPanDisplacement.y,
aEvent.mTimeStamp);
HandlePanningUpdate(physicalPanDisplacement);
ScreenPoint panDistance(fabs(physicalPanDisplacement.x),
fabs(physicalPanDisplacement.y));
OverscrollHandoffState handoffState(
*GetCurrentPanGestureBlock()->GetOverscrollHandoffChain(), panDistance,
ScrollSource::Wheel);
// Create fake "touch" positions that will result in the desired scroll
// motion. Note that the pan displacement describes the change in scroll
// position: positive displacement values mean that the scroll position
// increases. However, an increase in scroll position means that the scrolled
// contents are moved to the left / upwards. Since our simulated "touches"
// determine the motion of the scrolled contents, not of the scroll position,
// they need to move in the opposite direction of the pan displacement.
ParentLayerPoint startPoint = aEvent.mLocalPanStartPoint;
ParentLayerPoint endPoint =
aEvent.mLocalPanStartPoint - logicalPanDisplacement;
if (logicalPanDisplacement != ParentLayerPoint()) {
// Don't expect a composite to be triggered if the displacement is zero
RecordScrollPayload(aEvent.mTimeStamp);
}
bool consumed = CallDispatchScroll(startPoint, endPoint, handoffState);
if (!consumed && !aFingersOnTouchpad) {
// If there is unconsumed scroll and we're in the momentum part of the
// pan gesture, terminate the momentum scroll. This prevents momentum
// scroll events from unexpectedly causing scrolling later if somehow
// the APZC becomes scrollable again in this direction (e.g. if the user
// uses some other input method to scroll in the opposite direction).
SetState(NOTHING);
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPanEnd(const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-end in state %d\n", this, mState);
if (aEvent.mPanDisplacement != ScreenPoint{}) {
// Call into OnPan in order to process the delta included in this event.
OnPan(aEvent, true);
}
EndTouch(aEvent.mTimeStamp);
// Use HandleEndOfPan for fling on platforms that don't
// emit momentum events (Gtk).
if (aEvent.mSimulateMomentum) {
return HandleEndOfPan();
}
// Drop any velocity on axes where we don't have room to scroll anyways
// (in this APZC, or an APZC further in the handoff chain).
// This ensures that we don't enlarge the display port unnecessarily.
MOZ_ASSERT(GetCurrentPanGestureBlock());
RefPtr<const OverscrollHandoffChain> overscrollHandoffChain =
GetCurrentPanGestureBlock()->GetOverscrollHandoffChain();
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eHorizontal)) {
mX.SetVelocity(0);
}
if (!overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eVertical)) {
mY.SetVelocity(0);
}
}
SetState(NOTHING);
RequestContentRepaint();
if (!aEvent.mFollowedByMomentum) {
ScrollSnap();
}
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPanMomentumStart(
const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-momentumstart in state %d\n", this, mState);
if (mState == SMOOTHMSD_SCROLL) {
// SMOOTHMSD_SCROLL scrolls are cancelled by pan gestures.
CancelAnimation();
}
SetState(PAN_MOMENTUM);
ScrollSnapToDestination();
// Call into OnPan in order to process any delta included in this event.
OnPan(aEvent, false);
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnPanMomentumEnd(
const PanGestureInput& aEvent) {
APZC_LOG("%p got a pan-momentumend in state %d\n", this, mState);
// Call into OnPan in order to process any delta included in this event.
OnPan(aEvent, false);
// We need to reset the velocity to zero. We don't really have a "touch"
// here because the touch has already ended long before the momentum
// animation started, but I guess it doesn't really matter for now.
mX.CancelGesture();
mY.CancelGesture();
SetState(NOTHING);
RequestContentRepaint();
return nsEventStatus_eConsumeNoDefault;
}
nsEventStatus AsyncPanZoomController::OnLongPress(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a long-press in state %d\n", this, mState);
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (controller) {
if (Maybe<LayoutDevicePoint> geckoScreenPoint =
ConvertToGecko(aEvent.mPoint)) {
TouchBlockState* touch = GetCurrentTouchBlock();
if (!touch) {
APZC_LOG(
"%p dropping long-press because some non-touch block interrupted "
"it\n",
this);
return nsEventStatus_eIgnore;
}
if (touch->IsDuringFastFling()) {
APZC_LOG("%p dropping long-press because of fast fling\n", this);
return nsEventStatus_eIgnore;
}
uint64_t blockId = GetInputQueue()->InjectNewTouchBlock(this);
controller->HandleTap(TapType::eLongTap, *geckoScreenPoint,
aEvent.modifiers, GetGuid(), blockId);
return nsEventStatus_eConsumeNoDefault;
}
}
return nsEventStatus_eIgnore;
}
nsEventStatus AsyncPanZoomController::OnLongPressUp(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a long-tap-up in state %d\n", this, mState);
return GenerateSingleTap(TapType::eLongTapUp, aEvent.mPoint,
aEvent.modifiers);
}
nsEventStatus AsyncPanZoomController::GenerateSingleTap(
TapType aType, const ScreenIntPoint& aPoint,
mozilla::Modifiers aModifiers) {
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (controller) {
if (Maybe<LayoutDevicePoint> geckoScreenPoint = ConvertToGecko(aPoint)) {
TouchBlockState* touch = GetCurrentTouchBlock();
// |touch| may be null in the case where this function is
// invoked by GestureEventListener on a timeout. In that case we already
// verified that the single tap is allowed so we let it through.
// XXX there is a bug here that in such a case the touch block that
// generated this tap will not get its mSingleTapOccurred flag set.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1256344#c6
if (touch) {
if (touch->IsDuringFastFling()) {
APZC_LOG(
"%p dropping single-tap because it was during a fast-fling\n",
this);
return nsEventStatus_eIgnore;
}
touch->SetSingleTapOccurred();
}
// Because this may be being running as part of
// APZCTreeManager::ReceiveInputEvent, calling controller->HandleTap
// directly might mean that content receives the single tap message before
// the corresponding touch-up. To avoid that we schedule the singletap
// message to run on the next spin of the event loop. See bug 965381 for
// the issue this was causing.
APZC_LOG("posting runnable for HandleTap from GenerateSingleTap");
RefPtr<Runnable> runnable =
NewRunnableMethod<TapType, LayoutDevicePoint, mozilla::Modifiers,
ScrollableLayerGuid, uint64_t>(
"layers::GeckoContentController::HandleTap", controller,
&GeckoContentController::HandleTap, aType, *geckoScreenPoint,
aModifiers, GetGuid(), touch ? touch->GetBlockId() : 0);
controller->PostDelayedTask(runnable.forget(), 0);
return nsEventStatus_eConsumeNoDefault;
}
}
return nsEventStatus_eIgnore;
}
void AsyncPanZoomController::OnTouchEndOrCancel() {
if (RefPtr<GeckoContentController> controller = GetGeckoContentController()) {
MOZ_ASSERT(GetCurrentTouchBlock());
controller->NotifyAPZStateChange(
GetGuid(), APZStateChange::eEndTouch,
GetCurrentTouchBlock()->SingleTapOccurred());
}
}
nsEventStatus AsyncPanZoomController::OnSingleTapUp(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a single-tap-up in state %d\n", this, mState);
// If mZoomConstraints.mAllowDoubleTapZoom is true we wait for a call to
// OnSingleTapConfirmed before sending event to content
MOZ_ASSERT(GetCurrentTouchBlock());
if (!(mZoomConstraints.mAllowDoubleTapZoom &&
GetCurrentTouchBlock()->TouchActionAllowsDoubleTapZoom())) {
return GenerateSingleTap(TapType::eSingleTap, aEvent.mPoint,
aEvent.modifiers);
}
return nsEventStatus_eIgnore;
}
nsEventStatus AsyncPanZoomController::OnSingleTapConfirmed(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a single-tap-confirmed in state %d\n", this, mState);
return GenerateSingleTap(TapType::eSingleTap, aEvent.mPoint,
aEvent.modifiers);
}
nsEventStatus AsyncPanZoomController::OnDoubleTap(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a double-tap in state %d\n", this, mState);
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (controller) {
MOZ_ASSERT(GetCurrentTouchBlock());
if (mZoomConstraints.mAllowDoubleTapZoom &&
GetCurrentTouchBlock()->TouchActionAllowsDoubleTapZoom()) {
if (Maybe<LayoutDevicePoint> geckoScreenPoint =
ConvertToGecko(aEvent.mPoint)) {
controller->HandleTap(TapType::eDoubleTap, *geckoScreenPoint,
aEvent.modifiers, GetGuid(),
GetCurrentTouchBlock()->GetBlockId());
}
}
return nsEventStatus_eConsumeNoDefault;
}
return nsEventStatus_eIgnore;
}
nsEventStatus AsyncPanZoomController::OnSecondTap(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a second-tap in state %d\n", this, mState);
return GenerateSingleTap(TapType::eSecondTap, aEvent.mPoint,
aEvent.modifiers);
}
nsEventStatus AsyncPanZoomController::OnCancelTap(
const TapGestureInput& aEvent) {
APZC_LOG("%p got a cancel-tap in state %d\n", this, mState);
// XXX: Implement this.
return nsEventStatus_eIgnore;
}
ScreenToParentLayerMatrix4x4 AsyncPanZoomController::GetTransformToThis()
const {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
return treeManagerLocal->GetScreenToApzcTransform(this);
}
return ScreenToParentLayerMatrix4x4();
}
ScreenPoint AsyncPanZoomController::ToScreenCoordinates(
const ParentLayerPoint& aVector, const ParentLayerPoint& aAnchor) const {
return TransformVector(GetTransformToThis().Inverse(), aVector, aAnchor);
}
// TODO: figure out a good way to check the w-coordinate is positive and return
// the result
ParentLayerPoint AsyncPanZoomController::ToParentLayerCoordinates(
const ScreenPoint& aVector, const ScreenPoint& aAnchor) const {
return TransformVector(GetTransformToThis(), aVector, aAnchor);
}
ParentLayerPoint AsyncPanZoomController::ToParentLayerCoordinates(
const ScreenPoint& aVector, const ExternalPoint& aAnchor) const {
return ToParentLayerCoordinates(
aVector,
ViewAs<ScreenPixel>(aAnchor, PixelCastJustification::ExternalIsScreen));
}
ExternalPoint AsyncPanZoomController::ToExternalPoint(
const ExternalPoint& aScreenOffset, const ScreenPoint& aScreenPoint) {
return aScreenOffset +
ViewAs<ExternalPixel>(aScreenPoint,
PixelCastJustification::ExternalIsScreen);
}
ScreenPoint AsyncPanZoomController::PanVector(const ExternalPoint& aPos) const {
return ScreenPoint(fabs(aPos.x - mStartTouch.x),
fabs(aPos.y - mStartTouch.y));
}
bool AsyncPanZoomController::Contains(const ScreenIntPoint& aPoint) const {
ScreenToParentLayerMatrix4x4 transformToThis = GetTransformToThis();
Maybe<ParentLayerIntPoint> point = UntransformBy(transformToThis, aPoint);
if (!point) {
return false;
}
ParentLayerIntRect cb;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
GetFrameMetrics().GetCompositionBounds().ToIntRect(&cb);
}
return cb.Contains(*point);
}
ParentLayerPoint AsyncPanZoomController::PanStart() const {
return ParentLayerPoint(mX.PanStart(), mY.PanStart());
}
const ParentLayerPoint AsyncPanZoomController::GetVelocityVector() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return ParentLayerPoint(mX.GetVelocity(), mY.GetVelocity());
}
void AsyncPanZoomController::SetVelocityVector(
const ParentLayerPoint& aVelocityVector) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
mX.SetVelocity(aVelocityVector.x);
mY.SetVelocity(aVelocityVector.y);
}
void AsyncPanZoomController::HandlePanningWithTouchAction(double aAngle) {
// Handling of cross sliding will need to be added in this method after
// touch-action released enabled by default.
MOZ_ASSERT(GetCurrentTouchBlock());
RefPtr<const OverscrollHandoffChain> overscrollHandoffChain =
GetCurrentInputBlock()->GetOverscrollHandoffChain();
bool canScrollHorizontal =
!mX.IsAxisLocked() && overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eHorizontal);
bool canScrollVertical =
!mY.IsAxisLocked() && overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eVertical);
if (GetCurrentTouchBlock()->TouchActionAllowsPanningXY()) {
if (canScrollHorizontal && canScrollVertical) {
if (apz::IsCloseToHorizontal(aAngle,
StaticPrefs::apz_axis_lock_lock_angle())) {
mY.SetAxisLocked(true);
SetState(PANNING_LOCKED_X);
} else if (apz::IsCloseToVertical(
aAngle, StaticPrefs::apz_axis_lock_lock_angle())) {
mX.SetAxisLocked(true);
SetState(PANNING_LOCKED_Y);
} else {
SetState(PANNING);
}
} else if (canScrollHorizontal || canScrollVertical) {
SetState(PANNING);
} else {
SetState(NOTHING);
}
} else if (GetCurrentTouchBlock()->TouchActionAllowsPanningX()) {
// Using bigger angle for panning to keep behavior consistent
// with IE.
if (apz::IsCloseToHorizontal(
aAngle, StaticPrefs::apz_axis_lock_direct_pan_angle())) {
mY.SetAxisLocked(true);
SetState(PANNING_LOCKED_X);
mPanDirRestricted = true;
} else {
// Don't treat these touches as pan/zoom movements since 'touch-action'
// value requires it.
SetState(NOTHING);
}
} else if (GetCurrentTouchBlock()->TouchActionAllowsPanningY()) {
if (apz::IsCloseToVertical(aAngle,
StaticPrefs::apz_axis_lock_direct_pan_angle())) {
mX.SetAxisLocked(true);
SetState(PANNING_LOCKED_Y);
mPanDirRestricted = true;
} else {
SetState(NOTHING);
}
} else {
SetState(NOTHING);
}
if (!IsInPanningState()) {
// If we didn't enter a panning state because touch-action disallowed it,
// make sure to clear any leftover velocity from the pre-threshold
// touchmoves.
mX.SetVelocity(0);
mY.SetVelocity(0);
}
}
void AsyncPanZoomController::HandlePanning(double aAngle) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
MOZ_ASSERT(GetCurrentInputBlock());
RefPtr<const OverscrollHandoffChain> overscrollHandoffChain =
GetCurrentInputBlock()->GetOverscrollHandoffChain();
bool canScrollHorizontal =
!mX.IsAxisLocked() && overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eHorizontal);
bool canScrollVertical =
!mY.IsAxisLocked() && overscrollHandoffChain->CanScrollInDirection(
this, ScrollDirection::eVertical);
if (!canScrollHorizontal || !canScrollVertical) {
SetState(PANNING);
} else if (apz::IsCloseToHorizontal(
aAngle, StaticPrefs::apz_axis_lock_lock_angle())) {
mY.SetAxisLocked(true);
if (canScrollHorizontal) {
SetState(PANNING_LOCKED_X);
}
} else if (apz::IsCloseToVertical(aAngle,
StaticPrefs::apz_axis_lock_lock_angle())) {
mX.SetAxisLocked(true);
if (canScrollVertical) {
SetState(PANNING_LOCKED_Y);
}
} else {
SetState(PANNING);
}
}
void AsyncPanZoomController::HandlePanningUpdate(
const ScreenPoint& aPanDistance) {
// If we're axis-locked, check if the user is trying to break the lock
if (GetAxisLockMode() == STICKY && !mPanDirRestricted) {
ParentLayerPoint vector =
ToParentLayerCoordinates(aPanDistance, mStartTouch);
double angle = atan2(vector.y, vector.x); // range [-pi, pi]
angle = fabs(angle); // range [0, pi]
float breakThreshold =
StaticPrefs::apz_axis_lock_breakout_threshold() * GetDPI();
if (fabs(aPanDistance.x) > breakThreshold ||
fabs(aPanDistance.y) > breakThreshold) {
if (mState == PANNING_LOCKED_X) {
if (!apz::IsCloseToHorizontal(
angle, StaticPrefs::apz_axis_lock_breakout_angle())) {
mY.SetAxisLocked(false);
SetState(PANNING);
}
} else if (mState == PANNING_LOCKED_Y) {
if (!apz::IsCloseToVertical(
angle, StaticPrefs::apz_axis_lock_breakout_angle())) {
mX.SetAxisLocked(false);
SetState(PANNING);
}
}
}
}
}
void AsyncPanZoomController::HandlePinchLocking(
const PinchGestureInput& aEvent) {
// Focus change and span distance calculated from an event buffer
// Used to handle pinch locking irrespective of touch screen sensitivity
// Note: both values fall back to the same value as
// their un-buffered counterparts if there is only one (the latest)
// event in the buffer. ie: when the touch screen is dispatching
// events slower than the lifetime of the buffer
ParentLayerCoord bufferedSpanDistance;
ParentLayerPoint focusPoint, bufferedFocusChange;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
focusPoint = mPinchEventBuffer.back().mLocalFocusPoint -
Metrics().GetCompositionBounds().TopLeft();
ParentLayerPoint bufferedLastZoomFocus =
(mPinchEventBuffer.size() > 1)
? mPinchEventBuffer.front().mLocalFocusPoint -
Metrics().GetCompositionBounds().TopLeft()
: mLastZoomFocus;
bufferedFocusChange = bufferedLastZoomFocus - focusPoint;
bufferedSpanDistance = fabsf(mPinchEventBuffer.front().mPreviousSpan -
mPinchEventBuffer.back().mCurrentSpan);
}
// Convert to screen coordinates
ScreenCoord spanDistance =
ToScreenCoordinates(ParentLayerPoint(0, bufferedSpanDistance), focusPoint)
.Length();
ScreenPoint focusChange =
ToScreenCoordinates(bufferedFocusChange, focusPoint);
if (mPinchLocked) {
if (GetPinchLockMode() == PINCH_STICKY) {
ScreenCoord spanBreakoutThreshold =
StaticPrefs::apz_pinch_lock_span_breakout_threshold() * GetDPI();
mPinchLocked = !(spanDistance > spanBreakoutThreshold);
}
} else {
if (GetPinchLockMode() != PINCH_FREE) {
ScreenCoord spanLockThreshold =
StaticPrefs::apz_pinch_lock_span_lock_threshold() * GetDPI();
ScreenCoord scrollLockThreshold =
StaticPrefs::apz_pinch_lock_scroll_lock_threshold() * GetDPI();
if (spanDistance < spanLockThreshold &&
focusChange.Length() > scrollLockThreshold) {
mPinchLocked = true;
// We are transitioning to a two-finger pan that could trigger
// a fling at its end, so start tracking velocity.
StartTouch(aEvent.mLocalFocusPoint, aEvent.mTimeStamp);
}
}
}
}
nsEventStatus AsyncPanZoomController::StartPanning(
const ExternalPoint& aStartPoint, const TimeStamp& aEventTime) {
ParentLayerPoint vector =
ToParentLayerCoordinates(PanVector(aStartPoint), mStartTouch);
double angle = atan2(vector.y, vector.x); // range [-pi, pi]
angle = fabs(angle); // range [0, pi]
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (StaticPrefs::layout_css_touch_action_enabled()) {
HandlePanningWithTouchAction(angle);
} else {
if (GetAxisLockMode() == FREE) {
SetState(PANNING);
} else {
HandlePanning(angle);
}
}
if (IsInPanningState()) {
mozilla::Telemetry::Accumulate(mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethod::ApzTouch);
mTouchStartRestingTimeBeforePan = aEventTime - mTouchStartTime;
mMinimumVelocityDuringPan = Nothing();
if (RefPtr<GeckoContentController> controller =
GetGeckoContentController()) {
controller->NotifyAPZStateChange(GetGuid(),
APZStateChange::eStartPanning);
}
return nsEventStatus_eConsumeNoDefault;
}
// Don't consume an event that didn't trigger a panning.
return nsEventStatus_eIgnore;
}
void AsyncPanZoomController::UpdateWithTouchAtDevicePoint(
const MultiTouchInput& aEvent) {
const SingleTouchData& touchData = aEvent.mTouches[0];
// Take historical touch data into account in order to improve the accuracy
// of the velocity estimate. On many Android devices, the touch screen samples
// at a higher rate than vsync (e.g. 100Hz vs 60Hz), and the historical data
// lets us take advantage of those high-rate samples.
for (const auto& historicalData : touchData.mHistoricalData) {
ParentLayerPoint historicalPoint = historicalData.mLocalScreenPoint;
mX.UpdateWithTouchAtDevicePoint(historicalPoint.x,
historicalData.mTimeStamp);
mY.UpdateWithTouchAtDevicePoint(historicalPoint.y,
historicalData.mTimeStamp);
}
ParentLayerPoint point = touchData.mLocalScreenPoint;
mX.UpdateWithTouchAtDevicePoint(point.x, aEvent.mTimeStamp);
mY.UpdateWithTouchAtDevicePoint(point.y, aEvent.mTimeStamp);
}
Maybe<CompositionPayload> AsyncPanZoomController::NotifyScrollSampling() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return mSampledState.front().TakeScrollPayload();
}
bool AsyncPanZoomController::AttemptScroll(
ParentLayerPoint& aStartPoint, ParentLayerPoint& aEndPoint,
OverscrollHandoffState& aOverscrollHandoffState) {
// "start - end" rather than "end - start" because e.g. moving your finger
// down (*positive* direction along y axis) causes the vertical scroll offset
// to *decrease* as the page follows your finger.
ParentLayerPoint displacement = aStartPoint - aEndPoint;
ParentLayerPoint overscroll; // will be used outside monitor block
// If the direction of panning is reversed within the same input block,
// a later event in the block could potentially scroll an APZC earlier
// in the handoff chain, than an earlier event in the block (because
// the earlier APZC was scrolled to its extent in the original direction).
// We want to disallow this.
bool scrollThisApzc = false;
if (InputBlockState* block = GetCurrentInputBlock()) {
scrollThisApzc =
!block->GetScrolledApzc() || block->IsDownchainOfScrolledApzc(this);
}
if (scrollThisApzc) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
bool forcesVerticalOverscroll =
ScrollSource::Wheel == aOverscrollHandoffState.mScrollSource &&
mScrollMetadata.GetDisregardedDirection() ==
Some(ScrollDirection::eVertical);
bool forcesHorizontalOverscroll =
ScrollSource::Wheel == aOverscrollHandoffState.mScrollSource &&
mScrollMetadata.GetDisregardedDirection() ==
Some(ScrollDirection::eHorizontal);
ParentLayerPoint adjustedDisplacement;
bool yChanged =
mY.AdjustDisplacement(displacement.y, adjustedDisplacement.y,
overscroll.y, forcesVerticalOverscroll);
bool xChanged =
mX.AdjustDisplacement(displacement.x, adjustedDisplacement.x,
overscroll.x, forcesHorizontalOverscroll);
if (xChanged || yChanged) {
ScheduleComposite();
}
if (!IsZero(adjustedDisplacement) &&
Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
ScrollBy(adjustedDisplacement / Metrics().GetZoom());
if (InputBlockState* block = GetCurrentInputBlock()) {
bool displacementIsUserVisible = true;
{ // Release the APZC lock before calling ToScreenCoordinates which
// acquires the APZ tree lock. Note that this just unlocks the mutex
// once, so if we're locking it multiple times on the callstack then
// this will be insufficient.
RecursiveMutexAutoUnlock unlock(mRecursiveMutex);
ScreenIntPoint screenDisplacement = RoundedToInt(
ToScreenCoordinates(adjustedDisplacement, aStartPoint));
// If the displacement we just applied rounds to zero in screen space,
// then it's probably not going to be visible to the user. In that
// case let's not mark this APZC as scrolled, so that even if the
// immediate handoff pref is disabled, we'll allow doing the handoff
// to the next APZC.
if (screenDisplacement == ScreenIntPoint()) {
displacementIsUserVisible = false;
}
}
if (displacementIsUserVisible) {
block->SetScrolledApzc(this);
}
}
ScheduleCompositeAndMaybeRepaint();
UpdateSharedCompositorFrameMetrics();
}
// Adjust the start point to reflect the consumed portion of the scroll.
aStartPoint = aEndPoint + overscroll;
} else {
overscroll = displacement;
}
// If we consumed the entire displacement as a normal scroll, great.
if (IsZero(overscroll)) {
return true;
}
if (AllowScrollHandoffInCurrentBlock()) {
// If there is overscroll, first try to hand it off to an APZC later
// in the handoff chain to consume (either as a normal scroll or as
// overscroll).
// Note: "+ overscroll" rather than "- overscroll" because "overscroll"
// is what's left of "displacement", and "displacement" is "start - end".
++aOverscrollHandoffState.mChainIndex;
bool consumed =
CallDispatchScroll(aStartPoint, aEndPoint, aOverscrollHandoffState);
if (consumed) {
return true;
}
overscroll = aStartPoint - aEndPoint;
MOZ_ASSERT(!IsZero(overscroll));
}
// If there is no APZC later in the handoff chain that accepted the
// overscroll, try to accept it ourselves. We only accept it if we
// are pannable.
APZC_LOG("%p taking overscroll during panning\n", this);
OverscrollForPanning(overscroll, aOverscrollHandoffState.mPanDistance);
aStartPoint = aEndPoint + overscroll;
return IsZero(overscroll);
}
void AsyncPanZoomController::OverscrollForPanning(
ParentLayerPoint& aOverscroll, const ScreenPoint& aPanDistance) {
// Only allow entering overscroll along an axis if the pan distance along
// that axis is greater than the pan distance along the other axis by a
// configurable factor. If we are already overscrolled, don't check this.
if (!IsOverscrolled()) {
if (aPanDistance.x <
StaticPrefs::apz_overscroll_min_pan_distance_ratio() * aPanDistance.y) {
aOverscroll.x = 0;
}
if (aPanDistance.y <
StaticPrefs::apz_overscroll_min_pan_distance_ratio() * aPanDistance.x) {
aOverscroll.y = 0;
}
}
OverscrollBy(aOverscroll);
}
void AsyncPanZoomController::OverscrollBy(ParentLayerPoint& aOverscroll) {
if (!StaticPrefs::apz_overscroll_enabled()) {
return;
}
RecursiveMutexAutoLock lock(mRecursiveMutex);
// Do not go into overscroll in a direction in which we have no room to
// scroll to begin with.
bool xCanScroll = mX.CanScroll();
bool yCanScroll = mY.CanScroll();
bool xConsumed = FuzzyEqualsAdditive(aOverscroll.x, 0.0f, COORDINATE_EPSILON);
bool yConsumed = FuzzyEqualsAdditive(aOverscroll.y, 0.0f, COORDINATE_EPSILON);
bool shouldOverscrollX =
xCanScroll && !xConsumed && mX.OverscrollBehaviorAllowsOverscrollEffect();
bool shouldOverscrollY =
yCanScroll && !yConsumed && mY.OverscrollBehaviorAllowsOverscrollEffect();
mOverscrollEffect->ConsumeOverscroll(aOverscroll, shouldOverscrollX,
shouldOverscrollY);
}
RefPtr<const OverscrollHandoffChain>
AsyncPanZoomController::BuildOverscrollHandoffChain() {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
return treeManagerLocal->BuildOverscrollHandoffChain(this);
}
// This APZC IsDestroyed(). To avoid callers having to special-case this
// scenario, just build a 1-element chain containing ourselves.
OverscrollHandoffChain* result = new OverscrollHandoffChain;
result->Add(this);
return result;
}
ParentLayerPoint AsyncPanZoomController::AttemptFling(
const FlingHandoffState& aHandoffState) {
// The PLPPI computation acquires the tree lock, so it needs to be performed
// on the controller thread, and before the APZC lock is acquired.
APZThreadUtils::AssertOnControllerThread();
float PLPPI = ComputePLPPI(PanStart(), aHandoffState.mVelocity);
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!IsPannable()) {
return aHandoffState.mVelocity;
}
// We may have a pre-existing velocity for whatever reason (for example,
// a previously handed off fling). We don't want to clobber that.
APZC_LOG("%p accepting fling with velocity %s\n", this,
ToString(aHandoffState.mVelocity).c_str());
ParentLayerPoint residualVelocity = aHandoffState.mVelocity;
if (mX.CanScroll()) {
mX.SetVelocity(mX.GetVelocity() + aHandoffState.mVelocity.x);
residualVelocity.x = 0;
}
if (mY.CanScroll()) {
mY.SetVelocity(mY.GetVelocity() + aHandoffState.mVelocity.y);
residualVelocity.y = 0;
}
// If we're not scrollable in at least one of the directions in which we
// were handed velocity, don't start a fling animation.
// The |IsFinite()| condition should only fail when running some tests
// that generate events faster than the clock resolution.
ParentLayerPoint velocity = GetVelocityVector();
if (!velocity.IsFinite() ||
velocity.Length() <= StaticPrefs::apz_fling_min_velocity_threshold()) {
// Relieve overscroll now if needed, since we will not transition to a fling
// animation and then an overscroll animation, and relieve it then.
aHandoffState.mChain->SnapBackOverscrolledApzc(this);
return residualVelocity;
}
// If there's a scroll snap point near the predicted fling destination,
// scroll there using a smooth scroll animation. Otherwise, start a
// fling animation.
ScrollSnapToDestination();
if (mState != SMOOTHMSD_SCROLL) {
SetState(FLING);
AsyncPanZoomAnimation* fling =
GetPlatformSpecificState()->CreateFlingAnimation(*this, aHandoffState,
PLPPI);
StartAnimation(fling);
}
return residualVelocity;
}
float AsyncPanZoomController::ComputePLPPI(ParentLayerPoint aPoint,
ParentLayerPoint aDirection) const {
// Avoid division-by-zero.
if (aDirection == ParentLayerPoint()) {
return GetDPI();
}
// Convert |aDirection| into a unit vector.
aDirection = aDirection / aDirection.Length();
// Place the vector at |aPoint| and convert to screen coordinates.
// The length of the resulting vector is the number of Screen coordinates
// that equal 1 ParentLayer coordinate in the given direction.
float screenPerParent = ToScreenCoordinates(aDirection, aPoint).Length();
// Finally, factor in the DPI scale.
return GetDPI() / screenPerParent;
}
Maybe<CSSPoint> AsyncPanZoomController::GetCurrentAnimationDestination(
const RecursiveMutexAutoLock& aProofOfLock) const {
if (mState == WHEEL_SCROLL) {
return Some(mAnimation->AsWheelScrollAnimation()->GetDestination());
}
if (mState == SMOOTH_SCROLL) {
return Some(mAnimation->AsSmoothScrollAnimation()->GetDestination());
}
if (mState == SMOOTHMSD_SCROLL) {
return Some(mAnimation->AsSmoothMsdScrollAnimation()->GetDestination());
}
if (mState == KEYBOARD_SCROLL) {
return Some(mAnimation->AsSmoothScrollAnimation()->GetDestination());
}
return Nothing();
}
ParentLayerPoint
AsyncPanZoomController::AdjustHandoffVelocityForOverscrollBehavior(
ParentLayerPoint& aHandoffVelocity) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
ParentLayerPoint residualVelocity;
if (!mX.OverscrollBehaviorAllowsHandoff()) {
residualVelocity.x = aHandoffVelocity.x;
aHandoffVelocity.x = 0;
}
if (!mY.OverscrollBehaviorAllowsHandoff()) {
residualVelocity.y = aHandoffVelocity.y;
aHandoffVelocity.y = 0;
}
return residualVelocity;
}
bool AsyncPanZoomController::OverscrollBehaviorAllowsSwipe() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
// Swipe navigation is a "non-local" overscroll behavior like handoff.
return mX.OverscrollBehaviorAllowsHandoff();
}
void AsyncPanZoomController::HandleFlingOverscroll(
const ParentLayerPoint& aVelocity,
const RefPtr<const OverscrollHandoffChain>& aOverscrollHandoffChain,
const RefPtr<const AsyncPanZoomController>& aScrolledApzc) {
APZCTreeManager* treeManagerLocal = GetApzcTreeManager();
if (treeManagerLocal) {
const FlingHandoffState handoffState{
aVelocity, aOverscrollHandoffChain, Nothing(),
0, true /* handoff */, aScrolledApzc};
ParentLayerPoint residualVelocity =
treeManagerLocal->DispatchFling(this, handoffState);
FLING_LOG("APZC %p left with residual velocity %s\n", this,
ToString(residualVelocity).c_str());
if (!IsZero(residualVelocity) && IsPannable() &&
StaticPrefs::apz_overscroll_enabled()) {
// Obey overscroll-behavior.
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!mX.OverscrollBehaviorAllowsOverscrollEffect()) {
residualVelocity.x = 0;
}
if (!mY.OverscrollBehaviorAllowsOverscrollEffect()) {
residualVelocity.y = 0;
}
if (!IsZero(residualVelocity)) {
mOverscrollEffect->HandleFlingOverscroll(residualVelocity);
}
}
}
}
void AsyncPanZoomController::HandleSmoothScrollOverscroll(
const ParentLayerPoint& aVelocity) {
// We must call BuildOverscrollHandoffChain from this deferred callback
// function in order to avoid a deadlock when acquiring the tree lock.
HandleFlingOverscroll(aVelocity, BuildOverscrollHandoffChain(), nullptr);
}
void AsyncPanZoomController::SmoothScrollTo(const CSSPoint& aDestination,
const ScrollOrigin& aOrigin) {
// Convert velocity from ParentLayerPoints/ms to ParentLayerPoints/s and then
// to appunits/second.
nsPoint destination = CSSPoint::ToAppUnits(aDestination);
nsSize velocity;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
velocity = CSSSize::ToAppUnits(ParentLayerSize(mX.GetVelocity() * 1000.0f,
mY.GetVelocity() * 1000.0f) /
Metrics().GetZoom());
}
if (mState == SMOOTH_SCROLL && mAnimation) {
RefPtr<SmoothScrollAnimation> animation(
mAnimation->AsSmoothScrollAnimation());
if (animation->GetScrollOrigin() == aOrigin) {
APZC_LOG("%p updating destination on existing animation\n", this);
animation->UpdateDestination(GetFrameTime().Time(), destination,
velocity);
return;
}
}
CancelAnimation();
SetState(SMOOTH_SCROLL);
nsPoint initialPosition =
CSSPoint::ToAppUnits(Metrics().GetVisualScrollOffset());
RefPtr<SmoothScrollAnimation> animation =
new SmoothScrollAnimation(*this, initialPosition, aOrigin);
animation->UpdateDestination(GetFrameTime().Time(), destination, velocity);
StartAnimation(animation.get());
}
void AsyncPanZoomController::SmoothMsdScrollTo(const CSSPoint& aDestination) {
if (mState == SMOOTHMSD_SCROLL && mAnimation) {
APZC_LOG("%p updating destination on existing animation\n", this);
RefPtr<SmoothMsdScrollAnimation> animation(
static_cast<SmoothMsdScrollAnimation*>(mAnimation.get()));
animation->SetDestination(aDestination);
} else {
CancelAnimation();
SetState(SMOOTHMSD_SCROLL);
// Convert velocity from ParentLayerPoints/ms to ParentLayerPoints/s.
CSSPoint initialVelocity;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
initialVelocity = ParentLayerPoint(mX.GetVelocity() * 1000.0f,
mY.GetVelocity() * 1000.0f) /
Metrics().GetZoom();
}
StartAnimation(new SmoothMsdScrollAnimation(
*this, Metrics().GetVisualScrollOffset(), initialVelocity, aDestination,
StaticPrefs::layout_css_scroll_behavior_spring_constant(),
StaticPrefs::layout_css_scroll_behavior_damping_ratio()));
}
}
void AsyncPanZoomController::StartOverscrollAnimation(
const ParentLayerPoint& aVelocity) {
SetState(OVERSCROLL_ANIMATION);
StartAnimation(new OverscrollAnimation(*this, aVelocity));
}
bool AsyncPanZoomController::CallDispatchScroll(
ParentLayerPoint& aStartPoint, ParentLayerPoint& aEndPoint,
OverscrollHandoffState& aOverscrollHandoffState) {
// Make a local copy of the tree manager pointer and check if it's not
// null before calling DispatchScroll(). This is necessary because
// Destroy(), which nulls out mTreeManager, could be called concurrently.
APZCTreeManager* treeManagerLocal = GetApzcTreeManager();
if (!treeManagerLocal) {
return false;
}
// Obey overscroll-behavior.
ParentLayerPoint endPoint = aEndPoint;
if (aOverscrollHandoffState.mChainIndex > 0) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!mX.OverscrollBehaviorAllowsHandoff()) {
endPoint.x = aStartPoint.x;
}
if (!mY.OverscrollBehaviorAllowsHandoff()) {
endPoint.y = aStartPoint.y;
}
if (aStartPoint == endPoint) {
// Handoff not allowed in either direction - don't even bother.
return false;
}
}
return treeManagerLocal->DispatchScroll(this, aStartPoint, endPoint,
aOverscrollHandoffState);
}
void AsyncPanZoomController::RecordScrollPayload(const TimeStamp& aTimeStamp) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!mScrollPayload) {
mScrollPayload = Some(
CompositionPayload{CompositionPayloadType::eAPZScroll, aTimeStamp});
}
}
void AsyncPanZoomController::StartTouch(const ParentLayerPoint& aPoint,
TimeStamp aTimestamp) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
mX.StartTouch(aPoint.x, aTimestamp);
mY.StartTouch(aPoint.y, aTimestamp);
}
void AsyncPanZoomController::EndTouch(TimeStamp aTimestamp) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
mX.EndTouch(aTimestamp);
mY.EndTouch(aTimestamp);
}
void AsyncPanZoomController::TrackTouch(const MultiTouchInput& aEvent) {
ExternalPoint extPoint = GetFirstExternalTouchPoint(aEvent);
ScreenPoint panVector = PanVector(extPoint);
HandlePanningUpdate(panVector);
ParentLayerPoint prevTouchPoint(mX.GetPos(), mY.GetPos());
ParentLayerPoint touchPoint = GetFirstTouchPoint(aEvent);
UpdateWithTouchAtDevicePoint(aEvent);
auto velocity = GetVelocityVector().Length();
if (mMinimumVelocityDuringPan) {
mMinimumVelocityDuringPan =
Some(std::min(*mMinimumVelocityDuringPan, velocity));
} else {
mMinimumVelocityDuringPan = Some(velocity);
}
if (prevTouchPoint != touchPoint) {
MOZ_ASSERT(GetCurrentTouchBlock());
OverscrollHandoffState handoffState(
*GetCurrentTouchBlock()->GetOverscrollHandoffChain(), panVector,
ScrollSource::Touch);
RecordScrollPayload(aEvent.mTimeStamp);
CallDispatchScroll(prevTouchPoint, touchPoint, handoffState);
}
}
ParentLayerPoint AsyncPanZoomController::GetFirstTouchPoint(
const MultiTouchInput& aEvent) {
return ((SingleTouchData&)aEvent.mTouches[0]).mLocalScreenPoint;
}
ExternalPoint AsyncPanZoomController::GetFirstExternalTouchPoint(
const MultiTouchInput& aEvent) {
return ToExternalPoint(aEvent.mScreenOffset,
((SingleTouchData&)aEvent.mTouches[0]).mScreenPoint);
}
void AsyncPanZoomController::StartAnimation(AsyncPanZoomAnimation* aAnimation) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
mAnimation = aAnimation;
mLastSampleTime = GetFrameTime();
ScheduleComposite();
}
void AsyncPanZoomController::CancelAnimation(CancelAnimationFlags aFlags) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
APZC_LOG("%p running CancelAnimation(0x%x) in state %d\n", this, aFlags,
mState);
if ((aFlags & ExcludeWheel) && mState == WHEEL_SCROLL) {
return;
}
if (mAnimation) {
mAnimation->Cancel(aFlags);
}
SetState(NOTHING);
mAnimation = nullptr;
// Since there is no animation in progress now the axes should
// have no velocity either. If we are dropping the velocity from a non-zero
// value we should trigger a repaint as the displayport margins are dependent
// on the velocity and the last repaint request might not have good margins
// any more.
bool repaint = !IsZero(GetVelocityVector());
mX.SetVelocity(0);
mY.SetVelocity(0);
mX.SetAxisLocked(false);
mY.SetAxisLocked(false);
// Setting the state to nothing and cancelling the animation can
// preempt normal mechanisms for relieving overscroll, so we need to clear
// overscroll here.
if (!(aFlags & ExcludeOverscroll) && IsOverscrolled()) {
ClearOverscroll();
repaint = true;
}
// Similar to relieving overscroll, we also need to snap to any snap points
// if appropriate.
if (aFlags & CancelAnimationFlags::ScrollSnap) {
ScrollSnap();
}
if (repaint) {
RequestContentRepaint();
ScheduleComposite();
UpdateSharedCompositorFrameMetrics();
}
}
void AsyncPanZoomController::ClearOverscroll() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
mX.ClearOverscroll();
mY.ClearOverscroll();
}
void AsyncPanZoomController::SetCompositorController(
CompositorController* aCompositorController) {
mCompositorController = aCompositorController;
}
void AsyncPanZoomController::SetMetricsSharingController(
MetricsSharingController* aMetricsSharingController) {
mMetricsSharingController = aMetricsSharingController;
}
void AsyncPanZoomController::SetVisualScrollOffset(const CSSPoint& aOffset) {
Metrics().SetVisualScrollOffset(aOffset);
Metrics().RecalculateLayoutViewportOffset();
}
void AsyncPanZoomController::ClampAndSetVisualScrollOffset(
const CSSPoint& aOffset) {
Metrics().ClampAndSetVisualScrollOffset(aOffset);
Metrics().RecalculateLayoutViewportOffset();
}
void AsyncPanZoomController::ScrollBy(const CSSPoint& aOffset) {
SetVisualScrollOffset(Metrics().GetVisualScrollOffset() + aOffset);
}
void AsyncPanZoomController::ScrollByAndClamp(const CSSPoint& aOffset) {
ClampAndSetVisualScrollOffset(Metrics().GetVisualScrollOffset() + aOffset);
}
void AsyncPanZoomController::ScaleWithFocus(float aScale,
const CSSPoint& aFocus) {
Metrics().ZoomBy(aScale);
// We want to adjust the scroll offset such that the CSS point represented by
// aFocus remains at the same position on the screen before and after the
// change in zoom. The below code accomplishes this; see
// https://bugzilla.mozilla.org/show_bug.cgi?id=923431#c6 for an in-depth
// explanation of how.
SetVisualScrollOffset((Metrics().GetVisualScrollOffset() + aFocus) -
(aFocus / aScale));
}
/*static*/
gfx::IntSize AsyncPanZoomController::GetDisplayportAlignmentMultiplier(
const ScreenSize& aBaseSize) {
MOZ_ASSERT(gfx::gfxVars::UseWebRender());
gfx::IntSize multiplier(1, 1);
float baseWidth = aBaseSize.width;
while (baseWidth > 500) {
baseWidth /= 2;
multiplier.width *= 2;
if (multiplier.width >= 8) {
break;
}
}
float baseHeight = aBaseSize.height;
while (baseHeight > 500) {
baseHeight /= 2;
multiplier.height *= 2;
if (multiplier.height >= 8) {
break;
}
}
return multiplier;
}
/**
* Enlarges the displayport along both axes based on the velocity.
*/
static CSSSize CalculateDisplayPortSize(
const CSSSize& aCompositionSize, const CSSPoint& aVelocity,
AsyncPanZoomController::ZoomInProgress aZoomInProgress,
const CSSToScreenScale2D& aDpPerCSS) {
bool xIsStationarySpeed =
fabsf(aVelocity.x) < StaticPrefs::apz_min_skate_speed();
bool yIsStationarySpeed =
fabsf(aVelocity.y) < StaticPrefs::apz_min_skate_speed();
float xMultiplier = xIsStationarySpeed
? StaticPrefs::apz_x_stationary_size_multiplier()
: StaticPrefs::apz_x_skate_size_multiplier();
float yMultiplier = yIsStationarySpeed
? StaticPrefs::apz_y_stationary_size_multiplier()
: StaticPrefs::apz_y_skate_size_multiplier();
if (IsHighMemSystem() && !xIsStationarySpeed) {
xMultiplier += StaticPrefs::apz_x_skate_highmem_adjust();
}
if (IsHighMemSystem() && !yIsStationarySpeed) {
yMultiplier += StaticPrefs::apz_y_skate_highmem_adjust();
}
if (aZoomInProgress == AsyncPanZoomController::ZoomInProgress::Yes) {
// If a zoom is in progress, we will be making content visible on the
// x and y axes in equal proportion, because the zoom operation scales
// equally on the x and y axes. The default multipliers computed above are
// biased towards the y-axis since that's where most scrolling occurs, but
// in the case of zooming, we should really use equal multipliers on both
// axes. This does that while preserving the total displayport area
// quantity (aCompositionSize.Area() * xMultiplier * yMultiplier).
// Note that normally changing the shape of the displayport is expensive
// and should be avoided, but if a zoom is in progress the displayport
// is likely going to be fully repainted anyway due to changes in resolution
// so there should be no marginal cost to also changing the shape of it.
float areaMultiplier = xMultiplier * yMultiplier;
xMultiplier = sqrt(areaMultiplier);
yMultiplier = xMultiplier;
}
if (gfx::gfxVars::UseWebRender()) {
// Scale down the margin multipliers by the alignment multiplier because
// the alignment code will expand the displayport outward to the multiplied
// alignment. This is not necessary for correctness, but for performance;
// if we don't do this the displayport can end up much larger. The math here
// is actually just scaling the part of the multipler that is > 1, so that
// we never end up with xMultiplier or yMultiplier being less than 1 (that
// would result in a guaranteed checkerboarding situation). Note that the
// calculation doesn't cancel exactly the increased margin from applying
// the alignment multiplier, but this is simple and should provide
// reasonable behaviour in most cases.
gfx::IntSize alignmentMultipler =
AsyncPanZoomController::GetDisplayportAlignmentMultiplier(
aCompositionSize * aDpPerCSS);
if (xMultiplier > 1) {
xMultiplier = ((xMultiplier - 1) / alignmentMultipler.width) + 1;
}
if (yMultiplier > 1) {
yMultiplier = ((yMultiplier - 1) / alignmentMultipler.height) + 1;
}
}
return aCompositionSize * CSSSize(xMultiplier, yMultiplier);
}
/**
* Ensures that the displayport is at least as large as the visible area
* inflated by the danger zone. If this is not the case then the
* "AboutToCheckerboard" function in TiledContentClient.cpp will return true
* even in the stable state.
*/
static CSSSize ExpandDisplayPortToDangerZone(
const CSSSize& aDisplayPortSize, const FrameMetrics& aFrameMetrics) {
CSSSize dangerZone(0.0f, 0.0f);
if (aFrameMetrics.LayersPixelsPerCSSPixel().xScale != 0 &&
aFrameMetrics.LayersPixelsPerCSSPixel().yScale != 0) {
dangerZone = LayerSize(StaticPrefs::apz_danger_zone_x(),
StaticPrefs::apz_danger_zone_y()) /
aFrameMetrics.LayersPixelsPerCSSPixel();
}
const CSSSize compositionSize =
aFrameMetrics.CalculateBoundedCompositedSizeInCssPixels();
const float xSize = std::max(aDisplayPortSize.width,
compositionSize.width + (2 * dangerZone.width));
const float ySize =
std::max(aDisplayPortSize.height,
compositionSize.height + (2 * dangerZone.height));
return CSSSize(xSize, ySize);
}
/**
* Attempts to redistribute any area in the displayport that would get clipped
* by the scrollable rect, or be inaccessible due to disabled scrolling, to the
* other axis, while maintaining total displayport area.
*/
static void RedistributeDisplayPortExcess(CSSSize& aDisplayPortSize,
const CSSRect& aScrollableRect) {
// As aDisplayPortSize.height * aDisplayPortSize.width does not change,
// we are just scaling by the ratio and its inverse.
if (aDisplayPortSize.height > aScrollableRect.Height()) {
aDisplayPortSize.width *=
(aDisplayPortSize.height / aScrollableRect.Height());
aDisplayPortSize.height = aScrollableRect.Height();
} else if (aDisplayPortSize.width > aScrollableRect.Width()) {
aDisplayPortSize.height *=
(aDisplayPortSize.width / aScrollableRect.Width());
aDisplayPortSize.width = aScrollableRect.Width();
}
}
/* static */
const ScreenMargin AsyncPanZoomController::CalculatePendingDisplayPort(
const FrameMetrics& aFrameMetrics, const ParentLayerPoint& aVelocity,
ZoomInProgress aZoomInProgress) {
if (aFrameMetrics.IsScrollInfoLayer()) {
// Don't compute margins. Since we can't asynchronously scroll this frame,
// we don't want to paint anything more than the composition bounds.
return ScreenMargin();
}
CSSSize compositionSize =
aFrameMetrics.CalculateBoundedCompositedSizeInCssPixels();
CSSPoint velocity;
if (aFrameMetrics.GetZoom() != CSSToParentLayerScale2D(0, 0)) {
velocity = aVelocity / aFrameMetrics.GetZoom(); // avoid division by zero
}
CSSRect scrollableRect = aFrameMetrics.GetExpandedScrollableRect();
// Calculate the displayport size based on how fast we're moving along each
// axis.
CSSSize displayPortSize =
CalculateDisplayPortSize(compositionSize, velocity, aZoomInProgress,
aFrameMetrics.DisplayportPixelsPerCSSPixel());
displayPortSize =
ExpandDisplayPortToDangerZone(displayPortSize, aFrameMetrics);
if (StaticPrefs::apz_enlarge_displayport_when_clipped()) {
RedistributeDisplayPortExcess(displayPortSize, scrollableRect);
}
// We calculate a "displayport" here which is relative to the scroll offset.
// Note that the scroll offset we have here in the APZ code may not be the
// same as the base rect that gets used on the layout side when the
// displayport margins are actually applied, so it is important to only
// consider the displayport as margins relative to a scroll offset rather than
// relative to something more unchanging like the scrollable rect origin.
// Center the displayport based on its expansion over the composition size.
CSSRect displayPort((compositionSize.width - displayPortSize.width) / 2.0f,
(compositionSize.height - displayPortSize.height) / 2.0f,
displayPortSize.width, displayPortSize.height);
// Offset the displayport, depending on how fast we're moving and the
// estimated time it takes to paint, to try to minimise checkerboarding.
float paintFactor = kDefaultEstimatedPaintDurationMs;
displayPort.MoveBy(velocity * paintFactor * StaticPrefs::apz_velocity_bias());
APZC_LOGV_FM(aFrameMetrics,
"Calculated displayport as %s from velocity %s zooming %d paint "
"time %f metrics",
ToString(displayPort).c_str(), ToString(aVelocity).c_str(),
(int)aZoomInProgress, paintFactor);
CSSMargin cssMargins;
cssMargins.left = -displayPort.X();
cssMargins.top = -displayPort.Y();
cssMargins.right =
displayPort.Width() - compositionSize.width - cssMargins.left;
cssMargins.bottom =
displayPort.Height() - compositionSize.height - cssMargins.top;
return cssMargins * aFrameMetrics.DisplayportPixelsPerCSSPixel();
}
void AsyncPanZoomController::ScheduleComposite() {
if (mCompositorController) {
mCompositorController->ScheduleRenderOnCompositorThread();
}
}
void AsyncPanZoomController::ScheduleCompositeAndMaybeRepaint() {
ScheduleComposite();
RequestContentRepaint();
}
void AsyncPanZoomController::FlushRepaintForOverscrollHandoff() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
RequestContentRepaint();
UpdateSharedCompositorFrameMetrics();
}
void AsyncPanZoomController::FlushRepaintForNewInputBlock() {
APZC_LOG("%p flushing repaint for new input block\n", this);
RecursiveMutexAutoLock lock(mRecursiveMutex);
RequestContentRepaint();
UpdateSharedCompositorFrameMetrics();
}
bool AsyncPanZoomController::SnapBackIfOverscrolled() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
// It's possible that we're already in the middle of an overscroll
// animation - if so, don't start a new one.
if (IsOverscrolled() && mState != OVERSCROLL_ANIMATION) {
APZC_LOG("%p is overscrolled, starting snap-back\n", this);
StartOverscrollAnimation(ParentLayerPoint(0, 0));
return true;
}
// If we don't kick off an overscroll animation, we still need to ask the
// main thread to snap to any nearby snap points, assuming we haven't already
// done so when we started this fling
if (mState != FLING) {
ScrollSnap();
}
return false;
}
bool AsyncPanZoomController::IsFlingingFast() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (mState == FLING && GetVelocityVector().Length() >
StaticPrefs::apz_fling_stop_on_tap_threshold()) {
APZC_LOG("%p is moving fast\n", this);
return true;
}
return false;
}
bool AsyncPanZoomController::IsPannable() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return mX.CanScroll() || mY.CanScroll();
}
bool AsyncPanZoomController::IsScrollInfoLayer() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return Metrics().IsScrollInfoLayer();
}
int32_t AsyncPanZoomController::GetLastTouchIdentifier() const {
RefPtr<GestureEventListener> listener = GetGestureEventListener();
return listener ? listener->GetLastTouchIdentifier() : -1;
}
void AsyncPanZoomController::RequestContentRepaint(
RepaintUpdateType aUpdateType) {
// Reinvoke this method on the repaint thread if it's not there already. It's
// important to do this before the call to CalculatePendingDisplayPort, so
// that CalculatePendingDisplayPort uses the most recent available version of
// Metrics(). just before the paint request is dispatched to content.
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (!controller) {
return;
}
if (!controller->IsRepaintThread()) {
// Even though we want to do the actual repaint request on the repaint
// thread, we want to update the expected gecko metrics synchronously.
// Otherwise we introduce a race condition where we might read from the
// expected gecko metrics on the controller thread before or after it gets
// updated on the repaint thread, when in fact we always want the updated
// version when reading.
{ // scope lock
RecursiveMutexAutoLock lock(mRecursiveMutex);
mExpectedGeckoMetrics.UpdateFrom(Metrics());
}
// use the local variable to resolve the function overload.
auto func =
static_cast<void (AsyncPanZoomController::*)(RepaintUpdateType)>(
&AsyncPanZoomController::RequestContentRepaint);
controller->DispatchToRepaintThread(NewRunnableMethod<RepaintUpdateType>(
"layers::AsyncPanZoomController::RequestContentRepaint", this, func,
aUpdateType));
return;
}
MOZ_ASSERT(controller->IsRepaintThread());
RecursiveMutexAutoLock lock(mRecursiveMutex);
ParentLayerPoint velocity = GetVelocityVector();
ScreenMargin displayportMargins = CalculatePendingDisplayPort(
Metrics(), velocity,
mState == PINCHING ? ZoomInProgress::Yes : ZoomInProgress::No);
Metrics().SetPaintRequestTime(TimeStamp::Now());
RequestContentRepaint(Metrics(), velocity, displayportMargins, aUpdateType);
}
static CSSRect GetDisplayPortRect(const FrameMetrics& aFrameMetrics,
const ScreenMargin& aDisplayportMargins) {
// This computation is based on what happens in CalculatePendingDisplayPort.
// If that changes then this might need to change too.
// Note that the display port rect APZ computes is relative to the visual
// scroll offset. It's adjusted to be relative to the layout scroll offset
// when the main thread processes a repaint request (in
// APZCCallbackHelper::AdjustDisplayPortForScrollDelta()) and ultimately
// applied (in DisplayPortUtils::GetDisplayPort()) in this adjusted form.
CSSRect baseRect(aFrameMetrics.GetVisualScrollOffset(),
aFrameMetrics.CalculateBoundedCompositedSizeInCssPixels());
baseRect.Inflate(aDisplayportMargins /
aFrameMetrics.DisplayportPixelsPerCSSPixel());
return baseRect;
}
void AsyncPanZoomController::RequestContentRepaint(
const FrameMetrics& aFrameMetrics, const ParentLayerPoint& aVelocity,
const ScreenMargin& aDisplayportMargins, RepaintUpdateType aUpdateType) {
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (!controller) {
return;
}
MOZ_ASSERT(controller->IsRepaintThread());
const bool isAnimationInProgress = !!mAnimation;
RepaintRequest request(aFrameMetrics, aDisplayportMargins, aUpdateType,
isAnimationInProgress);
// If we're trying to paint what we already think is painted, discard this
// request since it's a pointless paint.
if (request.GetDisplayPortMargins().WithinEpsilonOf(
mLastPaintRequestMetrics.GetDisplayPortMargins(), EPSILON) &&
request.GetVisualScrollOffset().WithinEpsilonOf(
mLastPaintRequestMetrics.GetVisualScrollOffset(), EPSILON) &&
request.GetPresShellResolution() ==
mLastPaintRequestMetrics.GetPresShellResolution() &&
request.GetZoom() == mLastPaintRequestMetrics.GetZoom() &&
request.GetLayoutViewport().WithinEpsilonOf(
mLastPaintRequestMetrics.GetLayoutViewport(), EPSILON) &&
request.GetScrollGeneration() ==
mLastPaintRequestMetrics.GetScrollGeneration() &&
request.GetScrollUpdateType() ==
mLastPaintRequestMetrics.GetScrollUpdateType() &&
request.IsAnimationInProgress() ==
mLastPaintRequestMetrics.IsAnimationInProgress()) {
return;
}
APZC_LOGV("%p requesting content repaint %s", this,
ToString(request).c_str());
{ // scope lock
MutexAutoLock lock(mCheckerboardEventLock);
if (mCheckerboardEvent && mCheckerboardEvent->IsRecordingTrace()) {
std::stringstream info;
info << " velocity " << aVelocity;
std::string str = info.str();
mCheckerboardEvent->UpdateRendertraceProperty(
CheckerboardEvent::RequestedDisplayPort,
GetDisplayPortRect(aFrameMetrics, aDisplayportMargins), str);
}
}
controller->RequestContentRepaint(request);
mExpectedGeckoMetrics.UpdateFrom(aFrameMetrics);
mLastPaintRequestMetrics = request;
// We're holding the APZC lock here, so redispatch this so we can get
// the tree lock without the APZC lock.
controller->DispatchToRepaintThread(
NewRunnableMethod<AsyncPanZoomController*>(
"layers::APZCTreeManager::SendSubtreeTransformsToChromeMainThread",
GetApzcTreeManager(),
&APZCTreeManager::SendSubtreeTransformsToChromeMainThread, this));
}
bool AsyncPanZoomController::UpdateAnimation(
const RecursiveMutexAutoLock& aProofOfLock, const SampleTime& aSampleTime,
nsTArray<RefPtr<Runnable>>* aOutDeferredTasks) {
AssertOnSamplerThread();
// This function may get called multiple with the same sample time, if we
// composite multiple times at the same timestamp.
// However we only want to do one animation step per composition so we need
// to deduplicate these calls first.
if (mLastSampleTime == aSampleTime) {
return !!mAnimation;
}
// We're at a new timestamp, so advance to the next sample in the deque, if
// there is one. That one will be used for all the code that reads the
// eForCompositing transforms in this vsync interval.
AdvanceToNextSample();
// And then create a new sample, which will be used in the *next* vsync
// interval. We do the sample at this point and not later in order to try
// and enforce one frame delay between computing the async transform and
// compositing it to the screen. This one-frame delay gives code running on
// the main thread a chance to try and respond to the scroll position change,
// so that e.g. a main-thread animation can stay in sync with user-driven
// scrolling or a compositor animation.
bool needComposite = SampleCompositedAsyncTransform(aProofOfLock);
TimeDuration sampleTimeDelta = aSampleTime - mLastSampleTime;
mLastSampleTime = aSampleTime;
if (mAnimation) {
bool continueAnimation = mAnimation->Sample(Metrics(), sampleTimeDelta);
bool wantsRepaints = mAnimation->WantsRepaints();
*aOutDeferredTasks = mAnimation->TakeDeferredTasks();
if (!continueAnimation) {
mAnimation = nullptr;
SetState(NOTHING);
}
// Request a repaint at the end of the animation in case something such as a
// call to NotifyLayersUpdated was invoked during the animation and Gecko's
// current state is some intermediate point of the animation.
if (!continueAnimation || wantsRepaints) {
RequestContentRepaint();
}
UpdateSharedCompositorFrameMetrics();
needComposite = true;
}
return needComposite;
}
AsyncTransformComponentMatrix AsyncPanZoomController::GetOverscrollTransform(
AsyncTransformConsumer aMode) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (aMode == eForCompositing && mScrollMetadata.IsApzForceDisabled()) {
return AsyncTransformComponentMatrix();
}
if (!IsOverscrolled()) {
return AsyncTransformComponentMatrix();
}
// The overscroll effect is a simple translation by the overscroll offset.
ParentLayerPoint overscrollOffset(-mX.GetOverscroll(), -mY.GetOverscroll());
return AsyncTransformComponentMatrix().PostTranslate(overscrollOffset.x,
overscrollOffset.y, 0);
}
bool AsyncPanZoomController::AdvanceAnimations(const SampleTime& aSampleTime) {
AssertOnSamplerThread();
// Don't send any state-change notifications until the end of the function,
// because we may go through some intermediate states while we finish
// animations and start new ones.
StateChangeNotificationBlocker blocker(this);
// The eventual return value of this function. The compositor needs to know
// whether or not to advance by a frame as soon as it can. For example, if a
// fling is happening, it has to keep compositing so that the animation is
// smooth. If an animation frame is requested, it is the compositor's
// responsibility to schedule a composite.
mAsyncTransformAppliedToContent = false;
bool requestAnimationFrame = false;
nsTArray<RefPtr<Runnable>> deferredTasks;
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
{ // scope lock
MutexAutoLock lock2(mCheckerboardEventLock);
// Update RendertraceProperty before UpdateAnimation() call, since
// the UpdateAnimation() updates effective ScrollOffset for next frame
// if APZFrameDelay is enabled.
if (mCheckerboardEvent) {
mCheckerboardEvent->UpdateRendertraceProperty(
CheckerboardEvent::UserVisible, GetVisibleRect(lock));
}
}
requestAnimationFrame = UpdateAnimation(lock, aSampleTime, &deferredTasks);
}
// Execute any deferred tasks queued up by mAnimation's Sample() (called by
// UpdateAnimation()). This needs to be done after the monitor is released
// since the tasks are allowed to call APZCTreeManager methods which can grab
// the tree lock.
for (uint32_t i = 0; i < deferredTasks.Length(); ++i) {
APZThreadUtils::RunOnControllerThread(std::move(deferredTasks[i]));
}
// If any of the deferred tasks starts a new animation, it will request a
// new composite directly, so we can just return requestAnimationFrame here.
return requestAnimationFrame;
}
CSSRect AsyncPanZoomController::GetCurrentAsyncLayoutViewport(
AsyncTransformConsumer aMode) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
AutoApplyAsyncTestAttributes testAttributeApplier(this, lock);
MOZ_ASSERT(Metrics().IsRootContent(),
"Only the root content APZC has a layout viewport");
return GetEffectiveLayoutViewport(aMode, lock);
}
ParentLayerPoint AsyncPanZoomController::GetCurrentAsyncScrollOffset(
AsyncTransformConsumer aMode) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
AutoApplyAsyncTestAttributes testAttributeApplier(this, lock);
return GetEffectiveScrollOffset(aMode, lock) * GetEffectiveZoom(aMode, lock);
}
CSSPoint AsyncPanZoomController::GetCurrentAsyncScrollOffsetInCssPixels(
AsyncTransformConsumer aMode) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
AutoApplyAsyncTestAttributes testAttributeApplier(this, lock);
return GetEffectiveScrollOffset(aMode, lock);
}
AsyncTransform AsyncPanZoomController::GetCurrentAsyncTransform(
AsyncTransformConsumer aMode, AsyncTransformComponents aComponents) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
AutoApplyAsyncTestAttributes testAttributeApplier(this, lock);
CSSToParentLayerScale2D effectiveZoom;
if (aComponents.contains(AsyncTransformComponent::eVisual)) {
effectiveZoom = GetEffectiveZoom(aMode, lock);
} else {
effectiveZoom =
Metrics().LayersPixelsPerCSSPixel() * LayerToParentLayerScale(1.0f);
}
LayerToParentLayerScale compositedAsyncZoom =
(effectiveZoom / Metrics().LayersPixelsPerCSSPixel()).ToScaleFactor();
ParentLayerPoint translation;
if (aComponents.contains(AsyncTransformComponent::eVisual)) {
// There is no "lastPaintVisualOffset" to subtract here; the visual offset
// is entirely async.
CSSPoint currentVisualOffset =
GetEffectiveScrollOffset(aMode, lock) -
GetEffectiveLayoutViewport(aMode, lock).TopLeft();
translation += currentVisualOffset * effectiveZoom;
}
if (aComponents.contains(AsyncTransformComponent::eLayout)) {
CSSPoint lastPaintLayoutOffset;
if (mLastContentPaintMetrics.IsScrollable()) {
lastPaintLayoutOffset = mLastContentPaintMetrics.GetLayoutScrollOffset();
}
CSSPoint currentLayoutOffset =
GetEffectiveLayoutViewport(aMode, lock).TopLeft();
translation +=
(currentLayoutOffset - lastPaintLayoutOffset) * effectiveZoom;
}
return AsyncTransform(compositedAsyncZoom, -translation);
}
AsyncTransformComponentMatrix
AsyncPanZoomController::GetCurrentAsyncTransformWithOverscroll(
AsyncTransformConsumer aMode, AsyncTransformComponents aComponents) const {
return AsyncTransformComponentMatrix(
GetCurrentAsyncTransform(aMode, aComponents)) *
GetOverscrollTransform(aMode);
}
LayoutDeviceToParentLayerScale AsyncPanZoomController::GetCurrentPinchZoomScale(
AsyncTransformConsumer aMode) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
AutoApplyAsyncTestAttributes testAttributeApplier(this, lock);
CSSToParentLayerScale2D scale = GetEffectiveZoom(aMode, lock);
// Note that in general the zoom might have different x- and y-scales.
// However, this function in particular is only used on the WebRender codepath
// for which the scales should always be the same.
return scale.ToScaleFactor() / Metrics().GetDevPixelsPerCSSPixel();
}
CSSRect AsyncPanZoomController::GetEffectiveLayoutViewport(
AsyncTransformConsumer aMode,
const RecursiveMutexAutoLock& aProofOfLock) const {
if (aMode == eForCompositing && mScrollMetadata.IsApzForceDisabled()) {
return mLastContentPaintMetrics.GetLayoutViewport();
}
if (aMode == eForCompositing) {
return mSampledState.front().GetLayoutViewport();
}
return Metrics().GetLayoutViewport();
}
CSSPoint AsyncPanZoomController::GetEffectiveScrollOffset(
AsyncTransformConsumer aMode,
const RecursiveMutexAutoLock& aProofOfLock) const {
if (aMode == eForCompositing && mScrollMetadata.IsApzForceDisabled()) {
return mLastContentPaintMetrics.GetVisualScrollOffset();
}
if (aMode == eForCompositing) {
return mSampledState.front().GetVisualScrollOffset();
}
return Metrics().GetVisualScrollOffset();
}
CSSToParentLayerScale2D AsyncPanZoomController::GetEffectiveZoom(
AsyncTransformConsumer aMode,
const RecursiveMutexAutoLock& aProofOfLock) const {
if (aMode == eForCompositing && mScrollMetadata.IsApzForceDisabled()) {
return mLastContentPaintMetrics.GetZoom();
}
if (aMode == eForCompositing) {
return mSampledState.front().GetZoom();
}
return Metrics().GetZoom();
}
void AsyncPanZoomController::AdvanceToNextSample() {
AssertOnSamplerThread();
RecursiveMutexAutoLock lock(mRecursiveMutex);
// Always keep at least one state in mSampledState.
if (mSampledState.size() > 1) {
mSampledState.pop_front();
}
}
bool AsyncPanZoomController::SampleCompositedAsyncTransform(
const RecursiveMutexAutoLock& aProofOfLock) {
MOZ_ASSERT(mSampledState.size() <= 2);
bool sampleChanged = (mSampledState.back() != SampledAPZCState(Metrics()));
mSampledState.emplace_back(Metrics(), std::move(mScrollPayload));
return sampleChanged;
}
void AsyncPanZoomController::ResampleCompositedAsyncTransform(
const RecursiveMutexAutoLock& aProofOfLock) {
// This only gets called during testing situations, so the fact that this
// drops the scroll payload from mSampledState.front() is not really a
// problem.
mSampledState.front() = SampledAPZCState(Metrics());
}
void AsyncPanZoomController::ApplyAsyncTestAttributes(
const RecursiveMutexAutoLock& aProofOfLock) {
if (mTestAttributeAppliers == 0) {
if (mTestAsyncScrollOffset != CSSPoint() ||
mTestAsyncZoom != LayerToParentLayerScale()) {
// TODO Currently we update Metrics() and resample, which will cause
// the very latest user input to get immediately captured in the sample,
// and may defeat our attempt at "frame delay" (i.e. delaying the user
// input from affecting composition by one frame).
// Instead, maybe we should just apply the mTest* stuff directly to
// mSampledState.front(). We can even save/restore that SampledAPZCState
// instance in the AutoApplyAsyncTestAttributes instead of Metrics().
Metrics().ZoomBy(mTestAsyncZoom.scale);
ScrollBy(mTestAsyncScrollOffset);
ResampleCompositedAsyncTransform(aProofOfLock);
}
}
++mTestAttributeAppliers;
}
void AsyncPanZoomController::UnapplyAsyncTestAttributes(
const RecursiveMutexAutoLock& aProofOfLock,
const FrameMetrics& aPrevFrameMetrics) {
MOZ_ASSERT(mTestAttributeAppliers >= 1);
--mTestAttributeAppliers;
if (mTestAttributeAppliers == 0) {
if (mTestAsyncScrollOffset != CSSPoint() ||
mTestAsyncZoom != LayerToParentLayerScale()) {
Metrics() = aPrevFrameMetrics;
ResampleCompositedAsyncTransform(aProofOfLock);
}
}
}
Matrix4x4 AsyncPanZoomController::GetTransformToLastDispatchedPaint() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
LayerPoint scrollChange = (mLastContentPaintMetrics.GetLayoutScrollOffset() -
mExpectedGeckoMetrics.GetVisualScrollOffset()) *
mLastContentPaintMetrics.GetDevPixelsPerCSSPixel() *
mLastContentPaintMetrics.GetCumulativeResolution();
// We're interested in the async zoom change. Factor out the content scale
// that may change when dragging the window to a monitor with a different
// content scale.
LayoutDeviceToParentLayerScale2D lastContentZoom =
mLastContentPaintMetrics.GetZoom() /
mLastContentPaintMetrics.GetDevPixelsPerCSSPixel();
LayoutDeviceToParentLayerScale2D lastDispatchedZoom =
mExpectedGeckoMetrics.GetZoom() /
mExpectedGeckoMetrics.GetDevPixelsPerCSSPixel();
gfxSize zoomChange(1.0, 1.0);
if (lastDispatchedZoom != LayoutDeviceToParentLayerScale2D(0, 0)) {
zoomChange = lastContentZoom / lastDispatchedZoom;
}
return Matrix4x4::Translation(scrollChange.x, scrollChange.y, 0)
.PostScale(zoomChange.width, zoomChange.height, 1);
}
CSSRect AsyncPanZoomController::GetVisibleRect(
const RecursiveMutexAutoLock& aProofOfLock) const {
AutoApplyAsyncTestAttributes testAttributeApplier(this, aProofOfLock);
CSSPoint currentScrollOffset = GetEffectiveScrollOffset(
AsyncPanZoomController::eForCompositing, aProofOfLock);
CSSRect visible = CSSRect(currentScrollOffset,
Metrics().CalculateCompositedSizeInCssPixels());
return visible;
}
uint32_t AsyncPanZoomController::GetCheckerboardMagnitude(
const ParentLayerRect& aClippedCompositionBounds) const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
CSSRect painted = mLastContentPaintMetrics.GetDisplayPort() +
mLastContentPaintMetrics.GetLayoutScrollOffset();
painted.Inflate(CSSMargin::FromAppUnits(
nsMargin(1, 1, 1, 1))); // fuzz for rounding error
CSSRect visible = GetVisibleRect(lock); // relative to scrolled frame origin
if (visible.IsEmpty() || painted.Contains(visible)) {
// early-exit if we're definitely not checkerboarding
return 0;
}
// aClippedCompositionBounds and Metrics().GetCompositionBounds() are both
// relative to the layer tree origin.
// The "*RelativeToItself*" variables are relative to the comp bounds origin
ParentLayerRect visiblePartOfCompBoundsRelativeToItself =
aClippedCompositionBounds - Metrics().GetCompositionBounds().TopLeft();
CSSRect visiblePartOfCompBoundsRelativeToItselfInCssSpace;
if (Metrics().GetZoom() != CSSToParentLayerScale2D(0, 0)) {
visiblePartOfCompBoundsRelativeToItselfInCssSpace =
(visiblePartOfCompBoundsRelativeToItself / Metrics().GetZoom());
}
// This one is relative to the scrolled frame origin, same as `visible`
CSSRect visiblePartOfCompBoundsInCssSpace =
visiblePartOfCompBoundsRelativeToItselfInCssSpace + visible.TopLeft();
visible = visible.Intersect(visiblePartOfCompBoundsInCssSpace);
CSSIntRegion checkerboard;
// Round so as to minimize checkerboarding; if we're only showing fractional
// pixels of checkerboarding it's not really worth counting
checkerboard.Sub(RoundedIn(visible), RoundedOut(painted));
uint32_t area = checkerboard.Area();
if (area) {
APZC_LOG_FM(Metrics(),
"%p is currently checkerboarding (painted %s visible %s)", this,
ToString(painted).c_str(), ToString(visible).c_str());
}
return area;
}
void AsyncPanZoomController::ReportCheckerboard(
const SampleTime& aSampleTime,
const ParentLayerRect& aClippedCompositionBounds) {
if (mLastCheckerboardReport == aSampleTime) {
// This function will get called multiple times for each APZC on a single
// composite (once for each layer it is attached to). Only report the
// checkerboard once per composite though.
return;
}
mLastCheckerboardReport = aSampleTime;
bool recordTrace = StaticPrefs::apz_record_checkerboarding();
bool forTelemetry = Telemetry::CanRecordExtended();
uint32_t magnitude = GetCheckerboardMagnitude(aClippedCompositionBounds);
// IsInTransformingState() acquires the APZC lock and thus needs to
// be called before acquiring mCheckerboardEventLock.
bool inTransformingState = IsInTransformingState();
MutexAutoLock lock(mCheckerboardEventLock);
if (!mCheckerboardEvent && (recordTrace || forTelemetry)) {
mCheckerboardEvent = MakeUnique<CheckerboardEvent>(recordTrace);
}
mPotentialCheckerboardTracker.InTransform(inTransformingState);
if (magnitude) {
mPotentialCheckerboardTracker.CheckerboardSeen();
}
UpdateCheckerboardEvent(lock, magnitude);
}
void AsyncPanZoomController::UpdateCheckerboardEvent(
const MutexAutoLock& aProofOfLock, uint32_t aMagnitude) {
if (mCheckerboardEvent && mCheckerboardEvent->RecordFrameInfo(aMagnitude)) {
// This checkerboard event is done. Report some metrics to telemetry.
mozilla::Telemetry::Accumulate(mozilla::Telemetry::CHECKERBOARD_SEVERITY,
mCheckerboardEvent->GetSeverity());
mozilla::Telemetry::Accumulate(mozilla::Telemetry::CHECKERBOARD_PEAK,
mCheckerboardEvent->GetPeak());
mozilla::Telemetry::Accumulate(
mozilla::Telemetry::CHECKERBOARD_DURATION,
(uint32_t)mCheckerboardEvent->GetDuration().ToMilliseconds());
mPotentialCheckerboardTracker.CheckerboardDone();
if (StaticPrefs::apz_record_checkerboarding()) {
// if the pref is enabled, also send it to the storage class. it may be
// chosen for public display on about:checkerboard, the hall of fame for
// checkerboard events.
uint32_t severity = mCheckerboardEvent->GetSeverity();
std::string log = mCheckerboardEvent->GetLog();
CheckerboardEventStorage::Report(severity, log);
}
mCheckerboardEvent = nullptr;
}
}
void AsyncPanZoomController::FlushActiveCheckerboardReport() {
MutexAutoLock lock(mCheckerboardEventLock);
// Pretend like we got a frame with 0 pixels checkerboarded. This will
// terminate the checkerboard event and flush it out
UpdateCheckerboardEvent(lock, 0);
}
void AsyncPanZoomController::NotifyLayersUpdated(
const ScrollMetadata& aScrollMetadata, bool aIsFirstPaint,
bool aThisLayerTreeUpdated) {
AssertOnUpdaterThread();
RecursiveMutexAutoLock lock(mRecursiveMutex);
bool isDefault = mScrollMetadata.IsDefault();
const FrameMetrics& aLayerMetrics = aScrollMetadata.GetMetrics();
if ((aScrollMetadata == mLastContentPaintMetadata) && !isDefault) {
// No new information here, skip it.
APZC_LOGV("%p NotifyLayersUpdated short-circuit\n", this);
return;
}
// If the Metrics scroll offset is different from the last scroll offset
// that the main-thread sent us, then we know that the user has been doing
// something that triggers a scroll. This check is the APZ equivalent of the
// check on the main-thread at
// https://hg.mozilla.org/mozilla-central/file/97a52326b06a/layout/generic/nsGfxScrollFrame.cpp#l4050
// There is code below (the use site of userScrolled) that prevents a
// restored- scroll-position update from overwriting a user scroll, again
// equivalent to how the main thread code does the same thing.
// XXX Suspicious comparison between layout and visual scroll offsets.
// This may not do the right thing when we're zoomed in.
CSSPoint lastScrollOffset = mLastContentPaintMetrics.GetLayoutScrollOffset();
bool userScrolled = !FuzzyEqualsAdditive(Metrics().GetVisualScrollOffset().x,
lastScrollOffset.x) ||
!FuzzyEqualsAdditive(Metrics().GetVisualScrollOffset().y,
lastScrollOffset.y);
if (aScrollMetadata.DidContentGetPainted()) {
mLastContentPaintMetadata = aScrollMetadata;
}
mScrollMetadata.SetScrollParentId(aScrollMetadata.GetScrollParentId());
APZC_LOGV_FM(aLayerMetrics,
"%p got a NotifyLayersUpdated with aIsFirstPaint=%d, "
"aThisLayerTreeUpdated=%d",
this, aIsFirstPaint, aThisLayerTreeUpdated);
{ // scope lock
MutexAutoLock lock(mCheckerboardEventLock);
if (mCheckerboardEvent && mCheckerboardEvent->IsRecordingTrace()) {
std::string str;
if (aThisLayerTreeUpdated) {
if (!aLayerMetrics.GetPaintRequestTime().IsNull()) {
// Note that we might get the paint request time as non-null, but with
// aThisLayerTreeUpdated false. That can happen if we get a layer
// transaction from a different process right after we get the layer
// transaction with aThisLayerTreeUpdated == true. In this case we
// want to ignore the paint request time because it was already dumped
// in the previous layer transaction.
TimeDuration paintTime =
TimeStamp::Now() - aLayerMetrics.GetPaintRequestTime();
std::stringstream info;
info << " painttime " << paintTime.ToMilliseconds();
str = info.str();
} else {
// This might be indicative of a wasted paint particularly if it
// happens during a checkerboard event.
str = " (this layertree updated)";
}
}
mCheckerboardEvent->UpdateRendertraceProperty(
CheckerboardEvent::Page, aLayerMetrics.GetScrollableRect());
mCheckerboardEvent->UpdateRendertraceProperty(
CheckerboardEvent::PaintedDisplayPort,
aLayerMetrics.GetDisplayPort() +
aLayerMetrics.GetLayoutScrollOffset(),
str);
if (!aLayerMetrics.GetCriticalDisplayPort().IsEmpty()) {
mCheckerboardEvent->UpdateRendertraceProperty(
CheckerboardEvent::PaintedCriticalDisplayPort,
aLayerMetrics.GetCriticalDisplayPort() +
aLayerMetrics.GetLayoutScrollOffset());
}
}
}
// The main thread may send us a visual scroll offset update. This is
// different from a layout viewport offset update in that the layout viewport
// offset is limited to the layout scroll range, while the visual viewport
// offset is not.
// However, there are some conditions in which the layout update will clobber
// the visual update, and we want to ignore the visual update in those cases.
// This variable tracks that.
bool ignoreVisualUpdate = false;
// TODO if we're in a drag and scrollOffsetUpdated is set then we want to
// ignore it
bool needContentRepaint = false;
RepaintUpdateType contentRepaintType = RepaintUpdateType::eNone;
bool viewportSizeUpdated = false;
bool needToReclampScroll = false;
if ((aIsFirstPaint && aThisLayerTreeUpdated) || isDefault) {
// Initialize our internal state to something sane when the content
// that was just painted is something we knew nothing about previously
CancelAnimation();
// Keep our existing scroll generation, if there are scroll updates. In this
// case we'll update our scroll generation when processing the scroll update
// array below. If there are no scroll updates, take the generation from the
// incoming metrics. Bug 1662019 will simplify this later.
ScrollGeneration oldScrollGeneration = Metrics().GetScrollGeneration();
mScrollMetadata = aScrollMetadata;
if (!aScrollMetadata.GetScrollUpdates().IsEmpty()) {
Metrics().SetScrollGeneration(oldScrollGeneration);
}
mExpectedGeckoMetrics.UpdateFrom(aLayerMetrics);
ShareCompositorFrameMetrics();
for (auto& sampledState : mSampledState) {
sampledState.UpdateScrollProperties(Metrics());
sampledState.UpdateZoomProperties(Metrics());
}
// Make sure we have an up-to-date set of displayport margins.
needContentRepaint = true;
} else {
// If we're not taking the aLayerMetrics wholesale we still need to pull
// in some things into our local Metrics() because these things are
// determined by Gecko and our copy in Metrics() may be stale.
if (Metrics().GetLayoutViewport().Size() !=
aLayerMetrics.GetLayoutViewport().Size()) {
CSSRect layoutViewport = Metrics().GetLayoutViewport();
// The offset will be updated if necessary via
// RecalculateLayoutViewportOffset().
layoutViewport.SizeTo(aLayerMetrics.GetLayoutViewport().Size());
Metrics().SetLayoutViewport(layoutViewport);
needContentRepaint = true;
viewportSizeUpdated = true;
}
// TODO: Rely entirely on |aScrollMetadata.IsResolutionUpdated()| to
// determine which branch to take, and drop the other conditions.
if (FuzzyEqualsAdditive(Metrics().GetCompositionBounds().Width(),
aLayerMetrics.GetCompositionBounds().Width()) &&
Metrics().GetDevPixelsPerCSSPixel() ==
aLayerMetrics.GetDevPixelsPerCSSPixel() &&
!viewportSizeUpdated && !aScrollMetadata.IsResolutionUpdated()) {
// Any change to the pres shell resolution was requested by APZ and is
// already included in our zoom; however, other components of the
// cumulative resolution (a parent document's pres-shell resolution, or
// the css-driven resolution) may have changed, and we need to update
// our zoom to reflect that. Note that we can't just take
// aLayerMetrics.mZoom because the APZ may have additional async zoom
// since the repaint request.
gfxSize totalResolutionChange(1.0, 1.0);
if (Metrics().GetCumulativeResolution() !=
LayoutDeviceToLayerScale2D(0, 0)) {
totalResolutionChange = aLayerMetrics.GetCumulativeResolution() /
Metrics().GetCumulativeResolution();
}
float presShellResolutionChange = aLayerMetrics.GetPresShellResolution() /
Metrics().GetPresShellResolution();
if (presShellResolutionChange != 1.0f) {
needContentRepaint = true;
}
Metrics().ZoomBy(totalResolutionChange / presShellResolutionChange);
for (auto& sampledState : mSampledState) {
sampledState.ZoomBy(totalResolutionChange / presShellResolutionChange);
}
} else {
// Take the new zoom as either device scale or composition width or
// viewport size got changed (e.g. due to orientation change, or content
// changing the meta-viewport tag).
Metrics().SetZoom(aLayerMetrics.GetZoom());
for (auto& sampledState : mSampledState) {
sampledState.UpdateZoomProperties(aLayerMetrics);
}
Metrics().SetDevPixelsPerCSSPixel(
aLayerMetrics.GetDevPixelsPerCSSPixel());
}
if (!Metrics().GetScrollableRect().IsEqualEdges(
aLayerMetrics.GetScrollableRect())) {
Metrics().SetScrollableRect(aLayerMetrics.GetScrollableRect());
needContentRepaint = true;
needToReclampScroll = true;
}
if (!Metrics().GetCompositionBounds().IsEqualEdges(
aLayerMetrics.GetCompositionBounds())) {
Metrics().SetCompositionBounds(aLayerMetrics.GetCompositionBounds());
needToReclampScroll = true;
}
if (Metrics().IsRootContent() &&
Metrics().GetCompositionSizeWithoutDynamicToolbar() !=
aLayerMetrics.GetCompositionSizeWithoutDynamicToolbar()) {
Metrics().SetCompositionSizeWithoutDynamicToolbar(
aLayerMetrics.GetCompositionSizeWithoutDynamicToolbar());
needToReclampScroll = true;
}
Metrics().SetRootCompositionSize(aLayerMetrics.GetRootCompositionSize());
Metrics().SetPresShellResolution(aLayerMetrics.GetPresShellResolution());
Metrics().SetCumulativeResolution(aLayerMetrics.GetCumulativeResolution());
mScrollMetadata.SetHasScrollgrab(aScrollMetadata.GetHasScrollgrab());
mScrollMetadata.SetLineScrollAmount(aScrollMetadata.GetLineScrollAmount());
mScrollMetadata.SetPageScrollAmount(aScrollMetadata.GetPageScrollAmount());
mScrollMetadata.SetSnapInfo(ScrollSnapInfo(aScrollMetadata.GetSnapInfo()));
// The scroll clip can differ between layers associated a given scroll
// frame, so APZC (which keeps a single copy of ScrollMetadata per scroll
// frame) has no business using it.
mScrollMetadata.SetScrollClip(Nothing());
mScrollMetadata.SetIsLayersIdRoot(aScrollMetadata.IsLayersIdRoot());
mScrollMetadata.SetIsAutoDirRootContentRTL(
aScrollMetadata.IsAutoDirRootContentRTL());
Metrics().SetIsScrollInfoLayer(aLayerMetrics.IsScrollInfoLayer());
mScrollMetadata.SetForceDisableApz(aScrollMetadata.IsApzForceDisabled());
mScrollMetadata.SetIsRDMTouchSimulationActive(
aScrollMetadata.GetIsRDMTouchSimulationActive());
mScrollMetadata.SetDisregardedDirection(
aScrollMetadata.GetDisregardedDirection());
mScrollMetadata.SetOverscrollBehavior(
aScrollMetadata.GetOverscrollBehavior());
}
bool scrollOffsetUpdated = false;
for (const auto& scrollUpdate : aScrollMetadata.GetScrollUpdates()) {
APZC_LOG("%p processing scroll update %s\n", this,
ToString(scrollUpdate).c_str());
if (!(Metrics().GetScrollGeneration() < scrollUpdate.GetGeneration())) {
// This is stale, let's ignore it
APZC_LOG("%p scrollupdate generation stale, dropping\n", this);
continue;
}
Metrics().SetScrollGeneration(scrollUpdate.GetGeneration());
MOZ_ASSERT(scrollUpdate.GetOrigin() != ScrollOrigin::Apz);
if (userScrolled &&
!nsLayoutUtils::CanScrollOriginClobberApz(scrollUpdate.GetOrigin())) {
APZC_LOG("%p scrollupdate cannot clobber APZ userScrolled\n", this);
continue;
}
// XXX: if we get here, |scrollUpdate| is clobbering APZ, so we may want
// to reset |userScrolled| back to false so that subsequent scrollUpdates
// in this loop don't get dropped by the check above. Need to add a test
// that exercises this scenario, as we don't currently have one.
scrollOffsetUpdated = true;
if (scrollUpdate.GetMode() == ScrollMode::Smooth ||
scrollUpdate.GetMode() == ScrollMode::SmoothMsd) {
// Requests to animate the visual scroll position override requests to
// simply update the visual scroll offset to a particular point. Since
// we have an animation request, we set ignoreVisualUpdate to true to
// indicate we don't need to apply the visual scroll update in
// aLayerMetrics.
ignoreVisualUpdate = true;
// For relative updates we want to add the relative offset to any existing
// destination, or the current visual offset if there is no existing
// destination.
CSSPoint base = GetCurrentAnimationDestination(lock).valueOr(
Metrics().GetVisualScrollOffset());
CSSPoint destination;
if (scrollUpdate.GetType() == ScrollUpdateType::Relative) {
CSSPoint delta =
scrollUpdate.GetDestination() - scrollUpdate.GetSource();
APZC_LOG("%p relative smooth scrolling from %s by %s\n", this,
ToString(base).c_str(), ToString(delta).c_str());
destination = Metrics().CalculateScrollRange().ClampPoint(base + delta);
} else if (scrollUpdate.GetType() == ScrollUpdateType::PureRelative) {
CSSPoint delta = scrollUpdate.GetDelta();
APZC_LOG("%p pure-relative smooth scrolling from %s by %s\n", this,
ToString(base).c_str(), ToString(delta).c_str());
destination = Metrics().CalculateScrollRange().ClampPoint(base + delta);
} else {
APZC_LOG("%p smooth scrolling to %s\n", this,
ToString(scrollUpdate.GetDestination()).c_str());
destination = scrollUpdate.GetDestination();
}
if (scrollUpdate.GetMode() == ScrollMode::SmoothMsd) {
SmoothMsdScrollTo(destination);
} else {
MOZ_ASSERT(scrollUpdate.GetMode() == ScrollMode::Smooth);
SmoothScrollTo(destination, scrollUpdate.GetOrigin());
}
continue;
}
MOZ_ASSERT(scrollUpdate.GetMode() == ScrollMode::Instant ||
scrollUpdate.GetMode() == ScrollMode::Normal);
// If the layout update is of a higher priority than the visual update, then
// we don't want to apply the visual update.
// If the layout update is of a clobbering type (or a smooth scroll request,
// which is handled above) then it takes precedence over an eRestore visual
// update. But we also allow the possibility for the main thread to ask us
// to scroll both the layout and visual viewports to distinct (but
// compatible) locations (via e.g. both updates being of a non-clobbering/
// eRestore type).
if (nsLayoutUtils::CanScrollOriginClobberApz(scrollUpdate.GetOrigin()) &&
aLayerMetrics.GetVisualScrollUpdateType() !=
FrameMetrics::eMainThread) {
ignoreVisualUpdate = true;
}
Maybe<CSSPoint> relativeDelta;
if (scrollUpdate.GetType() == ScrollUpdateType::Relative) {
APZC_LOG(
"%p relative updating scroll offset from %s by %s\n", this,
ToString(Metrics().GetVisualScrollOffset()).c_str(),
ToString(scrollUpdate.GetDestination() - scrollUpdate.GetSource())
.c_str());
// It's possible that the main thread has ignored an APZ scroll offset
// update for the pending relative scroll that we have just received.
// When this happens, we need to send a new scroll offset update with
// the combined scroll offset or else the main thread may have an
// incorrect scroll offset for a period of time.
if (Metrics().HasPendingScroll(aLayerMetrics)) {
needContentRepaint = true;
contentRepaintType = RepaintUpdateType::eUserAction;
}
relativeDelta =
Some(Metrics().ApplyRelativeScrollUpdateFrom(scrollUpdate));
Metrics().RecalculateLayoutViewportOffset();
} else if (scrollUpdate.GetType() == ScrollUpdateType::PureRelative) {
APZC_LOG("%p pure-relative updating scroll offset from %s by %s\n", this,
ToString(Metrics().GetVisualScrollOffset()).c_str(),
ToString(scrollUpdate.GetDelta()).c_str());
// Always need a repaint request with a repaint type for pure relative
// scrolls because apz is doing the scroll at the main thread's request.
// The main thread has not updated it's scroll offset yet, it is depending
// on apz to tell it where to scroll.
needContentRepaint = true;
contentRepaintType = RepaintUpdateType::eVisualUpdate;
// We have to ignore a visual scroll offset update otherwise it will
// clobber the relative scrolling we are about to do. We perform
// visualScrollOffset = visualScrollOffset + delta. Then the
// visualScrollOffsetUpdated block below will do visualScrollOffset =
// aLayerMetrics.GetVisualDestination(). We need visual scroll offset
// updates to be incorporated into this scroll update loop to properly fix
// this.
ignoreVisualUpdate = true;
relativeDelta =
Some(Metrics().ApplyPureRelativeScrollUpdateFrom(scrollUpdate));
Metrics().RecalculateLayoutViewportOffset();
} else {
APZC_LOG("%p updating scroll offset from %s to %s\n", this,
ToString(Metrics().GetVisualScrollOffset()).c_str(),
ToString(scrollUpdate.GetDestination()).c_str());
Metrics().ApplyScrollUpdateFrom(scrollUpdate);
Metrics().RecalculateLayoutViewportOffset();
}
// If an animation is underway, tell it about the scroll offset update.
// Some animations can handle some scroll offset updates and continue
// running. Those that can't will return false, and we cancel them.
if (ShouldCancelAnimationForScrollUpdate(relativeDelta)) {
// Cancel the animation (which might also trigger a repaint request)
// after we update the scroll offset above. Otherwise we can be left
// in a state where things are out of sync.
CancelAnimation();
}
}
if (scrollOffsetUpdated) {
for (auto& sampledState : mSampledState) {
sampledState.UpdateScrollProperties(Metrics());
}
// Because of the scroll generation update, any inflight paint requests
// are going to be ignored by layout, and so mExpectedGeckoMetrics becomes
// incorrect for the purposes of calculating the LD transform. To correct
// this we need to update mExpectedGeckoMetrics to be the last thing we
// know was painted by Gecko.
mExpectedGeckoMetrics.UpdateFrom(aLayerMetrics);
// Since the scroll offset has changed, we need to recompute the
// displayport margins and send them to layout. Otherwise there might be
// scenarios where for example we scroll from the top of a page (where the
// top displayport margin is zero) to the bottom of a page, which will
// result in a displayport that doesn't extend upwards at all.
// Note that even if the CancelAnimation call above requested a repaint
// this is fine because we already have repaint request deduplication.
needContentRepaint = true;
// Since the main-thread scroll offset changed we should trigger a
// recomposite to make sure it becomes user-visible.
ScheduleComposite();
} else if (needToReclampScroll) {
// Even if we didn't accept a new scroll offset from content, the
// scrollable rect or composition bounds may have changed in a way that
// makes our local scroll offset out of bounds, so re-clamp it.
ClampAndSetVisualScrollOffset(Metrics().GetVisualScrollOffset());
for (auto& sampledState : mSampledState) {
sampledState.ClampVisualScrollOffset(Metrics());
}
}
// If `isDefault` is true, this APZC is a "new" one (this is the first time
// it's getting a NotifyLayersUpdated call). In this case we want to apply the
// visual scroll offset from the main thread to our scroll offset.
// The main thread may also ask us to scroll the visual viewport to a
// particular location. However, in all cases, we want to ignore the visual
// offset update if ignoreVisualUpdate is true, because we're clobbering
// the visual update with a layout update.
bool visualScrollOffsetUpdated =
!ignoreVisualUpdate &&
(isDefault ||
aLayerMetrics.GetVisualScrollUpdateType() != FrameMetrics::eNone);
if (visualScrollOffsetUpdated) {
APZC_LOG("%p updating visual scroll offset from %s to %s (updateType %d)\n",
this, ToString(Metrics().GetVisualScrollOffset()).c_str(),
ToString(aLayerMetrics.GetVisualDestination()).c_str(),
(int)aLayerMetrics.GetVisualScrollUpdateType());
Metrics().ClampAndSetVisualScrollOffset(
aLayerMetrics.GetVisualDestination());
// The rest of this branch largely follows the code in the
// |if (scrollOffsetUpdated)| branch above. Eventually it should get
// merged into that branch.
Metrics().RecalculateLayoutViewportOffset();
for (auto& sampledState : mSampledState) {
sampledState.UpdateScrollProperties(Metrics());
}
mExpectedGeckoMetrics.UpdateFrom(aLayerMetrics);
if (ShouldCancelAnimationForScrollUpdate(Nothing())) {
CancelAnimation();
}
// The main thread did not actually paint a displayport at the target
// visual offset, so we need to ask it to repaint. We need to set the
// contentRepaintType to something other than eNone, otherwise the main
// thread will short-circuit the repaint request.
// Don't do this for eRestore visual updates as a repaint coming from APZ
// breaks the scroll offset restoration mechanism.
needContentRepaint = true;
if (aLayerMetrics.GetVisualScrollUpdateType() ==
FrameMetrics::eMainThread) {
contentRepaintType = RepaintUpdateType::eVisualUpdate;
}
ScheduleComposite();
}
if (viewportSizeUpdated) {
// While we want to accept the main thread's layout viewport _size_,
// its position may be out of date in light of async scrolling, to
// adjust it if necessary to make sure it continues to enclose the
// visual viewport.
// Note: it's important to do this _after_ we've accepted any
// updated composition bounds.
Metrics().RecalculateLayoutViewportOffset();
}
if (needContentRepaint) {
// This repaint request could be driven by a user action if we accept a
// relative scroll offset update
RequestContentRepaint(contentRepaintType);
}
UpdateSharedCompositorFrameMetrics();
}
FrameMetrics& AsyncPanZoomController::Metrics() {
mRecursiveMutex.AssertCurrentThreadIn();
return mScrollMetadata.GetMetrics();
}
const FrameMetrics& AsyncPanZoomController::Metrics() const {
mRecursiveMutex.AssertCurrentThreadIn();
return mScrollMetadata.GetMetrics();
}
GeckoViewMetrics AsyncPanZoomController::GetGeckoViewMetrics() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return GeckoViewMetrics{GetEffectiveScrollOffset(eForCompositing, lock),
GetEffectiveZoom(eForCompositing, lock)};
}
bool AsyncPanZoomController::UpdateRootFrameMetricsIfChanged(
GeckoViewMetrics& aMetrics) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (!Metrics().IsRootContent()) {
return false;
}
GeckoViewMetrics newMetrics = GetGeckoViewMetrics();
bool hasChanged = RoundedToInt(aMetrics.mVisualScrollOffset) !=
RoundedToInt(newMetrics.mVisualScrollOffset) ||
aMetrics.mZoom != newMetrics.mZoom;
if (hasChanged) {
aMetrics = newMetrics;
}
return hasChanged;
}
const FrameMetrics& AsyncPanZoomController::GetFrameMetrics() const {
return Metrics();
}
const ScrollMetadata& AsyncPanZoomController::GetScrollMetadata() const {
mRecursiveMutex.AssertCurrentThreadIn();
return mScrollMetadata;
}
void AsyncPanZoomController::AssertOnSamplerThread() const {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
treeManagerLocal->AssertOnSamplerThread();
}
}
void AsyncPanZoomController::AssertOnUpdaterThread() const {
if (APZCTreeManager* treeManagerLocal = GetApzcTreeManager()) {
treeManagerLocal->AssertOnUpdaterThread();
}
}
APZCTreeManager* AsyncPanZoomController::GetApzcTreeManager() const {
mRecursiveMutex.AssertNotCurrentThreadIn();
return mTreeManager;
}
void AsyncPanZoomController::ZoomToRect(CSSRect aRect, const uint32_t aFlags) {
if (!aRect.IsFinite()) {
NS_WARNING("ZoomToRect got called with a non-finite rect; ignoring...");
return;
}
if (aRect.IsEmpty() && (aFlags & DISABLE_ZOOM_OUT)) {
// Double-tap-to-zooming uses an empty rect to mean "zoom out".
// If zooming out is disabled, an empty rect is nonsensical
// and will produce undesirable scrolling.
NS_WARNING(
"ZoomToRect got called with an empty rect and zoom out disabled; "
"ignoring...");
return;
}
SetState(ANIMATING_ZOOM);
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
// Only the root APZC is zoomable, and the root APZC is not allowed to have
// different x and y scales. If it did, the calculations in this function
// would have to be adjusted (as e.g. it would no longer be valid to take
// the minimum or maximum of the ratios of the widths and heights of the
// page rect and the composition bounds).
MOZ_ASSERT(Metrics().IsRootContent());
MOZ_ASSERT(Metrics().GetZoom().AreScalesSame());
ParentLayerRect compositionBounds = Metrics().GetCompositionBounds();
CSSRect cssPageRect = Metrics().GetScrollableRect();
CSSPoint scrollOffset = Metrics().GetVisualScrollOffset();
CSSToParentLayerScale currentZoom = Metrics().GetZoom().ToScaleFactor();
CSSToParentLayerScale targetZoom;
// The minimum zoom to prevent over-zoom-out.
// If the zoom factor is lower than this (i.e. we are zoomed more into the
// page), then the CSS content rect, in layers pixels, will be smaller than
// the composition bounds. If this happens, we can't fill the target
// composited area with this frame.
CSSToParentLayerScale localMinZoom(
std::max(mZoomConstraints.mMinZoom.scale,
std::max(compositionBounds.Width() / cssPageRect.Width(),
compositionBounds.Height() / cssPageRect.Height())));
CSSToParentLayerScale localMaxZoom =
std::max(localMinZoom, mZoomConstraints.mMaxZoom);
if (!aRect.IsEmpty()) {
// Intersect the zoom-to-rect to the CSS rect to make sure it fits.
aRect = aRect.Intersect(cssPageRect);
targetZoom = CSSToParentLayerScale(
std::min(compositionBounds.Width() / aRect.Width(),
compositionBounds.Height() / aRect.Height()));
if (aFlags & DISABLE_ZOOM_OUT) {
targetZoom = std::max(targetZoom, currentZoom);
}
}
// 1. If the rect is empty, the content-side logic for handling a double-tap
// requested that we zoom out.
// 2. currentZoom is equal to mZoomConstraints.mMaxZoom and user still
// double-tapping it
// 3. currentZoom is equal to localMinZoom and user still double-tapping it
// Treat these three cases as a request to zoom out as much as possible.
bool zoomOut;
if (aFlags & DISABLE_ZOOM_OUT) {
zoomOut = false;
} else {
zoomOut = aRect.IsEmpty() ||
(currentZoom == localMaxZoom && targetZoom >= localMaxZoom) ||
(currentZoom == localMinZoom && targetZoom <= localMinZoom);
}
if (zoomOut) {
CSSSize compositedSize = Metrics().CalculateCompositedSizeInCssPixels();
float y = scrollOffset.y;
float newHeight =
cssPageRect.Width() * (compositedSize.height / compositedSize.width);
float dh = compositedSize.height - newHeight;
aRect = CSSRect(0.0f, y + dh / 2, cssPageRect.Width(), newHeight);
aRect = aRect.Intersect(cssPageRect);
targetZoom = CSSToParentLayerScale(
std::min(compositionBounds.Width() / aRect.Width(),
compositionBounds.Height() / aRect.Height()));
}
targetZoom.scale =
clamped(targetZoom.scale, localMinZoom.scale, localMaxZoom.scale);
FrameMetrics endZoomToMetrics = Metrics();
if (aFlags & PAN_INTO_VIEW_ONLY) {
targetZoom = currentZoom;
} else if (aFlags & ONLY_ZOOM_TO_DEFAULT_SCALE) {
CSSToParentLayerScale zoomAtDefaultScale =
Metrics().GetDevPixelsPerCSSPixel() *
LayoutDeviceToParentLayerScale(1.0);
if (targetZoom.scale > zoomAtDefaultScale.scale) {
// Only change the zoom if we are less than the default zoom
if (currentZoom.scale < zoomAtDefaultScale.scale) {
targetZoom = zoomAtDefaultScale;
} else {
targetZoom = currentZoom;
}
}
}
endZoomToMetrics.SetZoom(CSSToParentLayerScale2D(targetZoom));
// Adjust the zoomToRect to a sensible position to prevent overscrolling.
CSSSize sizeAfterZoom =
endZoomToMetrics.CalculateCompositedSizeInCssPixels();
// Vertically center the zoomed element in the screen.
if (!zoomOut && (sizeAfterZoom.height > aRect.Height())) {
aRect.MoveByY(-(sizeAfterZoom.height - aRect.Height()) * 0.5f);
if (aRect.Y() < 0.0f) {
aRect.MoveToY(0.0f);
}
}
// If either of these conditions are met, the page will be
// overscrolled after zoomed
if (aRect.Y() + sizeAfterZoom.height > cssPageRect.Height()) {
aRect.MoveToY(std::max(0.f, cssPageRect.Height() - sizeAfterZoom.height));
}
if (aRect.X() + sizeAfterZoom.width > cssPageRect.Width()) {
aRect.MoveToX(std::max(0.f, cssPageRect.Width() - sizeAfterZoom.width));
}
endZoomToMetrics.SetVisualScrollOffset(aRect.TopLeft());
endZoomToMetrics.RecalculateLayoutViewportOffset();
StartAnimation(new ZoomAnimation(
*this, Metrics().GetVisualScrollOffset(), Metrics().GetZoom(),
endZoomToMetrics.GetVisualScrollOffset(), endZoomToMetrics.GetZoom()));
// Schedule a repaint now, so the new displayport will be painted before the
// animation finishes.
ParentLayerPoint velocity(0, 0);
ScreenMargin displayportMargins = CalculatePendingDisplayPort(
endZoomToMetrics, velocity, ZoomInProgress::Yes);
endZoomToMetrics.SetPaintRequestTime(TimeStamp::Now());
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (!controller) {
return;
}
if (controller->IsRepaintThread()) {
RequestContentRepaint(endZoomToMetrics, velocity, displayportMargins,
RepaintUpdateType::eUserAction);
} else {
// See comment on similar code in RequestContentRepaint
mExpectedGeckoMetrics.UpdateFrom(endZoomToMetrics);
// use a local var to resolve the function overload
auto func = static_cast<void (AsyncPanZoomController::*)(
const FrameMetrics&, const ParentLayerPoint&, const ScreenMargin&,
RepaintUpdateType)>(&AsyncPanZoomController::RequestContentRepaint);
controller->DispatchToRepaintThread(
NewRunnableMethod<FrameMetrics, ParentLayerPoint, ScreenMargin,
RepaintUpdateType>(
"layers::AsyncPanZoomController::ZoomToRect", this, func,
endZoomToMetrics, velocity, displayportMargins,
RepaintUpdateType::eUserAction));
}
}
}
InputBlockState* AsyncPanZoomController::GetCurrentInputBlock() const {
return GetInputQueue()->GetCurrentBlock();
}
TouchBlockState* AsyncPanZoomController::GetCurrentTouchBlock() const {
return GetInputQueue()->GetCurrentTouchBlock();
}
PanGestureBlockState* AsyncPanZoomController::GetCurrentPanGestureBlock()
const {
return GetInputQueue()->GetCurrentPanGestureBlock();
}
PinchGestureBlockState* AsyncPanZoomController::GetCurrentPinchGestureBlock()
const {
return GetInputQueue()->GetCurrentPinchGestureBlock();
}
void AsyncPanZoomController::ResetTouchInputState() {
MultiTouchInput cancel(MultiTouchInput::MULTITOUCH_CANCEL, 0,
TimeStamp::Now(), 0);
RefPtr<GestureEventListener> listener = GetGestureEventListener();
if (listener) {
listener->HandleInputEvent(cancel);
}
CancelAnimationAndGestureState();
// Clear overscroll along the entire handoff chain, in case an APZC
// later in the chain is overscrolled.
if (TouchBlockState* block = GetCurrentTouchBlock()) {
block->GetOverscrollHandoffChain()->ClearOverscroll();
}
}
void AsyncPanZoomController::CancelAnimationAndGestureState() {
mX.CancelGesture();
mY.CancelGesture();
CancelAnimation(CancelAnimationFlags::ScrollSnap);
}
bool AsyncPanZoomController::HasReadyTouchBlock() const {
return GetInputQueue()->HasReadyTouchBlock();
}
bool AsyncPanZoomController::CanHandleScrollOffsetUpdate(PanZoomState aState) {
return aState == PAN_MOMENTUM || aState == TOUCHING || IsPanningState(aState);
}
bool AsyncPanZoomController::ShouldCancelAnimationForScrollUpdate(
const Maybe<CSSPoint>& aRelativeDelta) {
// Never call CancelAnimation() for a no-op relative update.
if (aRelativeDelta == Some(CSSPoint())) {
return false;
}
if (mAnimation) {
return !mAnimation->HandleScrollOffsetUpdate(aRelativeDelta);
}
return !CanHandleScrollOffsetUpdate(mState);
}
void AsyncPanZoomController::SetState(PanZoomState aNewState) {
PanZoomState oldState;
// Intentional scoping for mutex
{
RecursiveMutexAutoLock lock(mRecursiveMutex);
APZC_LOG("%p changing from state %d to %d\n", this, mState, aNewState);
oldState = mState;
mState = aNewState;
}
DispatchStateChangeNotification(oldState, aNewState);
}
void AsyncPanZoomController::DispatchStateChangeNotification(
PanZoomState aOldState, PanZoomState aNewState) {
{ // scope the lock
RecursiveMutexAutoLock lock(mRecursiveMutex);
if (mNotificationBlockers > 0) {
return;
}
}
if (RefPtr<GeckoContentController> controller = GetGeckoContentController()) {
if (!IsTransformingState(aOldState) && IsTransformingState(aNewState)) {
controller->NotifyAPZStateChange(GetGuid(),
APZStateChange::eTransformBegin);
#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
// Let the compositor know about scroll state changes so it can manage
// windowed plugins.
if (StaticPrefs::gfx_e10s_hide_plugins_for_scroll_AtStartup() &&
mCompositorController) {
mCompositorController->ScheduleHideAllPluginWindows();
}
#endif
} else if (IsTransformingState(aOldState) &&
!IsTransformingState(aNewState)) {
controller->NotifyAPZStateChange(GetGuid(),
APZStateChange::eTransformEnd);
#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
if (StaticPrefs::gfx_e10s_hide_plugins_for_scroll_AtStartup() &&
mCompositorController) {
mCompositorController->ScheduleShowAllPluginWindows();
}
#endif
}
}
}
bool AsyncPanZoomController::IsInTransformingState() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return IsTransformingState(mState);
}
bool AsyncPanZoomController::IsTransformingState(PanZoomState aState) {
return !(aState == NOTHING || aState == TOUCHING);
}
bool AsyncPanZoomController::IsPanningState(PanZoomState aState) {
return (aState == PANNING || aState == PANNING_LOCKED_X ||
aState == PANNING_LOCKED_Y);
}
bool AsyncPanZoomController::IsInPanningState() const {
return IsPanningState(mState);
}
void AsyncPanZoomController::UpdateZoomConstraints(
const ZoomConstraints& aConstraints) {
APZC_LOG("%p updating zoom constraints to %d %d %f %f\n", this,
aConstraints.mAllowZoom, aConstraints.mAllowDoubleTapZoom,
aConstraints.mMinZoom.scale, aConstraints.mMaxZoom.scale);
if (IsNaN(aConstraints.mMinZoom.scale) ||
IsNaN(aConstraints.mMaxZoom.scale)) {
NS_WARNING("APZC received zoom constraints with NaN values; dropping...");
return;
}
RecursiveMutexAutoLock lock(mRecursiveMutex);
CSSToParentLayerScale min = Metrics().GetDevPixelsPerCSSPixel() *
kViewportMinScale / ParentLayerToScreenScale(1);
CSSToParentLayerScale max = Metrics().GetDevPixelsPerCSSPixel() *
kViewportMaxScale / ParentLayerToScreenScale(1);
// inf float values and other bad cases should be sanitized by the code below.
mZoomConstraints.mAllowZoom = aConstraints.mAllowZoom;
mZoomConstraints.mAllowDoubleTapZoom = aConstraints.mAllowDoubleTapZoom;
mZoomConstraints.mMinZoom =
(min > aConstraints.mMinZoom ? min : aConstraints.mMinZoom);
mZoomConstraints.mMaxZoom =
(max > aConstraints.mMaxZoom ? aConstraints.mMaxZoom : max);
if (mZoomConstraints.mMaxZoom < mZoomConstraints.mMinZoom) {
mZoomConstraints.mMaxZoom = mZoomConstraints.mMinZoom;
}
}
ZoomConstraints AsyncPanZoomController::GetZoomConstraints() const {
return mZoomConstraints;
}
void AsyncPanZoomController::PostDelayedTask(already_AddRefed<Runnable> aTask,
int aDelayMs) {
APZThreadUtils::AssertOnControllerThread();
RefPtr<Runnable> task = aTask;
RefPtr<GeckoContentController> controller = GetGeckoContentController();
if (controller) {
controller->PostDelayedTask(task.forget(), aDelayMs);
}
// If there is no controller, that means this APZC has been destroyed, and
// we probably don't need to run the task. It will get destroyed when the
// RefPtr goes out of scope.
}
bool AsyncPanZoomController::Matches(const ScrollableLayerGuid& aGuid) {
return aGuid == GetGuid();
}
bool AsyncPanZoomController::HasTreeManager(
const APZCTreeManager* aTreeManager) const {
return GetApzcTreeManager() == aTreeManager;
}
void AsyncPanZoomController::GetGuid(ScrollableLayerGuid* aGuidOut) const {
if (aGuidOut) {
*aGuidOut = GetGuid();
}
}
ScrollableLayerGuid AsyncPanZoomController::GetGuid() const {
RecursiveMutexAutoLock lock(mRecursiveMutex);
return ScrollableLayerGuid(mLayersId, Metrics().GetPresShellId(),
Metrics().GetScrollId());
}
void AsyncPanZoomController::UpdateSharedCompositorFrameMetrics() {
mRecursiveMutex.AssertCurrentThreadIn();
FrameMetrics* frame =
mSharedFrameMetricsBuffer
? static_cast<FrameMetrics*>(mSharedFrameMetricsBuffer->memory())
: nullptr;
if (frame && mSharedLock && StaticPrefs::layers_progressive_paint()) {
mSharedLock->Lock();
*frame = Metrics();
mSharedLock->Unlock();
}
}
void AsyncPanZoomController::ShareCompositorFrameMetrics() {
AssertOnUpdaterThread();
// Only create the shared memory buffer if it hasn't already been created,
// we are using progressive tile painting, and we have a
// controller to pass the shared memory back to the content process/thread.
if (!mSharedFrameMetricsBuffer && mMetricsSharingController &&
StaticPrefs::layers_progressive_paint()) {
// Create shared memory and initialize it with the current FrameMetrics
// value
mSharedFrameMetricsBuffer = new ipc::SharedMemoryBasic;
FrameMetrics* frame = nullptr;
mSharedFrameMetricsBuffer->Create(sizeof(FrameMetrics));
mSharedFrameMetricsBuffer->Map(sizeof(FrameMetrics));
frame = static_cast<FrameMetrics*>(mSharedFrameMetricsBuffer->memory());
if (frame) {
{ // scope the monitor, only needed to copy the FrameMetrics.
RecursiveMutexAutoLock lock(mRecursiveMutex);
*frame = Metrics();
}
// Get the process id of the content process
base::ProcessId otherPid = mMetricsSharingController->RemotePid();
ipc::SharedMemoryBasic::Handle mem = ipc::SharedMemoryBasic::NULLHandle();
// Get the shared memory handle to share with the content process
mSharedFrameMetricsBuffer->ShareToProcess(otherPid, &mem);
// Get the cross process mutex handle to share with the content process
mSharedLock = new CrossProcessMutex("AsyncPanZoomControlLock");
CrossProcessMutexHandle handle = mSharedLock->ShareToProcess(otherPid);
// Send the shared memory handle and cross process handle to the content
// process by an asynchronous ipc call. Include the APZC unique ID
// so the content process know which APZC sent this shared FrameMetrics.
if (!mMetricsSharingController->StartSharingMetrics(mem, handle,
mLayersId, mAPZCId)) {
APZC_LOG("%p failed to share FrameMetrics with content process.", this);
}
}
}
}
void AsyncPanZoomController::SetTestAsyncScrollOffset(const CSSPoint& aPoint) {
mTestAsyncScrollOffset = aPoint;
ScheduleComposite();
}
void AsyncPanZoomController::SetTestAsyncZoom(
const LayerToParentLayerScale& aZoom) {
mTestAsyncZoom = aZoom;
ScheduleComposite();
}
Maybe<CSSPoint> AsyncPanZoomController::FindSnapPointNear(
const CSSPoint& aDestination, ScrollUnit aUnit) {
mRecursiveMutex.AssertCurrentThreadIn();
APZC_LOG("%p scroll snapping near %s\n", this,
ToString(aDestination).c_str());
CSSRect scrollRange = Metrics().CalculateScrollRange();
if (Maybe<nsPoint> snapPoint = ScrollSnapUtils::GetSnapPointForDestination(
mScrollMetadata.GetSnapInfo(), aUnit,
CSSRect::ToAppUnits(scrollRange),
CSSPoint::ToAppUnits(Metrics().GetVisualScrollOffset()),
CSSPoint::ToAppUnits(aDestination))) {
CSSPoint cssSnapPoint = CSSPoint::FromAppUnits(snapPoint.ref());
// GetSnapPointForDestination() can produce a destination that's outside
// of the scroll frame's scroll range. Clamp it here (this matches the
// behaviour of the main-thread code path, which clamps it in
// nsGfxScrollFrame::ScrollTo()).
return Some(scrollRange.ClampPoint(cssSnapPoint));
}
return Nothing();
}
void AsyncPanZoomController::ScrollSnapNear(const CSSPoint& aDestination) {
if (Maybe<CSSPoint> snapPoint =
FindSnapPointNear(aDestination, ScrollUnit::DEVICE_PIXELS)) {
if (*snapPoint != Metrics().GetVisualScrollOffset()) {
APZC_LOG("%p smooth scrolling to snap point %s\n", this,
ToString(*snapPoint).c_str());
SmoothMsdScrollTo(*snapPoint);
}
}
}
void AsyncPanZoomController::ScrollSnap() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
ScrollSnapNear(Metrics().GetVisualScrollOffset());
}
void AsyncPanZoomController::ScrollSnapToDestination() {
RecursiveMutexAutoLock lock(mRecursiveMutex);
float friction = StaticPrefs::apz_fling_friction();
ParentLayerPoint velocity(mX.GetVelocity(), mY.GetVelocity());
ParentLayerPoint predictedDelta;
// "-velocity / log(1.0 - friction)" is the integral of the deceleration
// curve modeled for flings in the "Axis" class.
if (velocity.x != 0.0f && friction != 0.0f) {
predictedDelta.x = -velocity.x / log(1.0 - friction);
}
if (velocity.y != 0.0f && friction != 0.0f) {
predictedDelta.y = -velocity.y / log(1.0 - friction);
}
// If the fling will overscroll, don't scroll snap, because then the user
// user would not see any overscroll animation.
bool flingWillOverscroll =
IsOverscrolled() && ((velocity.x * mX.GetOverscroll() >= 0) ||
(velocity.y * mY.GetOverscroll() >= 0));
if (flingWillOverscroll) {
return;
}
CSSPoint startPosition = Metrics().GetVisualScrollOffset();
if (MaybeAdjustDeltaForScrollSnapping(ScrollUnit::LINES, predictedDelta,
startPosition)) {
APZC_LOG(
"%p fling snapping. friction: %f velocity: %f, %f "
"predictedDelta: %f, %f position: %f, %f "
"snapDestination: %f, %f\n",
this, friction, velocity.x, velocity.y, (float)predictedDelta.x,
(float)predictedDelta.y, (float)Metrics().GetVisualScrollOffset().x,
(float)Metrics().GetVisualScrollOffset().y, (float)startPosition.x,
(float)startPosition.y);
SmoothMsdScrollTo(startPosition);
}
}
bool AsyncPanZoomController::MaybeAdjustDeltaForScrollSnapping(
ScrollUnit aUnit, ParentLayerPoint& aDelta, CSSPoint& aStartPosition) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
CSSToParentLayerScale2D zoom = Metrics().GetZoom();
if (zoom == CSSToParentLayerScale2D(0, 0)) {
return false;
}
CSSPoint destination = Metrics().CalculateScrollRange().ClampPoint(
aStartPosition + (aDelta / zoom));
if (Maybe<CSSPoint> snapPoint = FindSnapPointNear(destination, aUnit)) {
aDelta = (*snapPoint - aStartPosition) * zoom;
aStartPosition = *snapPoint;
return true;
}
return false;
}
bool AsyncPanZoomController::MaybeAdjustDeltaForScrollSnappingOnWheelInput(
const ScrollWheelInput& aEvent, ParentLayerPoint& aDelta,
CSSPoint& aStartPosition) {
// Don't scroll snap for pixel scrolls. This matches the main thread
// behaviour in EventStateManager::DoScrollText().
if (aEvent.mDeltaType == ScrollWheelInput::SCROLLDELTA_PIXEL) {
return false;
}
return MaybeAdjustDeltaForScrollSnapping(
ScrollWheelInput::ScrollUnitForDeltaType(aEvent.mDeltaType), aDelta,
aStartPosition);
}
bool AsyncPanZoomController::MaybeAdjustDestinationForScrollSnapping(
const KeyboardInput& aEvent, CSSPoint& aDestination) {
RecursiveMutexAutoLock lock(mRecursiveMutex);
ScrollUnit unit = KeyboardScrollAction::GetScrollUnit(aEvent.mAction.mType);
if (Maybe<CSSPoint> snapPoint = FindSnapPointNear(aDestination, unit)) {
aDestination = *snapPoint;
return true;
}
return false;
}
void AsyncPanZoomController::SetZoomAnimationId(
const Maybe<uint64_t>& aZoomAnimationId) {
mZoomAnimationId = aZoomAnimationId;
}
Maybe<uint64_t> AsyncPanZoomController::GetZoomAnimationId() const {
return mZoomAnimationId;
}
} // namespace layers
} // namespace mozilla
|