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 (0100c63fd822)

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
/* -*- Mode: c++; c-basic-offset: 2; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: set sw=2 ts=4 expandtab:
 * 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 <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <math.h>
#include <queue>
#include <unistd.h>

#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/Preferences.h"
#include "mozilla/RWLock.h"
#include "mozilla/StaticPrefs_android.h"
#include "mozilla/StaticPrefs_ui.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/TypeTraits.h"
#include "mozilla/Unused.h"
#include "mozilla/WeakPtr.h"
#include "mozilla/WheelHandlingHelper.h"  // for WheelDeltaAdjustmentStrategy

#include "mozilla/Preferences.h"
#include "mozilla/Unused.h"
#include "mozilla/a11y/SessionAccessibility.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/layers/RenderTrace.h"
#include <algorithm>

using mozilla::Unused;
using mozilla::dom::ContentChild;
using mozilla::dom::ContentParent;

#include "nsWindow.h"

#include "AndroidGraphics.h"
#include "JavaExceptions.h"

#include "nsIBaseWindow.h"
#include "nsIBrowserDOMWindow.h"
#include "nsIDOMChromeWindow.h"
#include "nsIObserverService.h"
#include "nsISupportsPrimitives.h"
#include "nsIWidgetListener.h"
#include "nsIWindowWatcher.h"
#include "nsIXULWindow.h"

#include "nsAppShell.h"
#include "nsFocusManager.h"
#include "nsIdleService.h"
#include "nsLayoutUtils.h"
#include "nsViewManager.h"

#include "WidgetUtils.h"
#include "nsContentUtils.h"

#include "nsGfxCIID.h"
#include "nsGkAtoms.h"
#include "nsWidgetsCID.h"

#include "gfxContext.h"

#include "AndroidContentController.h"
#include "GLContext.h"
#include "GLContextProvider.h"
#include "Layers.h"
#include "ScopedGLHelpers.h"
#include "mozilla/layers/APZEventState.h"
#include "mozilla/layers/APZInputBridge.h"
#include "mozilla/layers/APZThreadUtils.h"
#include "mozilla/layers/AsyncCompositionManager.h"
#include "mozilla/layers/CompositorOGL.h"
#include "mozilla/layers/IAPZCTreeManager.h"
#include "mozilla/layers/LayerManagerComposite.h"

#include "nsTArray.h"

#include "AndroidBridge.h"
#include "AndroidBridgeUtilities.h"
#include "AndroidUiThread.h"
#include "FennecJNINatives.h"
#include "GeckoEditableSupport.h"
#include "GeneratedJNINatives.h"
#include "KeyEvent.h"
#include "MotionEvent.h"
#include "ScreenHelperAndroid.h"

#include "imgIEncoder.h"

#include "GeckoProfiler.h"  // For AUTO_PROFILER_LABEL
#include "nsIXULRuntime.h"
#include "nsPrintfCString.h"
#include "nsString.h"

#include "mozilla/ipc/Shmem.h"

using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::layers;
using namespace mozilla::java;
using namespace mozilla::widget;
using namespace mozilla::ipc;

#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/layers/CompositorSession.h"
#include "mozilla/layers/LayerTransactionParent.h"
#include "mozilla/layers/UiCompositorControllerChild.h"
#include "nsThreadUtils.h"

// All the toplevel windows that have been created; these are in
// stacking order, so the window at gTopLevelWindows[0] is the topmost
// one.
static nsTArray<nsWindow*> gTopLevelWindows;

static bool sFailedToCreateGLContext = false;

// Multitouch swipe thresholds in inches
static const double SWIPE_MAX_PINCH_DELTA_INCHES = 0.4;
static const double SWIPE_MIN_DISTANCE_INCHES = 0.6;

template <typename Lambda, bool IsStatic, typename InstanceType, class Impl>
class nsWindow::WindowEvent : public Runnable {
  bool IsStaleCall() {
    if (IsStatic) {
      // Static calls are never stale.
      return false;
    }

    JNIEnv* const env = mozilla::jni::GetEnvForThread();

    const auto natives = reinterpret_cast<mozilla::WeakPtr<Impl>*>(
        jni::GetNativeHandle(env, mInstance.Get()));
    MOZ_CATCH_JNI_EXCEPTION(env);

    // The call is stale if the nsWindow has been destroyed on the
    // Gecko side, but the Java object is still attached to it through
    // a weak pointer. Stale calls should be discarded. Note that it's
    // an error if natives is nullptr here; we return false but the
    // native call will throw an error.
    return natives && !natives->get();
  }

  Lambda mLambda;
  const InstanceType mInstance;

 public:
  WindowEvent(Lambda&& aLambda, InstanceType&& aInstance)
      : Runnable("nsWindowEvent"),
        mLambda(std::move(aLambda)),
        mInstance(std::forward<InstanceType>(aInstance)) {}

  explicit WindowEvent(Lambda&& aLambda)
      : Runnable("nsWindowEvent"),
        mLambda(std::move(aLambda)),
        mInstance(mLambda.GetThisArg()) {}

  NS_IMETHOD Run() override {
    if (!IsStaleCall()) {
      mLambda();
    }
    return NS_OK;
  }
};

namespace {
template <class Instance, class Impl>
typename EnableIf<jni::detail::NativePtrPicker<Impl>::value ==
                      jni::detail::REFPTR,
                  void>::Type
CallAttachNative(Instance aInstance, Impl* aImpl) {
  Impl::AttachNative(aInstance, RefPtr<Impl>(aImpl).get());
}

template <class Instance, class Impl>
typename EnableIf<jni::detail::NativePtrPicker<Impl>::value ==
                      jni::detail::OWNING,
                  void>::Type
CallAttachNative(Instance aInstance, Impl* aImpl) {
  Impl::AttachNative(aInstance, UniquePtr<Impl>(aImpl));
}

template <class Lambda>
bool DispatchToUiThread(const char* aName, Lambda&& aLambda) {
  if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
    uiThread->Dispatch(NS_NewRunnableFunction(aName, std::move(aLambda)));
    return true;
  }
  return false;
}
}  // namespace

template <class Impl>
template <class Cls, typename... Args>
void nsWindow::NativePtr<Impl>::Attach(const jni::LocalRef<Cls>& aInstance,
                                       nsWindow* aWindow, Args&&... aArgs) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(!mPtr && !mImpl);

  Impl* const impl = new Impl(this, aWindow, std::forward<Args>(aArgs)...);
  mImpl = impl;

  // CallAttachNative transfers ownership of impl.
  CallAttachNative<>(aInstance, impl);
}

template <class Impl>
template <class Cls, typename T>
void nsWindow::NativePtr<Impl>::Detach(const jni::Ref<Cls, T>& aInstance) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(mPtr && mImpl);

  // nsIRunnable that takes care of disposing the native object attached to
  // the Java object in a safe manner.
  class ImplDisposer : public Runnable {
    const typename Cls::GlobalRef mInstance;
    const uintptr_t mOldImpl;

   public:
    explicit ImplDisposer(const typename Cls::LocalRef& aInstance)
        : Runnable("nsWindow::NativePtr::Detach"),
          mInstance(aInstance.Env(), aInstance),
          mOldImpl(aInstance
                       ? jni::GetNativeHandle(aInstance.Env(), aInstance.Get())
                       : 0) {
      MOZ_CATCH_JNI_EXCEPTION(aInstance.Env());
    }

    NS_IMETHOD Run() override {
      if (!mInstance) {
        return NS_OK;
      }

      if (!NS_IsMainThread()) {
        NS_DispatchToMainThread(this);
        return NS_OK;
      }

      typename Cls::LocalRef instance(jni::GetGeckoThreadEnv(), mInstance);
      auto newImpl = jni::GetNativeHandle(instance.Env(), instance.Get());
      MOZ_CATCH_JNI_EXCEPTION(instance.Env());

      if (mOldImpl == newImpl) {
        // Only dispose the object if the native object has not changed.
        Impl::DisposeNative(instance);
      }
      return NS_OK;
    }
  };

  // Objects that use nsWindow::NativePtr are expected to implement a public
  // member function with signature "void OnDetach(
  // already_AddRefed<Runnable> aDisposer)".  This function should perform
  // necessary cleanups for the native/Java objects, as well as mark the Java
  // object as being disposed, so no native methods are called after that
  // point. After this disposal step, the function must call "aDisposer->
  // Run()" to finish disposing the native object. The disposer is
  // thread-safe and may be called on any thread as necessary.
  mImpl->OnDetach(
      do_AddRef(new ImplDisposer({jni::GetGeckoThreadEnv(), aInstance})));

  {
    Locked implLock(*this);
    mImpl = nullptr;
  }

  typename WindowPtr<Impl>::Locked lock(*mPtr);
  mPtr->mWindow = nullptr;
  mPtr->mPtr = nullptr;
  mPtr = nullptr;
}

template <class Impl>
class nsWindow::NativePtr<Impl>::Locked final : private MutexAutoLock {
  Impl* const mImpl;

 public:
  explicit Locked(NativePtr<Impl>& aPtr)
      : MutexAutoLock(aPtr.mImplLock), mImpl(aPtr.mImpl) {}

  operator Impl*() const { return mImpl; }
  Impl* operator->() const { return mImpl; }
};

class nsWindow::GeckoViewSupport final
    : public GeckoSession::Window::Natives<GeckoViewSupport>,
      public SupportsWeakPtr<GeckoViewSupport> {
  nsWindow& window;

  // We hold a WeakRef because we want to allow the
  // GeckoSession.Window to be garbage collected.
  // Callers need to create a LocalRef from this
  // before calling methods.
  GeckoSession::Window::WeakRef mGeckoViewWindow;

 public:
  typedef GeckoSession::Window::Natives<GeckoViewSupport> Base;
  typedef SupportsWeakPtr<GeckoViewSupport> SupportsWeakPtr;

  MOZ_DECLARE_WEAKREFERENCE_TYPENAME(GeckoViewSupport);

  template <typename Functor>
  static void OnNativeCall(Functor&& aCall) {
    NS_DispatchToMainThread(new WindowEvent<Functor>(std::move(aCall)));
  }

  GeckoViewSupport(nsWindow* aWindow,
                   const GeckoSession::Window::LocalRef& aInstance)
      : window(*aWindow), mGeckoViewWindow(aInstance) {
    Base::AttachNative(aInstance, static_cast<SupportsWeakPtr*>(this));
  }

  ~GeckoViewSupport();

  using Base::DisposeNative;

  /**
   * GeckoView methods
   */
 private:
  nsCOMPtr<nsPIDOMWindowOuter> mDOMWindow;
  bool mIsReady{false};

 public:
  // Create and attach a window.
  static void Open(const jni::Class::LocalRef& aCls,
                   GeckoSession::Window::Param aWindow,
                   jni::Object::Param aQueue, jni::Object::Param aCompositor,
                   jni::Object::Param aDispatcher,
                   jni::Object::Param aSessionAccessibility,
                   jni::Object::Param aInitData, jni::String::Param aId,
                   jni::String::Param aChromeURI, int32_t aScreenId,
                   bool aPrivateMode, bool aRemote);

  // Close and destroy the nsWindow.
  void Close();

  // Transfer this nsWindow to new GeckoSession objects.
  void Transfer(const GeckoSession::Window::LocalRef& inst,
                jni::Object::Param aQueue, jni::Object::Param aCompositor,
                jni::Object::Param aDispatcher,
                jni::Object::Param aSessionAccessibility,
                jni::Object::Param aInitData);

  void AttachEditable(const GeckoSession::Window::LocalRef& inst,
                      jni::Object::Param aEditableParent);

  void AttachAccessibility(const GeckoSession::Window::LocalRef& inst,
                           jni::Object::Param aSessionAccessibility);

  void OnReady(jni::Object::Param aQueue = nullptr);
};

