DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (5f0b392beadb)

VCS Links

Line Code
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
/* -*- 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 <stack>
#include <unordered_set>
#include "APZCTreeManager.h"
#include "AsyncPanZoomController.h"
#include "Compositor.h"             // for Compositor
#include "DragTracker.h"            // for DragTracker
#include "GenericFlingAnimation.h"  // for FLING_LOG
#include "HitTestingTreeNode.h"     // for HitTestingTreeNode
#include "InputBlockState.h"        // for InputBlockState
#include "InputData.h"              // for InputData, etc
#include "Layers.h"                 // for Layer, etc
#include "mozilla/RecursiveMutex.h"
#include "mozilla/dom/MouseEventBinding.h"  // for MouseEvent constants
#include "mozilla/dom/BrowserParent.h"      // for AreRecordReplayTabsActive
#include "mozilla/dom/Touch.h"              // for Touch
#include "mozilla/gfx/CompositorHitTestInfo.h"
#include "mozilla/gfx/LoggingConstants.h"
#include "mozilla/gfx/gfxVars.h"            // for gfxVars
#include "mozilla/gfx/GPUParent.h"          // for GPUParent
#include "mozilla/gfx/Logging.h"            // for gfx::TreeLog
#include "mozilla/gfx/Point.h"              // for Point
#include "mozilla/layers/APZSampler.h"      // for APZSampler
#include "mozilla/layers/APZThreadUtils.h"  // for AssertOnControllerThread, etc
#include "mozilla/layers/APZUpdater.h"      // for APZUpdater
#include "mozilla/layers/AsyncCompositionManager.h"  // for ViewTransform
#include "mozilla/layers/AsyncDragMetrics.h"         // for AsyncDragMetrics
#include "mozilla/layers/CompositorBridgeParent.h"  // for CompositorBridgeParent, etc
#include "mozilla/layers/LayerMetricsWrapper.h"
#include "mozilla/layers/MatrixMessage.h"
#include "mozilla/layers/WebRenderScrollDataWrapper.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/mozalloc.h"     // for operator new
#include "mozilla/Preferences.h"  // for Preferences
#include "mozilla/StaticPrefs_accessibility.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/EventStateManager.h"  // for WheelPrefs
#include "mozilla/webrender/WebRenderAPI.h"
#include "nsDebug.h"                 // for NS_WARNING
#include "nsPoint.h"                 // for nsIntPoint
#include "nsThreadUtils.h"           // for NS_IsMainThread
#include "OverscrollHandoffState.h"  // for OverscrollHandoffState
#include "TreeTraversal.h"           // for ForEachNode, BreadthFirstSearch, etc
#include "LayersLogging.h"           // for Stringify
#include "Units.h"                   // for ParentlayerPixel
#include "GestureEventListener.h"  // for GestureEventListener::setLongTapEnabled
#include "UnitTransforms.h"        // for ViewAs

#define ENABLE_APZCTM_LOGGING 0
// #define ENABLE_APZCTM_LOGGING 1

#if ENABLE_APZCTM_LOGGING
#  define APZCTM_LOG(...) printf_stderr("APZCTM: " __VA_ARGS__)
#else
#  define APZCTM_LOG(...)
#endif

// #define APZ_KEY_LOG(...) printf_stderr("APZKEY: " __VA_ARGS__)
#define APZ_KEY_LOG(...)

namespace mozilla {
namespace layers {

using mozilla::gfx::CompositorHitTestDispatchToContent;
using mozilla::gfx::CompositorHitTestFlags;
using mozilla::gfx::CompositorHitTestInfo;
using mozilla::gfx::CompositorHitTestInvisibleToHit;
using mozilla::gfx::LOG_DEFAULT;

typedef mozilla::gfx::Point Point;
typedef mozilla::gfx::Point4D Point4D;
typedef mozilla::gfx::Matrix4x4 Matrix4x4;

typedef CompositorBridgeParent::LayerTreeState LayerTreeState;

struct APZCTreeManager::TreeBuildingState {
  TreeBuildingState(LayersId aRootLayersId, bool aIsFirstPaint,
                    WRRootId aOriginatingWrRootId, APZTestData* aTestData,
                    uint32_t aPaintSequence)
      : mIsFirstPaint(aIsFirstPaint),
        mOriginatingWrRootId(aOriginatingWrRootId),
        mPaintLogger(aTestData, aPaintSequence) {
    CompositorBridgeParent::CallWithIndirectShadowTree(
        aRootLayersId, [this](LayerTreeState& aState) -> void {
          mCompositorController = aState.GetCompositorController();
          mInProcessSharingController = aState.InProcessSharingController();
        });
  }

  typedef std::unordered_map<AsyncPanZoomController*, gfx::Matrix4x4>
      DeferredTransformMap;

  // State that doesn't change as we recurse in the tree building
  RefPtr<CompositorController> mCompositorController;
  RefPtr<MetricsSharingController> mInProcessSharingController;
  const bool mIsFirstPaint;
  const WRRootId mOriginatingWrRootId;
  const APZPaintLogHelper mPaintLogger;

  // State that is updated as we perform the tree build

  // A list of nodes that need to be destroyed at the end of the tree building.
  // This is initialized with all nodes in the old tree, and nodes are removed
  // from it as we reuse them in the new tree.
  nsTArray<RefPtr<HitTestingTreeNode>> mNodesToDestroy;

  // This map is populated as we place APZCs into the new tree. Its purpose is
  // to facilitate re-using the same APZC for different layers that scroll
  // together (and thus have the same ScrollableLayerGuid). The presShellId
  // doesn't matter for this purpose, and we move the map to the APZCTreeManager
  // after we're done building, so it's useful to have the presshell-ignoring
  // map for that.
  std::unordered_map<ScrollableLayerGuid, RefPtr<AsyncPanZoomController>,
                     ScrollableLayerGuid::HashIgnoringPresShellFn,
                     ScrollableLayerGuid::EqualIgnoringPresShellFn>
      mApzcMap;

  // This is populated with all the HitTestingTreeNodes that are scroll thumbs
  // and have a scrollthumb animation id (which indicates that they need to be
  // sampled for WebRender on the sampler thread).
  std::vector<HitTestingTreeNode*> mScrollThumbs;
  // This is populated with all the scroll target nodes. We use in conjunction
  // with mScrollThumbs to build APZCTreeManager::mScrollThumbInfo.
  std::unordered_map<ScrollableLayerGuid, HitTestingTreeNode*,
                     ScrollableLayerGuid::HashIgnoringPresShellFn,
                     ScrollableLayerGuid::EqualIgnoringPresShellFn>
      mScrollTargets;

  // As the tree is traversed, the top element of this stack tracks whether
  // the parent scroll node has a perspective transform.
  std::stack<bool> mParentHasPerspective;

  // During the tree building process, the perspective transform component
  // of the ancestor transforms of some APZCs can be "deferred" to their
  // children, meaning they are added to the children's ancestor transforms
  // instead. Those deferred transforms are tracked here.
  DeferredTransformMap mPerspectiveTransformsDeferredToChildren;

  // As we recurse down through the tree, this picks up the zoom animation id
  // from a node in the layer tree, and propagates it downwards to the nearest
  // APZC instance that is for an RCD node. Generally it will be set on the
  // root node of the layers (sub-)tree, which may not be same as the RCD node
  // for the subtree, and so we need this mechanism to ensure it gets propagated
  // to the RCD's APZC instance. Once it is set on the APZC instance, the value
  // is cleared back to Nothing(). Note that this is only used in the WebRender
  // codepath.
  Maybe<uint64_t> mZoomAnimationId;
};

class APZCTreeManager::CheckerboardFlushObserver : public nsIObserver {
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  explicit CheckerboardFlushObserver(APZCTreeManager* aTreeManager)
      : mTreeManager(aTreeManager) {
    MOZ_ASSERT(NS_IsMainThread());
    nsCOMPtr<nsIObserverService> obsSvc =
        mozilla::services::GetObserverService();
    MOZ_ASSERT(obsSvc);
    if (obsSvc) {
      obsSvc->AddObserver(this, "APZ:FlushActiveCheckerboard", false);
    }
  }

  void Unregister() {
    MOZ_ASSERT(NS_IsMainThread());
    nsCOMPtr<nsIObserverService> obsSvc =
        mozilla::services::GetObserverService();
    if (obsSvc) {
      obsSvc->RemoveObserver(this, "APZ:FlushActiveCheckerboard");
    }
    mTreeManager = nullptr;
  }

 protected:
  virtual ~CheckerboardFlushObserver() = default;

 private:
  RefPtr<APZCTreeManager> mTreeManager;
};

NS_IMPL_ISUPPORTS(APZCTreeManager::CheckerboardFlushObserver, nsIObserver)

NS_IMETHODIMP
APZCTreeManager::CheckerboardFlushObserver::Observe(nsISupports* aSubject,
                                                    const char* aTopic,
                                                    const char16_t*) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(mTreeManager.get());

  RecursiveMutexAutoLock lock(mTreeManager->mTreeLock);
  if (mTreeManager->mRootNode) {
    ForEachNode<ReverseIterator>(
        mTreeManager->mRootNode.get(), [](HitTestingTreeNode* aNode) {
          if (aNode->IsPrimaryHolder()) {
            MOZ_ASSERT(aNode->GetApzc());
            aNode->GetApzc()->FlushActiveCheckerboardReport();
          }
        });
  }
  if (XRE_IsGPUProcess()) {
    if (gfx::GPUParent* gpu = gfx::GPUParent::GetSingleton()) {
      nsCString topic("APZ:FlushActiveCheckerboard:Done");
      Unused << gpu->SendNotifyUiObservers(topic);
    }
  } else {
    MOZ_ASSERT(XRE_IsParentProcess());
    nsCOMPtr<nsIObserverService> obsSvc =
        mozilla::services::GetObserverService();
    if (obsSvc) {
      obsSvc->NotifyObservers(nullptr, "APZ:FlushActiveCheckerboard:Done",
                              nullptr);
    }
  }
  return NS_OK;
}

/**
 * A RAII class used for setting the focus sequence number on input events
 * as they are being processed. Any input event is assumed to be potentially
 * focus changing unless explicitly marked otherwise.
 */
class MOZ_RAII AutoFocusSequenceNumberSetter {
 public:
  AutoFocusSequenceNumberSetter(FocusState& aFocusState, InputData& aEvent)
      : mFocusState(aFocusState), mEvent(aEvent), mMayChangeFocus(true) {}

  void MarkAsNonFocusChanging() { mMayChangeFocus = false; }

  ~AutoFocusSequenceNumberSetter() {
    if (mMayChangeFocus) {
      mFocusState.ReceiveFocusChangingEvent();

      APZ_KEY_LOG(
          "Marking input with type=%d as focus changing with seq=%" PRIu64 "\n",
          static_cast<int>(mEvent.mInputType),
          mFocusState.LastAPZProcessedEvent());
    } else {
      APZ_KEY_LOG(
          "Marking input with type=%d as non focus changing with seq=%" PRIu64
          "\n",
          static_cast<int>(mEvent.mInputType),
          mFocusState.LastAPZProcessedEvent());
    }

    mEvent.mFocusSequenceNumber = mFocusState.LastAPZProcessedEvent();
  }

 private:
  FocusState& mFocusState;
  InputData& mEvent;
  bool mMayChangeFocus;
};

APZCTreeManager::APZCTreeManager(LayersId aRootLayersId)
    : mInputQueue(new InputQueue()),
      mRootLayersId(aRootLayersId),
      mSampler(nullptr),
      mUpdater(nullptr),
      mTreeLock("APZCTreeLock"),
      mUsingAsyncZoomContainer(false),
      mMapLock("APZCMapLock"),
      mRetainedTouchIdentifier(-1),
      mInScrollbarTouchDrag(false),
      mApzcTreeLog("apzctree"),
      mTestDataLock("APZTestDataLock"),
      mDPI(160.0) {
  RefPtr<APZCTreeManager> self(this);
  NS_DispatchToMainThread(NS_NewRunnableFunction(
      "layers::APZCTreeManager::APZCTreeManager",
      [self] { self->mFlushObserver = new CheckerboardFlushObserver(self); }));
  AsyncPanZoomController::InitializeGlobalState();
  mApzcTreeLog.ConditionOnPrefFunction(StaticPrefs::apz_printtree);
#ifdef MOZ_WIDGET_ANDROID
  if (AndroidDynamicToolbarAnimator::IsEnabled()) {
    mToolbarAnimator = new AndroidDynamicToolbarAnimator(this);
  }
#endif  // (MOZ_WIDGET_ANDROID)
}

APZCTreeManager::~APZCTreeManager() = default;

void APZCTreeManager::SetSampler(APZSampler* aSampler) {
  // We're either setting the sampler or clearing it
  MOZ_ASSERT((mSampler == nullptr) != (aSampler == nullptr));
  mSampler = aSampler;
}

void APZCTreeManager::SetUpdater(APZUpdater* aUpdater) {
  // We're either setting the updater or clearing it
  MOZ_ASSERT((mUpdater == nullptr) != (aUpdater == nullptr));
  mUpdater = aUpdater;
}

void APZCTreeManager::NotifyLayerTreeAdopted(
    LayersId aLayersId, const RefPtr<APZCTreeManager>& aOldApzcTreeManager) {
  AssertOnUpdaterThread();

  if (aOldApzcTreeManager) {
    aOldApzcTreeManager->mFocusState.RemoveFocusTarget(aLayersId);
    // While we could move the focus target information from the old APZC tree
    // manager into this one, it's safer to not do that, as we'll probably have
    // that information repopulated soon anyway (on the next layers update).
  }

  UniquePtr<APZTestData> adoptedData;
  if (aOldApzcTreeManager) {
    MutexAutoLock lock(aOldApzcTreeManager->mTestDataLock);
    auto it = aOldApzcTreeManager->mTestData.find(aLayersId);
    if (it != aOldApzcTreeManager->mTestData.end()) {
      adoptedData = std::move(it->second);
      aOldApzcTreeManager->mTestData.erase(it);
    }
  }
  if (adoptedData) {
    MutexAutoLock lock(mTestDataLock);
    mTestData[aLayersId] = std::move(adoptedData);
  }
}

void APZCTreeManager::NotifyLayerTreeRemoved(LayersId aLayersId) {
  AssertOnUpdaterThread();

  mFocusState.RemoveFocusTarget(aLayersId);

  {  // scope lock
    MutexAutoLock lock(mTestDataLock);
    mTestData.erase(aLayersId);
  }
}

AsyncPanZoomController* APZCTreeManager::NewAPZCInstance(
    LayersId aLayersId, GeckoContentController* aController,
    wr::RenderRoot aRenderRoot) {
  return new AsyncPanZoomController(
      aLayersId, this, mInputQueue, aController, aRenderRoot,
      AsyncPanZoomController::USE_GESTURE_DETECTOR);
}

void APZCTreeManager::SetTestSampleTime(const Maybe<TimeStamp>& aTime) {
  mTestSampleTime = aTime;
}

TimeStamp APZCTreeManager::GetFrameTime() {
  if (mTestSampleTime) {
    return *mTestSampleTime;
  }
  return TimeStamp::Now();
}

void APZCTreeManager::SetAllowedTouchBehavior(
    uint64_t aInputBlockId, const nsTArray<TouchBehaviorFlags>& aValues) {
  APZThreadUtils::AssertOnControllerThread();

  mInputQueue->SetAllowedTouchBehavior(aInputBlockId, aValues);
}