/**
 * PanZoomController handles its native calls on the UI thread, so make
 * it separate from GeckoViewSupport.
 */
class nsWindow::NPZCSupport final
    : public PanZoomController::NativeProvider::Natives<NPZCSupport> {
  using LockedWindowPtr = WindowPtr<NPZCSupport>::Locked;

  WindowPtr<NPZCSupport> mWindow;
  PanZoomController::NativeProvider::WeakRef mNPZC;
  int mPreviousButtons;

  template <typename Lambda>
  class InputEvent final : public nsAppShell::Event {
    PanZoomController::NativeProvider::GlobalRef mNPZC;
    Lambda mLambda;

   public:
    InputEvent(const NPZCSupport* aNPZCSupport, Lambda&& aLambda)
        : mNPZC(aNPZCSupport->mNPZC), mLambda(std::move(aLambda)) {}

    void Run() override {
      MOZ_ASSERT(NS_IsMainThread());

      JNIEnv* const env = jni::GetGeckoThreadEnv();
      NPZCSupport* npzcSupport =
          GetNative(PanZoomController::NativeProvider::LocalRef(env, mNPZC));

      if (!npzcSupport || !npzcSupport->mWindow) {
        // We already shut down.
        env->ExceptionClear();
        return;
      }

      nsWindow* const window = npzcSupport->mWindow;
      window->UserActivity();
      return mLambda(window);
    }

    bool IsUIEvent() const override { return true; }
  };

  template <typename Lambda>
  void PostInputEvent(Lambda&& aLambda) {
    // Use priority queue for input events.
    nsAppShell::PostEvent(
        MakeUnique<InputEvent<Lambda>>(this, std::move(aLambda)));
  }

 public:
  typedef PanZoomController::NativeProvider::Natives<NPZCSupport> Base;

  NPZCSupport(NativePtr<NPZCSupport>* aPtr, nsWindow* aWindow,
              const PanZoomController::NativeProvider::LocalRef& aNPZC)
      : mWindow(aPtr, aWindow), mNPZC(aNPZC), mPreviousButtons(0) {
    MOZ_ASSERT(mWindow);
  }

  ~NPZCSupport() {}

  using Base::AttachNative;
  using Base::DisposeNative;

  void OnDetach(already_AddRefed<Runnable> aDisposer) {
    // There are several considerations when shutting down NPZC. 1) The
    // Gecko thread may destroy NPZC at any time when nsWindow closes. 2)
    // There may be pending events on the Gecko thread when NPZC is
    // destroyed. 3) mWindow may not be available when the pending event
    // runs. 4) The UI thread may destroy NPZC at any time when GeckoView
    // is destroyed. 5) The UI thread may destroy NPZC at the same time as
    // Gecko thread trying to destroy NPZC. 6) There may be pending calls
    // on the UI thread when NPZC is destroyed. 7) mWindow may have been
    // cleared on the Gecko thread when the pending call happens on the UI
    // thread.
    //
    // 1) happens through OnDetach, which first notifies the UI
    // thread through Destroy; Destroy then calls DisposeNative, which
    // finally disposes the native instance back on the Gecko thread. Using
    // Destroy to indirectly call DisposeNative here also solves 5), by
    // making everything go through the UI thread, avoiding contention.
    //
    // 2) and 3) are solved by clearing mWindow, which signals to the
    // pending event that we had shut down. In that case the event bails
    // and does not touch mWindow.
    //
    // 4) happens through DisposeNative directly. OnDetach is not
    // called.
    //
    // 6) is solved by keeping a destroyed flag in the Java NPZC instance,
    // and only make a pending call if the destroyed flag is not set.
    //
    // 7) is solved by taking a lock whenever mWindow is modified on the
    // Gecko thread or accessed on the UI thread. That way, we don't
    // release mWindow until the UI thread is done using it, thus avoiding
    // the race condition.

    if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
      auto npzc = PanZoomController::NativeProvider::GlobalRef(mNPZC);
      if (!npzc) {
        return;
      }

      uiThread->Dispatch(NS_NewRunnableFunction(
          "NPZCSupport::OnDetach",
          [npzc, disposer = RefPtr<Runnable>(aDisposer)] {
            npzc->SetAttached(false);
            disposer->Run();
          }));
    }
  }

  const PanZoomController::NativeProvider::Ref& GetJavaNPZC() const {
    return mNPZC;
  }

 public:
  void SetIsLongpressEnabled(bool aIsLongpressEnabled) {
    RefPtr<IAPZCTreeManager> controller;

    if (LockedWindowPtr window{mWindow}) {
      controller = window->mAPZC;
    }

    if (controller) {
      controller->SetLongTapEnabled(aIsLongpressEnabled);
    }
  }

  bool HandleScrollEvent(int64_t aTime, int32_t aMetaState, float aX, float aY,
                         float aHScroll, float aVScroll) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    RefPtr<IAPZCTreeManager> controller;

    if (LockedWindowPtr window{mWindow}) {
      controller = window->mAPZC;
    }

    if (!controller) {
      return false;
    }

    ScreenPoint origin = ScreenPoint(aX, aY);

    if (StaticPrefs::ui_scrolling_negate_wheel_scroll()) {
      aHScroll = -aHScroll;
      aVScroll = -aVScroll;
    }

    ScrollWheelInput input(
        aTime, GetEventTimeStamp(aTime), GetModifiers(aMetaState),
        ScrollWheelInput::SCROLLMODE_SMOOTH,
        ScrollWheelInput::SCROLLDELTA_PIXEL, origin, aHScroll, aVScroll, false,
        // XXX Do we need to support auto-dir scrolling
        // for Android widgets with a wheel device?
        // Currently, I just leave it unimplemented. If
        // we need to implement it, what's the extra work
        // to do?
        WheelDeltaAdjustmentStrategy::eNone);

    ScrollableLayerGuid guid;
    uint64_t blockId;
    nsEventStatus status =
        controller->InputBridge()->ReceiveInputEvent(input, &guid, &blockId);

    if (status == nsEventStatus_eConsumeNoDefault) {
      return true;
    }

    PostInputEvent([input, guid, blockId, status](nsWindow* window) {
      WidgetWheelEvent wheelEvent = input.ToWidgetWheelEvent(window);
      window->ProcessUntransformedAPZEvent(&wheelEvent, guid, blockId, status);
    });

    return true;
  }

 private:
  static MouseInput::ButtonType GetButtonType(int button) {
    MouseInput::ButtonType result = MouseInput::NONE;

    switch (button) {
      case java::sdk::MotionEvent::BUTTON_PRIMARY:
        result = MouseInput::LEFT_BUTTON;
        break;
      case java::sdk::MotionEvent::BUTTON_SECONDARY:
        result = MouseInput::RIGHT_BUTTON;
        break;
      case java::sdk::MotionEvent::BUTTON_TERTIARY:
        result = MouseInput::MIDDLE_BUTTON;
        break;
      default:
        break;
    }

    return result;
  }

  static int16_t ConvertButtons(int buttons) {
    int16_t result = 0;

    if (buttons & java::sdk::MotionEvent::BUTTON_PRIMARY) {
      result |= MouseButtonsFlag::eLeftFlag;
    }
    if (buttons & java::sdk::MotionEvent::BUTTON_SECONDARY) {
      result |= MouseButtonsFlag::eRightFlag;
    }
    if (buttons & java::sdk::MotionEvent::BUTTON_TERTIARY) {
      result |= MouseButtonsFlag::eMiddleFlag;
    }
    if (buttons & java::sdk::MotionEvent::BUTTON_BACK) {
      result |= MouseButtonsFlag::e4thFlag;
    }
    if (buttons & java::sdk::MotionEvent::BUTTON_FORWARD) {
      result |= MouseButtonsFlag::e5thFlag;
    }

    return result;
  }

 public:
  bool HandleMouseEvent(int32_t aAction, int64_t aTime, int32_t aMetaState,
                        float aX, float aY, int buttons) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    RefPtr<IAPZCTreeManager> controller;

    if (LockedWindowPtr window{mWindow}) {
      controller = window->mAPZC;
    }

    if (!controller) {
      return false;
    }

    MouseInput::MouseType mouseType = MouseInput::MOUSE_NONE;
    MouseInput::ButtonType buttonType = MouseInput::NONE;
    switch (aAction) {
      case java::sdk::MotionEvent::ACTION_DOWN:
        mouseType = MouseInput::MOUSE_DOWN;
        buttonType = GetButtonType(buttons ^ mPreviousButtons);
        mPreviousButtons = buttons;
        break;
      case java::sdk::MotionEvent::ACTION_UP:
        mouseType = MouseInput::MOUSE_UP;
        buttonType = GetButtonType(buttons ^ mPreviousButtons);
        mPreviousButtons = buttons;
        break;
      case java::sdk::MotionEvent::ACTION_MOVE:
        mouseType = MouseInput::MOUSE_MOVE;
        break;
      case java::sdk::MotionEvent::ACTION_HOVER_MOVE:
        mouseType = MouseInput::MOUSE_MOVE;
        break;
      case java::sdk::MotionEvent::ACTION_HOVER_ENTER:
        mouseType = MouseInput::MOUSE_WIDGET_ENTER;
        break;
      case java::sdk::MotionEvent::ACTION_HOVER_EXIT:
        mouseType = MouseInput::MOUSE_WIDGET_EXIT;
        break;
      default:
        break;
    }

    if (mouseType == MouseInput::MOUSE_NONE) {
      return false;
    }

    ScreenPoint origin = ScreenPoint(aX, aY);

    MouseInput input(mouseType, buttonType,
                     MouseEvent_Binding::MOZ_SOURCE_MOUSE,
                     ConvertButtons(buttons), origin, aTime,
                     GetEventTimeStamp(aTime), GetModifiers(aMetaState));

    ScrollableLayerGuid guid;
    uint64_t blockId;
    nsEventStatus status =
        controller->InputBridge()->ReceiveInputEvent(input, &guid, &blockId);

    if (status == nsEventStatus_eConsumeNoDefault) {
      return true;
    }

    PostInputEvent([input, guid, blockId, status](nsWindow* window) {
      WidgetMouseEvent mouseEvent = input.ToWidgetMouseEvent(window);
      window->ProcessUntransformedAPZEvent(&mouseEvent, guid, blockId, status);
    });

    return true;
  }

  bool HandleMotionEvent(
      const PanZoomController::NativeProvider::LocalRef& aInstance,
      int32_t aAction, int32_t aActionIndex, int64_t aTime, int32_t aMetaState,
      float aScreenX, float aScreenY, jni::IntArray::Param aPointerId,
      jni::FloatArray::Param aX, jni::FloatArray::Param aY,
      jni::FloatArray::Param aOrientation, jni::FloatArray::Param aPressure,
      jni::FloatArray::Param aToolMajor, jni::FloatArray::Param aToolMinor) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    RefPtr<IAPZCTreeManager> controller;

    if (LockedWindowPtr window{mWindow}) {
      controller = window->mAPZC;
    }

    if (!controller) {
      return false;
    }

    nsTArray<int32_t> pointerId(aPointerId->GetElements());
    MultiTouchInput::MultiTouchType type;
    size_t startIndex = 0;
    size_t endIndex = pointerId.Length();

    switch (aAction) {
      case sdk::MotionEvent::ACTION_DOWN:
      case sdk::MotionEvent::ACTION_POINTER_DOWN:
        type = MultiTouchInput::MULTITOUCH_START;
        break;
      case sdk::MotionEvent::ACTION_MOVE:
        type = MultiTouchInput::MULTITOUCH_MOVE;
        break;
      case sdk::MotionEvent::ACTION_UP:
      case sdk::MotionEvent::ACTION_POINTER_UP:
        // for pointer-up events we only want the data from
        // the one pointer that went up
        type = MultiTouchInput::MULTITOUCH_END;
        startIndex = aActionIndex;
        endIndex = aActionIndex + 1;
        break;
      case sdk::MotionEvent::ACTION_OUTSIDE:
      case sdk::MotionEvent::ACTION_CANCEL:
        type = MultiTouchInput::MULTITOUCH_CANCEL;
        break;
      default:
        return false;
    }

    MultiTouchInput input(type, aTime, GetEventTimeStamp(aTime), 0);
    input.modifiers = GetModifiers(aMetaState);
    input.mTouches.SetCapacity(endIndex - startIndex);
    input.mScreenOffset =
        ExternalIntPoint(int32_t(floorf(aScreenX)), int32_t(floorf(aScreenY)));

    nsTArray<float> x(aX->GetElements());
    nsTArray<float> y(aY->GetElements());
    nsTArray<float> orientation(aOrientation->GetElements());
    nsTArray<float> pressure(aPressure->GetElements());
    nsTArray<float> toolMajor(aToolMajor->GetElements());
    nsTArray<float> toolMinor(aToolMinor->GetElements());

    MOZ_ASSERT(pointerId.Length() == x.Length());
    MOZ_ASSERT(pointerId.Length() == y.Length());
    MOZ_ASSERT(pointerId.Length() == orientation.Length());
    MOZ_ASSERT(pointerId.Length() == pressure.Length());
    MOZ_ASSERT(pointerId.Length() == toolMajor.Length());
    MOZ_ASSERT(pointerId.Length() == toolMinor.Length());

    for (size_t i = startIndex; i < endIndex; i++) {
      float orien = orientation[i] * 180.0f / M_PI;
      // w3c touchevents spec does not allow orientations == 90
      // this shifts it to -90, which will be shifted to zero below
      if (orien >= 90.0) {
        orien -= 180.0f;
      }

      nsIntPoint point =
          nsIntPoint(int32_t(floorf(x[i])), int32_t(floorf(y[i])));

      // w3c touchevent radii are given with an orientation between 0 and
      // 90. The radii are found by removing the orientation and
      // measuring the x and y radii of the resulting ellipse. For
      // Android orientations >= 0 and < 90, use the y radius as the
      // major radius, and x as the minor radius. However, for an
      // orientation < 0, we have to shift the orientation by adding 90,
      // and reverse which radius is major and minor.
      gfx::Size radius;
      if (orien < 0.0f) {
        orien += 90.0f;
        radius = gfx::Size(int32_t(toolMajor[i] / 2.0f),
                           int32_t(toolMinor[i] / 2.0f));
      } else {
        radius = gfx::Size(int32_t(toolMinor[i] / 2.0f),
                           int32_t(toolMajor[i] / 2.0f));
      }

      input.mTouches.AppendElement(SingleTouchData(
          pointerId[i], ScreenIntPoint::FromUnknownPoint(point),
          ScreenSize::FromUnknownSize(radius), orien, pressure[i]));
    }

    ScrollableLayerGuid guid;
    uint64_t blockId;
    nsEventStatus status =
        controller->InputBridge()->ReceiveInputEvent(input, &guid, &blockId);

    if (status == nsEventStatus_eConsumeNoDefault) {
      return true;
    }

    // Dispatch APZ input event on Gecko thread.
    PostInputEvent([input, guid, blockId, status](nsWindow* window) {
      WidgetTouchEvent touchEvent = input.ToWidgetTouchEvent(window);
      window->ProcessUntransformedAPZEvent(&touchEvent, guid, blockId, status);
      window->DispatchHitTest(touchEvent);
    });
    return true;
  }
};

template <>
const char nsWindow::NativePtr<nsWindow::NPZCSupport>::sName[] = "NPZCSupport";

NS_IMPL_ISUPPORTS(nsWindow::AndroidView, nsIAndroidEventDispatcher,
                  nsIAndroidView)

nsresult nsWindow::AndroidView::GetInitData(JSContext* aCx,
                                            JS::MutableHandleValue aOut) {
  if (!mInitData) {
    aOut.setNull();
    return NS_OK;
  }

  return widget::EventDispatcher::UnboxBundle(aCx, mInitData, aOut);
}

/**
 * Compositor has some unique requirements for its native calls, so make it
 * separate from GeckoViewSupport.
 */
class nsWindow::LayerViewSupport final
    : public GeckoSession::Compositor::Natives<LayerViewSupport> {
  using LockedWindowPtr = WindowPtr<LayerViewSupport>::Locked;

  WindowPtr<LayerViewSupport> mWindow;
  GeckoSession::Compositor::WeakRef mCompositor;
  Atomic<bool, ReleaseAcquire> mCompositorPaused;
  jni::Object::GlobalRef mSurface;
  std::queue<java::GeckoResult::GlobalRef> mCapturePixelsResults;

  // In order to use Event::HasSameTypeAs in PostTo(), we cannot make
  // LayerViewEvent a template because each template instantiation is
  // a different type. So implement LayerViewEvent as a ProxyEvent.
  class LayerViewEvent final : public nsAppShell::ProxyEvent {
    using Event = nsAppShell::Event;

   public:
    static UniquePtr<Event> MakeEvent(UniquePtr<Event>&& event) {
      return MakeUnique<LayerViewEvent>(std::move(event));
    }

    explicit LayerViewEvent(UniquePtr<Event>&& event)
        : nsAppShell::ProxyEvent(std::move(event)) {}

    void PostTo(LinkedList<Event>& queue) override {
      // Give priority to compositor events, but keep in order with
      // existing compositor events.
      nsAppShell::Event* event = queue.getFirst();
      while (event && event->HasSameTypeAs(this)) {
        event = event->getNext();
      }
      if (event) {
        event->setPrevious(this);
      } else {
        queue.insertBack(this);
      }
    }
  };

 public:
  typedef GeckoSession::Compositor::Natives<LayerViewSupport> Base;

  static LayerViewSupport* FromNative(
      const GeckoSession::Compositor::LocalRef& instance) {
    return GetNative(instance);
  }

  LayerViewSupport(NativePtr<LayerViewSupport>* aPtr, nsWindow* aWindow,
                   const GeckoSession::Compositor::LocalRef& aInstance)
      : mWindow(aPtr, aWindow),
        mCompositor(aInstance),
        mCompositorPaused(true) {
    MOZ_ASSERT(mWindow);
  }

  ~LayerViewSupport() {}

  using Base::AttachNative;
  using Base::DisposeNative;

  void OnDetach(already_AddRefed<Runnable> aDisposer) {
    if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
      GeckoSession::Compositor::GlobalRef compositor(mCompositor);
      if (!compositor) {
        return;
      }

      uiThread->Dispatch(NS_NewRunnableFunction(
          "LayerViewSupport::OnDetach",
          [compositor, disposer = RefPtr<Runnable>(aDisposer),
           results = &mCapturePixelsResults, window = &mWindow] {
            if (LockedWindowPtr lock{*window}) {
              while (!results->empty()) {
                auto aResult = java::GeckoResult::LocalRef(results->front());
                if (aResult) {
                  aResult->CompleteExceptionally(
                      java::sdk::IllegalStateException::New(
                          "The compositor has detached from the session")
                          .Cast<jni::Throwable>());
                  results->pop();
                }
              }
              compositor->OnCompositorDetached();
              disposer->Run();
            }
          }));
    }
  }

  const GeckoSession::Compositor::Ref& GetJavaCompositor() const {
    return mCompositor;
  }

  bool CompositorPaused() const { return mCompositorPaused; }

  jni::Object::Param GetSurface() { return mSurface; }

 private:
  already_AddRefed<UiCompositorControllerChild>
  GetUiCompositorControllerChild() {
    RefPtr<UiCompositorControllerChild> child;
    if (LockedWindowPtr window{mWindow}) {
      child = window->GetUiCompositorControllerChild();
    }
    return child.forget();
  }

  int8_t* FlipScreenPixels(Shmem& aMem, const ScreenIntSize& aSize) {
    const IntSize size(aSize.width, aSize.height);
    RefPtr<DataSourceSurface> image = gfx::CreateDataSourceSurfaceFromData(
        size, SurfaceFormat::B8G8R8A8, aMem.get<uint8_t>(),
        StrideForFormatAndWidth(SurfaceFormat::B8G8R8A8, aSize.width));
    RefPtr<DrawTarget> drawTarget =
        gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
            size, SurfaceFormat::B8G8R8A8);
    drawTarget->SetTransform(Matrix::Scaling(1.0, -1.0) *
                             Matrix::Translation(0, aSize.height));

    gfx::Rect drawRect(0, 0, aSize.width, aSize.height);
    drawTarget->DrawSurface(image, drawRect, drawRect);

    RefPtr<SourceSurface> snapshot = drawTarget->Snapshot();
    RefPtr<DataSourceSurface> data = snapshot->GetDataSurface();
    DataSourceSurface::ScopedMap* smap =
        new DataSourceSurface::ScopedMap(data, DataSourceSurface::READ);
    return reinterpret_cast<int8_t*>(smap->GetData());
  }

  /**
   * Compositor methods
   */
 public:
  void AttachNPZC(jni::Object::Param aNPZC) {
    MOZ_ASSERT(NS_IsMainThread());
    if (!mWindow) {
      return;  // Already shut down.
    }

    MOZ_ASSERT(aNPZC);

    // We can have this situation if we get two GeckoViewSupport::Transfer()
    // called before the first AttachNPZC() gets here. Just detach the current
    // instance since that's what happens in GeckoViewSupport::Transfer() as
    // well.
    if (mWindow->mNPZCSupport) {
      mWindow->mNPZCSupport.Detach(mWindow->mNPZCSupport->GetJavaNPZC());
    }

    auto npzc = PanZoomController::NativeProvider::LocalRef(
        jni::GetGeckoThreadEnv(),
        PanZoomController::NativeProvider::Ref::From(aNPZC));
    mWindow->mNPZCSupport.Attach(npzc, mWindow, npzc);

    DispatchToUiThread("LayerViewSupport::AttachNPZC",
                       [npzc = PanZoomController::NativeProvider::GlobalRef(
                            npzc)] { npzc->SetAttached(true); });
  }

  void OnBoundsChanged(int32_t aLeft, int32_t aTop, int32_t aWidth,
                       int32_t aHeight) {
    MOZ_ASSERT(NS_IsMainThread());
    if (!mWindow) {
      return;  // Already shut down.
    }

    mWindow->Resize(aLeft, aTop, aWidth, aHeight, /* repaint */ false);
  }

  void SyncPauseCompositor() {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      mCompositorPaused = true;
      child->Pause();
    }
  }

  void SyncResumeCompositor() {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      mCompositorPaused = false;
      child->Resume();
    }
  }

  void SyncResumeResizeCompositor(
      const GeckoSession::Compositor::LocalRef& aObj, int32_t aX, int32_t aY,
      int32_t aWidth, int32_t aHeight, jni::Object::Param aSurface) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    mSurface = aSurface;

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->ResumeAndResize(aX, aY, aWidth, aHeight);
    }

    mCompositorPaused = false;

    class OnResumedEvent : public nsAppShell::Event {
      GeckoSession::Compositor::GlobalRef mCompositor;

     public:
      explicit OnResumedEvent(GeckoSession::Compositor::GlobalRef&& aCompositor)
          : mCompositor(std::move(aCompositor)) {}

      void Run() override {
        MOZ_ASSERT(NS_IsMainThread());

        JNIEnv* const env = jni::GetGeckoThreadEnv();
        LayerViewSupport* const lvs =
            GetNative(GeckoSession::Compositor::LocalRef(env, mCompositor));

        if (!lvs || !lvs->mWindow) {
          env->ExceptionClear();
          return;  // Already shut down.
        }

        // When we get here, the compositor has already been told to
        // resume. This means it's now safe for layer updates to occur.
        // Since we might have prevented one or more draw events from
        // occurring while the compositor was paused, we need to
        // schedule a draw event now.
        if (!lvs->mCompositorPaused) {
          lvs->mWindow->RedrawAll();
        }
      }
    };

    // Use priority queue for timing-sensitive event.
    nsAppShell::PostEvent(
        MakeUnique<LayerViewEvent>(MakeUnique<OnResumedEvent>(aObj)));
  }

  void SyncInvalidateAndScheduleComposite() {
    RefPtr<UiCompositorControllerChild> child =
        GetUiCompositorControllerChild();
    if (!child) {
      return;
    }

    if (AndroidBridge::IsJavaUiThread()) {
      child->InvalidateAndRender();
      return;
    }

    if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
      uiThread->Dispatch(NewRunnableMethod<>(
                             "LayerViewSupport::InvalidateAndRender", child,
                             &UiCompositorControllerChild::InvalidateAndRender),
                         nsIThread::DISPATCH_NORMAL);
    }
  }

  void SetMaxToolbarHeight(int32_t aHeight) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->SetMaxToolbarHeight(aHeight);
    }
  }

  void SetFixedBottomOffset(int32_t aOffset) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->SetFixedBottomOffset(aOffset);
    }
  }

  void SetPinned(bool aPinned, int32_t aReason) {
    RefPtr<UiCompositorControllerChild> child =
        GetUiCompositorControllerChild();
    if (!child) {
      return;
    }

    if (AndroidBridge::IsJavaUiThread()) {
      child->SetPinned(aPinned, aReason);
      return;
    }

    if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
      uiThread->Dispatch(
          NewRunnableMethod<bool, int32_t>(
              "LayerViewSupport::SetPinned", child,
              &UiCompositorControllerChild::SetPinned, aPinned, aReason),
          nsIThread::DISPATCH_NORMAL);
    }
  }

  void SendToolbarAnimatorMessage(int32_t aMessage) {
    RefPtr<UiCompositorControllerChild> child =
        GetUiCompositorControllerChild();
    if (!child) {
      return;
    }

    if (AndroidBridge::IsJavaUiThread()) {
      child->ToolbarAnimatorMessageFromUI(aMessage);
      return;
    }

    if (RefPtr<nsThread> uiThread = GetAndroidUiThread()) {
      uiThread->Dispatch(
          NewRunnableMethod<int32_t>(
              "LayerViewSupport::ToolbarAnimatorMessageFromUI", child,
              &UiCompositorControllerChild::ToolbarAnimatorMessageFromUI,
              aMessage),
          nsIThread::DISPATCH_NORMAL);
    }
  }

  void RecvToolbarAnimatorMessage(int32_t aMessage) {
    auto compositor = GeckoSession::Compositor::LocalRef(mCompositor);
    if (compositor) {
      compositor->RecvToolbarAnimatorMessage(aMessage);
    }
  }

  void SetDefaultClearColor(int32_t aColor) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->SetDefaultClearColor((uint32_t)aColor);
    }
  }

  void RequestScreenPixels(jni::Object::Param aResult) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    int size = 0;
    if (LockedWindowPtr window{mWindow}) {
      mCapturePixelsResults.push(
          java::GeckoResult::GlobalRef(java::GeckoResult::LocalRef(aResult)));
      size = mCapturePixelsResults.size();
    }

    if (size == 1) {
      if (RefPtr<UiCompositorControllerChild> child =
              GetUiCompositorControllerChild()) {
        child->RequestScreenPixels();
      }
    }
  }

  void RecvScreenPixels(Shmem&& aMem, const ScreenIntSize& aSize) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
    java::GeckoResult::LocalRef aResult = nullptr;
    if (LockedWindowPtr window{mWindow}) {
      aResult = java::GeckoResult::LocalRef(mCapturePixelsResults.front());
      if (aResult) {
        mCapturePixelsResults.pop();
      }
    }
    if (aResult) {
      auto pixels = mozilla::jni::ByteBuffer::New(FlipScreenPixels(aMem, aSize),
                                                  aMem.Size<int8_t>());
      auto bitmap = java::sdk::Bitmap::CreateBitmap(
          aSize.width, aSize.height, java::sdk::Config::ARGB_8888());
      bitmap->CopyPixelsFromBuffer(pixels);
      aResult->Complete(bitmap);
    }

    // Pixels have been copied, so Dealloc Shmem
    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->DeallocPixelBuffer(aMem);

      if (LockedWindowPtr window{mWindow}) {
        if (!mCapturePixelsResults.empty()) {
          child->RequestScreenPixels();
        }
      }
    }
  }

  void EnableLayerUpdateNotifications(bool aEnable) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      child->EnableLayerUpdateNotifications(aEnable);
    }
  }

  void SendToolbarPixelsToCompositor(int32_t aWidth, int32_t aHeight,
                                     jni::IntArray::Param aPixels) {
    MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

    if (RefPtr<UiCompositorControllerChild> child =
            GetUiCompositorControllerChild()) {
      Shmem mem;
      child->AllocPixelBuffer(aPixels->Length() * sizeof(int32_t), &mem);
      aPixels->CopyTo(mem.get<int32_t>(), mem.Size<int32_t>());
      if (!child->ToolbarPixelsToCompositor(mem,
                                            ScreenIntSize(aWidth, aHeight))) {
        child->DeallocPixelBuffer(mem);
      }
    }
  }
};