template <class ScrollNode>
void  // ScrollNode is a LayerMetricsWrapper or a WebRenderScrollDataWrapper
APZCTreeManager::UpdateHitTestingTreeImpl(const ScrollNode& aRoot,
                                          bool aIsFirstPaint,
                                          WRRootId aOriginatingWrRootId,
                                          uint32_t aPaintSequenceNumber) {
  RecursiveMutexAutoLock lock(mTreeLock);

  // For testing purposes, we log some data to the APZTestData associated with
  // the layers id that originated this update.
  APZTestData* testData = nullptr;
  if (StaticPrefs::apz_test_logging_enabled()) {
    MutexAutoLock lock(mTestDataLock);
    UniquePtr<APZTestData> ptr = MakeUnique<APZTestData>();
    auto result = mTestData.insert(
        std::make_pair(aOriginatingWrRootId.mLayersId, std::move(ptr)));
    testData = result.first->second.get();
    testData->StartNewPaint(aPaintSequenceNumber);
  }

  TreeBuildingState state(mRootLayersId, aIsFirstPaint, aOriginatingWrRootId,
                          testData, aPaintSequenceNumber);

  // We do this business with collecting the entire tree into an array because
  // otherwise it's very hard to determine which APZC instances need to be
  // destroyed. In the worst case, there are two scenarios: (a) a layer with an
  // APZC is removed from the layer tree and (b) a layer with an APZC is moved
  // in the layer tree from one place to a completely different place. In
  // scenario (a) we would want to destroy the APZC while walking the layer tree
  // and noticing that the layer/APZC is no longer there. But if we do that then
  // we run into a problem in scenario (b) because we might encounter that layer
  // later during the walk. To handle both of these we have to 'remember' that
  // the layer was not found, and then do the destroy only at the end of the
  // tree walk after we are sure that the layer was removed and not just
  // transplanted elsewhere. Doing that as part of a recursive tree walk is hard
  // and so maintaining a list and removing APZCs that are still alive is much
  // simpler.
  ForEachNode<ReverseIterator>(mRootNode.get(),
                               [&state](HitTestingTreeNode* aNode) {
                                 state.mNodesToDestroy.AppendElement(aNode);
                               });
  mRootNode = nullptr;
  mUsingAsyncZoomContainer = false;
  int asyncZoomContainerNestingDepth = 0;
  bool haveMultipleAsyncZoomContainers = false;
  bool haveRootContentOutsideAsyncZoomContainer = false;

  if (aRoot) {
    std::unordered_set<LayersId, LayersId::HashFn> seenLayersIds;
    std::stack<gfx::TreeAutoIndent<LOG_DEFAULT>> indents;
    std::stack<AncestorTransform> ancestorTransforms;
    HitTestingTreeNode* parent = nullptr;
    HitTestingTreeNode* next = nullptr;
    LayersId layersId = mRootLayersId;
    seenLayersIds.insert(mRootLayersId);
    std::stack<wr::RenderRoot> renderRoots;
    renderRoots.push(wr::RenderRoot::Default);
    ancestorTransforms.push(AncestorTransform());
    state.mParentHasPerspective.push(false);

    mApzcTreeLog << "[start]\n";
    mTreeLock.AssertCurrentThreadIn();

    ForEachNode<ReverseIterator>(
        aRoot,
        [&](ScrollNode aLayerMetrics) {
          mApzcTreeLog << aLayerMetrics.Name() << '\t';

          if (aLayerMetrics.IsAsyncZoomContainer()) {
            if (mUsingAsyncZoomContainer) {
              haveMultipleAsyncZoomContainers = true;
            }
            mUsingAsyncZoomContainer = true;
            ++asyncZoomContainerNestingDepth;
          }

          // Note that this check happens after the potential increment of
          // asyncZoomContainerNestingDepth, to allow the root content
          // metadata to be on the same node as the async zoom container.
          if (aLayerMetrics.Metrics().IsRootContent() &&
              asyncZoomContainerNestingDepth == 0) {
            haveRootContentOutsideAsyncZoomContainer = true;
          }

          HitTestingTreeNode* node = PrepareNodeForLayer(
              lock, aLayerMetrics, aLayerMetrics.Metrics(), layersId,
              ancestorTransforms.top(), parent, next, state, renderRoots.top());
          MOZ_ASSERT(node);
          AsyncPanZoomController* apzc = node->GetApzc();
          aLayerMetrics.SetApzc(apzc);

          // GetScrollbarAnimationId is only set when webrender is enabled,
          // which limits the extra thumb mapping work to the webrender-enabled
          // case where it is needed.
          // Note also that when webrender is enabled, a "valid" animation id
          // is always nonzero, so we don't need to worry about handling the
          // case where WR is enabled and the animation id is zero.
          if (node->IsScrollThumbNode() && node->GetScrollbarAnimationId()) {
            state.mScrollThumbs.push_back(node);
          }
          if (apzc && node->IsPrimaryHolder()) {
            state.mScrollTargets[apzc->GetGuid()] = node;
          }

          mApzcTreeLog << '\n';

          // Accumulate the CSS transform between layers that have an APZC.
          // In the terminology of the big comment above
          // APZCTreeManager::GetScreenToApzcTransform, if we are at layer M,
          // then aAncestorTransform is NC * OC * PC, and we left-multiply MC
          // and compute ancestorTransform to be MC * NC * OC * PC. This gets
          // passed down as the ancestor transform to layer L when we recurse
          // into the children below. If we are at a layer with an APZC, such as
          // P, then we reset the ancestorTransform to just PC, to start the new
          // accumulation as we go down.
          AncestorTransform currentTransform{
              aLayerMetrics.GetTransform(),
              aLayerMetrics.TransformIsPerspective()};
          if (!apzc) {
            currentTransform = currentTransform * ancestorTransforms.top();
          }
          ancestorTransforms.push(currentTransform);

          // Note that |node| at this point will not have any children,
          // otherwise we we would have to set next to node->GetFirstChild().
          MOZ_ASSERT(!node->GetFirstChild());
          parent = node;
          next = nullptr;

          // Update the layersId or renderroot if we have a new one
          if (Maybe<LayersId> newLayersId = aLayerMetrics.GetReferentId()) {
            layersId = *newLayersId;
            seenLayersIds.insert(layersId);
          }
          if (Maybe<wr::RenderRoot> newRenderRoot =
                  aLayerMetrics.GetReferentRenderRoot()) {
            renderRoots.push(*newRenderRoot);
          }

          indents.push(gfx::TreeAutoIndent<LOG_DEFAULT>(mApzcTreeLog));
          state.mParentHasPerspective.push(
              aLayerMetrics.TransformIsPerspective());
        },
        [&](ScrollNode aLayerMetrics) {
          if (aLayerMetrics.IsAsyncZoomContainer()) {
            --asyncZoomContainerNestingDepth;
          }

          next = parent;
          parent = parent->GetParent();
          layersId = next->GetLayersId();
          ancestorTransforms.pop();
          indents.pop();
          state.mParentHasPerspective.pop();
          if (aLayerMetrics.GetReferentRenderRoot()) {
            renderRoots.pop();
          }
        });

    mApzcTreeLog << "[end]\n";

    MOZ_ASSERT(
        !mUsingAsyncZoomContainer || !haveRootContentOutsideAsyncZoomContainer,
        "If there is an async zoom container, all scroll nodes with root "
        "content scroll metadata should be inside it");
    // TODO(bug 1534459): Avoid multiple async zoom containers. They
    // can't currently occur in production code, but that will become
    // possible with either OOP iframes or desktop zooming (due to
    // RDM), and will need to be guarded against.
    // MOZ_ASSERT(!haveMultipleAsyncZoomContainers,
    //           "Should only have one async zoom container");

    // If we have perspective transforms deferred to children, do another
    // walk of the tree and actually apply them to the children.
    // We can't do this "as we go" in the previous traversal, because by the
    // time we realize we need to defer a perspective transform for an APZC,
    // we may already have processed a previous layer (including children
    // found in its subtree) that shares that APZC.
    if (!state.mPerspectiveTransformsDeferredToChildren.empty()) {
      ForEachNode<ReverseIterator>(
          mRootNode.get(), [&state](HitTestingTreeNode* aNode) {
            AsyncPanZoomController* apzc = aNode->GetApzc();
            if (!apzc) {
              return;
            }
            if (!aNode->IsPrimaryHolder()) {
              return;
            }

            AsyncPanZoomController* parent = apzc->GetParent();
            if (!parent) {
              return;
            }

            auto it =
                state.mPerspectiveTransformsDeferredToChildren.find(parent);
            if (it != state.mPerspectiveTransformsDeferredToChildren.end()) {
              apzc->SetAncestorTransform(AncestorTransform{
                  it->second * apzc->GetAncestorTransform(), false});
            }
          });
    }

    // Remove any layers ids for which we no longer have content from
    // mDetachedLayersIds.
    for (auto iter = mDetachedLayersIds.begin();
         iter != mDetachedLayersIds.end();) {
      // unordered_set::erase() invalidates the iterator pointing to the
      // element being erased, but returns an iterator to the next element.
      if (seenLayersIds.find(*iter) == seenLayersIds.end()) {
        iter = mDetachedLayersIds.erase(iter);
      } else {
        ++iter;
      }
    }
  }

  // We do not support tree structures where the root node has siblings.
  MOZ_ASSERT(!(mRootNode && mRootNode->GetPrevSibling()));

  {  // scope lock and update our mApzcMap before we destroy all the unused
    // APZC instances
    MutexAutoLock lock(mMapLock);
    mApzcMap = std::move(state.mApzcMap);
    mScrollThumbInfo.clear();
    // For non-webrender, state.mScrollThumbs will be empty so this will be a
    // no-op.
    for (HitTestingTreeNode* thumb : state.mScrollThumbs) {
      MOZ_ASSERT(thumb->IsScrollThumbNode());
      ScrollableLayerGuid targetGuid(thumb->GetLayersId(), 0,
                                     thumb->GetScrollTargetId());
      auto it = state.mScrollTargets.find(targetGuid);
      if (it == state.mScrollTargets.end()) {
        // It could be that |thumb| is a scrollthumb for content which didn't
        // have an APZC, for example if the content isn't layerized. Regardless,
        // we can't async-scroll it so we don't need to worry about putting it
        // in mScrollThumbInfo.
        continue;
      }
      HitTestingTreeNode* target = it->second;
      mScrollThumbInfo.emplace_back(
          *(thumb->GetScrollbarAnimationId()), thumb->GetTransform(),
          thumb->GetScrollbarData(), targetGuid, target->GetTransform(),
          target->IsAncestorOf(thumb));
    }
  }

  for (size_t i = 0; i < state.mNodesToDestroy.Length(); i++) {
    APZCTM_LOG("Destroying node at %p with APZC %p\n",
               state.mNodesToDestroy[i].get(),
               state.mNodesToDestroy[i]->GetApzc());
    state.mNodesToDestroy[i]->Destroy();
  }

#if ENABLE_APZCTM_LOGGING
  // Make the hit-test tree line up with the layer dump
  printf_stderr("APZCTreeManager (%p)\n", this);
  if (mRootNode) {
    mRootNode->Dump("  ");
  }
#endif
  SendSubtreeTransformsToChromeMainThread(nullptr);
}

void APZCTreeManager::UpdateFocusState(LayersId aRootLayerTreeId,
                                       LayersId aOriginatingLayersId,
                                       const FocusTarget& aFocusTarget) {
  AssertOnUpdaterThread();

  if (!StaticPrefs::apz_keyboard_enabled_AtStartup()) {
    return;
  }

  mFocusState.Update(aRootLayerTreeId, aOriginatingLayersId, aFocusTarget);
}

void APZCTreeManager::UpdateHitTestingTree(Layer* aRoot, bool aIsFirstPaint,
                                           LayersId aOriginatingLayersId,
                                           uint32_t aPaintSequenceNumber) {
  AssertOnUpdaterThread();

  LayerMetricsWrapper root(aRoot);
  UpdateHitTestingTreeImpl(root, aIsFirstPaint,
                           WRRootId::NonWebRender(aOriginatingLayersId),
                           aPaintSequenceNumber);
}

void APZCTreeManager::UpdateHitTestingTree(
    const WebRenderScrollDataWrapper& aScrollWrapper, bool aIsFirstPaint,
    WRRootId aOriginatingWrRootId, uint32_t aPaintSequenceNumber) {
  AssertOnUpdaterThread();

  UpdateHitTestingTreeImpl(aScrollWrapper, aIsFirstPaint, aOriginatingWrRootId,
                           aPaintSequenceNumber);
}

void APZCTreeManager::SampleForWebRender(wr::TransactionWrapper& aTxn,
                                         const TimeStamp& aSampleTime,
                                         wr::RenderRoot aRenderRoot) {
  AssertOnSamplerThread();
  MutexAutoLock lock(mMapLock);

  nsTArray<wr::WrTransformProperty> transforms;

  // Sample async transforms on scrollable layers.
  for (const auto& mapping : mApzcMap) {
    AsyncPanZoomController* apzc = mapping.second;
    if (apzc->GetRenderRoot() != aRenderRoot) {
      // If this APZC belongs to a different render root, skip over it
      continue;
    }

    ParentLayerPoint layerTranslation =
        apzc->GetCurrentAsyncTransform(AsyncPanZoomController::eForCompositing)
            .mTranslation;
    LayoutDeviceToParentLayerScale zoom;
    if (Maybe<uint64_t> zoomAnimationId = apzc->GetZoomAnimationId()) {
      // for now we only support zooming on root content APZCs
      MOZ_ASSERT(apzc->IsRootContent());
      zoom = apzc->GetCurrentPinchZoomScale(
          AsyncPanZoomController::eForCompositing);
      transforms.AppendElement(wr::ToWrTransformProperty(
          *zoomAnimationId, Matrix4x4::Scaling(zoom.scale, zoom.scale, 1.0f)));

      aTxn.UpdateIsTransformPinchZooming(*zoomAnimationId,
                                         apzc->IsPinchZooming());
    }

    // The positive translation means the painted content is supposed to
    // move down (or to the right), and that corresponds to a reduction in
    // the scroll offset. Since we are effectively giving WR the async
    // scroll delta here, we want to negate the translation.
    LayoutDevicePoint asyncScrollDelta = -layerTranslation / zoom;
    aTxn.UpdateScrollPosition(wr::AsPipelineId(apzc->GetGuid().mLayersId),
                              apzc->GetGuid().mScrollId,
                              wr::ToRoundedLayoutPoint(asyncScrollDelta));

    apzc->ReportCheckerboard(aSampleTime);
  }

  // Now collect all the async transforms needed for the scrollthumbs.
  for (const ScrollThumbInfo& info : mScrollThumbInfo) {
    auto it = mApzcMap.find(info.mTargetGuid);
    if (it == mApzcMap.end()) {
      // It could be that |info| is a scrollthumb for content which didn't
      // have an APZC, for example if the content isn't layerized. Regardless,
      // we can't async-scroll it so we don't need to worry about putting it
      // in mScrollThumbInfo.
      continue;
    }
    AsyncPanZoomController* scrollTargetApzc = it->second;
    MOZ_ASSERT(scrollTargetApzc);
    if (scrollTargetApzc->GetRenderRoot() != aRenderRoot) {
      // If this APZC belongs to a different render root, skip over it
      continue;
    }
    LayerToParentLayerMatrix4x4 transform =
        scrollTargetApzc->CallWithLastContentPaintMetrics(
            [&](const FrameMetrics& aMetrics) {
              return ComputeTransformForScrollThumb(
                  info.mThumbTransform * AsyncTransformMatrix(),
                  info.mTargetTransform.ToUnknownMatrix(), scrollTargetApzc,
                  aMetrics, info.mThumbData, info.mTargetIsAncestor, nullptr);
            });
    transforms.AppendElement(
        wr::ToWrTransformProperty(info.mThumbAnimationId, transform));
  }
  aTxn.AppendTransformProperties(transforms);

  // Advance animations. It's important that this happens after
  // sampling all async transforms, because AdvanceAnimations() updates
  // the effective scroll offset to the value it should have for the *next*
  // composite after this one (if the APZ frame delay is enabled).
  bool activeAnimations = false;
  for (const auto& mapping : mApzcMap) {
    AsyncPanZoomController* apzc = mapping.second;
    if (apzc->GetRenderRoot() != aRenderRoot) {
      // If this APZC belongs to a different render root, skip over it
      continue;
    }
    activeAnimations |= apzc->AdvanceAnimations(aSampleTime);
  }
  if (activeAnimations) {
    RefPtr<CompositorController> controller;
    CompositorBridgeParent::CallWithIndirectShadowTree(
        mRootLayersId, [&](LayerTreeState& aState) -> void {
          controller = aState.GetCompositorController();
        });
    if (controller) {
      controller->ScheduleRenderOnCompositorThread(
          wr::RenderRootSet(aRenderRoot));
    }
  }
}

// Compute the clip region to be used for a layer with an APZC. This function
// is only called for layers which actually have scrollable metrics and an APZC.
template <class ScrollNode>
Maybe<ParentLayerIntRegion> APZCTreeManager::ComputeClipRegion(
    const ScrollNode& aLayer) {
  Maybe<ParentLayerIntRegion> clipRegion;
  if (aLayer.GetClipRect()) {
    clipRegion.emplace(*aLayer.GetClipRect());
  } else if (aLayer.Metrics().IsRootContent() && mUsingAsyncZoomContainer) {
    // If we are using containerless scrolling, part of the root content
    // layers' async transform has been lifted to the async zoom container
    // layer. The composition bounds clip, which applies after the async
    // transform, needs to be lifted too. Layout code already takes care of
    // this for us, we just need to not mess it up by introducing a
    // composition bounds clip here, so we leave the clip empty.
  } else {
    // if there is no clip on this layer (which should only happen for the
    // root scrollable layer in a process, or for some of the LayerMetrics
    // expansions of a multi-metrics layer), fall back to using the comp
    // bounds which should be equivalent.
    clipRegion.emplace(RoundedToInt(aLayer.Metrics().GetCompositionBounds()));
  }

  return clipRegion;
}

template <class ScrollNode>
void APZCTreeManager::PrintAPZCInfo(const ScrollNode& aLayer,
                                    const AsyncPanZoomController* apzc) {
  const FrameMetrics& metrics = aLayer.Metrics();
  mApzcTreeLog << "APZC " << apzc->GetGuid()
               << "\tcb=" << metrics.GetCompositionBounds()
               << "\tsr=" << metrics.GetScrollableRect()
               << (metrics.IsScrollInfoLayer() ? "\tscrollinfo" : "")
               << (apzc->HasScrollgrab() ? "\tscrollgrab" : "") << "\t"
               << aLayer.Metadata().GetContentDescription().get();
}

void APZCTreeManager::AttachNodeToTree(HitTestingTreeNode* aNode,
                                       HitTestingTreeNode* aParent,
                                       HitTestingTreeNode* aNextSibling) {
  if (aNextSibling) {
    aNextSibling->SetPrevSibling(aNode);
  } else if (aParent) {
    aParent->SetLastChild(aNode);
  } else {
    MOZ_ASSERT(!mRootNode);
    mRootNode = aNode;
    aNode->MakeRoot();
  }
}

template <class ScrollNode>
static EventRegions GetEventRegions(const ScrollNode& aLayer) {
  if (aLayer.Metrics().IsScrollInfoLayer()) {
    ParentLayerIntRect compositionBounds(
        RoundedToInt(aLayer.Metrics().GetCompositionBounds()));
    nsIntRegion hitRegion(compositionBounds.ToUnknownRect());
    EventRegions eventRegions(hitRegion);
    eventRegions.mDispatchToContentHitRegion = eventRegions.mHitRegion;
    return eventRegions;
  }
  return aLayer.GetEventRegions();
}

already_AddRefed<HitTestingTreeNode> APZCTreeManager::RecycleOrCreateNode(
    const RecursiveMutexAutoLock& aProofOfTreeLock, TreeBuildingState& aState,
    AsyncPanZoomController* aApzc, LayersId aLayersId) {
  // Find a node without an APZC and return it. Note that unless the layer tree
  // actually changes, this loop should generally do an early-return on the
  // first iteration, so it should be cheap in the common case.
  for (int32_t i = aState.mNodesToDestroy.Length() - 1; i >= 0; i--) {
    RefPtr<HitTestingTreeNode> node = aState.mNodesToDestroy[i];
    if (node->IsRecyclable(aProofOfTreeLock)) {
      aState.mNodesToDestroy.RemoveElementAt(i);
      node->RecycleWith(aProofOfTreeLock, aApzc, aLayersId);
      return node.forget();
    }
  }
  RefPtr<HitTestingTreeNode> node =
      new HitTestingTreeNode(aApzc, false, aLayersId);
  return node.forget();
}

template <class ScrollNode>
static EventRegionsOverride GetEventRegionsOverride(HitTestingTreeNode* aParent,
                                                    const ScrollNode& aLayer) {
  // Make it so that if the flag is set on the layer tree, it automatically
  // propagates to all the nodes in the corresponding subtree rooted at that
  // layer in the hit-test tree. This saves having to walk up the tree every
  // we want to see if a hit-test node is affected by this flag.
  EventRegionsOverride result = aLayer.GetEventRegionsOverride();
  if (result != EventRegionsOverride::NoOverride) {
    // Overrides should only ever get set for ref layers.
    MOZ_ASSERT(aLayer.GetReferentId());
  }
  if (aParent) {
    result |= aParent->GetEventRegionsOverride();
  }
  return result;
}

void APZCTreeManager::StartScrollbarDrag(const SLGuidAndRenderRoot& aGuid,
                                         const AsyncDragMetrics& aDragMetrics) {
  APZThreadUtils::AssertOnControllerThread();

  RefPtr<AsyncPanZoomController> apzc =
      GetTargetAPZC(aGuid.mScrollableLayerGuid);
  if (!apzc) {
    NotifyScrollbarDragRejected(aGuid.mScrollableLayerGuid);
    return;
  }

  uint64_t inputBlockId = aDragMetrics.mDragStartSequenceNumber;
  mInputQueue->ConfirmDragBlock(inputBlockId, apzc, aDragMetrics);
}

bool APZCTreeManager::StartAutoscroll(const SLGuidAndRenderRoot& aGuid,
                                      const ScreenPoint& aAnchorLocation) {
  APZThreadUtils::AssertOnControllerThread();

  RefPtr<AsyncPanZoomController> apzc =
      GetTargetAPZC(aGuid.mScrollableLayerGuid);
  if (!apzc) {
    if (XRE_IsGPUProcess()) {
      // If we're in the compositor process, the "return false" will be
      // ignored because the query comes over the PAPZCTreeManager protocol
      // via an async message. In this case, send an explicit rejection
      // message to content.
      NotifyAutoscrollRejected(aGuid.mScrollableLayerGuid);
    }
    return false;
  }

  apzc->StartAutoscroll(aAnchorLocation);
  return true;
}

void APZCTreeManager::StopAutoscroll(const SLGuidAndRenderRoot& aGuid) {
  APZThreadUtils::AssertOnControllerThread();

  if (RefPtr<AsyncPanZoomController> apzc =
          GetTargetAPZC(aGuid.mScrollableLayerGuid)) {
    apzc->StopAutoscroll();
  }
}

void APZCTreeManager::NotifyScrollbarDragInitiated(
    uint64_t aDragBlockId, const ScrollableLayerGuid& aGuid,
    ScrollDirection aDirection) const {
  RefPtr<GeckoContentController> controller =
      GetContentController(aGuid.mLayersId);
  if (controller) {
    controller->NotifyAsyncScrollbarDragInitiated(aDragBlockId, aGuid.mScrollId,
                                                  aDirection);
  }
}