template <>
const char nsWindow::NativePtr<nsWindow::LayerViewSupport>::sName[] =
    "LayerViewSupport";

nsWindow::GeckoViewSupport::~GeckoViewSupport() {
  // Disassociate our GeckoEditable instance with our native object.
  if (window.mEditableSupport) {
    window.mEditableSupport.Detach(window.mEditableSupport->GetJavaEditable());
    window.mEditableParent = nullptr;
  }

  if (window.mNPZCSupport) {
    window.mNPZCSupport.Detach(window.mNPZCSupport->GetJavaNPZC());
  }

  if (window.mLayerViewSupport) {
    window.mLayerViewSupport.Detach(
        window.mLayerViewSupport->GetJavaCompositor());
  }

  if (window.mSessionAccessibility) {
    window.mSessionAccessibility.Detach(
        window.mSessionAccessibility->GetJavaAccessibility());
  }
}

/* static */
void nsWindow::GeckoViewSupport::Open(
    const jni::Class::LocalRef& aCls, GeckoSession::Window::Param aWindow,
    jni::Object::Param aQueue, jni::Object::Param aCompositor,
    jni::Object::Param aDispatcher, jni::Object::Param aSessionAccessibility,
    jni::Object::Param aInitData, jni::String::Param aId,
    jni::String::Param aChromeURI, int32_t aScreenId, bool aPrivateMode,
    bool aRemote) {
  MOZ_ASSERT(NS_IsMainThread());

  AUTO_PROFILER_LABEL("nsWindow::GeckoViewSupport::Open", OTHER);

  nsCOMPtr<nsIWindowWatcher> ww = do_GetService(NS_WINDOWWATCHER_CONTRACTID);
  MOZ_RELEASE_ASSERT(ww);

  nsAutoCString url;
  if (aChromeURI) {
    url = aChromeURI->ToCString();
  } else {
    nsresult rv = Preferences::GetCString("toolkit.defaultChromeURI", url);
    if (NS_FAILED(rv)) {
      url = NS_LITERAL_CSTRING("chrome://geckoview/content/geckoview.xul");
    }
  }

  // Prepare an nsIAndroidView to pass as argument to the window.
  RefPtr<AndroidView> androidView = new AndroidView();
  androidView->mEventDispatcher->Attach(
      java::EventDispatcher::Ref::From(aDispatcher), nullptr);
  androidView->mInitData = java::GeckoBundle::Ref::From(aInitData);

  nsAutoCString chromeFlags("chrome,dialog=0,resizable,scrollbars");
  if (aPrivateMode) {
    chromeFlags += ",private";
  }
  if (aRemote) {
    chromeFlags += ",remote";
  }
  nsCOMPtr<mozIDOMWindowProxy> domWindow;
  ww->OpenWindow(nullptr, url.get(), aId->ToCString().get(), chromeFlags.get(),
                 androidView, getter_AddRefs(domWindow));
  MOZ_RELEASE_ASSERT(domWindow);

  nsCOMPtr<nsPIDOMWindowOuter> pdomWindow = nsPIDOMWindowOuter::From(domWindow);
  const RefPtr<nsWindow> window = nsWindow::From(pdomWindow);
  MOZ_ASSERT(window);
  window->SetScreenId(aScreenId);

  // Attach a new GeckoView support object to the new window.
  GeckoSession::Window::LocalRef sessionWindow(aCls.Env(), aWindow);
  window->mGeckoViewSupport =
      mozilla::MakeUnique<GeckoViewSupport>(window, sessionWindow);
  window->mGeckoViewSupport->mDOMWindow = pdomWindow;
  window->mAndroidView = androidView;

  // Attach other session support objects.
  window->mGeckoViewSupport->Transfer(sessionWindow, aQueue, aCompositor,
                                      aDispatcher, aSessionAccessibility,
                                      aInitData);

  if (window->mWidgetListener) {
    nsCOMPtr<nsIXULWindow> xulWindow(window->mWidgetListener->GetXULWindow());
    if (xulWindow) {
      // Our window is not intrinsically sized, so tell nsXULWindow to
      // not set a size for us.
      xulWindow->SetIntrinsicallySized(false);
    }
  }
}

void nsWindow::GeckoViewSupport::Close() {
  if (window.mAndroidView) {
    window.mAndroidView->mEventDispatcher->Detach();
  }

  if (!mDOMWindow) {
    return;
  }

  mDOMWindow->ForceClose();
  mDOMWindow = nullptr;
  mGeckoViewWindow = nullptr;
}

void nsWindow::GeckoViewSupport::Transfer(
    const GeckoSession::Window::LocalRef& inst, jni::Object::Param aQueue,
    jni::Object::Param aCompositor, jni::Object::Param aDispatcher,
    jni::Object::Param aSessionAccessibility, jni::Object::Param aInitData) {
  if (window.mNPZCSupport) {
    MOZ_ASSERT(window.mLayerViewSupport);
    window.mNPZCSupport.Detach(window.mNPZCSupport->GetJavaNPZC());
  }

  auto compositor = GeckoSession::Compositor::LocalRef(
      inst.Env(), GeckoSession::Compositor::Ref::From(aCompositor));
  if (window.mLayerViewSupport &&
      window.mLayerViewSupport->GetJavaCompositor() != compositor) {
    window.mLayerViewSupport.Detach(
        window.mLayerViewSupport->GetJavaCompositor());
  }
  if (!window.mLayerViewSupport) {
    window.mLayerViewSupport.Attach(compositor, &window, compositor);
  }

  MOZ_ASSERT(window.mAndroidView);
  window.mAndroidView->mEventDispatcher->Attach(
      java::EventDispatcher::Ref::From(aDispatcher), mDOMWindow);

  if (window.mSessionAccessibility) {
    window.mSessionAccessibility.Detach(
        window.mSessionAccessibility->GetJavaAccessibility());
  }
  if (aSessionAccessibility) {
    AttachAccessibility(inst, aSessionAccessibility);
  }

  if (mIsReady) {
    // We're in a transfer; update init-data and notify JS code.
    window.mAndroidView->mInitData = java::GeckoBundle::Ref::From(aInitData);
    OnReady(aQueue);
    window.mAndroidView->mEventDispatcher->Dispatch(
        u"GeckoView:UpdateInitData");
  }

  DispatchToUiThread("GeckoViewSupport::Transfer",
                     [compositor = GeckoSession::Compositor::GlobalRef(
                          compositor)] { compositor->OnCompositorAttached(); });
}

void nsWindow::GeckoViewSupport::AttachEditable(
    const GeckoSession::Window::LocalRef& inst,
    jni::Object::Param aEditableParent) {
  if (!window.mEditableSupport) {
    auto editableChild = java::GeckoEditableChild::New(aEditableParent,
                                                       /* default */ true);
    window.mEditableSupport.Attach(editableChild, &window, editableChild);
  } else {
    window.mEditableSupport->TransferParent(aEditableParent);
  }

  window.mEditableParent = aEditableParent;
}

void nsWindow::GeckoViewSupport::AttachAccessibility(
    const GeckoSession::Window::LocalRef& inst,
    jni::Object::Param aSessionAccessibility) {
  MOZ_ASSERT(!window.mSessionAccessibility);
  java::SessionAccessibility::NativeProvider::LocalRef sessionAccessibility(
      inst.Env());
  sessionAccessibility = java::SessionAccessibility::NativeProvider::Ref::From(
      aSessionAccessibility);

  if (window.mSessionAccessibility) {
    window.mSessionAccessibility.Detach(
        window.mSessionAccessibility->GetJavaAccessibility());
  }

  window.mSessionAccessibility.Attach(sessionAccessibility, &window,
                                      sessionAccessibility);
}

void nsWindow::InitNatives() {
  jni::InitConversionStatics();
  nsWindow::GeckoViewSupport::Base::Init();
  nsWindow::LayerViewSupport::Init();
  nsWindow::NPZCSupport::Init();

  GeckoEditableSupport::Init();
  a11y::SessionAccessibility::Init();
}

/* static */
already_AddRefed<nsWindow> nsWindow::From(nsPIDOMWindowOuter* aDOMWindow) {
  nsCOMPtr<nsIWidget> widget = WidgetUtils::DOMWindowToWidget(aDOMWindow);
  return From(widget);
}

/* static */
already_AddRefed<nsWindow> nsWindow::From(nsIWidget* aWidget) {
  // `widget` may be one of several different types in the parent
  // process, including the Android nsWindow, PuppetWidget, etc. To
  // ensure that the cast to the Android nsWindow is valid, we check that the
  // widget is a top-level window and that its NS_NATIVE_WIDGET value is
  // non-null, which is not the case for non-native widgets like
  // PuppetWidget.
  if (aWidget && aWidget->WindowType() == nsWindowType::eWindowType_toplevel &&
      aWidget->GetNativeData(NS_NATIVE_WIDGET) == aWidget) {
    RefPtr<nsWindow> window = static_cast<nsWindow*>(aWidget);
    return window.forget();
  }
  return nullptr;
}