void APZCTreeManager::NotifyScrollbarDragRejected(
    const ScrollableLayerGuid& aGuid) const {
  RefPtr<GeckoContentController> controller =
      GetContentController(aGuid.mLayersId);
  if (controller) {
    controller->NotifyAsyncScrollbarDragRejected(aGuid.mScrollId);
  }
}

void APZCTreeManager::NotifyAutoscrollRejected(
    const ScrollableLayerGuid& aGuid) const {
  RefPtr<GeckoContentController> controller =
      GetContentController(aGuid.mLayersId);
  MOZ_ASSERT(controller);
  controller->NotifyAsyncAutoscrollRejected(aGuid.mScrollId);
}

template <class ScrollNode>
void SetHitTestData(HitTestingTreeNode* aNode, HitTestingTreeNode* aParent,
                    const ScrollNode& aLayer,
                    const Maybe<ParentLayerIntRegion>& aClipRegion) {
  aNode->SetHitTestData(
      GetEventRegions(aLayer), aLayer.GetVisibleRegion(),
      aLayer.GetRemoteDocumentRect(), aLayer.GetTransformTyped(), aClipRegion,
      GetEventRegionsOverride(aParent, aLayer), aLayer.IsBackfaceHidden(),
      !!aLayer.IsAsyncZoomContainer());
}

template <class ScrollNode>
HitTestingTreeNode* APZCTreeManager::PrepareNodeForLayer(
    const RecursiveMutexAutoLock& aProofOfTreeLock, const ScrollNode& aLayer,
    const FrameMetrics& aMetrics, LayersId aLayersId,
    const AncestorTransform& aAncestorTransform, HitTestingTreeNode* aParent,
    HitTestingTreeNode* aNextSibling, TreeBuildingState& aState,
    wr::RenderRoot aRenderRoot) {
  bool needsApzc = true;
  if (!aMetrics.IsScrollable()) {
    needsApzc = false;
  }

  // XXX: As a future optimization we can probably stick these things on the
  // TreeBuildingState, and update them as we change layers id during the
  // traversal
  RefPtr<GeckoContentController> geckoContentController;
  RefPtr<MetricsSharingController> crossProcessSharingController;
  CompositorBridgeParent::CallWithIndirectShadowTree(
      aLayersId, [&](LayerTreeState& lts) -> void {
        geckoContentController = lts.mController;
        crossProcessSharingController = lts.CrossProcessSharingController();
      });

  if (!geckoContentController) {
    needsApzc = false;
  }

  bool parentHasPerspective = aState.mParentHasPerspective.top();

  if (Maybe<uint64_t> zoomAnimationId = aLayer.GetZoomAnimationId()) {
    aState.mZoomAnimationId = zoomAnimationId;
  }

  RefPtr<HitTestingTreeNode> node = nullptr;
  if (!needsApzc) {
    // Note: if layer properties must be propagated to nodes, RecvUpdate in
    // LayerTransactionParent.cpp must ensure that APZ will be notified
    // when those properties change.
    node = RecycleOrCreateNode(aProofOfTreeLock, aState, nullptr, aLayersId);
    AttachNodeToTree(node, aParent, aNextSibling);
    SetHitTestData(node, aParent, aLayer,
                   (!parentHasPerspective && aLayer.GetClipRect())
                       ? Some(ParentLayerIntRegion(*aLayer.GetClipRect()))
                       : Nothing());
    node->SetScrollbarData(aLayer.GetScrollbarAnimationId(),
                           aLayer.GetScrollbarData());
    node->SetFixedPosData(aLayer.GetFixedPositionScrollContainerId(),
                          aLayer.GetFixedPositionSides());
    return node;
  }

  AsyncPanZoomController* apzc = nullptr;
  // If we get here, aLayer is a scrollable layer and somebody
  // has registered a GeckoContentController for it, so we need to ensure
  // it has an APZC instance to manage its scrolling.

  // aState.mApzcMap allows reusing the exact same APZC instance for different
  // layers with the same FrameMetrics data. This is needed because in some
  // cases content that is supposed to scroll together is split into multiple
  // layers because of e.g. non-scrolling content interleaved in z-index order.
  ScrollableLayerGuid guid(aLayersId, aMetrics.GetPresShellId(),
                           aMetrics.GetScrollId());
  auto insertResult = aState.mApzcMap.insert(
      std::make_pair(guid, static_cast<AsyncPanZoomController*>(nullptr)));
  if (!insertResult.second) {
    apzc = insertResult.first->second;
    PrintAPZCInfo(aLayer, apzc);
  }
  APZCTM_LOG("Found APZC %p for layer %p with identifiers %" PRIx64 " %" PRId64
             "\n",
             apzc, aLayer.GetLayer(), uint64_t(guid.mLayersId), guid.mScrollId);

  // If we haven't encountered a layer already with the same metrics, then we
  // need to do the full reuse-or-make-an-APZC algorithm, which is contained
  // inside the block below.
  if (apzc == nullptr) {
    apzc = aLayer.GetApzc();

    // If the content represented by the scrollable layer has changed (which may
    // be possible because of DLBI heuristics) then we don't want to keep using
    // the same old APZC for the new content. Also, when reparenting a tab into
    // a new window a layer might get moved to a different layer tree with a
    // different APZCTreeManager. In these cases we don't want to reuse the same
    // APZC, so null it out so we run through the code to find another one or
    // create one.
    if (apzc && (!apzc->Matches(guid) || !apzc->HasTreeManager(this))) {
      apzc = nullptr;
    }

    // See if we can find an APZC from the previous tree that matches the
    // ScrollableLayerGuid from this layer. If there is one, then we know that
    // the layout of the page changed causing the layer tree to be rebuilt, but
    // the underlying content for the APZC is still there somewhere. Therefore,
    // we want to find the APZC instance and continue using it here.
    //
    // We particularly want to find the primary-holder node from the previous
    // tree that matches, because we don't want that node to get destroyed. If
    // it does get destroyed, then the APZC will get destroyed along with it by
    // definition, but we want to keep that APZC around in the new tree.
    // We leave non-primary-holder nodes in the destroy list because we don't
    // care about those nodes getting destroyed.
    for (size_t i = 0; i < aState.mNodesToDestroy.Length(); i++) {
      RefPtr<HitTestingTreeNode> n = aState.mNodesToDestroy[i];
      if (n->IsPrimaryHolder() && n->GetApzc() && n->GetApzc()->Matches(guid)) {
        node = n;
        if (apzc != nullptr) {
          // If there is an APZC already then it should match the one from the
          // old primary-holder node
          MOZ_ASSERT(apzc == node->GetApzc());
        }
        apzc = node->GetApzc();
        break;
      }
    }

    // The APZC we get off the layer may have been destroyed previously if the
    // layer was inactive or omitted from the layer tree for whatever reason
    // from a layers update. If it later comes back it will have a reference to
    // a destroyed APZC and so we need to throw that out and make a new one.
    bool newApzc = (apzc == nullptr || apzc->IsDestroyed());
    if (newApzc) {
      apzc = NewAPZCInstance(aLayersId, geckoContentController, aRenderRoot);
      apzc->SetCompositorController(aState.mCompositorController.get());
      if (crossProcessSharingController) {
        apzc->SetMetricsSharingController(crossProcessSharingController);
      } else {
        apzc->SetMetricsSharingController(
            aState.mInProcessSharingController.get());
      }
      MOZ_ASSERT(node == nullptr);
      node = new HitTestingTreeNode(apzc, true, aLayersId);
    } else {
      // If we are re-using a node for this layer clear the tree pointers
      // so that it doesn't continue pointing to nodes that might no longer
      // be in the tree. These pointers will get reset properly as we continue
      // building the tree. Also remove it from the set of nodes that are going
      // to be destroyed, because it's going to remain active.
      aState.mNodesToDestroy.RemoveElement(node);
      node->SetPrevSibling(nullptr);
      node->SetLastChild(nullptr);
    }

    if (aMetrics.IsRootContent()) {
      apzc->SetZoomAnimationId(aState.mZoomAnimationId);
      aState.mZoomAnimationId = Nothing();
    }

    APZCTM_LOG(
        "Using APZC %p for layer %p with identifiers %" PRIx64 " %" PRId64 "\n",
        apzc, aLayer.GetLayer(), uint64_t(aLayersId), aMetrics.GetScrollId());

    apzc->NotifyLayersUpdated(
        aLayer.Metadata(), aState.mIsFirstPaint,
        WRRootId(aLayersId, aRenderRoot) == aState.mOriginatingWrRootId);

    // Since this is the first time we are encountering an APZC with this guid,
    // the node holding it must be the primary holder. It may be newly-created
    // or not, depending on whether it went through the newApzc branch above.
    MOZ_ASSERT(node->IsPrimaryHolder() && node->GetApzc() &&
               node->GetApzc()->Matches(guid));

    Maybe<ParentLayerIntRegion> clipRegion =
        parentHasPerspective ? Nothing() : ComputeClipRegion(aLayer);
    SetHitTestData(node, aParent, aLayer, clipRegion);
    apzc->SetAncestorTransform(aAncestorTransform);

    PrintAPZCInfo(aLayer, apzc);

    // Bind the APZC instance into the tree of APZCs
    AttachNodeToTree(node, aParent, aNextSibling);

    // For testing, log the parent scroll id of every APZC that has a
    // parent. This allows test code to reconstruct the APZC tree.
    // Note that we currently only do this for APZCs in the layer tree
    // that originated the update, because the only identifying information
    // we are logging about APZCs is the scroll id, and otherwise we could
    // confuse APZCs from different layer trees with the same scroll id.
    if (aLayersId == aState.mOriginatingWrRootId.mLayersId) {
      if (apzc->HasNoParentWithSameLayersId()) {
        aState.mPaintLogger.LogTestData(aMetrics.GetScrollId(),
                                        "hasNoParentWithSameLayersId", true);
      } else {
        MOZ_ASSERT(apzc->GetParent());
        aState.mPaintLogger.LogTestData(aMetrics.GetScrollId(),
                                        "parentScrollId",
                                        apzc->GetParent()->GetGuid().mScrollId);
      }
      if (aMetrics.IsRootContent()) {
        aState.mPaintLogger.LogTestData(aMetrics.GetScrollId(), "isRootContent",
                                        true);
      }
      // Note that the async scroll offset is in ParentLayer pixels
      aState.mPaintLogger.LogTestData(
          aMetrics.GetScrollId(), "asyncScrollOffset",
          apzc->GetCurrentAsyncScrollOffset(
              AsyncPanZoomController::eForHitTesting));
      aState.mPaintLogger.LogTestData(aMetrics.GetScrollId(),
                                      "hasAsyncKeyScrolled",
                                      apzc->TestHasAsyncKeyScrolled());
    }

    if (newApzc) {
      auto it = mZoomConstraints.find(guid);
      if (it != mZoomConstraints.end()) {
        // We have a zoomconstraints for this guid, apply it.
        apzc->UpdateZoomConstraints(it->second);
      } else if (!apzc->HasNoParentWithSameLayersId()) {
        // This is a sub-APZC, so inherit the zoom constraints from its parent.
        // This ensures that if e.g. user-scalable=no was specified, none of the
        // APZCs for that subtree allow double-tap to zoom.
        apzc->UpdateZoomConstraints(apzc->GetParent()->GetZoomConstraints());
      }
      // Otherwise, this is the root of a layers id, but we didn't have a saved
      // zoom constraints. Leave it empty for now.
    }

    // Add a guid -> APZC mapping for the newly created APZC.
    insertResult.first->second = apzc;
  } else {
    // We already built an APZC earlier in this tree walk, but we have another
    // layer now that will also be using that APZC. The hit-test region on the
    // APZC needs to be updated to deal with the new layer's hit region.

    node = RecycleOrCreateNode(aProofOfTreeLock, aState, apzc, aLayersId);
    AttachNodeToTree(node, aParent, aNextSibling);

    // Even though different layers associated with a given APZC may be at
    // different levels in the layer tree (e.g. one being an uncle of another),
    // we require from Layout that the CSS transforms up to their common
    // ancestor be roughly the same. There are cases in which the transforms
    // are not exactly the same, for example if the parent is container layer
    // for an opacity, and this container layer has a resolution-induced scale
    // as its base transform and a prescale that is supposed to undo that scale.
    // Due to floating point inaccuracies those transforms can end up not quite
    // canceling each other. That's why we're using a fuzzy comparison here
    // instead of an exact one.
    // In addition, two ancestor transforms are allowed to differ if one of
    // them contains a perspective transform component and the other does not.
    // This represents situations where some content in a scrollable frame
    // is subject to a perspective transform and other content does not.
    // In such cases, go with the one that does not include the perspective
    // component; the perspective transform is remembered and applied to the
    // children instead.
    if (!aAncestorTransform.CombinedTransform().FuzzyEqualsMultiplicative(
            apzc->GetAncestorTransform())) {
      typedef TreeBuildingState::DeferredTransformMap::value_type PairType;
      if (!aAncestorTransform.ContainsPerspectiveTransform() &&
          !apzc->AncestorTransformContainsPerspective()) {
        MOZ_ASSERT(false,
                   "Two layers that scroll together have different ancestor "
                   "transforms");
      } else if (!aAncestorTransform.ContainsPerspectiveTransform()) {
        aState.mPerspectiveTransformsDeferredToChildren.insert(
            PairType{apzc, apzc->GetAncestorTransformPerspective()});
        apzc->SetAncestorTransform(aAncestorTransform);
      } else {
        aState.mPerspectiveTransformsDeferredToChildren.insert(
            PairType{apzc, aAncestorTransform.GetPerspectiveTransform()});
      }
    }

    Maybe<ParentLayerIntRegion> clipRegion =
        parentHasPerspective ? Nothing() : ComputeClipRegion(aLayer);
    SetHitTestData(node, aParent, aLayer, clipRegion);
  }

  // Note: if layer properties must be propagated to nodes, RecvUpdate in
  // LayerTransactionParent.cpp must ensure that APZ will be notified
  // when those properties change.
  node->SetScrollbarData(aLayer.GetScrollbarAnimationId(),
                         aLayer.GetScrollbarData());
  node->SetFixedPosData(aLayer.GetFixedPositionScrollContainerId(),
                        aLayer.GetFixedPositionSides());
  return node;
}

template <typename PanGestureOrScrollWheelInput>
static bool WillHandleInput(const PanGestureOrScrollWheelInput& aPanInput) {
  if (!XRE_IsParentProcess() || !NS_IsMainThread()) {
    return true;
  }

  WidgetWheelEvent wheelEvent = aPanInput.ToWidgetWheelEvent(nullptr);
  return APZInputBridge::ActionForWheelEvent(&wheelEvent).isSome();
}

/*static*/
void APZCTreeManager::FlushApzRepaints(LayersId aLayersId) {
  // Previously, paints were throttled and therefore this method was used to
  // ensure any pending paints were flushed. Now, paints are flushed
  // immediately, so it is safe to simply send a notification now.
  APZCTM_LOG("Flushing repaints for layers id 0x%" PRIx64 "\n",
             uint64_t(aLayersId));
  RefPtr<GeckoContentController> controller = GetContentController(aLayersId);
#ifndef MOZ_WIDGET_ANDROID
  // On Android, this code is run in production and may actually get a nullptr
  // controller here. On other platforms this code is test-only and should never
  // get a nullptr.
  MOZ_ASSERT(controller);
#endif
  if (controller) {
    controller->DispatchToRepaintThread(NewRunnableMethod(
        "layers::GeckoContentController::NotifyFlushComplete", controller,
        &GeckoContentController::NotifyFlushComplete));
  }
}

void APZCTreeManager::MarkAsDetached(LayersId aLayersId) {
  RecursiveMutexAutoLock lock(mTreeLock);
  mDetachedLayersIds.insert(aLayersId);
}