nsWindow* nsWindow::TopWindow() {
  if (!gTopLevelWindows.IsEmpty()) return gTopLevelWindows[0];
  return nullptr;
}

void nsWindow::LogWindow(nsWindow* win, int index, int indent) {
#if defined(DEBUG) || defined(FORCE_ALOG)
  char spaces[] = "                    ";
  spaces[indent < 20 ? indent : 20] = 0;
  ALOG("%s [% 2d] 0x%p [parent 0x%p] [% 3d,% 3dx% 3d,% 3d] vis %d type %d",
       spaces, index, win, win->mParent, win->mBounds.x, win->mBounds.y,
       win->mBounds.width, win->mBounds.height, win->mIsVisible,
       win->mWindowType);
#endif
}

void nsWindow::DumpWindows() { DumpWindows(gTopLevelWindows); }

void nsWindow::DumpWindows(const nsTArray<nsWindow*>& wins, int indent) {
  for (uint32_t i = 0; i < wins.Length(); ++i) {
    nsWindow* w = wins[i];
    LogWindow(w, i, indent);
    DumpWindows(w->mChildren, indent + 1);
  }
}

nsWindow::nsWindow()
    : mScreenId(0),  // Use 0 (primary screen) as the default value.
      mIsVisible(false),
      mParent(nullptr),
      mIsFullScreen(false),
      mIsDisablingWebRender(false) {}

nsWindow::~nsWindow() {
  gTopLevelWindows.RemoveElement(this);
  ALOG("nsWindow %p destructor", (void*)this);
  // The mCompositorSession should have been cleaned up in nsWindow::Destroy()
  // DestroyLayerManager() will call DestroyCompositor() which will crash if
  // called from nsBaseWidget destructor. See Bug 1392705
  MOZ_ASSERT(!mCompositorSession);
}

bool nsWindow::IsTopLevel() {
  return mWindowType == eWindowType_toplevel ||
         mWindowType == eWindowType_dialog ||
         mWindowType == eWindowType_invisible;
}

nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
                          const LayoutDeviceIntRect& aRect,
                          nsWidgetInitData* aInitData) {
  ALOG("nsWindow[%p]::Create %p [%d %d %d %d]", (void*)this, (void*)aParent,
       aRect.x, aRect.y, aRect.width, aRect.height);

  nsWindow* parent = (nsWindow*)aParent;
  if (aNativeParent) {
    if (parent) {
      ALOG(
          "Ignoring native parent on Android window [%p], "
          "since parent was specified (%p %p)",
          (void*)this, (void*)aNativeParent, (void*)aParent);
    } else {
      parent = (nsWindow*)aNativeParent;
    }
  }

  mBounds = aRect;

  BaseCreate(nullptr, aInitData);

  NS_ASSERTION(IsTopLevel() || parent,
               "non-top-level window doesn't have a parent!");

  if (IsTopLevel()) {
    gTopLevelWindows.AppendElement(this);

  } else if (parent) {
    parent->mChildren.AppendElement(this);
    mParent = parent;
  }

  // A default size of 1x1 confuses MobileViewportManager, so
  // use 0x0 instead. This is also a little more fitting since
  // we don't yet have a surface yet (and therefore a valid size)
  // and 0x0 is usually recognized as invalid.
  Resize(0, 0, false);

  CreateLayerManager();

#ifdef DEBUG_ANDROID_WIDGET
  DumpWindows();
#endif

  return NS_OK;
}

void nsWindow::Destroy() {
  nsBaseWidget::mOnDestroyCalled = true;

  if (mGeckoViewSupport) {
    // Disassociate our native object with GeckoView.
    mGeckoViewSupport = nullptr;
  }

  // Stuff below may release the last ref to this
  nsCOMPtr<nsIWidget> kungFuDeathGrip(this);

  while (mChildren.Length()) {
    // why do we still have children?
    ALOG("### Warning: Destroying window %p and reparenting child %p to null!",
         (void*)this, (void*)mChildren[0]);
    mChildren[0]->SetParent(nullptr);
  }

  // Ensure the compositor has been shutdown before this nsWindow is potentially
  // deleted
  nsBaseWidget::DestroyCompositor();

  nsBaseWidget::Destroy();

  if (IsTopLevel()) gTopLevelWindows.RemoveElement(this);

  SetParent(nullptr);

  nsBaseWidget::OnDestroy();

#ifdef DEBUG_ANDROID_WIDGET
  DumpWindows();
#endif
}

nsresult nsWindow::ConfigureChildren(
    const nsTArray<nsIWidget::Configuration>& config) {
  for (uint32_t i = 0; i < config.Length(); ++i) {
    nsWindow* childWin = (nsWindow*)config[i].mChild.get();
    childWin->Resize(config[i].mBounds.x, config[i].mBounds.y,
                     config[i].mBounds.width, config[i].mBounds.height, false);
  }

  return NS_OK;
}

void nsWindow::RedrawAll() {
  if (mAttachedWidgetListener) {
    mAttachedWidgetListener->RequestRepaint();
  } else if (mWidgetListener) {
    mWidgetListener->RequestRepaint();
  }
}

RefPtr<UiCompositorControllerChild> nsWindow::GetUiCompositorControllerChild() {
  return mCompositorSession
             ? mCompositorSession->GetUiCompositorControllerChild()
             : nullptr;
}

mozilla::layers::LayersId nsWindow::GetRootLayerId() const {
  return mCompositorSession ? mCompositorSession->RootLayerTreeId()
                            : mozilla::layers::LayersId{0};
}

void nsWindow::OnGeckoViewReady() {
  if (!mGeckoViewSupport) {
    return;
  }
  mGeckoViewSupport->OnReady();
}

void nsWindow::SetParent(nsIWidget* aNewParent) {
  if ((nsIWidget*)mParent == aNewParent) return;

  // If we had a parent before, remove ourselves from its list of
  // children.
  if (mParent) mParent->mChildren.RemoveElement(this);

  mParent = (nsWindow*)aNewParent;

  if (mParent) mParent->mChildren.AppendElement(this);

  // if we are now in the toplevel window's hierarchy, schedule a redraw
  if (FindTopLevel() == nsWindow::TopWindow()) RedrawAll();
}

nsIWidget* nsWindow::GetParent() { return mParent; }

float nsWindow::GetDPI() {
  float dpi = 160.0f;

  nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
  if (screen) {
    screen->GetDpi(&dpi);
  }

  return dpi;
}

double nsWindow::GetDefaultScaleInternal() {
  double scale = 1.0f;

  nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
  if (screen) {
    screen->GetContentsScaleFactor(&scale);
  }

  return scale;
}

void nsWindow::Show(bool aState) {
  ALOG("nsWindow[%p]::Show %d", (void*)this, aState);

  if (mWindowType == eWindowType_invisible) {
    ALOG("trying to show invisible window! ignoring..");
    return;
  }

  if (aState == mIsVisible) return;

  mIsVisible = aState;

  if (IsTopLevel()) {
    // XXX should we bring this to the front when it's shown,
    // if it's a toplevel widget?

    // XXX we should synthesize a eMouseExitFromWidget (for old top
    // window)/eMouseEnterIntoWidget (for new top window) since we need
    // to pretend that the top window always has focus.  Not sure
    // if Show() is the right place to do this, though.

    if (aState) {
      // It just became visible, so bring it to the front.
      BringToFront();

    } else if (nsWindow::TopWindow() == this) {
      // find the next visible window to show
      unsigned int i;
      for (i = 1; i < gTopLevelWindows.Length(); i++) {
        nsWindow* win = gTopLevelWindows[i];
        if (!win->mIsVisible) continue;

        win->BringToFront();
        break;
      }
    }
  } else if (FindTopLevel() == nsWindow::TopWindow()) {
    RedrawAll();
  }

#ifdef DEBUG_ANDROID_WIDGET
  DumpWindows();
#endif
}

bool nsWindow::IsVisible() const { return mIsVisible; }

void nsWindow::ConstrainPosition(bool aAllowSlop, int32_t* aX, int32_t* aY) {
  ALOG("nsWindow[%p]::ConstrainPosition %d [%d %d]", (void*)this, aAllowSlop,
       *aX, *aY);

  // constrain toplevel windows; children we don't care about
  if (IsTopLevel()) {
    *aX = 0;
    *aY = 0;
  }
}

void nsWindow::Move(double aX, double aY) {
  if (IsTopLevel()) return;

  Resize(aX, aY, mBounds.width, mBounds.height, true);
}

void nsWindow::Resize(double aWidth, double aHeight, bool aRepaint) {
  Resize(mBounds.x, mBounds.y, aWidth, aHeight, aRepaint);
}

void nsWindow::Resize(double aX, double aY, double aWidth, double aHeight,
                      bool aRepaint) {
  ALOG("nsWindow[%p]::Resize [%f %f %f %f] (repaint %d)", (void*)this, aX, aY,
       aWidth, aHeight, aRepaint);

  bool needPositionDispatch = aX != mBounds.x || aY != mBounds.y;
  bool needSizeDispatch = aWidth != mBounds.width || aHeight != mBounds.height;

  mBounds.x = NSToIntRound(aX);
  mBounds.y = NSToIntRound(aY);
  mBounds.width = NSToIntRound(aWidth);
  mBounds.height = NSToIntRound(aHeight);

  if (needSizeDispatch) {
    OnSizeChanged(gfx::IntSize::Truncate(aWidth, aHeight));
  }

  if (needPositionDispatch) {
    NotifyWindowMoved(mBounds.x, mBounds.y);
  }

  // Should we skip honoring aRepaint here?
  if (aRepaint && FindTopLevel() == nsWindow::TopWindow()) RedrawAll();
}

void nsWindow::SetZIndex(int32_t aZIndex) {
  ALOG("nsWindow[%p]::SetZIndex %d ignored", (void*)this, aZIndex);
}

void nsWindow::SetSizeMode(nsSizeMode aMode) {
  if (aMode == mSizeMode) {
    return;
  }

  nsBaseWidget::SetSizeMode(aMode);

  switch (aMode) {
    case nsSizeMode_Minimized:
      GeckoAppShell::MoveTaskToBack();
      break;
    case nsSizeMode_Fullscreen:
      MakeFullScreen(true);
      break;
    default:
      break;
  }
}

void nsWindow::Enable(bool aState) {
  ALOG("nsWindow[%p]::Enable %d ignored", (void*)this, aState);
}

bool nsWindow::IsEnabled() const { return true; }

void nsWindow::Invalidate(const LayoutDeviceIntRect& aRect) {}

nsWindow* nsWindow::FindTopLevel() {
  nsWindow* toplevel = this;
  while (toplevel) {
    if (toplevel->IsTopLevel()) return toplevel;

    toplevel = toplevel->mParent;
  }

  ALOG(
      "nsWindow::FindTopLevel(): couldn't find a toplevel or dialog window in "
      "this [%p] widget's hierarchy!",
      (void*)this);
  return this;
}

void nsWindow::SetFocus(Raise) {
  // FIXME: Shouldn't this account for the argument?
  FindTopLevel()->BringToFront();
}

void nsWindow::BringToFront() {
  // If the window to be raised is the same as the currently raised one,
  // do nothing. We need to check the focus manager as well, as the first
  // window that is created will be first in the window list but won't yet
  // be focused.
  nsCOMPtr<nsIFocusManager> fm = do_GetService(FOCUSMANAGER_CONTRACTID);
  nsCOMPtr<mozIDOMWindowProxy> existingTopWindow;
  fm->GetActiveWindow(getter_AddRefs(existingTopWindow));
  if (existingTopWindow && FindTopLevel() == nsWindow::TopWindow()) return;

  if (!IsTopLevel()) {
    FindTopLevel()->BringToFront();
    return;
  }

  RefPtr<nsWindow> kungFuDeathGrip(this);

  nsWindow* oldTop = nullptr;
  if (!gTopLevelWindows.IsEmpty()) {
    oldTop = gTopLevelWindows[0];
  }

  gTopLevelWindows.RemoveElement(this);
  gTopLevelWindows.InsertElementAt(0, this);

  if (oldTop) {
    nsIWidgetListener* listener = oldTop->GetWidgetListener();
    if (listener) {
      listener->WindowDeactivated();
    }
  }

  if (mWidgetListener) {
    mWidgetListener->WindowActivated();
  }

  RedrawAll();
}

LayoutDeviceIntRect nsWindow::GetScreenBounds() {
  return LayoutDeviceIntRect(WidgetToScreenOffset(), mBounds.Size());
}

LayoutDeviceIntPoint nsWindow::WidgetToScreenOffset() {
  LayoutDeviceIntPoint p(0, 0);

  for (nsWindow* w = this; !!w; w = w->mParent) {
    p.x += w->mBounds.x;
    p.y += w->mBounds.y;

    if (w->IsTopLevel()) {
      break;
    }
  }
  return p;
}

nsresult nsWindow::DispatchEvent(WidgetGUIEvent* aEvent,
                                 nsEventStatus& aStatus) {
  aStatus = DispatchEvent(aEvent);
  return NS_OK;
}

nsEventStatus nsWindow::DispatchEvent(WidgetGUIEvent* aEvent) {
  if (mAttachedWidgetListener) {
    return mAttachedWidgetListener->HandleEvent(aEvent, mUseAttachedEvents);
  } else if (mWidgetListener) {
    return mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents);
  }
  return nsEventStatus_eIgnore;
}

nsresult nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen*) {
  if (!mAndroidView) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  mIsFullScreen = aFullScreen;
  mAndroidView->mEventDispatcher->Dispatch(
      aFullScreen ? u"GeckoView:FullScreenEnter" : u"GeckoView:FullScreenExit");

  nsIWidgetListener* listener = GetWidgetListener();
  if (listener) {
    mSizeMode = mIsFullScreen ? nsSizeMode_Fullscreen : nsSizeMode_Normal;
    listener->SizeModeChanged(mSizeMode);
    listener->FullscreenChanged(mIsFullScreen);
  }
  return NS_OK;
}

mozilla::layers::LayerManager* nsWindow::GetLayerManager(
    PLayerTransactionChild*, LayersBackend, LayerManagerPersistence) {
  if (mLayerManager) {
    return mLayerManager;
  }

  if (mIsDisablingWebRender) {
    CreateLayerManager();
    mIsDisablingWebRender = false;
    return mLayerManager;
  }

  return nullptr;
}

void nsWindow::CreateLayerManager() {
  if (mLayerManager) {
    return;
  }

  nsWindow* topLevelWindow = FindTopLevel();
  if (!topLevelWindow || topLevelWindow->mWindowType == eWindowType_invisible) {
    // don't create a layer manager for an invisible top-level window
    return;
  }

  // Ensure that gfxPlatform is initialized first.
  gfxPlatform::GetPlatform();

  if (ShouldUseOffMainThreadCompositing()) {
    LayoutDeviceIntRect rect = GetBounds();
    CreateCompositor(rect.Width(), rect.Height());
    if (mLayerManager) {
      return;
    }

    // If we get here, then off main thread compositing failed to initialize.
    sFailedToCreateGLContext = true;
  }

  if (!ComputeShouldAccelerate() || sFailedToCreateGLContext) {
    printf_stderr(" -- creating basic, not accelerated\n");
    mLayerManager = CreateBasicLayerManager();
  }
}

void nsWindow::NotifyDisablingWebRender() {
  mIsDisablingWebRender = true;
  RedrawAll();
}

void nsWindow::OnSizeChanged(const gfx::IntSize& aSize) {
  ALOG("nsWindow: %p OnSizeChanged [%d %d]", (void*)this, aSize.width,
       aSize.height);

  mBounds.width = aSize.width;
  mBounds.height = aSize.height;

  if (mWidgetListener) {
    mWidgetListener->WindowResized(this, aSize.width, aSize.height);
  }

  if (mAttachedWidgetListener) {
    mAttachedWidgetListener->WindowResized(this, aSize.width, aSize.height);
  }
}

void nsWindow::InitEvent(WidgetGUIEvent& event, LayoutDeviceIntPoint* aPoint) {
  if (aPoint) {
    event.mRefPoint = *aPoint;
  } else {
    event.mRefPoint = LayoutDeviceIntPoint(0, 0);
  }

  event.mTime = PR_Now() / 1000;
}

void nsWindow::UpdateOverscrollVelocity(const float aX, const float aY) {
  if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
    const auto& compositor = lvs->GetJavaCompositor();
    if (AndroidBridge::IsJavaUiThread()) {
      compositor->UpdateOverscrollVelocity(aX, aY);
      return;
    }

    DispatchToUiThread(
        "nsWindow::UpdateOverscrollVelocity",
        [compositor = GeckoSession::Compositor::GlobalRef(compositor), aX, aY] {
          compositor->UpdateOverscrollVelocity(aX, aY);
        });
  }
}

void nsWindow::UpdateOverscrollOffset(const float aX, const float aY) {
  if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
    const auto& compositor = lvs->GetJavaCompositor();
    if (AndroidBridge::IsJavaUiThread()) {
      compositor->UpdateOverscrollOffset(aX, aY);
      return;
    }

    DispatchToUiThread(
        "nsWindow::UpdateOverscrollOffset",
        [compositor = GeckoSession::Compositor::GlobalRef(compositor), aX, aY] {
          compositor->UpdateOverscrollOffset(aX, aY);
        });
  }
}

void* nsWindow::GetNativeData(uint32_t aDataType) {
  switch (aDataType) {
    // used by GLContextProviderEGL, nullptr is EGL_DEFAULT_DISPLAY
    case NS_NATIVE_DISPLAY:
      return nullptr;

    case NS_NATIVE_WIDGET:
      return (void*)this;

    case NS_RAW_NATIVE_IME_CONTEXT: {
      void* pseudoIMEContext = GetPseudoIMEContext();
      if (pseudoIMEContext) {
        return pseudoIMEContext;
      }
      // We assume that there is only one context per process on Android
      return NS_ONLY_ONE_NATIVE_IME_CONTEXT;
    }

    case NS_JAVA_SURFACE:
      if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
        return lvs->GetSurface().Get();
      }
      return nullptr;
  }

  return nullptr;
}

void nsWindow::SetNativeData(uint32_t aDataType, uintptr_t aVal) {
  switch (aDataType) {}
}

void nsWindow::DispatchHitTest(const WidgetTouchEvent& aEvent) {
  if (aEvent.mMessage == eTouchStart && aEvent.mTouches.Length() == 1) {
    // Since touch events don't get retargeted by PositionedEventTargeting.cpp
    // code on Fennec, we dispatch a dummy mouse event that *does* get
    // retargeted. The Fennec browser.js code can use this to activate the
    // highlight element in case the this touchstart is the start of a tap.
    WidgetMouseEvent hittest(true, eMouseHitTest, this,
                             WidgetMouseEvent::eReal);
    hittest.mRefPoint = aEvent.mTouches[0]->mRefPoint;
    hittest.mIgnoreRootScrollFrame = true;
    hittest.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
    nsEventStatus status;
    DispatchEvent(&hittest, status);

    if (mAPZEventState && hittest.mHitCluster) {
      mAPZEventState->ProcessClusterHit();
    }
  }
}

mozilla::Modifiers nsWindow::GetModifiers(int32_t metaState) {
  using mozilla::java::sdk::KeyEvent;
  return (metaState & KeyEvent::META_ALT_MASK ? MODIFIER_ALT : 0) |
         (metaState & KeyEvent::META_SHIFT_MASK ? MODIFIER_SHIFT : 0) |
         (metaState & KeyEvent::META_CTRL_MASK ? MODIFIER_CONTROL : 0) |
         (metaState & KeyEvent::META_META_MASK ? MODIFIER_META : 0) |
         (metaState & KeyEvent::META_FUNCTION_ON ? MODIFIER_FN : 0) |
         (metaState & KeyEvent::META_CAPS_LOCK_ON ? MODIFIER_CAPSLOCK : 0) |
         (metaState & KeyEvent::META_NUM_LOCK_ON ? MODIFIER_NUMLOCK : 0) |
         (metaState & KeyEvent::META_SCROLL_LOCK_ON ? MODIFIER_SCROLLLOCK : 0);
}