APZEventResult APZCTreeManager::ReceiveInputEvent(InputData& aEvent) {
  APZThreadUtils::AssertOnControllerThread();
  APZEventResult result;

  // Ignore input events when there are active tabs that are recording or
  // replaying. APZ does not work with the special layers constructed by
  // the middleman processes being communicated with here.
  if (dom::BrowserParent::AreRecordReplayTabsActive()) {
    return result;
  }

  // Use a RAII class for updating the focus sequence number of this event
  AutoFocusSequenceNumberSetter focusSetter(mFocusState, aEvent);

#if defined(MOZ_WIDGET_ANDROID)
  if (mToolbarAnimator) {
    ScreenPoint scrollOffset;
    {
      RecursiveMutexAutoLock lock(mTreeLock);
      RefPtr<AsyncPanZoomController> apzc = FindRootContentOrRootApzc();
      if (apzc) {
        scrollOffset = ViewAs<ScreenPixel>(
            apzc->GetCurrentAsyncScrollOffset(
                AsyncPanZoomController::eForHitTesting),
            PixelCastJustification::ScreenIsParentLayerForRoot);
      }
    }
    RefPtr<APZCTreeManager> self = this;
    nsEventStatus isConsumed =
        mToolbarAnimator->ReceiveInputEvent(self, aEvent, scrollOffset);
    // Check if the mToolbarAnimator consumed the event.
    if (isConsumed == nsEventStatus_eConsumeNoDefault) {
      APZCTM_LOG("Dynamic toolbar consumed event");
      result.mStatus = isConsumed;
      return result;
    }
  }
#endif  // (MOZ_WIDGET_ANDROID)

  CompositorHitTestInfo hitResult = CompositorHitTestInvisibleToHit;
  switch (aEvent.mInputType) {
    case MULTITOUCH_INPUT: {
      MultiTouchInput& touchInput = aEvent.AsMultiTouchInput();
      result = ProcessTouchInput(touchInput);
      break;
    }
    case MOUSE_INPUT: {
      MouseInput& mouseInput = aEvent.AsMouseInput();
      mouseInput.mHandledByAPZ = true;

      mCurrentMousePosition = mouseInput.mOrigin;

      bool startsDrag = DragTracker::StartsDrag(mouseInput);
      if (startsDrag) {
        // If this is the start of a drag we need to unambiguously know if it's
        // going to land on a scrollbar or not. We can't apply an untransform
        // here without knowing that, so we need to ensure the untransform is
        // a no-op.
        FlushRepaintsToClearScreenToGeckoTransform();
      }

      HitTestResult hit = GetTargetAPZC(mouseInput.mOrigin);
      aEvent.mLayersId = hit.mLayersId;
      hitResult = hit.mHitResult;
      bool hitScrollbar = (bool)hit.mScrollbarNode;

      // When the mouse is outside the window we still want to handle dragging
      // but we won't find an APZC. Fallback to root APZC then.
      {  // scope lock
        RecursiveMutexAutoLock lock(mTreeLock);
        if (!hit.mTargetApzc && mRootNode) {
          hit.mTargetApzc = mRootNode->GetApzc();
        }
      }

      if (hit.mTargetApzc) {
        if (StaticPrefs::apz_test_logging_enabled() &&
            mouseInput.mType == MouseInput::MOUSE_HITTEST) {
          ScrollableLayerGuid guid = hit.mTargetApzc->GetGuid();

          MutexAutoLock lock(mTestDataLock);
          auto it = mTestData.find(guid.mLayersId);
          MOZ_ASSERT(it != mTestData.end());
          it->second->RecordHitResult(mouseInput.mOrigin, hitResult,
                                      guid.mLayersId, guid.mScrollId);
        }

        TargetConfirmationFlags confFlags{hitResult};
        bool apzDragEnabled = StaticPrefs::apz_drag_enabled();
        if (apzDragEnabled && hitScrollbar) {
          // If scrollbar dragging is enabled and we hit a scrollbar, wait
          // for the main-thread confirmation because it contains drag metrics
          // that we need.
          confFlags.mTargetConfirmed = false;
        }
        result.mStatus = mInputQueue->ReceiveInputEvent(
            hit.mTargetApzc, confFlags, mouseInput, &result.mInputBlockId);

        // If we're starting an async scrollbar drag
        if (apzDragEnabled && startsDrag && hit.mScrollbarNode &&
            hit.mScrollbarNode->IsScrollThumbNode() &&
            hit.mScrollbarNode->GetScrollbarData().mThumbIsAsyncDraggable) {
          SetupScrollbarDrag(mouseInput, hit.mScrollbarNode,
                             hit.mTargetApzc.get());
        }

        if (result.mStatus == nsEventStatus_eConsumeDoDefault) {
          // This input event is part of a drag block, so whether or not it is
          // directed at a scrollbar depends on whether the drag block started
          // on a scrollbar.
          hitScrollbar = mInputQueue->IsDragOnScrollbar(hitScrollbar);
        }

        // Update the out-parameters so they are what the caller expects.
        hit.mTargetApzc->GetGuid(&result.mTargetGuid);

        if (!hitScrollbar) {
          // The input was not targeted at a scrollbar, so we untransform it
          // like we do for other content. Scrollbars are "special" because they
          // have special handling in AsyncCompositionManager when resolution is
          // applied. TODO: we should find a better way to deal with this.
          ScreenToParentLayerMatrix4x4 transformToApzc =
              GetScreenToApzcTransform(hit.mTargetApzc);
          ParentLayerToScreenMatrix4x4 transformToGecko =
              GetApzcToGeckoTransform(hit.mTargetApzc);
          ScreenToScreenMatrix4x4 outTransform =
              transformToApzc * transformToGecko;
          Maybe<ScreenPoint> untransformedRefPoint =
              UntransformBy(outTransform, mouseInput.mOrigin);
          if (untransformedRefPoint) {
            mouseInput.mOrigin = *untransformedRefPoint;
          }
        } else {
          // Likewise, if the input was targeted at a scrollbar, we don't want
          // to apply the callback transform in the main thread, so we remove
          // the scrollid from the guid. We need to keep the layersId intact so
          // that the response from the child process doesn't get discarded.
          result.mTargetGuid.mScrollId = ScrollableLayerGuid::NULL_SCROLL_ID;
        }
      }
      break;
    }
    case SCROLLWHEEL_INPUT: {
      FlushRepaintsToClearScreenToGeckoTransform();

      // Do this before early return for Fission hit testing.
      ScrollWheelInput& wheelInput = aEvent.AsScrollWheelInput();
      HitTestResult hit = GetTargetAPZC(wheelInput.mOrigin);
      aEvent.mLayersId = hit.mLayersId;
      hitResult = hit.mHitResult;

      wheelInput.mHandledByAPZ = WillHandleInput(wheelInput);
      if (!wheelInput.mHandledByAPZ) {
        return result;
      }

      if (hit.mTargetApzc) {
        MOZ_ASSERT(hitResult != CompositorHitTestInvisibleToHit);

        if (wheelInput.mAPZAction == APZWheelAction::PinchZoom) {
          // The mousewheel may have hit a subframe, but we want to send the
          // pinch-zoom events to the root-content APZC.
          {
            RecursiveMutexAutoLock lock(mTreeLock);
            hit.mTargetApzc =
                FindRootContentApzcForLayersId(hit.mTargetApzc->GetLayersId());
          }
          if (hit.mTargetApzc) {
            SynthesizePinchGestureFromMouseWheel(wheelInput, hit.mTargetApzc);
          }
          result.mStatus = nsEventStatus_eConsumeNoDefault;
          return result;
        }

        MOZ_ASSERT(wheelInput.mAPZAction == APZWheelAction::Scroll);

        // For wheel events, the call to ReceiveInputEvent below may result in
        // scrolling, which changes the async transform. However, the event we
        // want to pass to gecko should be the pre-scroll event coordinates,
        // transformed into the gecko space. (pre-scroll because the mouse
        // cursor is stationary during wheel scrolling, unlike touchmove
        // events). Since we just flushed the pending repaints the transform to
        // gecko space should only consist of overscroll-cancelling transforms.
        ScreenToScreenMatrix4x4 transformToGecko =
            GetScreenToApzcTransform(hit.mTargetApzc) *
            GetApzcToGeckoTransform(hit.mTargetApzc);
        Maybe<ScreenPoint> untransformedOrigin =
            UntransformBy(transformToGecko, wheelInput.mOrigin);

        if (!untransformedOrigin) {
          return result;
        }

        result.mStatus = mInputQueue->ReceiveInputEvent(
            hit.mTargetApzc, TargetConfirmationFlags{hitResult}, wheelInput,
            &result.mInputBlockId);

        // Update the out-parameters so they are what the caller expects.
        hit.mTargetApzc->GetGuid(&result.mTargetGuid);
        wheelInput.mOrigin = *untransformedOrigin;
      }
      break;
    }
    case PANGESTURE_INPUT: {
      FlushRepaintsToClearScreenToGeckoTransform();

      // Do this before early return for Fission hit testing.
      PanGestureInput& panInput = aEvent.AsPanGestureInput();
      HitTestResult hit = GetTargetAPZC(panInput.mPanStartPoint);
      aEvent.mLayersId = hit.mLayersId;
      hitResult = hit.mHitResult;

      panInput.mHandledByAPZ = WillHandleInput(panInput);
      if (!panInput.mHandledByAPZ) {
        return result;
      }

      // If/when we enable support for pan inputs off-main-thread, we'll need
      // to duplicate this EventStateManager code or something. See the call to
      // GetUserPrefsForWheelEvent in IAPZCTreeManager.cpp for why these fields
      // are stored separately.
      MOZ_ASSERT(NS_IsMainThread());
      WidgetWheelEvent wheelEvent = panInput.ToWidgetWheelEvent(nullptr);
      EventStateManager::GetUserPrefsForWheelEvent(
          &wheelEvent, &panInput.mUserDeltaMultiplierX,
          &panInput.mUserDeltaMultiplierY);

      if (hit.mTargetApzc) {
        MOZ_ASSERT(hitResult != CompositorHitTestInvisibleToHit);

        // For pan gesture events, the call to ReceiveInputEvent below may
        // result in scrolling, which changes the async transform. However, the
        // event we want to pass to gecko should be the pre-scroll event
        // coordinates, transformed into the gecko space. (pre-scroll because
        // the mouse cursor is stationary during pan gesture scrolling, unlike
        // touchmove events). Since we just flushed the pending repaints the
        // transform to gecko space should only consist of overscroll-cancelling
        // transforms.
        ScreenToScreenMatrix4x4 transformToGecko =
            GetScreenToApzcTransform(hit.mTargetApzc) *
            GetApzcToGeckoTransform(hit.mTargetApzc);
        Maybe<ScreenPoint> untransformedStartPoint =
            UntransformBy(transformToGecko, panInput.mPanStartPoint);
        Maybe<ScreenPoint> untransformedDisplacement =
            UntransformVector(transformToGecko, panInput.mPanDisplacement,
                              panInput.mPanStartPoint);

        if (!untransformedStartPoint || !untransformedDisplacement) {
          return result;
        }

        result.mStatus = mInputQueue->ReceiveInputEvent(
            hit.mTargetApzc, TargetConfirmationFlags{hitResult}, panInput,
            &result.mInputBlockId);

        // Update the out-parameters so they are what the caller expects.
        hit.mTargetApzc->GetGuid(&result.mTargetGuid);
        panInput.mPanStartPoint = *untransformedStartPoint;
        panInput.mPanDisplacement = *untransformedDisplacement;

        panInput.mOverscrollBehaviorAllowsSwipe =
            hit.mTargetApzc->OverscrollBehaviorAllowsSwipe();
      }
      break;
    }
    case PINCHGESTURE_INPUT: {  // note: no one currently sends these
      PinchGestureInput& pinchInput = aEvent.AsPinchGestureInput();
      HitTestResult hit = GetTargetAPZC(pinchInput.mFocusPoint);
      aEvent.mLayersId = hit.mLayersId;
      hitResult = hit.mHitResult;

      if (hit.mTargetApzc) {
        MOZ_ASSERT(hitResult != CompositorHitTestInvisibleToHit);

        ScreenToScreenMatrix4x4 outTransform =
            GetScreenToApzcTransform(hit.mTargetApzc) *
            GetApzcToGeckoTransform(hit.mTargetApzc);
        Maybe<ScreenPoint> untransformedFocusPoint =
            UntransformBy(outTransform, pinchInput.mFocusPoint);

        if (!untransformedFocusPoint) {
          return result;
        }

        result.mStatus = mInputQueue->ReceiveInputEvent(
            hit.mTargetApzc, TargetConfirmationFlags{hitResult}, pinchInput,
            &result.mInputBlockId);

        // Update the out-parameters so they are what the caller expects.
        hit.mTargetApzc->GetGuid(&result.mTargetGuid);
        pinchInput.mFocusPoint = *untransformedFocusPoint;
      }
      break;
    }
    case TAPGESTURE_INPUT: {  // note: no one currently sends these
      TapGestureInput& tapInput = aEvent.AsTapGestureInput();
      HitTestResult hit = GetTargetAPZC(tapInput.mPoint);
      aEvent.mLayersId = hit.mLayersId;
      hitResult = hit.mHitResult;

      if (hit.mTargetApzc) {
        MOZ_ASSERT(hitResult != CompositorHitTestInvisibleToHit);

        ScreenToScreenMatrix4x4 outTransform =
            GetScreenToApzcTransform(hit.mTargetApzc) *
            GetApzcToGeckoTransform(hit.mTargetApzc);
        Maybe<ScreenIntPoint> untransformedPoint =
            UntransformBy(outTransform, tapInput.mPoint);

        if (!untransformedPoint) {
          return result;
        }

        result.mStatus = mInputQueue->ReceiveInputEvent(
            hit.mTargetApzc, TargetConfirmationFlags{hitResult}, tapInput,
            &result.mInputBlockId);

        // Update the out-parameters so they are what the caller expects.
        hit.mTargetApzc->GetGuid(&result.mTargetGuid);
        tapInput.mPoint = *untransformedPoint;
      }
      break;
    }
    case KEYBOARD_INPUT: {
      // Disable async keyboard scrolling when accessibility.browsewithcaret is
      // enabled
      if (!StaticPrefs::apz_keyboard_enabled_AtStartup() ||
          StaticPrefs::accessibility_browsewithcaret()) {
        APZ_KEY_LOG("Skipping key input from invalid prefs\n");
        return result;
      }

      KeyboardInput& keyInput = aEvent.AsKeyboardInput();

      // Try and find a matching shortcut for this keyboard input
      Maybe<KeyboardShortcut> shortcut = mKeyboardMap.FindMatch(keyInput);

      if (!shortcut) {
        APZ_KEY_LOG("Skipping key input with no shortcut\n");

        // If we don't have a shortcut for this key event, then we can keep our
        // focus only if we know there are no key event listeners for this
        // target
        if (mFocusState.CanIgnoreKeyboardShortcutMisses()) {
          focusSetter.MarkAsNonFocusChanging();
        }
        return result;
      }

      // Check if this shortcut needs to be dispatched to content. Anything
      // matching this is assumed to be able to change focus.
      if (shortcut->mDispatchToContent) {
        APZ_KEY_LOG("Skipping key input with dispatch-to-content shortcut\n");
        return result;
      }

      // We know we have an action to execute on whatever is the current focus
      // target
      const KeyboardScrollAction& action = shortcut->mAction;

      // The current focus target depends on which direction the scroll is to
      // happen
      Maybe<ScrollableLayerGuid> targetGuid;
      switch (action.mType) {
        case KeyboardScrollAction::eScrollCharacter: {
          targetGuid = mFocusState.GetHorizontalTarget();
          break;
        }
        case KeyboardScrollAction::eScrollLine:
        case KeyboardScrollAction::eScrollPage:
        case KeyboardScrollAction::eScrollComplete: {
          targetGuid = mFocusState.GetVerticalTarget();
          break;
        }
      }

      // If we don't have a scroll target then either we have a stale focus
      // target, the focused element has event listeners, or the focused element
      // doesn't have a layerized scroll frame. In any case we need to dispatch
      // to content.
      if (!targetGuid) {
        APZ_KEY_LOG("Skipping key input with no current focus target\n");
        return result;
      }

      RefPtr<AsyncPanZoomController> targetApzc =
          GetTargetAPZC(targetGuid->mLayersId, targetGuid->mScrollId);

      if (!targetApzc) {
        APZ_KEY_LOG("Skipping key input with focus target but no APZC\n");
        return result;
      }

      // Attach the keyboard scroll action to the input event for processing
      // by the input queue.
      keyInput.mAction = action;

      APZ_KEY_LOG("Dispatching key input with apzc=%p\n", targetApzc.get());

      // Dispatch the event to the input queue.
      result.mStatus = mInputQueue->ReceiveInputEvent(
          targetApzc, TargetConfirmationFlags{true}, keyInput,
          &result.mInputBlockId);

      // Any keyboard event that is dispatched to the input queue at this point
      // should have been consumed
      MOZ_ASSERT(result.mStatus == nsEventStatus_eConsumeDoDefault ||
                 result.mStatus == nsEventStatus_eConsumeNoDefault);

      keyInput.mHandledByAPZ = true;
      focusSetter.MarkAsNonFocusChanging();

      break;
    }
  }
  return result;
}

static TouchBehaviorFlags ConvertToTouchBehavior(
    const CompositorHitTestInfo& info) {
  TouchBehaviorFlags result = AllowedTouchBehavior::UNKNOWN;
  if (info == CompositorHitTestInvisibleToHit) {
    result = AllowedTouchBehavior::NONE;
  } else if (info.contains(CompositorHitTestFlags::eIrregularArea)) {
    // Note that eApzAwareListeners and eInactiveScrollframe are similar
    // to eIrregularArea in some respects, but are not relevant for the
    // purposes of this function, which deals specifically with touch-action.
    result = AllowedTouchBehavior::UNKNOWN;
  } else {
    result = AllowedTouchBehavior::VERTICAL_PAN |
             AllowedTouchBehavior::HORIZONTAL_PAN |
             AllowedTouchBehavior::PINCH_ZOOM |
             AllowedTouchBehavior::DOUBLE_TAP_ZOOM;
    if (info.contains(CompositorHitTestFlags::eTouchActionPanXDisabled)) {
      result &= ~AllowedTouchBehavior::HORIZONTAL_PAN;
    }
    if (info.contains(CompositorHitTestFlags::eTouchActionPanYDisabled)) {
      result &= ~AllowedTouchBehavior::VERTICAL_PAN;
    }
    if (info.contains(CompositorHitTestFlags::eTouchActionPinchZoomDisabled)) {
      result &= ~AllowedTouchBehavior::PINCH_ZOOM;
    }
    if (info.contains(
            CompositorHitTestFlags::eTouchActionDoubleTapZoomDisabled)) {
      result &= ~AllowedTouchBehavior::DOUBLE_TAP_ZOOM;
    }
  }
  return result;
}

APZCTreeManager::HitTestResult APZCTreeManager::GetTouchInputBlockAPZC(
    const MultiTouchInput& aEvent,
    nsTArray<TouchBehaviorFlags>* aOutTouchBehaviors) {
  HitTestResult hit;
  if (aEvent.mTouches.Length() == 0) {
    return hit;
  }

  FlushRepaintsToClearScreenToGeckoTransform();

  hit = GetTargetAPZC(aEvent.mTouches[0].mScreenPoint);
  // Don't set a layers id on multi-touch events.
  if (aEvent.mTouches.Length() != 1) {
    hit.mLayersId = LayersId{0};
  }

  if (aOutTouchBehaviors) {
    aOutTouchBehaviors->AppendElement(ConvertToTouchBehavior(hit.mHitResult));
  }
  for (size_t i = 1; i < aEvent.mTouches.Length(); i++) {
    HitTestResult hit2 = GetTargetAPZC(aEvent.mTouches[i].mScreenPoint);
    if (aOutTouchBehaviors) {
      aOutTouchBehaviors->AppendElement(
          ConvertToTouchBehavior(hit2.mHitResult));
    }
    hit.mTargetApzc = GetZoomableTarget(hit.mTargetApzc, hit2.mTargetApzc);
    APZCTM_LOG("Using APZC %p as the root APZC for multi-touch\n", apzc.get());
    // A multi-touch gesture will not be a scrollbar drag, even if the
    // first touch point happened to hit a scrollbar.
    hit.mScrollbarNode.Clear();

    // XXX we should probably be combining the hit results from the different
    // touch points somehow, instead of just using the last one.
    hit.mHitResult = hit2.mHitResult;
  }

  return hit;
}

/**
 * Returns whether |aHitResult| *may* indicate that we hit a region with
 * APZ-aware listeners.
 */
bool MayHaveApzAwareListeners(CompositorHitTestInfo aHitResult) {
  // With WebRender, we can answer this accurately.
  if (gfx::gfxVars::UseWebRender()) {
    return aHitResult.contains(CompositorHitTestFlags::eApzAwareListeners);
  }
  // With non-WebRender, several hit results including eApzAwareListeners
  // get lumped together into the dispatch-to-content region. We err on
  // the side of false positives.
  return !((aHitResult & CompositorHitTestDispatchToContent).isEmpty());
}