TimeStamp nsWindow::GetEventTimeStamp(int64_t aEventTime) {
  // Android's event time is SystemClock.uptimeMillis that is counted in ms
  // since OS was booted.
  // (https://developer.android.com/reference/android/os/SystemClock.html)
  // and this SystemClock.uptimeMillis uses SYSTEM_TIME_MONOTONIC.
  // Our posix implemententaion of TimeStamp::Now uses SYSTEM_TIME_MONOTONIC
  //  too. Due to same implementation, we can use this via FromSystemTime.
  int64_t tick =
      BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aEventTime);
  return TimeStamp::FromSystemTime(tick);
}

void nsWindow::GeckoViewSupport::OnReady(jni::Object::Param aQueue) {
  GeckoSession::Window::LocalRef window(mGeckoViewWindow);
  if (!window) {
    return;
  }
  window->OnReady(aQueue);
  mIsReady = true;
}

void nsWindow::UserActivity() {
  if (!mIdleService) {
    mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
  }

  if (mIdleService) {
    mIdleService->ResetIdleTimeOut(0);
  }

  if (FindTopLevel() != nsWindow::TopWindow()) {
    BringToFront();
  }
}

TextEventDispatcherListener* nsWindow::GetNativeTextEventDispatcherListener() {
  nsWindow* top = FindTopLevel();
  MOZ_ASSERT(top);

  if (!top->mEditableSupport) {
    // Non-GeckoView windows don't support IME operations.
    return nullptr;
  }
  return top->mEditableSupport;
}

void nsWindow::SetInputContext(const InputContext& aContext,
                               const InputContextAction& aAction) {
  nsWindow* top = FindTopLevel();
  MOZ_ASSERT(top);

  if (!top->mEditableSupport) {
    // Non-GeckoView windows don't support IME operations.
    return;
  }

  // We are using an IME event later to notify Java, and the IME event
  // will be processed by the top window. Therefore, to ensure the
  // IME event uses the correct mInputContext, we need to let the top
  // window process SetInputContext
  top->mEditableSupport->SetInputContext(aContext, aAction);
}

InputContext nsWindow::GetInputContext() {
  nsWindow* top = FindTopLevel();
  MOZ_ASSERT(top);

  if (!top->mEditableSupport) {
    // Non-GeckoView windows don't support IME operations.
    return InputContext();
  }

  // We let the top window process SetInputContext,
  // so we should let it process GetInputContext as well.
  return top->mEditableSupport->GetInputContext();
}

nsresult nsWindow::SynthesizeNativeTouchPoint(uint32_t aPointerId,
                                              TouchPointerState aPointerState,
                                              LayoutDeviceIntPoint aPoint,
                                              double aPointerPressure,
                                              uint32_t aPointerOrientation,
                                              nsIObserver* aObserver) {
  mozilla::widget::AutoObserverNotifier notifier(aObserver, "touchpoint");

  int eventType;
  switch (aPointerState) {
    case TOUCH_CONTACT:
      // This could be a ACTION_DOWN or ACTION_MOVE depending on the
      // existing state; it is mapped to the right thing in Java.
      eventType = sdk::MotionEvent::ACTION_POINTER_DOWN;
      break;
    case TOUCH_REMOVE:
      // This could be turned into a ACTION_UP in Java
      eventType = sdk::MotionEvent::ACTION_POINTER_UP;
      break;
    case TOUCH_CANCEL:
      eventType = sdk::MotionEvent::ACTION_CANCEL;
      break;
    case TOUCH_HOVER:  // not supported for now
    default:
      return NS_ERROR_UNEXPECTED;
  }

  MOZ_ASSERT(mNPZCSupport);
  const auto& npzc = mNPZCSupport->GetJavaNPZC();
  const auto& bounds = FindTopLevel()->mBounds;
  aPoint.x -= bounds.x;
  aPoint.y -= bounds.y;

  DispatchToUiThread(
      "nsWindow::SynthesizeNativeTouchPoint",
      [npzc = PanZoomController::NativeProvider::GlobalRef(npzc), aPointerId,
       eventType, aPoint, aPointerPressure, aPointerOrientation] {
        npzc->SynthesizeNativeTouchPoint(aPointerId, eventType, aPoint.x,
                                         aPoint.y, aPointerPressure,
                                         aPointerOrientation);
      });
  return NS_OK;
}

nsresult nsWindow::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint,
                                              uint32_t aNativeMessage,
                                              uint32_t aModifierFlags,
                                              nsIObserver* aObserver) {
  mozilla::widget::AutoObserverNotifier notifier(aObserver, "mouseevent");

  MOZ_ASSERT(mNPZCSupport);
  const auto& npzc = mNPZCSupport->GetJavaNPZC();
  const auto& bounds = FindTopLevel()->mBounds;
  aPoint.x -= bounds.x;
  aPoint.y -= bounds.y;

  DispatchToUiThread("nsWindow::SynthesizeNativeMouseEvent",
                     [npzc = PanZoomController::NativeProvider::GlobalRef(npzc),
                      aNativeMessage, aPoint] {
                       npzc->SynthesizeNativeMouseEvent(aNativeMessage,
                                                        aPoint.x, aPoint.y);
                     });
  return NS_OK;
}

nsresult nsWindow::SynthesizeNativeMouseMove(LayoutDeviceIntPoint aPoint,
                                             nsIObserver* aObserver) {
  mozilla::widget::AutoObserverNotifier notifier(aObserver, "mouseevent");

  MOZ_ASSERT(mNPZCSupport);
  const auto& npzc = mNPZCSupport->GetJavaNPZC();
  const auto& bounds = FindTopLevel()->mBounds;
  aPoint.x -= bounds.x;
  aPoint.y -= bounds.y;

  DispatchToUiThread(
      "nsWindow::SynthesizeNativeMouseMove",
      [npzc = PanZoomController::NativeProvider::GlobalRef(npzc), aPoint] {
        npzc->SynthesizeNativeMouseEvent(sdk::MotionEvent::ACTION_HOVER_MOVE,
                                         aPoint.x, aPoint.y);
      });
  return NS_OK;
}

bool nsWindow::WidgetPaintsBackground() {
  return StaticPrefs::android_widget_paints_background();
}

bool nsWindow::NeedsPaint() {
  if (!mLayerViewSupport || mLayerViewSupport->CompositorPaused() ||
      // FindTopLevel() != nsWindow::TopWindow() ||
      !GetLayerManager(nullptr)) {
    return false;
  }
  return nsIWidget::NeedsPaint();
}

void nsWindow::ConfigureAPZControllerThread() {
  APZThreadUtils::SetControllerThread(mozilla::GetAndroidUiThreadMessageLoop());
}

already_AddRefed<GeckoContentController>
nsWindow::CreateRootContentController() {
  RefPtr<GeckoContentController> controller =
      new AndroidContentController(this, mAPZEventState, mAPZC);
  return controller.forget();
}

uint32_t nsWindow::GetMaxTouchPoints() const {
  return GeckoAppShell::GetMaxTouchPoints();
}

void nsWindow::UpdateZoomConstraints(
    const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
    const mozilla::Maybe<ZoomConstraints>& aConstraints) {
  nsBaseWidget::UpdateZoomConstraints(aPresShellId, aViewId, aConstraints);
}

CompositorBridgeChild* nsWindow::GetCompositorBridgeChild() const {
  return mCompositorSession ? mCompositorSession->GetCompositorBridgeChild()
                            : nullptr;
}

already_AddRefed<nsIScreen> nsWindow::GetWidgetScreen() {
  RefPtr<nsIScreen> screen =
      ScreenHelperAndroid::GetSingleton()->ScreenForId(mScreenId);
  return screen.forget();
}

void nsWindow::SetContentDocumentDisplayed(bool aDisplayed) {
  mContentDocumentDisplayed = aDisplayed;
}

bool nsWindow::IsContentDocumentDisplayed() {
  return mContentDocumentDisplayed;
}

void nsWindow::RecvToolbarAnimatorMessageFromCompositor(int32_t aMessage) {
  MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
  if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
    lvs->RecvToolbarAnimatorMessage(aMessage);
  }
}

void nsWindow::UpdateRootFrameMetrics(const ScreenPoint& aScrollOffset,
                                      const CSSToScreenScale& aZoom) {
  MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
  if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
    const auto& compositor = lvs->GetJavaCompositor();
    mContentDocumentDisplayed = true;
    compositor->UpdateRootFrameMetrics(aScrollOffset.x, aScrollOffset.y,
                                       aZoom.scale);
  }
}

void nsWindow::RecvScreenPixels(Shmem&& aMem, const ScreenIntSize& aSize) {
  MOZ_ASSERT(AndroidBridge::IsJavaUiThread());
  if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
    lvs->RecvScreenPixels(std::move(aMem), aSize);
  }
}

nsresult nsWindow::SetPrefersReducedMotionOverrideForTest(bool aValue) {
  nsXPLookAndFeel::GetInstance()->SetPrefersReducedMotionOverrideForTest(
      aValue);

  java::GeckoSystemStateListener::NotifyPrefersReducedMotionChangedForTest();
  return NS_OK;
}

nsresult nsWindow::ResetPrefersReducedMotionOverrideForTest() {
  nsXPLookAndFeel::GetInstance()->ResetPrefersReducedMotionOverrideForTest();
  return NS_OK;
}

already_AddRefed<nsIWidget> nsIWidget::CreateTopLevelWindow() {
  nsCOMPtr<nsIWidget> window = new nsWindow();
  return window.forget();
}

already_AddRefed<nsIWidget> nsIWidget::CreateChildWindow() {
  nsCOMPtr<nsIWidget> window = new nsWindow();
  return window.forget();
}