APZEventResult APZCTreeManager::ProcessTouchInput(MultiTouchInput& aInput) {
  APZEventResult result;  // mStatus == eIgnore
  aInput.mHandledByAPZ = true;
  nsTArray<TouchBehaviorFlags> touchBehaviors;
  HitTestingTreeNodeAutoLock hitScrollbarNode;
  if (aInput.mType == MultiTouchInput::MULTITOUCH_START) {
    // If we are panned into overscroll and a second finger goes down,
    // ignore that second touch point completely. The touch-start for it is
    // dropped completely; subsequent touch events until the touch-end for it
    // will have this touch point filtered out.
    // (By contrast, if we're in overscroll but not panning, such as after
    // putting two fingers down during an overscroll animation, we process the
    // second touch and proceed to pinch.)
    if (mApzcForInputBlock && mApzcForInputBlock->IsInPanningState() &&
        BuildOverscrollHandoffChain(mApzcForInputBlock)
            ->HasOverscrolledApzc()) {
      if (mRetainedTouchIdentifier == -1) {
        mRetainedTouchIdentifier = mApzcForInputBlock->GetLastTouchIdentifier();
      }
      result.mStatus = nsEventStatus_eConsumeNoDefault;
      return result;
    }

    mHitResultForInputBlock = CompositorHitTestInvisibleToHit;
    HitTestResult hit = GetTouchInputBlockAPZC(aInput, &touchBehaviors);
    mApzcForInputBlock = hit.mTargetApzc;
    mHitResultForInputBlock = hit.mHitResult;
    mFixedPosSidesForInputBlock = hit.mFixedPosSides;
    if (hit.mLayersId.IsValid()) {
      // Check for validity because we won't get a layers id for multi-touch
      // events.
      aInput.mLayersId = hit.mLayersId;
    }
    hitScrollbarNode = std::move(hit.mScrollbarNode);

    // Check if this event starts a scrollbar touch-drag. The conditions
    // checked are similar to the ones we check for MOUSE_INPUT starting
    // a scrollbar mouse-drag.
    mInScrollbarTouchDrag =
        StaticPrefs::apz_drag_enabled() &&
        StaticPrefs::apz_drag_touch_enabled() && hitScrollbarNode &&
        hitScrollbarNode->IsScrollThumbNode() &&
        hitScrollbarNode->GetScrollbarData().mThumbIsAsyncDraggable;

    MOZ_ASSERT(touchBehaviors.Length() == aInput.mTouches.Length());
    for (size_t i = 0; i < touchBehaviors.Length(); i++) {
      APZCTM_LOG("Touch point has allowed behaviours 0x%02x\n",
                 touchBehaviors[i]);
      if (touchBehaviors[i] == AllowedTouchBehavior::UNKNOWN) {
        // If there's any unknown items in the list, throw it out and we'll
        // wait for the main thread to send us a notification.
        touchBehaviors.Clear();
        break;
      }
    }
  } else if (mApzcForInputBlock) {
    APZCTM_LOG("Re-using APZC %p as continuation of event block\n",
               mApzcForInputBlock.get());
  }

  if (mInScrollbarTouchDrag) {
    result = ProcessTouchInputForScrollbarDrag(aInput, hitScrollbarNode);
  } else {
    // If we receive a touch-cancel, it means all touches are finished, so we
    // can stop ignoring any that we were ignoring.
    if (aInput.mType == MultiTouchInput::MULTITOUCH_CANCEL) {
      mRetainedTouchIdentifier = -1;
    }

    // If we are currently ignoring any touch points, filter them out from the
    // set of touch points included in this event. Note that we modify aInput
    // itself, so that the touch points are also filtered out when the caller
    // passes the event on to content.
    if (mRetainedTouchIdentifier != -1) {
      for (size_t j = 0; j < aInput.mTouches.Length(); ++j) {
        if (aInput.mTouches[j].mIdentifier != mRetainedTouchIdentifier) {
          aInput.mTouches.RemoveElementAt(j);
          if (!touchBehaviors.IsEmpty()) {
            MOZ_ASSERT(touchBehaviors.Length() > j);
            touchBehaviors.RemoveElementAt(j);
          }
          --j;
        }
      }
      if (aInput.mTouches.IsEmpty()) {
        result.mStatus = nsEventStatus_eConsumeNoDefault;
        return result;
      }
    }

    if (mApzcForInputBlock) {
      MOZ_ASSERT(mHitResultForInputBlock != CompositorHitTestInvisibleToHit);

      mApzcForInputBlock->GetGuid(&result.mTargetGuid);
      result.mStatus = mInputQueue->ReceiveInputEvent(
          mApzcForInputBlock, TargetConfirmationFlags{mHitResultForInputBlock},
          aInput, &result.mInputBlockId,
          touchBehaviors.IsEmpty() ? Nothing() : Some(touchBehaviors));
      result.mHitRegionWithApzAwareListeners =
          MayHaveApzAwareListeners(mHitResultForInputBlock);

      // For computing the event to pass back to Gecko, use up-to-date
      // transforms (i.e. not anything cached in an input block). This ensures
      // that transformToApzc and transformToGecko are in sync.
      // Note: we are not using ConvertToGecko() here, because we don't
      // want to multiply transformToApzc and transformToGecko once
      // for each touch point.
      ScreenToParentLayerMatrix4x4 transformToApzc =
          GetScreenToApzcTransform(mApzcForInputBlock);
      ParentLayerToScreenMatrix4x4 transformToGecko =
          GetApzcToGeckoTransform(mApzcForInputBlock);
      ScreenToScreenMatrix4x4 outTransform = transformToApzc * transformToGecko;

      for (size_t i = 0; i < aInput.mTouches.Length(); i++) {
        SingleTouchData& touchData = aInput.mTouches[i];
        Maybe<ScreenIntPoint> untransformedScreenPoint =
            UntransformBy(outTransform, touchData.mScreenPoint);
        if (!untransformedScreenPoint) {
          result.mStatus = nsEventStatus_eIgnore;
          return result;
        }
        touchData.mScreenPoint = *untransformedScreenPoint;
        if (mFixedPosSidesForInputBlock != eSideBitsNone) {
          RecursiveMutexAutoLock lock(mTreeLock);
          touchData.mScreenPoint -=
              RoundedToInt(AsyncCompositionManager::ComputeFixedMarginsOffset(
                  mFixedLayerMargins, mFixedPosSidesForInputBlock));
        }
      }
    }
  }

  mTouchCounter.Update(aInput);

  // If it's the end of the touch sequence then clear out variables so we
  // don't keep dangling references and leak things.
  if (mTouchCounter.GetActiveTouchCount() == 0) {
    mApzcForInputBlock = nullptr;
    mHitResultForInputBlock = CompositorHitTestInvisibleToHit;
    mRetainedTouchIdentifier = -1;
    mInScrollbarTouchDrag = false;
  }

  return result;
}

static MouseInput::MouseType MultiTouchTypeToMouseType(
    MultiTouchInput::MultiTouchType aType) {
  switch (aType) {
    case MultiTouchInput::MULTITOUCH_START:
      return MouseInput::MOUSE_DOWN;
    case MultiTouchInput::MULTITOUCH_MOVE:
      return MouseInput::MOUSE_MOVE;
    case MultiTouchInput::MULTITOUCH_END:
    case MultiTouchInput::MULTITOUCH_CANCEL:
      return MouseInput::MOUSE_UP;
  }
  MOZ_ASSERT_UNREACHABLE("Invalid multi-touch type");
  return MouseInput::MOUSE_NONE;
}

APZEventResult APZCTreeManager::ProcessTouchInputForScrollbarDrag(
    MultiTouchInput& aTouchInput,
    const HitTestingTreeNodeAutoLock& aScrollThumbNode) {
  MOZ_ASSERT(mRetainedTouchIdentifier == -1);
  MOZ_ASSERT(mApzcForInputBlock);
  MOZ_ASSERT(aTouchInput.mTouches.Length() == 1);

  // Synthesize a mouse event based on the touch event, so that we can
  // reuse code in InputQueue and APZC for handling scrollbar mouse-drags.
  MouseInput mouseInput{MultiTouchTypeToMouseType(aTouchInput.mType),
                        MouseInput::LEFT_BUTTON,
                        dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH,
                        MouseButtonsFlag::eLeftFlag,
                        aTouchInput.mTouches[0].mScreenPoint,
                        aTouchInput.mTime,
                        aTouchInput.mTimeStamp,
                        aTouchInput.modifiers};
  mouseInput.mHandledByAPZ = true;

  // The value of |targetConfirmed| passed to InputQueue::ReceiveInputEvent()
  // only matters for the first event, which creates the drag block. For
  // that event, the correct value is false, since the drag block will, at the
  // earliest, be confirmed in the subsequent SetupScrollbarDrag() call.
  TargetConfirmationFlags targetConfirmed{false};

  APZEventResult result;
  result.mStatus = mInputQueue->ReceiveInputEvent(
      mApzcForInputBlock, targetConfirmed, mouseInput, &result.mInputBlockId);

  // |aScrollThumbNode| is non-null iff. this is the event that starts the drag.
  // If so, set up the drag.
  if (aScrollThumbNode) {
    SetupScrollbarDrag(mouseInput, aScrollThumbNode, mApzcForInputBlock.get());
  }

  mApzcForInputBlock->GetGuid(&result.mTargetGuid);

  // Since the input was targeted at a scrollbar:
  //    - The original touch event (which will be sent on to content) will
  //      not be untransformed.
  //    - We don't want to apply the callback transform in the main thread,
  //      so we remove the scrollid from the guid.
  // Both of these match the behaviour of mouse events that target a scrollbar;
  // see the code for handling mouse events in ReceiveInputEvent() for
  // additional explanation.
  result.mTargetGuid.mScrollId = ScrollableLayerGuid::NULL_SCROLL_ID;

  return result;
}

void APZCTreeManager::SetupScrollbarDrag(
    MouseInput& aMouseInput, const HitTestingTreeNodeAutoLock& aScrollThumbNode,
    AsyncPanZoomController* aApzc) {
  DragBlockState* dragBlock = mInputQueue->GetCurrentDragBlock();
  if (!dragBlock) {
    return;
  }

  const ScrollbarData& thumbData = aScrollThumbNode->GetScrollbarData();
  MOZ_ASSERT(thumbData.mDirection.isSome());

  // Record the thumb's position at the start of the drag.
  // We snap back to this position if, during the drag, the mouse
  // gets sufficiently far away from the scrollbar.
  dragBlock->SetInitialThumbPos(thumbData.mThumbStart);

  // Under some conditions, we can confirm the drag block right away.
  // Otherwise, we have to wait for a main-thread confirmation.
  if (StaticPrefs::apz_drag_initial_enabled() &&
      // check that the scrollbar's target scroll frame is layerized
      aScrollThumbNode->GetScrollTargetId() == aApzc->GetGuid().mScrollId &&
      !aApzc->IsScrollInfoLayer()) {
    uint64_t dragBlockId = dragBlock->GetBlockId();
    // AsyncPanZoomController::HandleInputEvent() will call
    // TransformToLocal() on the event, but we need its mLocalOrigin now
    // to compute a drag start offset for the AsyncDragMetrics.
    aMouseInput.TransformToLocal(aApzc->GetTransformToThis());
    CSSCoord dragStart =
        aApzc->ConvertScrollbarPoint(aMouseInput.mLocalOrigin, thumbData);
    // ConvertScrollbarPoint() got the drag start offset relative to
    // the scroll track. Now get it relative to the thumb.
    // ScrollThumbData::mThumbStart stores the offset of the thumb
    // relative to the scroll track at the time of the last paint.
    // Since that paint, the thumb may have acquired an async transform
    // due to async scrolling, so look that up and apply it.
    LayerToParentLayerMatrix4x4 thumbTransform;
    {
      RecursiveMutexAutoLock lock(mTreeLock);
      thumbTransform = ComputeTransformForNode(aScrollThumbNode.Get(lock));
    }
    // Only consider the translation, since we do not support both
    // zooming and scrollbar dragging on any platform.
    CSSCoord thumbStart =
        thumbData.mThumbStart +
        ((*thumbData.mDirection == ScrollDirection::eHorizontal)
             ? thumbTransform._41
             : thumbTransform._42);
    dragStart -= thumbStart;

    // Content can't prevent scrollbar dragging with preventDefault(),
    // so we don't need to wait for a content response. It's important
    // to do this before calling ConfirmDragBlock() since that can
    // potentially process and consume the block.
    dragBlock->SetContentResponse(false);

    NotifyScrollbarDragInitiated(dragBlockId, aApzc->GetGuid(),
                                 *thumbData.mDirection);

    mInputQueue->ConfirmDragBlock(
        dragBlockId, aApzc,
        AsyncDragMetrics(aApzc->GetGuid().mScrollId,
                         aApzc->GetGuid().mPresShellId, dragBlockId, dragStart,
                         *thumbData.mDirection));
  }
}

void APZCTreeManager::SynthesizePinchGestureFromMouseWheel(
    const ScrollWheelInput& aWheelInput,
    const RefPtr<AsyncPanZoomController>& aTarget) {
  MOZ_ASSERT(aTarget);

  ScreenPoint focusPoint = aWheelInput.mOrigin;

  // Compute span values based on the wheel delta.
  ScreenCoord oldSpan = 100;
  ScreenCoord newSpan = oldSpan + aWheelInput.mDeltaY;

  // There's no ambiguity as to the target for pinch gesture events.
  TargetConfirmationFlags confFlags{true};

  PinchGestureInput pinchStart{PinchGestureInput::PINCHGESTURE_START,
                               aWheelInput.mTime,
                               aWheelInput.mTimeStamp,
                               ExternalPoint(0, 0),
                               focusPoint,
                               oldSpan,
                               oldSpan,
                               aWheelInput.modifiers};
  PinchGestureInput pinchScale1{PinchGestureInput::PINCHGESTURE_SCALE,
                                aWheelInput.mTime,
                                aWheelInput.mTimeStamp,
                                ExternalPoint(0, 0),
                                focusPoint,
                                oldSpan,
                                oldSpan,
                                aWheelInput.modifiers};
  PinchGestureInput pinchScale2{PinchGestureInput::PINCHGESTURE_SCALE,
                                aWheelInput.mTime,
                                aWheelInput.mTimeStamp,
                                ExternalPoint(0, 0),
                                focusPoint,
                                oldSpan,
                                newSpan,
                                aWheelInput.modifiers};
  PinchGestureInput pinchEnd{
      PinchGestureInput::PINCHGESTURE_END,
      aWheelInput.mTime,
      aWheelInput.mTimeStamp,
      ExternalPoint(0, 0),
      PinchGestureInput::BothFingersLifted<ScreenPixel>(),
      newSpan,
      newSpan,
      aWheelInput.modifiers};

  mInputQueue->ReceiveInputEvent(aTarget, confFlags, pinchStart, nullptr);
  mInputQueue->ReceiveInputEvent(aTarget, confFlags, pinchScale1, nullptr);
  mInputQueue->ReceiveInputEvent(aTarget, confFlags, pinchScale2, nullptr);
  mInputQueue->ReceiveInputEvent(aTarget, confFlags, pinchEnd, nullptr);
}

void APZCTreeManager::UpdateWheelTransaction(LayoutDeviceIntPoint aRefPoint,
                                             EventMessage aEventMessage) {
  APZThreadUtils::AssertOnControllerThread();

  WheelBlockState* txn = mInputQueue->GetActiveWheelTransaction();
  if (!txn) {
    return;
  }

  // If the transaction has simply timed out, we don't need to do anything
  // else.
  if (txn->MaybeTimeout(TimeStamp::Now())) {
    return;
  }

  switch (aEventMessage) {
    case eMouseMove:
    case eDragOver: {
      ScreenIntPoint point = ViewAs<ScreenPixel>(
          aRefPoint,
          PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent);

      txn->OnMouseMove(point);

      return;
    }
    case eKeyPress:
    case eKeyUp:
    case eKeyDown:
    case eMouseUp:
    case eMouseDown:
    case eMouseDoubleClick:
    case eMouseAuxClick:
    case eMouseClick:
    case eContextMenu:
    case eDrop:
      txn->EndTransaction();
      return;
    default:
      break;
  }
}

void APZCTreeManager::ProcessUnhandledEvent(LayoutDeviceIntPoint* aRefPoint,
                                            ScrollableLayerGuid* aOutTargetGuid,
                                            uint64_t* aOutFocusSequenceNumber,
                                            LayersId* aOutLayersId) {
  APZThreadUtils::AssertOnControllerThread();

  // Transform the aRefPoint.
  // If the event hits an overscrolled APZC, instruct the caller to ignore it.
  PixelCastJustification LDIsScreen =
      PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent;
  ScreenIntPoint refPointAsScreen = ViewAs<ScreenPixel>(*aRefPoint, LDIsScreen);
  HitTestResult hit = GetTargetAPZC(refPointAsScreen);
  if (aOutLayersId) {
    *aOutLayersId = hit.mLayersId;
  }
  if (hit.mTargetApzc) {
    MOZ_ASSERT(hit.mHitResult != CompositorHitTestInvisibleToHit);
    hit.mTargetApzc->GetGuid(aOutTargetGuid);
    ScreenToParentLayerMatrix4x4 transformToApzc =
        GetScreenToApzcTransform(hit.mTargetApzc);
    ParentLayerToScreenMatrix4x4 transformToGecko =
        GetApzcToGeckoTransform(hit.mTargetApzc);
    ScreenToScreenMatrix4x4 outTransform = transformToApzc * transformToGecko;
    Maybe<ScreenIntPoint> untransformedRefPoint =
        UntransformBy(outTransform, refPointAsScreen);
    if (untransformedRefPoint) {
      *aRefPoint =
          ViewAs<LayoutDevicePixel>(*untransformedRefPoint, LDIsScreen);
    }
  }

  // Update the focus sequence number and attach it to the event
  mFocusState.ReceiveFocusChangingEvent();
  *aOutFocusSequenceNumber = mFocusState.LastAPZProcessedEvent();
}

void APZCTreeManager::ProcessDynamicToolbarMovement(uint32_t aStartTimestampMs,
                                                    uint32_t aEndTimestampMs,
                                                    ScreenCoord aDeltaY) {
  if (mApzcForInputBlock) {
    mApzcForInputBlock->HandleDynamicToolbarMovement(
        aStartTimestampMs, aEndTimestampMs,
        ViewAs<ParentLayerPixel>(
            aDeltaY, PixelCastJustification::ScreenIsParentLayerForRoot));
  }
}

void APZCTreeManager::SetKeyboardMap(const KeyboardMap& aKeyboardMap) {
  APZThreadUtils::AssertOnControllerThread();

  mKeyboardMap = aKeyboardMap;
}

void APZCTreeManager::ZoomToRect(const SLGuidAndRenderRoot& aGuid,
                                 const CSSRect& aRect, const uint32_t aFlags) {
  // We could probably move this to run on the updater thread if needed, but
  // either way we should restrict it to a single thread. For now let's use the
  // controller thread.
  APZThreadUtils::AssertOnControllerThread();

  RefPtr<AsyncPanZoomController> apzc =
      GetTargetAPZC(aGuid.mScrollableLayerGuid);
  if (apzc) {
    apzc->ZoomToRect(aRect, aFlags);
  }
}

void APZCTreeManager::ContentReceivedInputBlock(uint64_t aInputBlockId,
                                                bool aPreventDefault) {
  APZThreadUtils::AssertOnControllerThread();

  mInputQueue->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
}

void APZCTreeManager::SetTargetAPZC(
    uint64_t aInputBlockId, const nsTArray<SLGuidAndRenderRoot>& aTargets) {
  APZThreadUtils::AssertOnControllerThread();

  RefPtr<AsyncPanZoomController> target = nullptr;
  if (aTargets.Length() > 0) {
    target = GetTargetAPZC(aTargets[0].mScrollableLayerGuid);
  }
  for (size_t i = 1; i < aTargets.Length(); i++) {
    RefPtr<AsyncPanZoomController> apzc =
        GetTargetAPZC(aTargets[i].mScrollableLayerGuid);
    target = GetZoomableTarget(target, apzc);
  }
  mInputQueue->SetConfirmedTargetApzc(aInputBlockId, target);
}

void APZCTreeManager::UpdateZoomConstraints(
    const SLGuidAndRenderRoot& aGuid,
    const Maybe<ZoomConstraints>& aConstraints) {
  if (!GetUpdater()->IsUpdaterThread()) {
    // This can happen if we're in the UI process and got a call directly from
    // nsBaseWidget or from a content process over PAPZCTreeManager. In that
    // case we get this call on the compositor thread, which may be different
    // from the updater thread. It can also happen in the GPU process if that is
    // enabled, since the call will go over PAPZCTreeManager and arrive on the
    // compositor thread in the GPU process.
    GetUpdater()->RunOnUpdaterThread(
        UpdaterQueueSelector(aGuid.GetWRRootId()),
        NewRunnableMethod<SLGuidAndRenderRoot, Maybe<ZoomConstraints>>(
            "APZCTreeManager::UpdateZoomConstraints", this,
            &APZCTreeManager::UpdateZoomConstraints, aGuid, aConstraints));
    return;
  }

  AssertOnUpdaterThread();

  ScrollableLayerGuid guid = aGuid.mScrollableLayerGuid;
  RecursiveMutexAutoLock lock(mTreeLock);
  RefPtr<HitTestingTreeNode> node = GetTargetNode(guid, nullptr);
  MOZ_ASSERT(!node || node->GetApzc());  // any node returned must have an APZC

  // Propagate the zoom constraints down to the subtree, stopping at APZCs
  // which have their own zoom constraints or are in a different layers id.
  if (aConstraints) {
    APZCTM_LOG("Recording constraints %s for guid %s\n",
               Stringify(aConstraints.value()).c_str(),
               Stringify(guid).c_str());
    mZoomConstraints[guid] = aConstraints.ref();
  } else {
    APZCTM_LOG("Removing constraints for guid %s\n", Stringify(guid).c_str());
    mZoomConstraints.erase(guid);
  }
  if (node && aConstraints) {
    ForEachNode<ReverseIterator>(
        node.get(), [&aConstraints, &node, this](HitTestingTreeNode* aNode) {
          if (aNode != node) {
            if (AsyncPanZoomController* childApzc = aNode->GetApzc()) {
              // We can have subtrees with their own zoom constraints or
              // separate layers id - leave these alone.
              if (childApzc->HasNoParentWithSameLayersId() ||
                  this->mZoomConstraints.find(childApzc->GetGuid()) !=
                      this->mZoomConstraints.end()) {
                return TraversalFlag::Skip;
              }
            }
          }
          if (aNode->IsPrimaryHolder()) {
            MOZ_ASSERT(aNode->GetApzc());
            aNode->GetApzc()->UpdateZoomConstraints(aConstraints.ref());
          }
          return TraversalFlag::Continue;
        });
  }
}

void APZCTreeManager::FlushRepaintsToClearScreenToGeckoTransform() {
  // As the name implies, we flush repaint requests for the entire APZ tree in
  // order to clear the screen-to-gecko transform (aka the "untransform" applied
  // to incoming input events before they can be passed on to Gecko).
  //
  // The primary reason we do this is to avoid the problem where input events,
  // after being untransformed, end up hit-testing differently in Gecko. This
  // might happen in cases where the input event lands on content that is async-
  // scrolled into view, but Gecko still thinks it is out of view given the
  // visible area of a scrollframe.
  //
  // Another reason we want to clear the untransform is that if our APZ hit-test
  // hits a dispatch-to-content region then that's an ambiguous result and we
  // need to ask Gecko what actually got hit. In order to do this we need to
  // untransform the input event into Gecko space - but to do that we need to
  // know which APZC got hit! This leads to a circular dependency; the only way
  // to get out of it is to make sure that the untransform for all the possible
  // matched APZCs is the same. It is simplest to ensure that by flushing the
  // pending repaint requests, which makes all of the untransforms empty (and
  // therefore equal).
  RecursiveMutexAutoLock lock(mTreeLock);

  ForEachNode<ReverseIterator>(mRootNode.get(), [](HitTestingTreeNode* aNode) {
    if (aNode->IsPrimaryHolder()) {
      MOZ_ASSERT(aNode->GetApzc());
      aNode->GetApzc()->FlushRepaintForNewInputBlock();
    }
  });
}

void APZCTreeManager::AdjustScrollForSurfaceShift(const ScreenPoint& aShift) {
  RecursiveMutexAutoLock lock(mTreeLock);
  RefPtr<AsyncPanZoomController> apzc = FindRootContentOrRootApzc();
  if (apzc) {
    apzc->AdjustScrollForSurfaceShift(aShift);
  }
}

void APZCTreeManager::ClearTree() {
  AssertOnUpdaterThread();

#if defined(MOZ_WIDGET_ANDROID)
  if (mToolbarAnimator) {
    mToolbarAnimator->ClearTreeManager();
  }
#endif

  // Ensure that no references to APZCs are alive in any lingering input
  // blocks. This breaks cycles from InputBlockState::mTargetApzc back to
  // the InputQueue.
  APZThreadUtils::RunOnControllerThread(NewRunnableMethod(
      "layers::InputQueue::Clear", mInputQueue, &InputQueue::Clear));

  RecursiveMutexAutoLock lock(mTreeLock);

  // Collect the nodes into a list, and then destroy each one.
  // We can't destroy them as we collect them, because ForEachNode()
  // does a pre-order traversal of the tree, and Destroy() nulls out
  // the fields needed to reach the children of the node.
  nsTArray<RefPtr<HitTestingTreeNode>> nodesToDestroy;
  ForEachNode<ReverseIterator>(mRootNode.get(),
                               [&nodesToDestroy](HitTestingTreeNode* aNode) {
                                 nodesToDestroy.AppendElement(aNode);
                               });

  for (size_t i = 0; i < nodesToDestroy.Length(); i++) {
    nodesToDestroy[i]->Destroy();
  }
  mRootNode = nullptr;

  RefPtr<APZCTreeManager> self(this);
  NS_DispatchToMainThread(
      NS_NewRunnableFunction("layers::APZCTreeManager::ClearTree", [self] {
        self->mFlushObserver->Unregister();
        self->mFlushObserver = nullptr;
      }));
}

RefPtr<HitTestingTreeNode> APZCTreeManager::GetRootNode() const {
  RecursiveMutexAutoLock lock(mTreeLock);
  return mRootNode;
}

/**
 * Transform a displacement from the ParentLayer coordinates of a source APZC
 * to the ParentLayer coordinates of a target APZC.
 * @param aTreeManager the tree manager for the APZC tree containing |aSource|
 *                     and |aTarget|
 * @param aSource the source APZC
 * @param aTarget the target APZC
 * @param aStartPoint the start point of the displacement
 * @param aEndPoint the end point of the displacement
 * @return true on success, false if aStartPoint or aEndPoint cannot be
 * transformed into target's coordinate space
 */
static bool TransformDisplacement(APZCTreeManager* aTreeManager,
                                  AsyncPanZoomController* aSource,
                                  AsyncPanZoomController* aTarget,
                                  ParentLayerPoint& aStartPoint,
                                  ParentLayerPoint& aEndPoint) {
  if (aSource == aTarget) {
    return true;
  }

  // Convert start and end points to Screen coordinates.
  ParentLayerToScreenMatrix4x4 untransformToApzc =
      aTreeManager->GetScreenToApzcTransform(aSource).Inverse();
  ScreenPoint screenStart = TransformBy(untransformToApzc, aStartPoint);
  ScreenPoint screenEnd = TransformBy(untransformToApzc, aEndPoint);

  // Convert start and end points to aTarget's ParentLayer coordinates.
  ScreenToParentLayerMatrix4x4 transformToApzc =
      aTreeManager->GetScreenToApzcTransform(aTarget);
  Maybe<ParentLayerPoint> startPoint =
      UntransformBy(transformToApzc, screenStart);
  Maybe<ParentLayerPoint> endPoint = UntransformBy(transformToApzc, screenEnd);
  if (!startPoint || !endPoint) {
    return false;
  }
  aEndPoint = *endPoint;
  aStartPoint = *startPoint;

  return true;
}

void APZCTreeManager::DispatchScroll(
    AsyncPanZoomController* aPrev, ParentLayerPoint& aStartPoint,
    ParentLayerPoint& aEndPoint,
    OverscrollHandoffState& aOverscrollHandoffState) {
  const OverscrollHandoffChain& overscrollHandoffChain =
      aOverscrollHandoffState.mChain;
  uint32_t overscrollHandoffChainIndex = aOverscrollHandoffState.mChainIndex;
  RefPtr<AsyncPanZoomController> next;
  // If we have reached the end of the overscroll handoff chain, there is
  // nothing more to scroll, so we ignore the rest of the pan gesture.
  if (overscrollHandoffChainIndex >= overscrollHandoffChain.Length()) {
    // Nothing more to scroll - ignore the rest of the pan gesture.
    return;
  }

  next = overscrollHandoffChain.GetApzcAtIndex(overscrollHandoffChainIndex);

  if (next == nullptr || next->IsDestroyed()) {
    return;
  }

  // Convert the start and end points from |aPrev|'s coordinate space to
  // |next|'s coordinate space.
  if (!TransformDisplacement(this, aPrev, next, aStartPoint, aEndPoint)) {
    return;
  }

  // Scroll |next|. If this causes overscroll, it will call DispatchScroll()
  // again with an incremented index.
  if (!next->AttemptScroll(aStartPoint, aEndPoint, aOverscrollHandoffState)) {
    // Transform |aStartPoint| and |aEndPoint| (which now represent the
    // portion of the displacement that wasn't consumed by APZCs later
    // in the handoff chain) back into |aPrev|'s coordinate space. This
    // allows the caller (which is |aPrev|) to interpret the unconsumed
    // displacement in its own coordinate space, and make use of it
    // (e.g. by going into overscroll).
    if (!TransformDisplacement(this, next, aPrev, aStartPoint, aEndPoint)) {
      NS_WARNING("Failed to untransform scroll points during dispatch");
    }
  }
}

ParentLayerPoint APZCTreeManager::DispatchFling(
    AsyncPanZoomController* aPrev, const FlingHandoffState& aHandoffState) {
  // If immediate handoff is disallowed, do not allow handoff beyond the
  // single APZC that's scrolled by the input block that triggered this fling.
  if (aHandoffState.mIsHandoff && !StaticPrefs::apz_allow_immediate_handoff() &&
      aHandoffState.mScrolledApzc == aPrev) {
    FLING_LOG("APZCTM dropping handoff due to disallowed immediate handoff\n");
    return aHandoffState.mVelocity;
  }

  const OverscrollHandoffChain* chain = aHandoffState.mChain;
  RefPtr<AsyncPanZoomController> current;
  uint32_t overscrollHandoffChainLength = chain->Length();
  uint32_t startIndex;

  // The fling's velocity needs to be transformed from the screen coordinates
  // of |aPrev| to the screen coordinates of |next|. To transform a velocity
  // correctly, we need to convert it to a displacement. For now, we do this
  // by anchoring it to a start point of (0, 0).
  // TODO: For this to be correct in the presence of 3D transforms, we should
  // use the end point of the touch that started the fling as the start point
  // rather than (0, 0).
  ParentLayerPoint startPoint;  // (0, 0)
  ParentLayerPoint endPoint;

  if (aHandoffState.mIsHandoff) {
    startIndex = chain->IndexOf(aPrev) + 1;

    // IndexOf will return aOverscrollHandoffChain->Length() if
    // |aPrev| is not found.
    if (startIndex >= overscrollHandoffChainLength) {
      return aHandoffState.mVelocity;
    }
  } else {
    startIndex = 0;
  }

  // This will store any velocity left over after the entire handoff.
  ParentLayerPoint finalResidualVelocity = aHandoffState.mVelocity;

  ParentLayerPoint currentVelocity = aHandoffState.mVelocity;
  for (; startIndex < overscrollHandoffChainLength; startIndex++) {
    current = chain->GetApzcAtIndex(startIndex);

    // Make sure the apzc about to be handled can be handled
    if (current == nullptr || current->IsDestroyed()) {
      break;
    }

    endPoint = startPoint + currentVelocity;

    RefPtr<AsyncPanZoomController> prevApzc =
        (startIndex > 0) ? chain->GetApzcAtIndex(startIndex - 1) : nullptr;

    // Only transform when current apzc can be transformed with previous
    if (prevApzc) {
      if (!TransformDisplacement(this, prevApzc, current, startPoint,
                                 endPoint)) {
        break;
      }
    }

    ParentLayerPoint availableVelocity = (endPoint - startPoint);
    ParentLayerPoint residualVelocity;

    FlingHandoffState transformedHandoffState = aHandoffState;
    transformedHandoffState.mVelocity = availableVelocity;

    // Obey overscroll-behavior.
    if (prevApzc) {
      residualVelocity += prevApzc->AdjustHandoffVelocityForOverscrollBehavior(
          transformedHandoffState.mVelocity);
    }

    residualVelocity += current->AttemptFling(transformedHandoffState);

    // If there's no residual velocity, there's nothing more to hand off.
    if (IsZero(residualVelocity)) {
      return ParentLayerPoint();
    }

    // If any of the velocity available to be handed off was consumed,
    // subtract the proportion of consumed velocity from finalResidualVelocity.
    // Note: it's important to compare |residualVelocity| to |availableVelocity|
    // here and not to |transformedHandoffState.mVelocity|, since the latter
    // may have been modified by AdjustHandoffVelocityForOverscrollBehavior().
    if (!FuzzyEqualsAdditive(availableVelocity.x, residualVelocity.x,
                             COORDINATE_EPSILON)) {
      finalResidualVelocity.x *= (residualVelocity.x / availableVelocity.x);
    }
    if (!FuzzyEqualsAdditive(availableVelocity.y, residualVelocity.y,
                             COORDINATE_EPSILON)) {
      finalResidualVelocity.y *= (residualVelocity.y / availableVelocity.y);
    }

    currentVelocity = residualVelocity;
  }

  // Return any residual velocity left over after the entire handoff process.
  return finalResidualVelocity;
}

already_AddRefed<AsyncPanZoomController> APZCTreeManager::GetTargetAPZC(
    const ScrollableLayerGuid& aGuid) {
  RecursiveMutexAutoLock lock(mTreeLock);
  RefPtr<HitTestingTreeNode> node = GetTargetNode(aGuid, nullptr);
  MOZ_ASSERT(!node || node->GetApzc());  // any node returned must have an APZC
  RefPtr<AsyncPanZoomController> apzc = node ? node->GetApzc() : nullptr;
  return apzc.forget();
}

static bool GuidComparatorIgnoringPresShell(const ScrollableLayerGuid& aOne,
                                            const ScrollableLayerGuid& aTwo) {
  return aOne.mLayersId == aTwo.mLayersId && aOne.mScrollId == aTwo.mScrollId;
}

already_AddRefed<AsyncPanZoomController> APZCTreeManager::GetTargetAPZC(
    const LayersId& aLayersId,
    const ScrollableLayerGuid::ViewID& aScrollId) const {
  MutexAutoLock lock(mMapLock);
  ScrollableLayerGuid guid(aLayersId, 0, aScrollId);
  auto it = mApzcMap.find(guid);
  RefPtr<AsyncPanZoomController> apzc =
      (it != mApzcMap.end() ? it->second : nullptr);
  return apzc.forget();
}

already_AddRefed<HitTestingTreeNode> APZCTreeManager::GetTargetNode(
    const ScrollableLayerGuid& aGuid, GuidComparator aComparator) const {
  mTreeLock.AssertCurrentThreadIn();
  RefPtr<HitTestingTreeNode> target =
      DepthFirstSearchPostOrder<ReverseIterator>(
          mRootNode.get(), [&aGuid, &aComparator](HitTestingTreeNode* node) {
            bool matches = false;
            if (node->GetApzc()) {
              if (aComparator) {
                matches = aComparator(aGuid, node->GetApzc()->GetGuid());
              } else {
                matches = node->GetApzc()->Matches(aGuid);
              }
            }
            return matches;
          });
  return target.forget();
}

APZCTreeManager::HitTestResult APZCTreeManager::GetTargetAPZC(
    const ScreenPoint& aPoint) {
  RecursiveMutexAutoLock lock(mTreeLock);

  if (gfx::gfxVars::UseWebRender()) {
    return GetAPZCAtPointWR(aPoint, lock);
  }
  return GetAPZCAtPoint(aPoint, lock);
}

APZCTreeManager::HitTestResult APZCTreeManager::GetAPZCAtPointWR(
    const ScreenPoint& aHitTestPoint,
    const RecursiveMutexAutoLock& aProofOfTreeLock) {
  HitTestResult hit;
  RefPtr<wr::WebRenderAPI> wr = GetWebRenderAPIAtPoint(aHitTestPoint);
  if (!wr) {
    // If WebRender isn't running, fall back to the root APZC.
    // This is mostly for the benefit of GTests which do not
    // run a WebRender instance, but gracefully falling back
    // here allows those tests which are not specifically
    // testing the hit-test algorithm to still work.
    hit.mTargetApzc = FindRootApzcForLayersId(mRootLayersId);
    hit.mHitResult = CompositorHitTestFlags::eVisibleToHitTest;
    return hit;
  }

  wr::WrPipelineId pipelineId;
  ScrollableLayerGuid::ViewID scrollId;
  gfx::CompositorHitTestInfo hitInfo;
  bool hitSomething = wr->HitTest(wr::ToWorldPoint(aHitTestPoint), pipelineId,
                                  scrollId, hitInfo);
  if (!hitSomething) {
    return hit;
  }

  hit.mLayersId = wr::AsLayersId(pipelineId);
  ScrollableLayerGuid guid{hit.mLayersId, 0, scrollId};
  if (RefPtr<HitTestingTreeNode> node =
          GetTargetNode(guid, &GuidComparatorIgnoringPresShell)) {
    MOZ_ASSERT(node->GetApzc());  // any node returned must have an APZC
    hit.mTargetApzc = node->GetApzc();
    EventRegionsOverride flags = node->GetEventRegionsOverride();
    if (flags & EventRegionsOverride::ForceDispatchToContent) {
      hitInfo += CompositorHitTestFlags::eApzAwareListeners;
    }
  }
  APZCTM_LOG("Successfully matched APZC %p (hit result 0x%x)\n", result.get(),
             hitInfo.serialize());
  if (!hit.mTargetApzc) {
    // It falls back to the root
    MOZ_ASSERT(scrollId == ScrollableLayerGuid::NULL_SCROLL_ID);
    hit.mTargetApzc = FindRootApzcForLayersId(hit.mLayersId);
    MOZ_ASSERT(hit.mTargetApzc);
  }

  const bool isScrollbar =
      hitInfo.contains(gfx::CompositorHitTestFlags::eScrollbar);
  const bool isScrollbarThumb =
      hitInfo.contains(gfx::CompositorHitTestFlags::eScrollbarThumb);
  const ScrollDirection direction =
      hitInfo.contains(gfx::CompositorHitTestFlags::eScrollbarVertical)
          ? ScrollDirection::eVertical
          : ScrollDirection::eHorizontal;
  HitTestingTreeNode* scrollbarNode = nullptr;
  if (isScrollbar || isScrollbarThumb) {
    scrollbarNode = BreadthFirstSearch<ReverseIterator>(
        mRootNode.get(), [&](HitTestingTreeNode* aNode) {
          return (aNode->GetLayersId() == hit.mLayersId) &&
                 (aNode->IsScrollbarNode() == isScrollbar) &&
                 (aNode->IsScrollThumbNode() == isScrollbarThumb) &&
                 (aNode->GetScrollbarDirection() == direction) &&
                 (aNode->GetScrollTargetId() == scrollId);
        });
  }

  hit.mHitResult = hitInfo;

  if (scrollbarNode) {
    RefPtr<HitTestingTreeNode> scrollbarRef = scrollbarNode;
    hit.mScrollbarNode.Initialize(aProofOfTreeLock, scrollbarRef.forget(),
                                  mTreeLock);
  }

  // TODO: Setting hit.mFixedPosSides needs to be implemented for WebRender.
  // There are two possible implementation strategies here:
  //  (1) Have the WebRender HitTest API call return enough information
  //      to locate the fixed node that was hit, and use
  //      HitTestingTreeNode::GetFixedPosSides() to get the fixed sides.
  //      Note that the fixed node that was hit may be a descendant of
  //      the scrolling node found via GetTargetNode() above, so it's
  //      not enough to simply walk up the hit testing tree from that node.
  //      Note also that, in this case,
  //      WebRenderScrollDataWrapper::GetFixedPositionSides() needs to be
  //      implemented as well, so the fixed pos sides are populated in the
  //      hit testing tree.
  //  (2) Propagate the fixed position sides to WebRender itself, and have
  //      the WebRender HitTest API call return them directly.

  return hit;
}

RefPtr<const OverscrollHandoffChain>
APZCTreeManager::BuildOverscrollHandoffChain(
    const RefPtr<AsyncPanZoomController>& aInitialTarget) {
  // Scroll grabbing is a mechanism that allows content to specify that
  // the initial target of a pan should be not the innermost scrollable
  // frame at the touch point (which is what GetTargetAPZC finds), but
  // something higher up in the tree.
  // It's not sufficient to just find the initial target, however, as
  // overscroll can be handed off to another APZC. Without scroll grabbing,
  // handoff just occurs from child to parent. With scroll grabbing, the
  // handoff order can be different, so we build a chain of APZCs in the
  // order in which scroll will be handed off to them.

  // Grab tree lock since we'll be walking the APZC tree.
  RecursiveMutexAutoLock lock(mTreeLock);

  // Build the chain. If there is a scroll parent link, we use that. This is
  // needed to deal with scroll info layers, because they participate in handoff
  // but do not follow the expected layer tree structure. If there are no
  // scroll parent links we just walk up the tree to find the scroll parent.
  OverscrollHandoffChain* result = new OverscrollHandoffChain;
  AsyncPanZoomController* apzc = aInitialTarget;
  while (apzc != nullptr) {
    result->Add(apzc);

    if (apzc->GetScrollHandoffParentId() ==
        ScrollableLayerGuid::NULL_SCROLL_ID) {
      if (!apzc->IsRootForLayersId()) {
        // This probably indicates a bug or missed case in layout code
        NS_WARNING("Found a non-root APZ with no handoff parent");
      }
      apzc = apzc->GetParent();
      continue;
    }

    // Guard against a possible infinite-loop condition. If we hit this, the
    // layout code that generates the handoff parents did something wrong.
    MOZ_ASSERT(apzc->GetScrollHandoffParentId() != apzc->GetGuid().mScrollId);
    RefPtr<AsyncPanZoomController> scrollParent = GetTargetAPZC(
        apzc->GetGuid().mLayersId, apzc->GetScrollHandoffParentId());
    apzc = scrollParent.get();
  }

  // Now adjust the chain to account for scroll grabbing. Sorting is a bit
  // of an overkill here, but scroll grabbing will likely be generalized
  // to scroll priorities, so we might as well do it this way.
  result->SortByScrollPriority();

  // Print the overscroll chain for debugging.
  for (uint32_t i = 0; i < result->Length(); ++i) {
    APZCTM_LOG("OverscrollHandoffChain[%d] = %p\n", i,
               result->GetApzcAtIndex(i).get());
  }

  return result;
}

void APZCTreeManager::SetLongTapEnabled(bool aLongTapEnabled) {
  APZThreadUtils::AssertOnControllerThread();
  GestureEventListener::SetLongTapEnabled(aLongTapEnabled);
}

void APZCTreeManager::FindScrollThumbNode(
    const AsyncDragMetrics& aDragMetrics,
    HitTestingTreeNodeAutoLock& aOutThumbNode) {
  if (!aDragMetrics.mDirection) {
    // The AsyncDragMetrics has not been initialized yet - there will be
    // no matching node, so don't bother searching the tree.
    return;
  }

  RecursiveMutexAutoLock lock(mTreeLock);

  RefPtr<HitTestingTreeNode> result = DepthFirstSearch<ReverseIterator>(
      mRootNode.get(), [&aDragMetrics](HitTestingTreeNode* aNode) {
        return aNode->MatchesScrollDragMetrics(aDragMetrics);
      });
  if (result) {
    aOutThumbNode.Initialize(lock, result.forget(), mTreeLock);
  }
}

AsyncPanZoomController* APZCTreeManager::GetTargetApzcForNode(
    HitTestingTreeNode* aNode) {
  for (const HitTestingTreeNode* n = aNode;
       n && n->GetLayersId() == aNode->GetLayersId(); n = n->GetParent()) {
    if (n->GetApzc()) {
      APZCTM_LOG("Found target %p using ancestor lookup\n", n->GetApzc());
      return n->GetApzc();
    }
    if (n->GetFixedPosTarget() != ScrollableLayerGuid::NULL_SCROLL_ID) {
      RefPtr<AsyncPanZoomController> fpTarget =
          GetTargetAPZC(n->GetLayersId(), n->GetFixedPosTarget());
      APZCTM_LOG("Found target APZC %p using fixed-pos lookup on %" PRIu64 "\n",
                 fpTarget.get(), n->GetFixedPosTarget());
      return fpTarget.get();
    }
  }
  return nullptr;
}

APZCTreeManager::HitTestResult APZCTreeManager::GetAPZCAtPoint(
    const ScreenPoint& aHitTestPoint,
    const RecursiveMutexAutoLock& aProofOfTreeLock) {
  HitTestResult hit;
  // This walks the tree in depth-first, reverse order, so that it encounters
  // APZCs front-to-back on the screen.
  HitTestingTreeNode* resultNode;
  HitTestingTreeNode* root = mRootNode;
  HitTestingTreeNode* scrollbarNode = nullptr;
  std::stack<LayerPoint> hitTestPoints;
  ParentLayerPoint point = ViewAs<ParentLayerPixel>(
      aHitTestPoint, PixelCastJustification::ScreenIsParentLayerForRoot);
  hitTestPoints.push(
      ViewAs<LayerPixel>(point, PixelCastJustification::MovingDownToChildren));

  ForEachNode<ReverseIterator>(
      root,
      [&hitTestPoints, this](HitTestingTreeNode* aNode) {
        ParentLayerPoint hitTestPointForParent = ViewAs<ParentLayerPixel>(
            hitTestPoints.top(), PixelCastJustification::MovingDownToChildren);
        if (aNode->IsOutsideClip(hitTestPointForParent)) {
          // If the point being tested is outside the clip region for this node
          // then we don't need to test against this node or any of its
          // children. Just skip it and move on.
          APZCTM_LOG("Point %f %f outside clip for node %p\n",
                     hitTestPoints.top().x, hitTestPoints.top().y, aNode);
          return TraversalFlag::Skip;
        }
        // First check the subtree rooted at this node, because deeper nodes
        // are more "in front".
        Maybe<LayerPoint> hitTestPoint = aNode->Untransform(
            hitTestPointForParent, ComputeTransformForNode(aNode));
        APZCTM_LOG(
            "Transformed ParentLayer point %s to layer %s\n",
            Stringify(hitTestPointForParent).c_str(),
            hitTestPoint ? Stringify(hitTestPoint.ref()).c_str() : "nil");
        if (!hitTestPoint) {
          return TraversalFlag::Skip;
        }
        hitTestPoints.push(hitTestPoint.ref());
        return TraversalFlag::Continue;
      },
      [&resultNode, &hitTestPoints, &hit](HitTestingTreeNode* aNode) {
        CompositorHitTestInfo hitResult = aNode->HitTest(hitTestPoints.top());
        hitTestPoints.pop();
        APZCTM_LOG("Testing Layer point %s against node %p\n",
                   Stringify(hitTestPoints.top()).c_str(), aNode);
        if (hitResult != CompositorHitTestInvisibleToHit) {
          resultNode = aNode;
          hit.mHitResult = hitResult;
          return TraversalFlag::Abort;
        }
        return TraversalFlag::Continue;
      });

  if (hit.mHitResult != CompositorHitTestInvisibleToHit) {
    MOZ_ASSERT(resultNode);
    for (HitTestingTreeNode* n = resultNode; n; n = n->GetParent()) {
      if (n->IsScrollbarNode()) {
        scrollbarNode = n;
        hit.mHitResult += CompositorHitTestFlags::eScrollbar;
        if (n->IsScrollThumbNode()) {
          hit.mHitResult += CompositorHitTestFlags::eScrollbarThumb;
        }
        if (n->GetScrollbarDirection() == ScrollDirection::eVertical) {
          hit.mHitResult += CompositorHitTestFlags::eScrollbarVertical;
        }

        // If we hit a scrollbar, target the APZC for the content scrolled
        // by the scrollbar. (The scrollbar itself doesn't scroll with the
        // scrolled content, so it doesn't carry the scrolled content's
        // scroll metadata).
        RefPtr<AsyncPanZoomController> scrollTarget =
            GetTargetAPZC(n->GetLayersId(), n->GetScrollTargetId());
        if (scrollTarget) {
          hit.mLayersId = n->GetLayersId();
          hit.mTargetApzc = scrollTarget.forget();
          RefPtr<HitTestingTreeNode> scrollbarRef = scrollbarNode;
          hit.mScrollbarNode.Initialize(aProofOfTreeLock, scrollbarRef.forget(),
                                        mTreeLock);
          return hit;
        }
      } else if (IsFixedToRootContent(n)) {
        hit.mFixedPosSides = n->GetFixedPosSides();
      }
    }

    hit.mTargetApzc = GetTargetApzcForNode(resultNode);
    if (!hit.mTargetApzc) {
      hit.mTargetApzc = FindRootApzcForLayersId(resultNode->GetLayersId());
      MOZ_ASSERT(hit.mTargetApzc);
      APZCTM_LOG("Found target %p using root lookup\n", result);
    }
    APZCTM_LOG("Successfully matched APZC %p via node %p (hit result 0x%x)\n",
               result, resultNode, aOutHitResult->serialize());
    hit.mLayersId = resultNode->GetLayersId();

    return hit;
  }

  return hit;
}

AsyncPanZoomController* APZCTreeManager::FindRootApzcForLayersId(
    LayersId aLayersId) const {
  mTreeLock.AssertCurrentThreadIn();

  HitTestingTreeNode* resultNode = BreadthFirstSearch<ReverseIterator>(
      mRootNode.get(), [aLayersId](HitTestingTreeNode* aNode) {
        AsyncPanZoomController* apzc = aNode->GetApzc();
        return apzc && apzc->GetLayersId() == aLayersId &&
               apzc->IsRootForLayersId();
      });
  return resultNode ? resultNode->GetApzc() : nullptr;
}

already_AddRefed<AsyncPanZoomController> APZCTreeManager::FindZoomableApzc(
    AsyncPanZoomController* aStart) const {
  return GetZoomableTarget(aStart, aStart);
}

AsyncPanZoomController* APZCTreeManager::FindRootContentApzcForLayersId(
    LayersId aLayersId) const {
  mTreeLock.AssertCurrentThreadIn();

  HitTestingTreeNode* resultNode = BreadthFirstSearch<ReverseIterator>(
      mRootNode.get(), [aLayersId](HitTestingTreeNode* aNode) {
        AsyncPanZoomController* apzc = aNode->GetApzc();
        return apzc && apzc->GetLayersId() == aLayersId &&
               apzc->IsRootContent();
      });
  return resultNode ? resultNode->GetApzc() : nullptr;
}

AsyncPanZoomController* APZCTreeManager::FindRootContentOrRootApzc() const {
  mTreeLock.AssertCurrentThreadIn();

  // Note: this is intended to find the same "root" that would be found
  // by AsyncCompositionManager::ApplyAsyncContentTransformToTree inside
  // the MOZ_WIDGET_ANDROID block. That is, it should find the RCD node if there
  // is one, or the root APZC if there is not.
  // Since BreadthFirstSearch is a pre-order search, we first do a search for
  // the RCD, and then if we don't find one, we do a search for the root APZC.
  HitTestingTreeNode* resultNode = BreadthFirstSearch<ReverseIterator>(
      mRootNode.get(), [](HitTestingTreeNode* aNode) {
        AsyncPanZoomController* apzc = aNode->GetApzc();
        return apzc && apzc->IsRootContent();
      });
  if (resultNode) {
    return resultNode->GetApzc();
  }
  resultNode = BreadthFirstSearch<ReverseIterator>(
      mRootNode.get(), [](HitTestingTreeNode* aNode) {
        AsyncPanZoomController* apzc = aNode->GetApzc();
        return (apzc != nullptr);
      });
  return resultNode ? resultNode->GetApzc() : nullptr;
}

// clang-format off
/* The methods GetScreenToApzcTransform() and GetApzcToGeckoTransform() return
   some useful transformations that input events may need applied. This is best
   illustrated with an example. Consider a chain of layers, L, M, N, O, P, Q, R. Layer L
   is the layer that corresponds to the argument |aApzc|, and layer R is the root
   of the layer tree. Layer M is the parent of L, N is the parent of M, and so on.
   When layer L is displayed to the screen by the compositor, the set of transforms that
   are applied to L are (in order from top to bottom):

        L's CSS transform                   (hereafter referred to as transform matrix LC)
        L's nontransient async transform    (hereafter referred to as transform matrix LN)
        L's transient async transform       (hereafter referred to as transform matrix LT)
        M's CSS transform                   (hereafter referred to as transform matrix MC)
        M's nontransient async transform    (hereafter referred to as transform matrix MN)
        M's transient async transform       (hereafter referred to as transform matrix MT)
        ...
        R's CSS transform                   (hereafter referred to as transform matrix RC)
        R's nontransient async transform    (hereafter referred to as transform matrix RN)
        R's transient async transform       (hereafter referred to as transform matrix RT)

   Also, for any layer, the async transform is the combination of its transient and non-transient
   parts. That is, for any layer L:
                  LA === LN * LT
        LA.Inverse() === LT.Inverse() * LN.Inverse()

   If we want user input to modify L's transient async transform, we have to first convert
   user input from screen space to the coordinate space of L's transient async transform. Doing
   this involves applying the following transforms (in order from top to bottom):
        RT.Inverse()
        RN.Inverse()
        RC.Inverse()
        ...
        MT.Inverse()
        MN.Inverse()
        MC.Inverse()
   This combined transformation is returned by GetScreenToApzcTransform().

   Next, if we want user inputs sent to gecko for event-dispatching, we will need to strip
   out all of the async transforms that are involved in this chain. This is because async
   transforms are stored only in the compositor and gecko does not account for them when
   doing display-list-based hit-testing for event dispatching.
   Furthermore, because these input events are processed by Gecko in a FIFO queue that
   includes other things (specifically paint requests), it is possible that by time the
   input event reaches gecko, it will have painted something else. Therefore, we need to
   apply another transform to the input events to account for the possible disparity between
   what we know gecko last painted and the last paint request we sent to gecko. Let this
   transform be represented by LD, MD, ... RD.
   Therefore, given a user input in screen space, the following transforms need to be applied
   (in order from top to bottom):
        RT.Inverse()
        RN.Inverse()
        RC.Inverse()
        ...
        MT.Inverse()
        MN.Inverse()
        MC.Inverse()
        LT.Inverse()
        LN.Inverse()
        LC.Inverse()
        LC
        LD
        MC
        MD
        ...
        RC
        RD
   This sequence can be simplified and refactored to the following:
        GetScreenToApzcTransform()
        LA.Inverse()
        LD
        MC
        MD
        ...
        RC
        RD
   Since GetScreenToApzcTransform() can be obtained by calling that function, GetApzcToGeckoTransform()
   returns the remaining transforms (LA.Inverse() * LD * ... * RD), so that the caller code can
   combine it with GetScreenToApzcTransform() to get the final transform required in this case.

   Note that for many of these layers, there will be no AsyncPanZoomController attached, and
   so the async transform will be the identity transform. So, in the example above, if layers
   L and P have APZC instances attached, MT, MN, MD, NT, NN, ND, OT, ON, OD, QT, QN, QD, RT,
   RN and RD will be identity transforms.
   Additionally, for space-saving purposes, each APZC instance stores its layer's individual
   CSS transform and the accumulation of CSS transforms to its parent APZC. So the APZC for
   layer L would store LC and (MC * NC * OC), and the layer P would store PC and (QC * RC).
   The APZC instances track the last dispatched paint request and so are able to calculate LD and
   PD using those internally stored values.
   The APZCs also obviously have LT, LN, PT, and PN, so all of the above transformation combinations
   required can be generated.
 */
// clang-format on

/*
 * See the long comment above for a detailed explanation of this function.
 */
ScreenToParentLayerMatrix4x4 APZCTreeManager::GetScreenToApzcTransform(
    const AsyncPanZoomController* aApzc) const {
  Matrix4x4 result;
  RecursiveMutexAutoLock lock(mTreeLock);

  // The comments below assume there is a chain of layers L..R with L and P
  // having APZC instances as explained in the comment above. This function is
  // called with aApzc at L, and the loop below performs one iteration, where
  // parent is at P. The comments explain what values are stored in the
  // variables at these two levels. All the comments use standard matrix
  // notation where the leftmost matrix in a multiplication is applied first.

  // ancestorUntransform is PC.Inverse() * OC.Inverse() * NC.Inverse() *
  // MC.Inverse()
  Matrix4x4 ancestorUntransform = aApzc->GetAncestorTransform().Inverse();

  // result is initialized to PC.Inverse() * OC.Inverse() * NC.Inverse() *
  // MC.Inverse()
  result = ancestorUntransform;

  for (AsyncPanZoomController* parent = aApzc->GetParent(); parent;
       parent = parent->GetParent()) {
    // ancestorUntransform is updated to RC.Inverse() * QC.Inverse() when parent
    // == P
    ancestorUntransform = parent->GetAncestorTransform().Inverse();
    // asyncUntransform is updated to PA.Inverse() when parent == P
    Matrix4x4 asyncUntransform = parent
                                     ->GetCurrentAsyncTransformWithOverscroll(
                                         AsyncPanZoomController::eForHitTesting)
                                     .Inverse()
                                     .ToUnknownMatrix();
    // untransformSinceLastApzc is RC.Inverse() * QC.Inverse() * PA.Inverse()
    Matrix4x4 untransformSinceLastApzc = ancestorUntransform * asyncUntransform;

    // result is RC.Inverse() * QC.Inverse() * PA.Inverse() * PC.Inverse() *
    // OC.Inverse() * NC.Inverse() * MC.Inverse()
    result = untransformSinceLastApzc * result;

    // The above value for result when parent == P matches the required output
    // as explained in the comment above this method. Note that any missing
    // terms are guaranteed to be identity transforms.
  }

  return ViewAs<ScreenToParentLayerMatrix4x4>(result);
}

/*
 * See the long comment above GetScreenToApzcTransform() for a detailed
 * explanation of this function.
 */
ParentLayerToScreenMatrix4x4 APZCTreeManager::GetApzcToGeckoTransform(
    const AsyncPanZoomController* aApzc) const {
  Matrix4x4 result;
  RecursiveMutexAutoLock lock(mTreeLock);

  // The comments below assume there is a chain of layers L..R with L and P
  // having APZC instances as explained in the comment above. This function is
  // called with aApzc at L, and the loop below performs one iteration, where
  // parent is at P. The comments explain what values are stored in the
  // variables at these two levels. All the comments use standard matrix
  // notation where the leftmost matrix in a multiplication is applied first.

  // asyncUntransform is LA.Inverse()
  Matrix4x4 asyncUntransform = aApzc
                                   ->GetCurrentAsyncTransformWithOverscroll(
                                       AsyncPanZoomController::eForHitTesting)
                                   .Inverse()
                                   .ToUnknownMatrix();

  // aTransformToGeckoOut is initialized to LA.Inverse() * LD * MC * NC * OC *
  // PC
  result = asyncUntransform * aApzc->GetTransformToLastDispatchedPaint() *
           aApzc->GetAncestorTransform();

  for (AsyncPanZoomController* parent = aApzc->GetParent(); parent;
       parent = parent->GetParent()) {
    // aTransformToGeckoOut is LA.Inverse() * LD * MC * NC * OC * PC * PD * QC *
    // RC
    result = result * parent->GetTransformToLastDispatchedPaint() *
             parent->GetAncestorTransform();

    // The above value for result when parent == P matches the required output
    // as explained in the comment above this method. Note that any missing
    // terms are guaranteed to be identity transforms.
  }

  return ViewAs<ParentLayerToScreenMatrix4x4>(result);
}

ScreenPoint APZCTreeManager::GetCurrentMousePosition() const {
  return mCurrentMousePosition;
}

already_AddRefed<AsyncPanZoomController> APZCTreeManager::GetZoomableTarget(
    AsyncPanZoomController* aApzc1, AsyncPanZoomController* aApzc2) const {
  RecursiveMutexAutoLock lock(mTreeLock);
  RefPtr<AsyncPanZoomController> apzc;
  // For now, we only ever want to do pinching on the root-content APZC for
  // a given layers id.
  if (aApzc1 && aApzc2 && aApzc1->GetLayersId() == aApzc2->GetLayersId()) {
    // If the two APZCs have the same layers id, find the root-content APZC
    // for that layers id. Don't call CommonAncestor() because there may not
    // be a common ancestor for the layers id (e.g. if one APZCs is inside a
    // fixed-position element).
    apzc = FindRootContentApzcForLayersId(aApzc1->GetLayersId());
  } else {
    // Otherwise, find the common ancestor (to reach a common layers id), and
    // get the root-content APZC for that layers id.
    apzc = CommonAncestor(aApzc1, aApzc2);
    if (apzc) {
      apzc = FindRootContentApzcForLayersId(apzc->GetLayersId());
    }
  }
  return apzc.forget();
}

Maybe<ScreenIntPoint> APZCTreeManager::ConvertToGecko(
    const ScreenIntPoint& aPoint, AsyncPanZoomController* aApzc) {
  RecursiveMutexAutoLock lock(mTreeLock);
  ScreenToScreenMatrix4x4 transformScreenToGecko =
      GetScreenToApzcTransform(aApzc) * GetApzcToGeckoTransform(aApzc);
  Maybe<ScreenIntPoint> geckoPoint =
      UntransformBy(transformScreenToGecko, aPoint);
  if (geckoPoint) {
    if (mFixedPosSidesForInputBlock != eSideBitsNone) {
      *geckoPoint -=
          RoundedToInt(AsyncCompositionManager::ComputeFixedMarginsOffset(
              mFixedLayerMargins, mFixedPosSidesForInputBlock));
    }
  }
  return geckoPoint;
}

already_AddRefed<AsyncPanZoomController> APZCTreeManager::CommonAncestor(
    AsyncPanZoomController* aApzc1, AsyncPanZoomController* aApzc2) const {
  mTreeLock.AssertCurrentThreadIn();
  RefPtr<AsyncPanZoomController> ancestor;

  // If either aApzc1 or aApzc2 is null, min(depth1, depth2) will be 0 and this
  // function will return null.

  // Calculate depth of the APZCs in the tree
  int depth1 = 0, depth2 = 0;
  for (AsyncPanZoomController* parent = aApzc1; parent;
       parent = parent->GetParent()) {
    depth1++;
  }
  for (AsyncPanZoomController* parent = aApzc2; parent;
       parent = parent->GetParent()) {
    depth2++;
  }

  // At most one of the following two loops will be executed; the deeper APZC
  // pointer will get walked up to the depth of the shallower one.
  int minDepth = depth1 < depth2 ? depth1 : depth2;
  while (depth1 > minDepth) {
    depth1--;
    aApzc1 = aApzc1->GetParent();
  }
  while (depth2 > minDepth) {
    depth2--;
    aApzc2 = aApzc2->GetParent();
  }

  // Walk up the ancestor chains of both APZCs, always staying at the same depth
  // for either APZC, and return the the first common ancestor encountered.
  while (true) {
    if (aApzc1 == aApzc2) {
      ancestor = aApzc1;
      break;
    }
    if (depth1 <= 0) {
      break;
    }
    aApzc1 = aApzc1->GetParent();
    aApzc2 = aApzc2->GetParent();
  }
  return ancestor.forget();
}

bool APZCTreeManager::IsFixedToRootContent(
    const HitTestingTreeNode* aNode) const {
  mTreeLock.AssertCurrentThreadIn();
  ScrollableLayerGuid::ViewID fixedTarget = aNode->GetFixedPosTarget();
  if (fixedTarget == ScrollableLayerGuid::NULL_SCROLL_ID) {
    return false;
  }
  RefPtr<AsyncPanZoomController> targetApzc =
      GetTargetAPZC(aNode->GetLayersId(), fixedTarget);
  return targetApzc && targetApzc->IsRootContent();
}

LayerToParentLayerMatrix4x4 APZCTreeManager::ComputeTransformForNode(
    const HitTestingTreeNode* aNode) const {
  mTreeLock.AssertCurrentThreadIn();
  // The async transforms applied here for hit-testing purposes, are intended
  // to match the ones AsyncCompositionManager (or equivalent WebRender code)
  // applies for rendering purposes.
  // Note that with containerless scrolling, the layer structure looks like
  // this:
  //
  //   root container layer
  //     async zoom container layer
  //       scrollable content layers (with scroll metadata)
  //       fixed content layers (no scroll metadta, annotated isFixedPosition)
  //     scrollbar layers
  //
  // The intended async transforms in this case are:
  //  * On the async zoom container layer, the "visual" portion of the root
  //    content APZC's async transform (which includes the zoom, and async
  //    scrolling of the visual viewport relative to the layout viewport).
  //  * On the scrollable layers bearing the root content APZC's scroll
  //    metadata, the "layout" portion of the root content APZC's async
  //    transform (which includes async scrolling of the layout viewport
  //    relative to the visual viewport).
  if (AsyncPanZoomController* apzc = aNode->GetApzc()) {
    // If the node represents scrollable content, apply the async transform
    // from its APZC.
    bool visualTransformIsInheritedFromAncestor =
        apzc->IsRootContent() &&        /* we're the APZC whose visual transform
                                           might be on the async zoom container */
        mUsingAsyncZoomContainer &&     /* there is an async zoom container */
        !aNode->IsAsyncZoomContainer(); /* it's not us */
    AsyncTransformComponents components =
        visualTransformIsInheritedFromAncestor
            ? AsyncTransformComponents{AsyncTransformComponent::eLayout}
            : LayoutAndVisual;
    return aNode->GetTransform() *
           CompleteAsyncTransform(apzc->GetCurrentAsyncTransformWithOverscroll(
               AsyncPanZoomController::eForHitTesting, components));
  } else if (aNode->IsAsyncZoomContainer()) {
    if (AsyncPanZoomController* rootContent =
            FindRootContentApzcForLayersId(aNode->GetLayersId())) {
      return aNode->GetTransform() *
             CompleteAsyncTransform(
                 rootContent->GetCurrentAsyncTransformWithOverscroll(
                     AsyncPanZoomController::eForHitTesting,
                     {AsyncTransformComponent::eVisual}));
    }
  } else if (aNode->IsScrollThumbNode()) {
    // If the node represents a scrollbar thumb, compute and apply the
    // transformation that will be applied to the thumb in
    // AsyncCompositionManager.
    ScrollableLayerGuid guid{aNode->GetLayersId(), 0,
                             aNode->GetScrollTargetId()};
    if (RefPtr<HitTestingTreeNode> scrollTargetNode =
            GetTargetNode(guid, &GuidComparatorIgnoringPresShell)) {
      AsyncPanZoomController* scrollTargetApzc = scrollTargetNode->GetApzc();
      MOZ_ASSERT(scrollTargetApzc);
      return scrollTargetApzc->CallWithLastContentPaintMetrics(
          [&](const FrameMetrics& aMetrics) {
            return ComputeTransformForScrollThumb(
                aNode->GetTransform() * AsyncTransformMatrix(),
                scrollTargetNode->GetTransform().ToUnknownMatrix(),
                scrollTargetApzc, aMetrics, aNode->GetScrollbarData(),
                scrollTargetNode->IsAncestorOf(aNode), nullptr);
          });
    }
  } else if (IsFixedToRootContent(aNode)) {
    ParentLayerPoint translation = ViewAs<ParentLayerPixel>(
        AsyncCompositionManager::ComputeFixedMarginsOffset(
            mFixedLayerMargins, aNode->GetFixedPosSides()),
        PixelCastJustification::ScreenIsParentLayerForRoot);
    return aNode->GetTransform() *
           CompleteAsyncTransform(
               AsyncTransformComponentMatrix::Translation(translation));
  }
  // Otherwise, the node does not have an async transform.
  return aNode->GetTransform() * AsyncTransformMatrix();
}

already_AddRefed<wr::WebRenderAPI> APZCTreeManager::GetWebRenderAPI(
    wr::RenderRoot aRenderRoot) const {
  RefPtr<wr::WebRenderAPI> api;
  CompositorBridgeParent::CallWithIndirectShadowTree(
      mRootLayersId, [&](LayerTreeState& aState) -> void {
        if (aState.mWrBridge) {
          api = aState.mWrBridge->GetWebRenderAPI(aRenderRoot);
        }
      });
  return api.forget();
}

already_AddRefed<wr::WebRenderAPI> APZCTreeManager::GetWebRenderAPIAtPoint(
    const ScreenPoint& aPoint) const {
  RefPtr<wr::WebRenderAPI> api;
  CompositorBridgeParent::CallWithIndirectShadowTree(
      mRootLayersId, [&](LayerTreeState& aState) -> void {
        if (aState.mWrBridge) {
          api = aState.mWrBridge->GetWebRenderAPIAtPoint(aPoint);
        }
      });
  return api.forget();
}

/*static*/
already_AddRefed<GeckoContentController> APZCTreeManager::GetContentController(
    LayersId aLayersId) {
  RefPtr<GeckoContentController> controller;
  CompositorBridgeParent::CallWithIndirectShadowTree(
      aLayersId,
      [&](LayerTreeState& aState) -> void { controller = aState.mController; });
  return controller.forget();
}

bool APZCTreeManager::GetAPZTestData(LayersId aLayersId,
                                     APZTestData* aOutData) {
  AssertOnUpdaterThread();
  MutexAutoLock lock(mTestDataLock);
  auto it = mTestData.find(aLayersId);
  if (it == mTestData.end()) {
    return false;
  }
  *aOutData = *(it->second);
  return true;
}

void APZCTreeManager::SendSubtreeTransformsToChromeMainThread(
    const AsyncPanZoomController* aAncestor) {
  if (!mRootNode) {
    // Event dispatched during shutdown, after ClearTree().
    return;
  }
  RefPtr<GeckoContentController> controller =
      GetContentController(mRootLayersId);
  if (!controller) {
    return;
  }
  nsTArray<MatrixMessage> messages;
  bool underAncestor = (aAncestor == nullptr);
  {
    RecursiveMutexAutoLock lock(mTreeLock);
    // This formulation duplicates matrix multiplications closer
    // to the root of the tree. For now, aiming for separation
    // of concerns rather than minimum number of multiplications.
    ForEachNode<ReverseIterator>(
        mRootNode.get(),
        [&](HitTestingTreeNode* aNode) {
          bool atAncestor = (aAncestor && aNode->GetApzc() == aAncestor);
          MOZ_ASSERT(!(underAncestor && atAncestor));
          underAncestor |= atAncestor;
          if (!underAncestor) {
            return;
          }
          LayersId layersId = aNode->GetLayersId();
          HitTestingTreeNode* parent = aNode->GetParent();
          if (!parent) {
            messages.AppendElement(MatrixMessage(Some(LayerToScreenMatrix4x4()),
                                                 ScreenRect(), layersId));
          } else if (layersId != parent->GetLayersId()) {
            if (mDetachedLayersIds.find(layersId) != mDetachedLayersIds.end()) {
              messages.AppendElement(
                  MatrixMessage(Nothing(), ScreenRect(), layersId));
            } else {
              messages.AppendElement(MatrixMessage(
                  Some(parent->GetTransformToGecko()),
                  parent->GetRemoteDocumentScreenRect(), layersId));
            }
          }
        },
        [&](HitTestingTreeNode* aNode) {
          bool atAncestor = (aAncestor && aNode->GetApzc() == aAncestor);
          if (atAncestor) {
            MOZ_ASSERT(underAncestor);
            underAncestor = false;
          }
        });
  }
  controller->NotifyLayerTransforms(messages);
}

void APZCTreeManager::SetFixedLayerMargins(ScreenIntCoord aTop,
                                           ScreenIntCoord aBottom) {
  RecursiveMutexAutoLock lock(mTreeLock);
  mFixedLayerMargins.top = aTop;
  mFixedLayerMargins.bottom = aBottom;
}

/*static*/
LayerToParentLayerMatrix4x4 APZCTreeManager::ComputeTransformForScrollThumb(
    const LayerToParentLayerMatrix4x4& aCurrentTransform,
    const Matrix4x4& aScrollableContentTransform, AsyncPanZoomController* aApzc,
    const FrameMetrics& aMetrics, const ScrollbarData& aScrollbarData,
    bool aScrollbarIsDescendant,
    AsyncTransformComponentMatrix* aOutClipTransform) {
  // We only apply the transform if the scroll-target layer has non-container
  // children (i.e. when it has some possibly-visible content). This is to
  // avoid moving scroll-bars in the situation that only a scroll information
  // layer has been built for a scroll frame, as this would result in a
  // disparity between scrollbars and visible content.
  if (aMetrics.IsScrollInfoLayer()) {
    return LayerToParentLayerMatrix4x4{};
  }

  MOZ_RELEASE_ASSERT(aApzc);

  AsyncTransformComponentMatrix asyncTransform =
      aApzc->GetCurrentAsyncTransform(AsyncPanZoomController::eForCompositing);

  // |asyncTransform| represents the amount by which we have scrolled and
  // zoomed since the last paint. Because the scrollbar was sized and positioned
  // based on the painted content, we need to adjust it based on asyncTransform
  // so that it reflects what the user is actually seeing now.
  AsyncTransformComponentMatrix scrollbarTransform;
  if (*aScrollbarData.mDirection == ScrollDirection::eVertical) {
    const ParentLayerCoord asyncScrollY = asyncTransform._42;
    const float asyncZoomY = asyncTransform._22;

    // The scroll thumb needs to be scaled in the direction of scrolling by the
    // inverse of the async zoom. This is because zooming in decreases the
    // fraction of the whole srollable rect that is in view.
    const float yScale = 1.f / asyncZoomY;

    // Note: |metrics.GetZoom()| doesn't yet include the async zoom.
    const CSSToParentLayerScale effectiveZoom(aMetrics.GetZoom().yScale *
                                              asyncZoomY);

    // Here we convert the scrollbar thumb ratio into a true unitless ratio by
    // dividing out the conversion factor from the scrollframe's parent's space
    // to the scrollframe's space.
    const float ratio = aScrollbarData.mThumbRatio /
                        (aMetrics.GetPresShellResolution() * asyncZoomY);
    // The scroll thumb needs to be translated in opposite direction of the
    // async scroll. This is because scrolling down, which translates the layer
    // content up, should result in moving the scroll thumb down.
    ParentLayerCoord yTranslation = -asyncScrollY * ratio;

    // The scroll thumb additionally needs to be translated to compensate for
    // the scale applied above. The origin with respect to which the scale is
    // applied is the origin of the entire scrollbar, rather than the origin of
    // the scroll thumb (meaning, for a vertical scrollbar it's at the top of
    // the composition bounds). This means that empty space above the thumb
    // is scaled too, effectively translating the thumb. We undo that
    // translation here.
    // (One can think of the adjustment being done to the translation here as
    // a change of basis. We have a method to help with that,
    // Matrix4x4::ChangeBasis(), but it wouldn't necessarily make the code
    // cleaner in this case).
    const CSSCoord thumbOrigin = (aMetrics.GetScrollOffset().y * ratio);
    const CSSCoord thumbOriginScaled = thumbOrigin * yScale;
    const CSSCoord thumbOriginDelta = thumbOriginScaled - thumbOrigin;
    const ParentLayerCoord thumbOriginDeltaPL =
        thumbOriginDelta * effectiveZoom;
    yTranslation -= thumbOriginDeltaPL;

    scrollbarTransform.PostScale(1.f, yScale, 1.f);
    scrollbarTransform.PostTranslate(0, yTranslation, 0);
  }
  if (*aScrollbarData.mDirection == ScrollDirection::eHorizontal) {
    // See detailed comments under the eVertical case.

    const ParentLayerCoord asyncScrollX = asyncTransform._41;
    const float asyncZoomX = asyncTransform._11;

    const float xScale = 1.f / asyncZoomX;

    const CSSToParentLayerScale effectiveZoom(aMetrics.GetZoom().xScale *
                                              asyncZoomX);

    const float ratio = aScrollbarData.mThumbRatio /
                        (aMetrics.GetPresShellResolution() * asyncZoomX);
    ParentLayerCoord xTranslation = -asyncScrollX * ratio;

    const CSSCoord thumbOrigin = (aMetrics.GetScrollOffset().x * ratio);
    const CSSCoord thumbOriginScaled = thumbOrigin * xScale;
    const CSSCoord thumbOriginDelta = thumbOriginScaled - thumbOrigin;
    const ParentLayerCoord thumbOriginDeltaPL =
        thumbOriginDelta * effectiveZoom;
    xTranslation -= thumbOriginDeltaPL;

    scrollbarTransform.PostScale(xScale, 1.f, 1.f);
    scrollbarTransform.PostTranslate(xTranslation, 0, 0);
  }

  LayerToParentLayerMatrix4x4 transform =
      aCurrentTransform * scrollbarTransform;

  AsyncTransformComponentMatrix compensation;
  // If the scrollbar layer is a child of the content it is a scrollbar for,
  // then we need to adjust for any async transform (including an overscroll
  // transform) on the content. This needs to be cancelled out because layout
  // positions and sizes the scrollbar on the assumption that there is no async
  // transform, and without this adjustment the scrollbar will end up in the
  // wrong place.
  //
  // Note that since the async transform is applied on top of the content's
  // regular transform, we need to make sure to unapply the async transform in
  // the same coordinate space. This requires applying the content transform
  // and then unapplying it after unapplying the async transform.
  if (aScrollbarIsDescendant) {
    AsyncTransformComponentMatrix overscroll =
        aApzc->GetOverscrollTransform(AsyncPanZoomController::eForCompositing);
    Matrix4x4 asyncUntransform =
        (asyncTransform * overscroll).Inverse().ToUnknownMatrix();
    const Matrix4x4& contentTransform = aScrollableContentTransform;
    Matrix4x4 contentUntransform = contentTransform.Inverse();

    compensation *= ViewAs<AsyncTransformComponentMatrix>(
        contentTransform * asyncUntransform * contentUntransform);

    // Pass the total compensation out to the caller so that it can use it
    // to transform clip transforms as needed.
    if (aOutClipTransform) {
      *aOutClipTransform = compensation;
    }
  }
  transform = transform * compensation;

  return transform;
}

APZSampler* APZCTreeManager::GetSampler() const {
  // We should always have a sampler here, since in practice the sampler
  // is destroyed at the same time that this APZCTreeMAnager instance is.
  MOZ_ASSERT(mSampler);
  return mSampler;
}

void APZCTreeManager::AssertOnSamplerThread() {
  GetSampler()->AssertOnSamplerThread();
}

APZUpdater* APZCTreeManager::GetUpdater() const {
  // We should always have an updater here, since in practice the updater
  // is destroyed at the same time that this APZCTreeManager instance is.
  MOZ_ASSERT(mUpdater);
  return mUpdater;
}

void APZCTreeManager::AssertOnUpdaterThread() {
  GetUpdater()->AssertOnUpdaterThread();
}

void APZCTreeManager::LockTree() {
  AssertOnUpdaterThread();
  mTreeLock.Lock();
}

void APZCTreeManager::UnlockTree() {
  AssertOnUpdaterThread();
  mTreeLock.Unlock();
}

void APZCTreeManager::SetDPI(float aDpiValue) {
  APZThreadUtils::AssertOnControllerThread();
  mDPI = aDpiValue;
}

float APZCTreeManager::GetDPI() const {
  APZThreadUtils::AssertOnControllerThread();
  return mDPI;
}

#if defined(MOZ_WIDGET_ANDROID)
AndroidDynamicToolbarAnimator*
APZCTreeManager::GetAndroidDynamicToolbarAnimator() {
  return mToolbarAnimator;
}
#endif  // defined(MOZ_WIDGET_ANDROID)

}  // namespace layers
}  // namespace mozilla