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 (31ec81b5d7bb)

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
/* -*- Mode: c++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
 * 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 <math.h>
#include <unistd.h>

#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/unused.h"
#include "mozilla/Preferences.h"
#include "mozilla/layers/RenderTrace.h"
#include <algorithm>

using mozilla::dom::ContentParent;
using mozilla::dom::ContentChild;
using mozilla::unused;

#include "nsAppShell.h"
#include "nsIdleService.h"
#include "nsWindow.h"
#include "nsIObserverService.h"
#include "nsFocusManager.h"
#include "nsIWidgetListener.h"
#include "nsViewManager.h"

#include "nsRenderingContext.h"
#include "nsIDOMSimpleGestureEvent.h"

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

#include "gfxImageSurface.h"
#include "gfxContext.h"

#include "Layers.h"
#include "LayerManagerOGL.h"
#include "mozilla/layers/LayerManagerComposite.h"
#include "mozilla/layers/AsyncCompositionManager.h"
#include "mozilla/layers/APZCTreeManager.h"
#include "GLContext.h"
#include "GLContextProvider.h"

#include "nsTArray.h"

#include "AndroidBridge.h"
#include "android_npapi.h"

#include "imgIEncoder.h"

#include "nsStringGlue.h"

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

NS_IMPL_ISUPPORTS_INHERITED0(nsWindow, nsBaseWidget)

// The dimensions of the current android view
static gfxIntSize gAndroidBounds = gfxIntSize(0, 0);
static gfxIntSize gAndroidScreenBounds;

#include "mozilla/layers/AsyncPanZoomController.h"
#include "mozilla/layers/CompositorChild.h"
#include "mozilla/layers/CompositorParent.h"
#include "mozilla/layers/LayerTransactionParent.h"
#include "mozilla/Mutex.h"
#include "nsThreadUtils.h"

class ContentCreationNotifier;
static StaticRefPtr<ContentCreationNotifier> gContentCreationNotifier;

// A helper class to send updates when content processes
// are created. Currently an update for the screen size is sent.
class ContentCreationNotifier MOZ_FINAL : public nsIObserver
{
    NS_DECL_ISUPPORTS

    NS_IMETHOD Observe(nsISupports* aSubject,
                       const char* aTopic,
                       const PRUnichar* aData)
    {
        if (!strcmp(aTopic, "ipc:content-created")) {
            nsCOMPtr<nsIObserver> cpo = do_QueryInterface(aSubject);
            ContentParent* cp = static_cast<ContentParent*>(cpo.get());
            unused << cp->SendScreenSizeChanged(gAndroidScreenBounds);
        } else if (!strcmp(aTopic, "xpcom-shutdown")) {
            nsCOMPtr<nsIObserverService>
                obs(do_GetService("@mozilla.org/observer-service;1"));
            if (obs) {
                obs->RemoveObserver(static_cast<nsIObserver*>(this),
                                    "xpcom-shutdown");
                obs->RemoveObserver(static_cast<nsIObserver*>(this),
                                    "ipc:content-created");
            }
            gContentCreationNotifier = nullptr;
        }

        return NS_OK;
    }
};

NS_IMPL_ISUPPORTS1(ContentCreationNotifier,
                   nsIObserver)

static bool gMenu;
static bool gMenuConsumed;

// All the toplevel windows that have been created; these are in
// stacking order, so the window at gAndroidBounds[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;

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%08x [parent 0x%08x] [% 3d,% 3dx% 3d,% 3d] vis %d type %d",
         spaces, index, (intptr_t)win, (intptr_t)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() :
    mIsVisible(false),
    mParent(nullptr),
    mFocus(nullptr),
    mIMEComposing(false),
    mIMEMaskSelectionUpdate(false),
    mIMEMaskTextUpdate(false),
    mIMEMaskEventsCount(1), // Mask IME events since there's no focus yet
    mIMEUpdatingContext(false),
    mIMESelectionChanged(false)
{
}

nsWindow::~nsWindow()
{
    gTopLevelWindows.RemoveElement(this);
    nsWindow *top = FindTopLevel();
    if (top->mFocus == this)
        top->mFocus = nullptr;
    ALOG("nsWindow %p destructor", (void*)this);
    if (mLayerManager == sLayerManager) {
        // If this window was the one that created the global OMTC layer manager
        // and compositor, then we should null those out.
        SetCompositor(NULL, NULL, NULL);
    }
}

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

NS_IMETHODIMP
nsWindow::Create(nsIWidget *aParent,
                 nsNativeWidget aNativeParent,
                 const nsIntRect &aRect,
                 nsDeviceContext *aContext,
                 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 (!AndroidBridge::Bridge()) {
        aNativeParent = nullptr;
    }

    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;

    // for toplevel windows, bounds are fixed to full screen size
    if (!parent) {
        mBounds.x = 0;
        mBounds.y = 0;
        mBounds.width = gAndroidBounds.width;
        mBounds.height = gAndroidBounds.height;
    }

    BaseCreate(nullptr, mBounds, aContext, aInitData);

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

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

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

#ifdef DEBUG_ANDROID_WIDGET
    DumpWindows();
#endif

    return NS_OK;
}

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

    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);
    }

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

    SetParent(nullptr);

    nsBaseWidget::OnDestroy();

#ifdef DEBUG_ANDROID_WIDGET
    DumpWindows();
#endif

    return NS_OK;
}

NS_IMETHODIMP
nsWindow::ConfigureChildren(const nsTArray<nsIWidget::Configuration>& config)
{
    for (uint32_t i = 0; i < config.Length(); ++i) {
        nsWindow *childWin = (nsWindow*) config[i].mChild;
        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 (mFocus && mFocus->mWidgetListener) {
        mFocus->mWidgetListener->RequestRepaint();
    }
}

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

    // 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();

    return NS_OK;
}

NS_IMETHODIMP
nsWindow::ReparentNativeWidget(nsIWidget *aNewParent)
{
    NS_PRECONDITION(aNewParent, "");
    return NS_OK;
}

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

float
nsWindow::GetDPI()
{
    if (AndroidBridge::Bridge())
        return AndroidBridge::Bridge()->GetDPI();
    return 160.0f;
}

double
nsWindow::GetDefaultScaleInternal()
{
    float dpi = GetDPI();
    if (dpi < 200) { // includes desktop displays, LDPI, and MDPI Android devices
        return 1.0;
    }
    if (dpi < 300) { // includes Nokia N900, HDPI Android devices
        return 1.5;
    }
    // for very high-density displays calculate an integer ratio.
    return floor(dpi / 150);
}

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

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

    if (aState == mIsVisible)
        return NS_OK;

    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 NS_MOUSE_EXIT (for old top
        // window)/NS_MOUSE_ENTER (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 send a resize update if necessary
            // and bring it to the front.
            Resize(0, 0, gAndroidBounds.width, gAndroidBounds.height, false);
            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

    return NS_OK;
}

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

    return NS_OK;
}

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

NS_IMETHODIMP
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;
    }

    return NS_OK;
}

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

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

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

NS_IMETHODIMP
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 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(gfxIntSize(aWidth, aHeight));

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

    return NS_OK;
}

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

    return NS_OK;
}

NS_IMETHODIMP
nsWindow::PlaceBehind(nsTopLevelWidgetZPlacement aPlacement,
                      nsIWidget *aWidget,
                      bool aActivate)
{
    return NS_OK;
}

NS_IMETHODIMP
nsWindow::SetSizeMode(int32_t aMode)
{
    switch (aMode) {
        case nsSizeMode_Minimized:
            AndroidBridge::Bridge()->MoveTaskToBack();
            break;
        case nsSizeMode_Fullscreen:
            MakeFullScreen(true);
            break;
    }
    return NS_OK;
}

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

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

NS_IMETHODIMP
nsWindow::Invalidate(const nsIntRect &aRect)
{
    AndroidGeckoEvent *event = AndroidGeckoEvent::MakeDrawEvent(aRect);
    nsAppShell::gAppShell->PostEvent(event);
    return NS_OK;
}

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;
}

NS_IMETHODIMP
nsWindow::SetFocus(bool aRaise)
{
    if (!aRaise) {
        ALOG("nsWindow::SetFocus: can't set focus without raising, ignoring aRaise = false!");
    }

    if (!AndroidBridge::Bridge())
        return NS_OK;

    nsWindow *top = FindTopLevel();
    top->mFocus = this;
    top->BringToFront();

    return NS_OK;
}

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<nsIDOMWindow> existingTopWindow;
    fm->GetActiveWindow(getter_AddRefs(existingTopWindow));
    if (existingTopWindow && FindTopLevel() == nsWindow::TopWindow())
        return;

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

    nsRefPtr<nsWindow> kungFuDeathGrip(this);

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

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

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

    if (Destroyed()) {
        // somehow the deactivate event handler destroyed this window.
        // try to recover by grabbing the next window in line and activating
        // that instead
        if (gTopLevelWindows.IsEmpty())
            return;
        newTop = gTopLevelWindows[0];
    }

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

    // force a window resize
    nsAppShell::gAppShell->ResendLastResizeEvent(newTop);
    RedrawAll();
}

NS_IMETHODIMP
nsWindow::GetScreenBounds(nsIntRect &aRect)
{
    nsIntPoint p = WidgetToScreenOffset();

    aRect.x = p.x;
    aRect.y = p.y;
    aRect.width = mBounds.width;
    aRect.height = mBounds.height;
    
    return NS_OK;
}

nsIntPoint
nsWindow::WidgetToScreenOffset()
{
    nsIntPoint p(0, 0);
    nsWindow *w = this;

    while (w && !w->IsTopLevel()) {
        p.x += w->mBounds.x;
        p.y += w->mBounds.y;

        w = w->mParent;
    }

    return p;
}

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

nsEventStatus
nsWindow::DispatchEvent(nsGUIEvent *aEvent)
{
    if (mWidgetListener) {
        nsEventStatus status = mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents);

        switch (aEvent->message) {
        case NS_COMPOSITION_START:
            MOZ_ASSERT(!mIMEComposing);
            mIMEComposing = true;
            break;
        case NS_COMPOSITION_END:
            MOZ_ASSERT(mIMEComposing);
            mIMEComposing = false;
            mIMEComposingText.Truncate();
            break;
        case NS_TEXT_TEXT:
            MOZ_ASSERT(mIMEComposing);
            mIMEComposingText = static_cast<nsTextEvent*>(aEvent)->theText;
            break;
        }
        return status;
    }
    return nsEventStatus_eIgnore;
}

NS_IMETHODIMP
nsWindow::MakeFullScreen(bool aFullScreen)
{
    AndroidBridge::Bridge()->SetFullScreen(aFullScreen);
    return NS_OK;
}

NS_IMETHODIMP
nsWindow::SetWindowClass(const nsAString& xulWinType)
{
    return NS_OK;
}

mozilla::layers::LayerManager*
nsWindow::GetLayerManager(PLayerTransactionChild*, LayersBackend, LayerManagerPersistence,
                          bool* aAllowRetaining)
{
    if (aAllowRetaining) {
        *aAllowRetaining = true;
    }
    if (mLayerManager) {
        return mLayerManager;
    }
    // for OMTC allow use of the single layer manager/compositor
    // shared across all windows
    if (ShouldUseOffMainThreadCompositing()) {
        return sLayerManager;
    }
    return nullptr;
}

void
nsWindow::CreateLayerManager(int aCompositorWidth, int aCompositorHeight)
{
    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;
    }

    mUseLayersAcceleration = ComputeShouldAccelerate(mUseLayersAcceleration);

    if (ShouldUseOffMainThreadCompositing()) {
        if (sLayerManager) {
            return;
        }
        CreateCompositor(aCompositorWidth, aCompositorHeight);
        if (mLayerManager) {
            // for OMTC create a single layer manager and compositor that will be
            // used for all windows.
            SetCompositor(mLayerManager, mCompositorParent, mCompositorChild);
            sCompositorPaused = false;
            return;
        }

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

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

void
nsWindow::OnGlobalAndroidEvent(AndroidGeckoEvent *ae)
{
    if (!AndroidBridge::Bridge())
        return;

    nsWindow *win = TopWindow();
    if (!win)
        return;

    switch (ae->Type()) {
        case AndroidGeckoEvent::FORCED_RESIZE:
            win->mBounds.width = 0;
            win->mBounds.height = 0;
            // also resize the children
            for (uint32_t i = 0; i < win->mChildren.Length(); i++) {
                win->mChildren[i]->mBounds.width = 0;
                win->mChildren[i]->mBounds.height = 0;
            }
        case AndroidGeckoEvent::SIZE_CHANGED: {
            const nsTArray<nsIntPoint>& points = ae->Points();
            NS_ASSERTION(points.Length() == 2, "Size changed does not have enough coordinates");

            int nw = points[0].x;
            int nh = points[0].y;

            if (ae->Type() == AndroidGeckoEvent::FORCED_RESIZE || nw != gAndroidBounds.width ||
                nh != gAndroidBounds.height) {
                gAndroidBounds.width = nw;
                gAndroidBounds.height = nh;

                // tell all the windows about the new size
                for (size_t i = 0; i < gTopLevelWindows.Length(); ++i) {
                    if (gTopLevelWindows[i]->mIsVisible)
                        gTopLevelWindows[i]->Resize(gAndroidBounds.width,
                                                    gAndroidBounds.height,
                                                    false);
                }
            }

            int newScreenWidth = points[1].x;
            int newScreenHeight = points[1].y;

            if (newScreenWidth == gAndroidScreenBounds.width &&
                newScreenHeight == gAndroidScreenBounds.height)
                break;

            gAndroidScreenBounds.width = newScreenWidth;
            gAndroidScreenBounds.height = newScreenHeight;

            if (XRE_GetProcessType() != GeckoProcessType_Default)
                break;

            // Tell the content process the new screen size.
            nsTArray<ContentParent*> cplist;
            ContentParent::GetAll(cplist);
            for (uint32_t i = 0; i < cplist.Length(); ++i)
                unused << cplist[i]->SendScreenSizeChanged(gAndroidScreenBounds);

            if (gContentCreationNotifier)
                break;

            // If the content process is not created yet, wait until it's
            // created and then tell it the screen size.
            nsCOMPtr<nsIObserverService> obs = do_GetService("@mozilla.org/observer-service;1");
            if (!obs)
                break;

            nsRefPtr<ContentCreationNotifier> notifier = new ContentCreationNotifier;
            if (NS_SUCCEEDED(obs->AddObserver(notifier, "ipc:content-created", false))) {
                if (NS_SUCCEEDED(obs->AddObserver(notifier, "xpcom-shutdown", false)))
                    gContentCreationNotifier = notifier;
                else
                    obs->RemoveObserver(notifier, "ipc:content-created");
            }
            break;
        }

        case AndroidGeckoEvent::MOTION_EVENT: {
            win->UserActivity();
            if (!gTopLevelWindows.IsEmpty()) {
                nsIntPoint pt(0,0);
                const nsTArray<nsIntPoint>& points = ae->Points();
                if (points.Length() > 0) {
                    pt = points[0];
                }
                pt.x = clamped(pt.x, 0, std::max(gAndroidBounds.width - 1, 0));
                pt.y = clamped(pt.y, 0, std::max(gAndroidBounds.height - 1, 0));
                nsWindow *target = win->FindWindowForPoint(pt);
#if 0
                ALOG("MOTION_EVENT %f,%f -> %p (visible: %d children: %d)", pt.x, pt.y, (void*)target,
                     target ? target->mIsVisible : 0,
                     target ? target->mChildren.Length() : 0);

                DumpWindows();
#endif
                if (target) {
                    bool preventDefaultActions = target->OnMultitouchEvent(ae);
                    if (!preventDefaultActions && ae->Count() < 2)
                        target->OnMouseEvent(ae);
                }
            }
            break;
        }

        case AndroidGeckoEvent::NATIVE_GESTURE_EVENT: {
            nsIntPoint pt(0,0);
            const nsTArray<nsIntPoint>& points = ae->Points();
            if (points.Length() > 0) {
                pt = points[0];
            }
            pt.x = clamped(pt.x, 0, std::max(gAndroidBounds.width - 1, 0));
            pt.y = clamped(pt.y, 0, std::max(gAndroidBounds.height - 1, 0));
            nsWindow *target = win->FindWindowForPoint(pt);

            target->OnNativeGestureEvent(ae);
            break;
        }

        case AndroidGeckoEvent::KEY_EVENT:
            win->UserActivity();
            if (win->mFocus)
                win->mFocus->OnKeyEvent(ae);
            break;

        case AndroidGeckoEvent::DRAW:
            layers::renderTraceEventStart("Global draw start", "414141");
            win->OnDraw(ae);
            layers::renderTraceEventEnd("414141");
            break;

        case AndroidGeckoEvent::IME_EVENT:
            win->UserActivity();
            if (win->mFocus) {
                win->mFocus->OnIMEEvent(ae);
            } else {
                NS_WARNING("Sending unexpected IME event to top window");
                win->OnIMEEvent(ae);
            }
            break;

        case AndroidGeckoEvent::IME_KEY_EVENT:
            // Keys synthesized by Java IME code are saved in the mIMEKeyEvents
            // array until the next IME_REPLACE_TEXT event, at which point
            // these keys are dispatched in sequence.
            if (win->mFocus) {
                win->mFocus->mIMEKeyEvents.AppendElement(*ae);
            }
            break;

        case AndroidGeckoEvent::COMPOSITOR_CREATE:
            win->CreateLayerManager(ae->Width(), ae->Height());
            break;

        case AndroidGeckoEvent::COMPOSITOR_PAUSE:
            // The compositor gets paused when the app is about to go into the
            // background. While the compositor is paused, we need to ensure that
            // no layer tree updates (from draw events) occur, since the compositor
            // cannot make a GL context current in order to process updates.
            if (sCompositorChild) {
                sCompositorChild->SendPause();
            }
            sCompositorPaused = true;
            break;

        case AndroidGeckoEvent::COMPOSITOR_RESUME:
            // When we receive this, the compositor has already been told to
            // resume. (It turns out that waiting till we reach here to tell
            // the compositor to resume takes too long, resulting in a black
            // flash.) 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 (!sCompositorPaused) {
                win->RedrawAll();
            }
            break;
    }
}

void
nsWindow::OnAndroidEvent(AndroidGeckoEvent *ae)
{
    if (!AndroidBridge::Bridge())
        return;

    switch (ae->Type()) {
        case AndroidGeckoEvent::DRAW:
            OnDraw(ae);
            break;

        default:
            ALOG("Window got targetted android event type %d, but didn't handle!", ae->Type());
            break;
    }
}

bool
nsWindow::DrawTo(gfxASurface *targetSurface)
{
    nsIntRect boundsRect(0, 0, mBounds.width, mBounds.height);
    return DrawTo(targetSurface, boundsRect);
}

bool
nsWindow::DrawTo(gfxASurface *targetSurface, const nsIntRect &invalidRect)
{
    mozilla::layers::RenderTraceScope trace("DrawTo", "717171");
    if (!mIsVisible || !mWidgetListener || !GetLayerManager(nullptr))
        return false;

    nsRefPtr<nsWindow> kungFuDeathGrip(this);
    nsIntRect boundsRect(0, 0, mBounds.width, mBounds.height);

    // Figure out if any of our children cover this widget completely
    int32_t coveringChildIndex = -1;
    for (uint32_t i = 0; i < mChildren.Length(); ++i) {
        if (mChildren[i]->mBounds.IsEmpty())
            continue;

        if (mChildren[i]->mBounds.Contains(boundsRect)) {
            coveringChildIndex = int32_t(i);
        }
    }

    // If we have no covering child, then we need to render this.
    if (coveringChildIndex == -1) {
        nsIntRegion region = invalidRect;

        mWidgetListener->WillPaintWindow(this);

        switch (GetLayerManager(nullptr)->GetBackendType()) {
            case mozilla::layers::LAYERS_BASIC: {

                nsRefPtr<gfxContext> ctx = new gfxContext(targetSurface);

                {
                    mozilla::layers::RenderTraceScope trace2("Basic DrawTo", "727272");
                    AutoLayerManagerSetup
                      setupLayerManager(this, ctx, mozilla::layers::BUFFER_NONE);

                    mWidgetListener->PaintWindow(this, region);
                }
                break;
            }

            case mozilla::layers::LAYERS_CLIENT: {
                mWidgetListener->PaintWindow(this, region);
                break;
            }

            case mozilla::layers::LAYERS_OPENGL: {

                static_cast<mozilla::layers::LayerManagerOGL*>(GetLayerManager(nullptr))->
                    SetClippingRegion(nsIntRegion(boundsRect));

                mWidgetListener->PaintWindow(this, region);
                break;
            }

            default:
                NS_ERROR("Invalid layer manager");
        }

        mWidgetListener->DidPaintWindow();

        // We had no covering child, so make sure we draw all the children,
        // starting from index 0.
        coveringChildIndex = 0;
    }

    gfxPoint offset;

    if (targetSurface)
        offset = targetSurface->GetDeviceOffset();

    for (uint32_t i = coveringChildIndex; i < mChildren.Length(); ++i) {
        if (mChildren[i]->mBounds.IsEmpty() ||
            !mChildren[i]->mBounds.Intersects(boundsRect)) {
            continue;
        }

        if (targetSurface)
            targetSurface->SetDeviceOffset(offset + gfxPoint(mChildren[i]->mBounds.x,
                                                             mChildren[i]->mBounds.y));

        bool ok = mChildren[i]->DrawTo(targetSurface, invalidRect);

        if (!ok) {
            ALOG("nsWindow[%p]::DrawTo child %d[%p] returned FALSE!", (void*) this, i, (void*)mChildren[i]);
        }
    }

    if (targetSurface)
        targetSurface->SetDeviceOffset(offset);

    return true;
}

void
nsWindow::OnDraw(AndroidGeckoEvent *ae)
{
    if (!IsTopLevel()) {
        ALOG("##### redraw for window %p, which is not a toplevel window -- sending to toplevel!", (void*) this);
        DumpWindows();
        return;
    }

    if (!mIsVisible) {
        ALOG("##### redraw for window %p, which is not visible -- ignoring!", (void*) this);
        DumpWindows();
        return;
    }

    nsRefPtr<nsWindow> kungFuDeathGrip(this);

    JNIEnv *env = AndroidBridge::GetJNIEnv();
    if (!env)
        return;
    AutoLocalJNIFrame jniFrame;

    // We're paused, or we haven't been given a window-size yet, so do nothing
    if (sCompositorPaused || gAndroidBounds.width <= 0 || gAndroidBounds.height <= 0) {
        return;
    }

    int bytesPerPixel = 2;
    gfxASurface::gfxImageFormat format = gfxASurface::ImageFormatRGB16_565;
    if (AndroidBridge::Bridge()->GetScreenDepth() == 24) {
        bytesPerPixel = 4;
        format = gfxASurface::ImageFormatRGB24;
    }

    layers::renderTraceEventStart("Get surface", "424545");
    static unsigned char bits2[32 * 32 * 4];
    nsRefPtr<gfxImageSurface> targetSurface =
        new gfxImageSurface(bits2, gfxIntSize(32, 32), 32 * bytesPerPixel, format);
    layers::renderTraceEventEnd("Get surface", "424545");

    layers::renderTraceEventStart("Widget draw to", "434646");
    if (targetSurface->CairoStatus()) {
        ALOG("### Failed to create a valid surface from the bitmap");
    } else {
        DrawTo(targetSurface, ae->Rect());
    }
    layers::renderTraceEventEnd("Widget draw to", "434646");
}

void
nsWindow::OnSizeChanged(const gfxIntSize& 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);
    }
}

void
nsWindow::InitEvent(nsGUIEvent& event, nsIntPoint* aPoint)
{
    if (aPoint) {
        event.refPoint.x = aPoint->x;
        event.refPoint.y = aPoint->y;
    } else {
        event.refPoint.x = 0;
        event.refPoint.y = 0;
    }

    event.time = PR_Now() / 1000;
}

gfxIntSize
nsWindow::GetAndroidScreenBounds()
{
    if (XRE_GetProcessType() == GeckoProcessType_Content) {
        return ContentChild::GetSingleton()->GetScreenSize();
    }
    return gAndroidScreenBounds;
}

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

        case NS_NATIVE_WIDGET:
            return (void *) this;
    }

    return nullptr;
}

void
nsWindow::OnMouseEvent(AndroidGeckoEvent *ae)
{
    nsRefPtr<nsWindow> kungFuDeathGrip(this);

    nsMouseEvent event = ae->MakeMouseEvent(this);
    if (event.message == NS_EVENT_NULL) {
        // invalid event type, abort
        return;
    }

    // XXX add the double-click handling logic here
    DispatchEvent(&event);
}

bool nsWindow::OnMultitouchEvent(AndroidGeckoEvent *ae)
{
    nsRefPtr<nsWindow> kungFuDeathGrip(this);

    // End any composition in progress in case the touch event listener
    // modifies the input field value (see bug 856155)
    RemoveIMEComposition();

    // This is set to true once we have called SetPreventPanning() exactly
    // once for a given sequence of touch events. It is reset on the start
    // of the next sequence.
    static bool sDefaultPreventedNotified = false;
    static bool sLastWasDownEvent = false;

    bool preventDefaultActions = false;
    bool isDownEvent = false;

    nsTouchEvent event = ae->MakeTouchEvent(this);
    if (event.message != NS_EVENT_NULL) {
        nsEventStatus status;
        DispatchEvent(&event, status);
        // We check mMultipleActionsPrevented because that's what <input type=range>
        // sets when someone starts dragging the thumb. It doesn't set the status
        // because it doesn't want to prevent the code that gives the input focus
        // from running.
        preventDefaultActions = (status == nsEventStatus_eConsumeNoDefault ||
                                event.mFlags.mMultipleActionsPrevented);
        isDownEvent = (event.message == NS_TOUCH_START);
    }

    // if the last event we got was a down event, then by now we know for sure whether
    // this block has been default-prevented or not. if we haven't already sent the
    // notification for this block, do so now.
    if (sLastWasDownEvent && !sDefaultPreventedNotified) {
        // if this event is a down event, that means it's the start of a new block, and the
        // previous block should not be default-prevented
        bool defaultPrevented = isDownEvent ? false : preventDefaultActions;
        AndroidBridge::Bridge()->NotifyDefaultPrevented(defaultPrevented);
        sDefaultPreventedNotified = true;
    }

    // now, if this event is a down event, then we might already know that it has been
    // default-prevented. if so, we send the notification right away; otherwise we wait
    // for the next event.
    if (isDownEvent) {
        if (preventDefaultActions) {
            AndroidBridge::Bridge()->NotifyDefaultPrevented(true);
            sDefaultPreventedNotified = true;
        } else {
            sDefaultPreventedNotified = false;
        }
    }
    sLastWasDownEvent = isDownEvent;

    return preventDefaultActions;
}

void
nsWindow::OnNativeGestureEvent(AndroidGeckoEvent *ae)
{
  nsIntPoint pt(ae->Points()[0].x,
                ae->Points()[0].y);
  double delta = ae->X();
  int msg = 0;

  switch (ae->Action()) {
      case AndroidMotionEvent::ACTION_MAGNIFY_START:
          msg = NS_SIMPLE_GESTURE_MAGNIFY_START;
          mStartDist = delta;
          mLastDist = delta;
          break;
      case AndroidMotionEvent::ACTION_MAGNIFY:
          msg = NS_SIMPLE_GESTURE_MAGNIFY_UPDATE;
          delta -= mLastDist;
          mLastDist += delta;
          break;
      case AndroidMotionEvent::ACTION_MAGNIFY_END:
          msg = NS_SIMPLE_GESTURE_MAGNIFY;
          delta -= mStartDist;
          break;
      default:
          return;
  }

  nsRefPtr<nsWindow> kungFuDeathGrip(this);
  DispatchGestureEvent(msg, 0, delta, pt, ae->Time());
}

void
nsWindow::DispatchGestureEvent(uint32_t msg, uint32_t direction, double delta,
                               const nsIntPoint &refPoint, uint64_t time)
{
    nsSimpleGestureEvent event(true, msg, this, direction, delta);

    event.modifiers = 0;
    event.time = time;
    event.refPoint = LayoutDeviceIntPoint::FromUntyped(refPoint);

    DispatchEvent(&event);
}


void
nsWindow::DispatchMotionEvent(nsInputEvent &event, AndroidGeckoEvent *ae,
                              const nsIntPoint &refPoint)
{
    nsIntPoint offset = WidgetToScreenOffset();

    event.modifiers = 0;
    event.time = ae->Time();

    // XXX possibly bound the range of event.refPoint here.
    //     some code may get confused.
    event.refPoint = LayoutDeviceIntPoint::FromUntyped(refPoint - offset);

    DispatchEvent(&event);
}

static unsigned int ConvertAndroidKeyCodeToDOMKeyCode(int androidKeyCode)
{
    // Special-case alphanumeric keycodes because they are most common.
    if (androidKeyCode >= AKEYCODE_A &&
        androidKeyCode <= AKEYCODE_Z) {
        return androidKeyCode - AKEYCODE_A + NS_VK_A;
    }

    if (androidKeyCode >= AKEYCODE_0 &&
        androidKeyCode <= AKEYCODE_9) {
        return androidKeyCode - AKEYCODE_0 + NS_VK_0;
    }

    switch (androidKeyCode) {
        // KEYCODE_UNKNOWN (0) ... KEYCODE_HOME (3)
        case AKEYCODE_BACK:               return NS_VK_ESCAPE;
        // KEYCODE_CALL (5) ... KEYCODE_POUND (18)
        case AKEYCODE_DPAD_UP:            return NS_VK_UP;
        case AKEYCODE_DPAD_DOWN:          return NS_VK_DOWN;
        case AKEYCODE_DPAD_LEFT:          return NS_VK_LEFT;
        case AKEYCODE_DPAD_RIGHT:         return NS_VK_RIGHT;
        case AKEYCODE_DPAD_CENTER:        return NS_VK_RETURN;
        case AKEYCODE_VOLUME_UP:          return NS_VK_VOLUME_UP;
        case AKEYCODE_VOLUME_DOWN:        return NS_VK_VOLUME_DOWN;
        // KEYCODE_VOLUME_POWER (26) ... KEYCODE_Z (54)
        case AKEYCODE_COMMA:              return NS_VK_COMMA;
        case AKEYCODE_PERIOD:             return NS_VK_PERIOD;
        case AKEYCODE_ALT_LEFT:           return NS_VK_ALT;
        case AKEYCODE_ALT_RIGHT:          return NS_VK_ALT;
        case AKEYCODE_SHIFT_LEFT:         return NS_VK_SHIFT;
        case AKEYCODE_SHIFT_RIGHT:        return NS_VK_SHIFT;
        case AKEYCODE_TAB:                return NS_VK_TAB;
        case AKEYCODE_SPACE:              return NS_VK_SPACE;
        // KEYCODE_SYM (63) ... KEYCODE_ENVELOPE (65)
        case AKEYCODE_ENTER:              return NS_VK_RETURN;
        case AKEYCODE_DEL:                return NS_VK_BACK; // Backspace
        case AKEYCODE_GRAVE:              return NS_VK_BACK_QUOTE;
        // KEYCODE_MINUS (69)
        case AKEYCODE_EQUALS:             return NS_VK_EQUALS;
        case AKEYCODE_LEFT_BRACKET:       return NS_VK_OPEN_BRACKET;
        case AKEYCODE_RIGHT_BRACKET:      return NS_VK_CLOSE_BRACKET;
        case AKEYCODE_BACKSLASH:          return NS_VK_BACK_SLASH;
        case AKEYCODE_SEMICOLON:          return NS_VK_SEMICOLON;
        // KEYCODE_APOSTROPHE (75)
        case AKEYCODE_SLASH:              return NS_VK_SLASH;
        // KEYCODE_AT (77) ... KEYCODE_MEDIA_FAST_FORWARD (90)
        case AKEYCODE_MUTE:               return NS_VK_VOLUME_MUTE;
        case AKEYCODE_PAGE_UP:            return NS_VK_PAGE_UP;
        case AKEYCODE_PAGE_DOWN:          return NS_VK_PAGE_DOWN;
        // KEYCODE_PICTSYMBOLS (94) ... KEYCODE_BUTTON_MODE (110)
        case AKEYCODE_ESCAPE:             return NS_VK_ESCAPE;
        case AKEYCODE_FORWARD_DEL:        return NS_VK_DELETE;
        case AKEYCODE_CTRL_LEFT:          return NS_VK_CONTROL;
        case AKEYCODE_CTRL_RIGHT:         return NS_VK_CONTROL;
        case AKEYCODE_CAPS_LOCK:          return NS_VK_CAPS_LOCK;
        case AKEYCODE_SCROLL_LOCK:        return NS_VK_SCROLL_LOCK;
        // KEYCODE_META_LEFT (117) ... KEYCODE_FUNCTION (119)
        case AKEYCODE_SYSRQ:              return NS_VK_PRINTSCREEN;
        case AKEYCODE_BREAK:              return NS_VK_PAUSE;
        case AKEYCODE_MOVE_HOME:          return NS_VK_HOME;
        case AKEYCODE_MOVE_END:           return NS_VK_END;
        case AKEYCODE_INSERT:             return NS_VK_INSERT;
        // KEYCODE_FORWARD (125) ... KEYCODE_MEDIA_RECORD (130)
        case AKEYCODE_F1:                 return NS_VK_F1;
        case AKEYCODE_F2:                 return NS_VK_F2;
        case AKEYCODE_F3:                 return NS_VK_F3;
        case AKEYCODE_F4:                 return NS_VK_F4;
        case AKEYCODE_F5:                 return NS_VK_F5;
        case AKEYCODE_F6:                 return NS_VK_F6;
        case AKEYCODE_F7:                 return NS_VK_F7;
        case AKEYCODE_F8:                 return NS_VK_F8;
        case AKEYCODE_F9:                 return NS_VK_F9;
        case AKEYCODE_F10:                return NS_VK_F10;
        case AKEYCODE_F11:                return NS_VK_F11;
        case AKEYCODE_F12:                return NS_VK_F12;
        case AKEYCODE_NUM_LOCK:           return NS_VK_NUM_LOCK;
        case AKEYCODE_NUMPAD_0:           return NS_VK_NUMPAD0;
        case AKEYCODE_NUMPAD_1:           return NS_VK_NUMPAD1;
        case AKEYCODE_NUMPAD_2:           return NS_VK_NUMPAD2;
        case AKEYCODE_NUMPAD_3:           return NS_VK_NUMPAD3;
        case AKEYCODE_NUMPAD_4:           return NS_VK_NUMPAD4;
        case AKEYCODE_NUMPAD_5:           return NS_VK_NUMPAD5;
        case AKEYCODE_NUMPAD_6:           return NS_VK_NUMPAD6;
        case AKEYCODE_NUMPAD_7:           return NS_VK_NUMPAD7;
        case AKEYCODE_NUMPAD_8:           return NS_VK_NUMPAD8;
        case AKEYCODE_NUMPAD_9:           return NS_VK_NUMPAD9;
        case AKEYCODE_NUMPAD_DIVIDE:      return NS_VK_DIVIDE;
        case AKEYCODE_NUMPAD_MULTIPLY:    return NS_VK_MULTIPLY;
        case AKEYCODE_NUMPAD_SUBTRACT:    return NS_VK_SUBTRACT;
        case AKEYCODE_NUMPAD_ADD:         return NS_VK_ADD;
        case AKEYCODE_NUMPAD_DOT:         return NS_VK_DECIMAL;
        case AKEYCODE_NUMPAD_COMMA:       return NS_VK_SEPARATOR;
        case AKEYCODE_NUMPAD_ENTER:       return NS_VK_RETURN;
        case AKEYCODE_NUMPAD_EQUALS:      return NS_VK_EQUALS;
        // KEYCODE_NUMPAD_LEFT_PAREN (162) ... KEYCODE_CALCULATOR (210)

        // Needs to confirm the behavior.  If the key switches the open state
        // of Japanese IME (or switches input character between Hiragana and
        // Roman numeric characters), then, it might be better to use
        // NS_VK_KANJI which is used for Alt+Zenkaku/Hankaku key on Windows.
        case AKEYCODE_ZENKAKU_HANKAKU:    return 0;
        case AKEYCODE_EISU:               return NS_VK_EISU;
        case AKEYCODE_MUHENKAN:           return NS_VK_NONCONVERT;
        case AKEYCODE_HENKAN:             return NS_VK_CONVERT;
        case AKEYCODE_KATAKANA_HIRAGANA:  return 0;
        case AKEYCODE_YEN:                return NS_VK_BACK_SLASH; // Same as other platforms.
        case AKEYCODE_RO:                 return NS_VK_BACK_SLASH; // Same as other platforms.
        case AKEYCODE_KANA:               return NS_VK_KANA;
        case AKEYCODE_ASSIST:             return NS_VK_HELP;

        default:
            ALOG("ConvertAndroidKeyCodeToDOMKeyCode: "
                 "No DOM keycode for Android keycode %d", androidKeyCode);
        return 0;
    }
}

static KeyNameIndex ConvertAndroidKeyCodeToKeyNameIndex(int aAndroidKeyCode)
{
    // Special-case alphanumeric keycodes because they are most common.
    if (aAndroidKeyCode >= AKEYCODE_A && aAndroidKeyCode <= AKEYCODE_Z) {
        return KEY_NAME_INDEX_PrintableKey;
    }

    if (aAndroidKeyCode >= AKEYCODE_0 && aAndroidKeyCode <= AKEYCODE_9) {
        return KEY_NAME_INDEX_PrintableKey;
    }

    switch (aAndroidKeyCode) {

#define NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, aKeyNameIndex) \
        case aNativeKey: return aKeyNameIndex;

#include "NativeKeyToDOMKeyName.h"

#undef NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX

        // KEYCODE_0 (7) ... KEYCODE_9 (16)
        case AKEYCODE_STAR:               // '*' key
        case AKEYCODE_POUND:              // '#' key

        // KEYCODE_A (29) ... KEYCODE_Z (54)

        case AKEYCODE_COMMA:              // ',' key
        case AKEYCODE_PERIOD:             // '.' key
        case AKEYCODE_GRAVE:              // '`' key
        case AKEYCODE_MINUS:              // '-' key
        case AKEYCODE_EQUALS:             // '=' key
        case AKEYCODE_LEFT_BRACKET:       // '[' key
        case AKEYCODE_RIGHT_BRACKET:      // ']' key
        case AKEYCODE_BACKSLASH:          // '\' key
        case AKEYCODE_SEMICOLON:          // ';' key
        case AKEYCODE_APOSTROPHE:         // ''' key
        case AKEYCODE_SLASH:              // '/' key
        case AKEYCODE_AT:                 // '@' key
        case AKEYCODE_PLUS:               // '+' key

        case AKEYCODE_UNKNOWN:
        case AKEYCODE_NUMPAD_0:
        case AKEYCODE_NUMPAD_1:
        case AKEYCODE_NUMPAD_2:
        case AKEYCODE_NUMPAD_3:
        case AKEYCODE_NUMPAD_4:
        case AKEYCODE_NUMPAD_5:
        case AKEYCODE_NUMPAD_6:
        case AKEYCODE_NUMPAD_7:
        case AKEYCODE_NUMPAD_8:
        case AKEYCODE_NUMPAD_9:

        case AKEYCODE_NUMPAD_LEFT_PAREN:
        case AKEYCODE_NUMPAD_RIGHT_PAREN:

        case AKEYCODE_YEN:                // yen sign key
        case AKEYCODE_RO:                 // Japanese Ro key
            return KEY_NAME_INDEX_PrintableKey;

        case AKEYCODE_SOFT_LEFT:
        case AKEYCODE_SOFT_RIGHT:
        case AKEYCODE_CALL:
        case AKEYCODE_ENDCALL:
        case AKEYCODE_SYM:                // Symbol modifier
        case AKEYCODE_NUM:                // XXX Not sure
        case AKEYCODE_HEADSETHOOK:
        case AKEYCODE_FOCUS:
        case AKEYCODE_NOTIFICATION:       // XXX Not sure
        case AKEYCODE_PICTSYMBOLS:

        case AKEYCODE_BUTTON_A:
        case AKEYCODE_BUTTON_B:
        case AKEYCODE_BUTTON_C:
        case AKEYCODE_BUTTON_X:
        case AKEYCODE_BUTTON_Y:
        case AKEYCODE_BUTTON_Z:
        case AKEYCODE_BUTTON_L1:
        case AKEYCODE_BUTTON_R1:
        case AKEYCODE_BUTTON_L2:
        case AKEYCODE_BUTTON_R2:
        case AKEYCODE_BUTTON_THUMBL:
        case AKEYCODE_BUTTON_THUMBR:
        case AKEYCODE_BUTTON_START:
        case AKEYCODE_BUTTON_SELECT:
        case AKEYCODE_BUTTON_MODE:

        case AKEYCODE_MUTE: // mutes the microphone
        case AKEYCODE_MEDIA_CLOSE:

        case AKEYCODE_ZOOM_IN:
        case AKEYCODE_ZOOM_OUT:
        case AKEYCODE_DVR:
        case AKEYCODE_TV_POWER:
        case AKEYCODE_TV_INPUT:
        case AKEYCODE_STB_POWER:
        case AKEYCODE_STB_INPUT:
        case AKEYCODE_AVR_POWER:
        case AKEYCODE_AVR_INPUT:

        case AKEYCODE_BUTTON_1:
        case AKEYCODE_BUTTON_2:
        case AKEYCODE_BUTTON_3:
        case AKEYCODE_BUTTON_4:
        case AKEYCODE_BUTTON_5:
        case AKEYCODE_BUTTON_6:
        case AKEYCODE_BUTTON_7:
        case AKEYCODE_BUTTON_8:
        case AKEYCODE_BUTTON_9:
        case AKEYCODE_BUTTON_10:
        case AKEYCODE_BUTTON_11:
        case AKEYCODE_BUTTON_12:
        case AKEYCODE_BUTTON_13:
        case AKEYCODE_BUTTON_14:
        case AKEYCODE_BUTTON_15:
        case AKEYCODE_BUTTON_16:

        case AKEYCODE_LANGUAGE_SWITCH:
        case AKEYCODE_MANNER_MODE:
        case AKEYCODE_3D_MODE:
        case AKEYCODE_CONTACTS:
        case AKEYCODE_CALENDAR:
        case AKEYCODE_MUSIC:
        case AKEYCODE_CALCULATOR:

        case AKEYCODE_ZENKAKU_HANKAKU:
        case AKEYCODE_KATAKANA_HIRAGANA:
            return KEY_NAME_INDEX_Unidentified;

        default:
            ALOG("ConvertAndroidKeyCodeToKeyNameIndex: "
                 "No DOM key name index for Android keycode %d", aAndroidKeyCode);
            return KEY_NAME_INDEX_Unidentified;
    }
}

static void InitPluginEvent(ANPEvent* pluginEvent, ANPKeyActions keyAction,
                            AndroidGeckoEvent& key)
{
    int androidKeyCode = key.KeyCode();
    uint32_t domKeyCode = ConvertAndroidKeyCodeToDOMKeyCode(androidKeyCode);

    int modifiers = 0;
    if (key.IsAltPressed())
      modifiers |= kAlt_ANPKeyModifier;
    if (key.IsShiftPressed())
      modifiers |= kShift_ANPKeyModifier;

    pluginEvent->inSize = sizeof(ANPEvent);
    pluginEvent->eventType = kKey_ANPEventType;
    pluginEvent->data.key.action = keyAction;
    pluginEvent->data.key.nativeCode = androidKeyCode;
    pluginEvent->data.key.virtualCode = domKeyCode;
    pluginEvent->data.key.unichar = key.UnicodeChar();
    pluginEvent->data.key.modifiers = modifiers;
    pluginEvent->data.key.repeatCount = key.RepeatCount();
}

void
nsWindow::InitKeyEvent(nsKeyEvent& event, AndroidGeckoEvent& key,
                       ANPEvent* pluginEvent)
{
    int androidKeyCode = key.KeyCode();
    event.mKeyNameIndex = ConvertAndroidKeyCodeToKeyNameIndex(androidKeyCode);
    uint32_t domKeyCode = ConvertAndroidKeyCodeToDOMKeyCode(androidKeyCode);

    if (event.message == NS_KEY_PRESS) {
        // Android gives us \n, so filter out some control characters.
        int charCode = key.UnicodeChar();
        if (!charCode) {
            charCode = key.BaseUnicodeChar();
        }
        event.isChar = (charCode >= ' ');
        event.charCode = event.isChar ? charCode : 0;
        event.keyCode = (event.charCode > 0) ? 0 : domKeyCode;
        event.pluginEvent = NULL;
    } else {
#ifdef DEBUG
        if (event.message != NS_KEY_DOWN && event.message != NS_KEY_UP) {
            ALOG("InitKeyEvent: unexpected event.message %d", event.message);
        }
#endif // DEBUG

        // Flash will want a pluginEvent for keydown and keyup events.
        ANPKeyActions action = event.message == NS_KEY_DOWN
                             ? kDown_ANPKeyAction
                             : kUp_ANPKeyAction;
        InitPluginEvent(pluginEvent, action, key);

        event.isChar = false;
        event.charCode = 0;
        event.keyCode = domKeyCode;
        event.pluginEvent = pluginEvent;
    }

    if (event.message != NS_KEY_PRESS ||
        !key.UnicodeChar() || !key.BaseUnicodeChar() ||
        key.UnicodeChar() == key.BaseUnicodeChar()) {
        // For keypress, if the unicode char already has modifiers applied, we
        // don't specify extra modifiers. If UnicodeChar() != BaseUnicodeChar()
        // it means UnicodeChar() already has modifiers applied.
        event.InitBasicModifiers(gMenu || key.IsCtrlPressed(),
                                 key.IsAltPressed(),
                                 key.IsShiftPressed(),
                                 key.IsMetaPressed());
    }
    event.location = key.DomKeyLocation();
    event.time = key.Time();

    if (gMenu)
        gMenuConsumed = true;
}

void
nsWindow::HandleSpecialKey(AndroidGeckoEvent *ae)
{
    nsRefPtr<nsWindow> kungFuDeathGrip(this);
    nsCOMPtr<nsIAtom> command;
    bool isDown = ae->Action() == AKEY_EVENT_ACTION_DOWN;
    bool isLongPress = !!(ae->Flags() & AKEY_EVENT_FLAG_LONG_PRESS);
    bool doCommand = false;
    uint32_t keyCode = ae->KeyCode();

    if (isDown) {
        switch (keyCode) {
            case AKEYCODE_BACK:
                if (isLongPress) {
                    command = nsGkAtoms::Clear;
                    doCommand = true;
                }
                break;
            case AKEYCODE_MENU:
                gMenu = true;
                gMenuConsumed = isLongPress;
                break;
        }
    } else {
        switch (keyCode) {
            case AKEYCODE_BACK: {
                // XXX Where is the keydown event for this??
                nsKeyEvent pressEvent(true, NS_KEY_PRESS, this);
                ANPEvent pluginEvent;
                InitKeyEvent(pressEvent, *ae, &pluginEvent);
                DispatchEvent(&pressEvent);
                return;
            }
            case AKEYCODE_MENU:
                gMenu = false;
                if (!gMenuConsumed) {
                    command = nsGkAtoms::Menu;
                    doCommand = true;
                }
                break;
            case AKEYCODE_SEARCH:
                command = nsGkAtoms::Search;
                doCommand = true;
                break;
            default:
                ALOG("Unknown special key code!");
                return;
        }
    }
    if (doCommand) {
        nsCommandEvent event(true, nsGkAtoms::onAppCommand, command, this);
        InitEvent(event);
        DispatchEvent(&event);
    }
}

void
nsWindow::OnKeyEvent(AndroidGeckoEvent *ae)
{
    nsRefPtr<nsWindow> kungFuDeathGrip(this);
    RemoveIMEComposition();
    uint32_t msg;
    switch (ae->Action()) {
    case AKEY_EVENT_ACTION_DOWN:
        msg = NS_KEY_DOWN;
        break;
    case AKEY_EVENT_ACTION_UP:
        msg = NS_KEY_UP;
        break;
    case AKEY_EVENT_ACTION_MULTIPLE:
        {
            nsTextEvent event(true, NS_TEXT_TEXT, this);
            event.theText.Assign(ae->Characters());
            DispatchEvent(&event);
        }
        return;
    default:
        ALOG("Unknown key action event!");
        return;
    }

    bool firePress = ae->Action() == AKEY_EVENT_ACTION_DOWN;
    switch (ae->KeyCode()) {
    case AKEYCODE_SHIFT_LEFT:
    case AKEYCODE_SHIFT_RIGHT:
    case AKEYCODE_ALT_LEFT:
    case AKEYCODE_ALT_RIGHT:
    case AKEYCODE_CTRL_LEFT:
    case AKEYCODE_CTRL_RIGHT:
        firePress = false;
        break;
    case AKEYCODE_BACK:
    case AKEYCODE_MENU:
    case AKEYCODE_SEARCH:
        HandleSpecialKey(ae);
        return;
    }

    nsEventStatus status;
    nsKeyEvent event(true, msg, this);
    ANPEvent pluginEvent;
    InitKeyEvent(event, *ae, &pluginEvent);
    DispatchEvent(&event, status);

    if (Destroyed())
        return;
    if (!firePress || status == nsEventStatus_eConsumeNoDefault) {
        return;
    }

    nsKeyEvent pressEvent(true, NS_KEY_PRESS, this);
    InitKeyEvent(pressEvent, *ae, &pluginEvent);
#ifdef DEBUG_ANDROID_WIDGET
    __android_log_print(ANDROID_LOG_INFO, "Gecko", "Dispatching key pressEvent with keyCode %d charCode %d shift %d alt %d sym/ctrl %d metamask %d", pressEvent.keyCode, pressEvent.charCode, pressEvent.IsShift(), pressEvent.IsAlt(), pressEvent.IsControl(), ae->MetaState());
#endif
    DispatchEvent(&pressEvent);
}

#ifdef DEBUG_ANDROID_IME
#define ALOGIME(args...) ALOG(args)
#else
#define ALOGIME(args...) ((void)0)
#endif

static nscolor
ConvertAndroidColor(uint32_t argb)
{
    return NS_RGBA((argb & 0x00ff0000) >> 16,
                   (argb & 0x0000ff00) >> 8,
                   (argb & 0x000000ff),
                   (argb & 0xff000000) >> 24);
}

class AutoIMEMask {
private:
    bool mOldMask, *mMask;
public:
    AutoIMEMask(bool &mask) : mOldMask(mask), mMask(&mask) {
        mask = true;
    }
    ~AutoIMEMask() {
        *mMask = mOldMask;
    }
};

/*
    Remove the composition but leave the text content as-is
*/
void
nsWindow::RemoveIMEComposition()
{
    // Remove composition on Gecko side
    if (!mIMEComposing)
        return;

    nsRefPtr<nsWindow> kungFuDeathGrip(this);
    AutoIMEMask selMask(mIMEMaskSelectionUpdate);
    AutoIMEMask textMask(mIMEMaskTextUpdate);

    nsTextEvent textEvent(true, NS_TEXT_TEXT, this);
    InitEvent(textEvent, nullptr);
    textEvent.theText = mIMEComposingText;
    DispatchEvent(&textEvent);

    nsCompositionEvent event(true, NS_COMPOSITION_END, this);
    InitEvent(event, nullptr);
    DispatchEvent(&event);
}

void
nsWindow::OnIMEEvent(AndroidGeckoEvent *ae)
{
    MOZ_ASSERT(!mIMEMaskTextUpdate);
    MOZ_ASSERT(!mIMEMaskSelectionUpdate);
    /*
        Rules for managing IME between Gecko and Java:

        * Gecko controls the text content, and Java shadows the Gecko text
           through text updates
        * Java controls the selection, and Gecko shadows the Java selection
           through set selection events
        * Java controls the composition, and Gecko shadows the Java
           composition through update composition events
    */
    nsRefPtr<nsWindow> kungFuDeathGrip(this);

    if (ae->Action() == AndroidGeckoEvent::IME_ACKNOWLEDGE_FOCUS) {
        MOZ_ASSERT(mIMEMaskEventsCount > 0);
        mIMEMaskEventsCount--;
        if (!mIMEMaskEventsCount) {
            // The focusing handshake sequence is complete, and Java is waiting
            // on Gecko. Now we can notify Java of the newly focused content
            mIMETextChanges.Clear();
            mIMESelectionChanged = false;
            // NotifyIMEOfTextChange also notifies selection
            // Use 'INT32_MAX / 2' here because subsequent text changes might
            // combine with this text change, and overflow might occur if
            // we just use INT32_MAX
            NotifyIMEOfTextChange(0, INT32_MAX / 2, INT32_MAX / 2);
            FlushIMEChanges();
        }
        AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_REPLY_EVENT);
        return;
    } else if (ae->Action() == AndroidGeckoEvent::IME_UPDATE_CONTEXT) {
        AndroidBridge::NotifyIMEContext(mInputContext.mIMEState.mEnabled,
                                        mInputContext.mHTMLInputType,
                                        mInputContext.mHTMLInputInputmode,
                                        mInputContext.mActionHint);
        mIMEUpdatingContext = false;
        return;
    }
    if (mIMEMaskEventsCount > 0) {
        // Still reply to events, but don't do anything else
        if (ae->Action() == AndroidGeckoEvent::IME_SYNCHRONIZE ||
            ae->Action() == AndroidGeckoEvent::IME_REPLACE_TEXT) {
            AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_REPLY_EVENT);
        }
        return;
    }
    switch (ae->Action()) {
    case AndroidGeckoEvent::IME_FLUSH_CHANGES:
        {
            FlushIMEChanges();
        }
        break;
    case AndroidGeckoEvent::IME_SYNCHRONIZE:
        {
            FlushIMEChanges();
            AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_REPLY_EVENT);
        }
        break;
    case AndroidGeckoEvent::IME_REPLACE_TEXT:
        {
            /*
                Replace text in Gecko thread from ae->Start() to ae->End()
                  with the string ae->Characters()

                Selection updates are masked so the result of our temporary
                  selection event is not passed on to Java

                Text updates are passed on, so the Java text can shadow the
                  Gecko text
            */
            AutoIMEMask selMask(mIMEMaskSelectionUpdate);
            RemoveIMEComposition();
            {
                nsSelectionEvent event(true, NS_SELECTION_SET, this);
                InitEvent(event, nullptr);
                event.mOffset = uint32_t(ae->Start());
                event.mLength = uint32_t(ae->End() - ae->Start());
                event.mExpandToClusterBoundary = false;
                DispatchEvent(&event);
            }

            if (!mIMEKeyEvents.IsEmpty()) {
                for (uint32_t i = 0; i < mIMEKeyEvents.Length(); i++) {
                    OnKeyEvent(&mIMEKeyEvents[i]);
                }
                mIMEKeyEvents.Clear();
                FlushIMEChanges();
                AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_REPLY_EVENT);
                break;
            }

            {
                nsCompositionEvent event(true, NS_COMPOSITION_START, this);
                InitEvent(event, nullptr);
                DispatchEvent(&event);
            }
            {
                nsTextEvent event(true, NS_TEXT_TEXT, this);
                InitEvent(event, nullptr);
                event.theText = ae->Characters();
                DispatchEvent(&event);
            }
            {
                nsCompositionEvent event(true, NS_COMPOSITION_END, this);
                InitEvent(event, nullptr);
                event.data = ae->Characters();
                DispatchEvent(&event);
            }
            FlushIMEChanges();
            AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_REPLY_EVENT);
        }
        break;
    case AndroidGeckoEvent::IME_SET_SELECTION:
        {
            /*
                Set Gecko selection to ae->Start() to ae->End()

                Selection updates are masked to prevent Java from being
                  notified of the new selection
            */
            AutoIMEMask selMask(mIMEMaskSelectionUpdate);
            RemoveIMEComposition();
            nsSelectionEvent selEvent(true, NS_SELECTION_SET, this);
            InitEvent(selEvent, nullptr);

            int32_t start = ae->Start(), end = ae->End();

            if (start < 0 || end < 0) {
                nsQueryContentEvent event(true, NS_QUERY_SELECTED_TEXT, this);
                InitEvent(event, nullptr);
                DispatchEvent(&event);
                MOZ_ASSERT(event.mSucceeded && !event.mWasAsync);

                if (start < 0)
                    start = int32_t(event.GetSelectionStart());
                if (end < 0)
                    end = int32_t(event.GetSelectionEnd());
            }

            selEvent.mOffset = std::min(start, end);
            selEvent.mLength = std::max(start, end) - selEvent.mOffset;
            selEvent.mReversed = start > end;
            selEvent.mExpandToClusterBoundary = false;

            DispatchEvent(&selEvent);
        }
        break;
    case AndroidGeckoEvent::IME_ADD_COMPOSITION_RANGE:
        {
            nsTextRange range;
            range.mStartOffset = ae->Start();
            range.mEndOffset = ae->End();
            range.mRangeType = ae->RangeType();
            range.mRangeStyle.mDefinedStyles = ae->RangeStyles();
            range.mRangeStyle.mLineStyle = ae->RangeLineStyle();
            range.mRangeStyle.mIsBoldLine = ae->RangeBoldLine();
            range.mRangeStyle.mForegroundColor =
                    ConvertAndroidColor(uint32_t(ae->RangeForeColor()));
            range.mRangeStyle.mBackgroundColor =
                    ConvertAndroidColor(uint32_t(ae->RangeBackColor()));
            range.mRangeStyle.mUnderlineColor =
                    ConvertAndroidColor(uint32_t(ae->RangeLineColor()));
            mIMERanges.AppendElement(range);
        }
        break;
    case AndroidGeckoEvent::IME_UPDATE_COMPOSITION:
        {
            /*
                Update the composition from ae->Start() to ae->End() using
                  information from added ranges. This is only used for
                  visual indication and does not affect the text content.
                  Only the offsets are specified and not the text content
                  to eliminate the possibility of this event altering the
                  text content unintentionally.

                Selection and text updates are masked so the result of
                  temporary events are not passed on to Java
            */
            AutoIMEMask selMask(mIMEMaskSelectionUpdate);
            AutoIMEMask textMask(mIMEMaskTextUpdate);
            RemoveIMEComposition();

            nsTextEvent event(true, NS_TEXT_TEXT, this);
            InitEvent(event, nullptr);

            event.rangeArray = mIMERanges.Elements();
            event.rangeCount = mIMERanges.Length();

            {
                nsSelectionEvent event(true, NS_SELECTION_SET, this);
                InitEvent(event, nullptr);
                event.mOffset = uint32_t(ae->Start());
                event.mLength = uint32_t(ae->End() - ae->Start());
                event.mExpandToClusterBoundary = false;
                DispatchEvent(&event);
            }
            {
                nsQueryContentEvent queryEvent(true,
                        NS_QUERY_SELECTED_TEXT, this);
                InitEvent(queryEvent, nullptr);
                DispatchEvent(&queryEvent);
                MOZ_ASSERT(queryEvent.mSucceeded && !queryEvent.mWasAsync);
                event.theText = queryEvent.mReply.mString;
            }
            {
                nsCompositionEvent event(true, NS_COMPOSITION_START, this);
                InitEvent(event, nullptr);
                DispatchEvent(&event);
            }

            if (mIMEComposing &&
                event.theText != mIMEComposingText) {
                nsCompositionEvent compositionUpdate(true,
                                                     NS_COMPOSITION_UPDATE,
                                                     this);
                InitEvent(compositionUpdate, nullptr);
                compositionUpdate.data = event.theText;
                DispatchEvent(&compositionUpdate);
                if (Destroyed())
                    return;
            }

#ifdef DEBUG_ANDROID_IME
            const NS_ConvertUTF16toUTF8 theText8(event.theText);
            const char* text = theText8.get();
            ALOGIME("IME: IME_SET_TEXT: text=\"%s\", length=%u, range=%u",
                    text, event.theText.Length(), mIMERanges.Length());
#endif // DEBUG_ANDROID_IME

            DispatchEvent(&event);
            mIMERanges.Clear();
        }
        break;
    case AndroidGeckoEvent::IME_REMOVE_COMPOSITION:
        {
            /*
             *  Remove any previous composition.  This is only used for
             *    visual indication and does not affect the text content.
             *
             *  Selection and text updates are masked so the result of
             *    temporary events are not passed on to Java
             */
            AutoIMEMask selMask(mIMEMaskSelectionUpdate);
            AutoIMEMask textMask(mIMEMaskTextUpdate);
            RemoveIMEComposition();
            mIMERanges.Clear();
        }
        break;
    }
}

nsWindow *
nsWindow::FindWindowForPoint(const nsIntPoint& pt)
{
    if (!mBounds.Contains(pt))
        return nullptr;

    // children mBounds are relative to their parent
    nsIntPoint childPoint(pt.x - mBounds.x, pt.y - mBounds.y);

    for (uint32_t i = 0; i < mChildren.Length(); ++i) {
        if (mChildren[i]->mBounds.Contains(childPoint))
            return mChildren[i]->FindWindowForPoint(childPoint);
    }

    return this;
}

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

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

NS_IMETHODIMP
nsWindow::NotifyIME(NotificationToIME aNotification)
{
    switch (aNotification) {
        case REQUEST_TO_COMMIT_COMPOSITION:
            //ALOGIME("IME: REQUEST_TO_COMMIT_COMPOSITION: s=%d", aState);
            RemoveIMEComposition();
            AndroidBridge::NotifyIME(REQUEST_TO_COMMIT_COMPOSITION);
            return NS_OK;
        case REQUEST_TO_CANCEL_COMPOSITION:
            ALOGIME("IME: REQUEST_TO_CANCEL_COMPOSITION");

            // Cancel composition on Gecko side
            if (mIMEComposing) {
                nsRefPtr<nsWindow> kungFuDeathGrip(this);

                nsTextEvent textEvent(true, NS_TEXT_TEXT, this);
                InitEvent(textEvent, nullptr);
                DispatchEvent(&textEvent);

                nsCompositionEvent compEvent(true, NS_COMPOSITION_END, this);
                InitEvent(compEvent, nullptr);
                DispatchEvent(&compEvent);
            }

            AndroidBridge::NotifyIME(REQUEST_TO_CANCEL_COMPOSITION);
            return NS_OK;
        case NOTIFY_IME_OF_FOCUS:
            ALOGIME("IME: NOTIFY_IME_OF_FOCUS");
            AndroidBridge::NotifyIME(NOTIFY_IME_OF_FOCUS);
            return NS_OK;
        case NOTIFY_IME_OF_BLUR:
            ALOGIME("IME: NOTIFY_IME_OF_BLUR");

            // Mask events because we lost focus. On the next focus event,
            // Gecko will notify Java, and Java will send an acknowledge focus
            // event back to Gecko. That is where we unmask event handling
            mIMEMaskEventsCount++;
            mIMEComposing = false;
            mIMEComposingText.Truncate();

            AndroidBridge::NotifyIME(NOTIFY_IME_OF_BLUR);
            return NS_OK;
        case NOTIFY_IME_OF_SELECTION_CHANGE:
            if (mIMEMaskSelectionUpdate) {
                return NS_OK;
            }

            ALOGIME("IME: NOTIFY_IME_OF_SELECTION_CHANGE");

            PostFlushIMEChanges();
            mIMESelectionChanged = true;
            return NS_OK;
        default:
            return NS_ERROR_NOT_IMPLEMENTED;
    }
}

NS_IMETHODIMP_(void)
nsWindow::SetInputContext(const InputContext& aContext,
                          const InputContextAction& aAction)
{
    nsWindow *top = TopWindow();
    if (top && top->mFocus && this != top->mFocus) {
        // We are using an IME event later to notify Java, and the IME event
        // will be processed by the focused window. Therefore, to ensure the
        // IME event uses the correct mInputContext, we need to let the focused
        // window process SetInputContext
        top->mFocus->SetInputContext(aContext, aAction);
        return;
    }

    ALOGIME("IME: SetInputContext: s=0x%X, 0x%X, action=0x%X, 0x%X",
            aContext.mIMEState.mEnabled, aContext.mIMEState.mOpen,
            aAction.mCause, aAction.mFocusChange);

    mInputContext = aContext;

    // Ensure that opening the virtual keyboard is allowed for this specific
    // InputContext depending on the content.ime.strict.policy pref
    if (aContext.mIMEState.mEnabled != IMEState::DISABLED && 
        aContext.mIMEState.mEnabled != IMEState::PLUGIN &&
        Preferences::GetBool("content.ime.strict_policy", false) &&
        !aAction.ContentGotFocusByTrustedCause() &&
        !aAction.UserMightRequestOpenVKB()) {
        return;
    }

    IMEState::Enabled enabled = aContext.mIMEState.mEnabled;

    // Only show the virtual keyboard for plugins if mOpen is set appropriately.
    // This avoids showing it whenever a plugin is focused. Bug 747492
    if (aContext.mIMEState.mEnabled == IMEState::PLUGIN &&
        aContext.mIMEState.mOpen != IMEState::OPEN) {
        enabled = IMEState::DISABLED;
    }

    mInputContext.mIMEState.mEnabled = enabled;

    if (enabled == IMEState::ENABLED && aAction.UserMightRequestOpenVKB()) {
        // Don't reset keyboard when we should simply open the vkb
        AndroidBridge::NotifyIME(AndroidBridge::NOTIFY_IME_OPEN_VKB);
        return;
    }

    if (mIMEUpdatingContext) {
        return;
    }
    AndroidGeckoEvent *event = AndroidGeckoEvent::MakeIMEEvent(
            AndroidGeckoEvent::IME_UPDATE_CONTEXT);
    nsAppShell::gAppShell->PostEvent(event);
    mIMEUpdatingContext = true;
}

NS_IMETHODIMP_(InputContext)
nsWindow::GetInputContext()
{
    nsWindow *top = TopWindow();
    if (top && top->mFocus && this != top->mFocus) {
        // We let the focused window process SetInputContext,
        // so we should let it process GetInputContext as well.
        return top->mFocus->GetInputContext();
    }
    InputContext context = mInputContext;
    context.mIMEState.mOpen = IMEState::OPEN_STATE_NOT_SUPPORTED;
    // We assume that there is only one context per process on Android
    context.mNativeIMEContext = nullptr;
    return context;
}

void
nsWindow::PostFlushIMEChanges()
{
    if (!mIMETextChanges.IsEmpty() || mIMESelectionChanged) {
        // Already posted
        return;
    }
    AndroidGeckoEvent *event = AndroidGeckoEvent::MakeIMEEvent(
            AndroidGeckoEvent::IME_FLUSH_CHANGES);
    nsAppShell::gAppShell->PostEvent(event);
}

void
nsWindow::FlushIMEChanges()
{
    nsRefPtr<nsWindow> kungFuDeathGrip(this);
    for (uint32_t i = 0; i < mIMETextChanges.Length(); i++) {
        IMEChange &change = mIMETextChanges[i];

        nsQueryContentEvent event(true, NS_QUERY_TEXT_CONTENT, this);
        InitEvent(event, nullptr);
        event.InitForQueryTextContent(change.mStart,
                                      change.mNewEnd - change.mStart);
        DispatchEvent(&event);
        if (!event.mSucceeded)
            return;

        AndroidBridge::NotifyIMEChange(event.mReply.mString,
                                       change.mStart,
                                       change.mOldEnd,
                                       change.mNewEnd);
    }
    mIMETextChanges.Clear();

    if (mIMESelectionChanged) {
        nsQueryContentEvent event(true, NS_QUERY_SELECTED_TEXT, this);
        InitEvent(event, nullptr);

        DispatchEvent(&event);
        if (!event.mSucceeded)
            return;

        AndroidBridge::NotifyIMEChange(EmptyString(),
                             (int32_t) event.GetSelectionStart(),
                             (int32_t) event.GetSelectionEnd(), -1);
        mIMESelectionChanged = false;
    }
}

NS_IMETHODIMP
nsWindow::NotifyIMEOfTextChange(uint32_t aStart,
                                uint32_t aOldEnd,
                                uint32_t aNewEnd)
{
    if (mIMEMaskTextUpdate)
        return NS_OK;

    ALOGIME("IME: NotifyIMEOfTextChange: s=%d, oe=%d, ne=%d",
            aStart, aOldEnd, aNewEnd);

    /* Make sure Java's selection is up-to-date */
    mIMESelectionChanged = false;
    NotifyIME(NOTIFY_IME_OF_SELECTION_CHANGE);
    PostFlushIMEChanges();

    mIMETextChanges.AppendElement(IMEChange(aStart, aOldEnd, aNewEnd));
    // Now that we added a new range we need to go back and
    // update all the ranges before that.
    // Ranges that have offsets which follow this new range
    // need to be updated to reflect new offsets
    int32_t delta = (int32_t)(aNewEnd - aOldEnd);
    for (int32_t i = mIMETextChanges.Length() - 2; i >= 0; i--) {
        IMEChange &previousChange = mIMETextChanges[i];
        if (previousChange.mStart > (int32_t)aOldEnd) {
            previousChange.mStart += delta;
            previousChange.mOldEnd += delta;
            previousChange.mNewEnd += delta;
        }
    }

    // Now go through all ranges to merge any ranges that are connected
    // srcIndex is the index of the range to merge from
    // dstIndex is the index of the range to potentially merge into
    int32_t srcIndex = mIMETextChanges.Length() - 1;
    int32_t dstIndex = srcIndex;

    while (--dstIndex >= 0) {
        IMEChange &src = mIMETextChanges[srcIndex];
        IMEChange &dst = mIMETextChanges[dstIndex];
        // When merging a more recent change into an older
        // change, we need to compare recent change's (start, oldEnd)
        // range to the older change's (start, newEnd)
        if (src.mOldEnd < dst.mStart || dst.mNewEnd < src.mStart) {
            // No overlap between ranges
            continue;
        }
        // When merging two ranges, there are generally four posibilities:
        // [----(----]----), (----[----]----),
        // [----(----)----], (----[----)----]
        // where [----] is the first range and (----) is the second range
        // As seen above, the start of the merged range is always the lesser
        // of the two start offsets. OldEnd and NewEnd then need to be
        // adjusted separately depending on the case. In any case, the change
        // in text length of the merged range should be the sum of text length
        // changes of the two original ranges, i.e.,
        // newNewEnd - newOldEnd == newEnd1 - oldEnd1 + newEnd2 - oldEnd2
        dst.mStart = std::min(dst.mStart, src.mStart);
        if (src.mOldEnd < dst.mNewEnd) {
            // New range overlaps or is within previous range; merge
            dst.mNewEnd += src.mNewEnd - src.mOldEnd;
        } else { // src.mOldEnd >= dst.mNewEnd
            // New range overlaps previous range; merge
            dst.mOldEnd += src.mOldEnd - dst.mNewEnd;
            dst.mNewEnd = src.mNewEnd;
        }
        // src merged to dst; delete src.
        mIMETextChanges.RemoveElementAt(srcIndex);
        // Any ranges that we skip over between src and dst are not mergeable
        // so we can safely continue the merge starting at dst
        srcIndex = dstIndex;
    }
    return NS_OK;
}

nsIMEUpdatePreference
nsWindow::GetIMEUpdatePreference()
{
    int8_t notifications = (nsIMEUpdatePreference::NOTIFY_SELECTION_CHANGE |
                            nsIMEUpdatePreference::NOTIFY_TEXT_CHANGE);
    return nsIMEUpdatePreference(notifications, true);
}

void
nsWindow::DrawWindowUnderlay(LayerManager* aManager, nsIntRect aRect)
{
    JNIEnv *env = GetJNIForThread();
    NS_ABORT_IF_FALSE(env, "No JNI environment at DrawWindowUnderlay()!");
    if (!env)
        return;

    AutoLocalJNIFrame jniFrame(env);

    AndroidGeckoLayerClient& client = AndroidBridge::Bridge()->GetLayerClient();
    if (!client.CreateFrame(&jniFrame, mLayerRendererFrame)) return;
    
    if (!WidgetPaintsBackground())
        return;

    if (!client.ActivateProgram(&jniFrame)) return;
    if (!mLayerRendererFrame.BeginDrawing(&jniFrame)) return;
    if (!mLayerRendererFrame.DrawBackground(&jniFrame)) return;
    if (!client.DeactivateProgram(&jniFrame)) return; // redundant, but in case somebody adds code after this...
}

void
nsWindow::DrawWindowOverlay(LayerManager* aManager, nsIntRect aRect)
{
    JNIEnv *env = GetJNIForThread();
    NS_ABORT_IF_FALSE(env, "No JNI environment at DrawWindowOverlay()!");
    if (!env)
        return;

    AutoLocalJNIFrame jniFrame(env);

    NS_ABORT_IF_FALSE(!mLayerRendererFrame.isNull(),
                      "Frame should have been created in DrawWindowUnderlay()!");

    AndroidGeckoLayerClient& client = AndroidBridge::Bridge()->GetLayerClient();

    if (!client.ActivateProgram(&jniFrame)) return;
    if (!mLayerRendererFrame.DrawForeground(&jniFrame)) return;
    if (!mLayerRendererFrame.EndDrawing(&jniFrame)) return;
    if (!client.DeactivateProgram(&jniFrame)) return;
    mLayerRendererFrame.Dispose(env);
}

// off-main-thread compositor fields and functions

StaticRefPtr<mozilla::layers::APZCTreeManager> nsWindow::sApzcTreeManager;
StaticRefPtr<mozilla::layers::LayerManager> nsWindow::sLayerManager;
StaticRefPtr<mozilla::layers::CompositorParent> nsWindow::sCompositorParent;
StaticRefPtr<mozilla::layers::CompositorChild> nsWindow::sCompositorChild;
bool nsWindow::sCompositorPaused = true;

void
nsWindow::SetCompositor(mozilla::layers::LayerManager* aLayerManager,
                        mozilla::layers::CompositorParent* aCompositorParent,
                        mozilla::layers::CompositorChild* aCompositorChild)
{
    sLayerManager = aLayerManager;
    sCompositorParent = aCompositorParent;
    sCompositorChild = aCompositorChild;
}

void
nsWindow::ScheduleComposite()
{
    if (sCompositorParent) {
        sCompositorParent->ScheduleRenderOnCompositorThread();
    }
}

void
nsWindow::ScheduleResumeComposition(int width, int height)
{
    if (sCompositorParent && sCompositorParent->ScheduleResumeOnCompositorThread(width, height)) {
        sCompositorPaused = false;
    }
}

void
nsWindow::ForceIsFirstPaint()
{
    if (sCompositorParent) {
        sCompositorParent->ForceIsFirstPaint();
    }
}

float
nsWindow::ComputeRenderIntegrity()
{
    if (sCompositorParent) {
        mozilla::layers::LayerManagerComposite* manager =
          static_cast<mozilla::layers::LayerManagerComposite*>(sCompositorParent->GetLayerManager());
        if (manager) {
            return manager->ComputeRenderIntegrity();
        }
    }

    return 1.f;
}

bool
nsWindow::WidgetPaintsBackground()
{
    static bool sWidgetPaintsBackground = true;
    static bool sWidgetPaintsBackgroundPrefCached = false;

    if (!sWidgetPaintsBackgroundPrefCached) {
        sWidgetPaintsBackgroundPrefCached = true;
        mozilla::Preferences::AddBoolVarCache(&sWidgetPaintsBackground,
                                              "android.widget_paints_background",
                                              true);
    }

    return sWidgetPaintsBackground;
}

bool
nsWindow::NeedsPaint()
{
  if (sCompositorPaused || FindTopLevel() != nsWindow::TopWindow() || !GetLayerManager(nullptr)) {
    return false;
  }
  return nsIWidget::NeedsPaint();
}

CompositorParent*
nsWindow::NewCompositorParent(int aSurfaceWidth, int aSurfaceHeight)
{
    return new CompositorParent(this, true, aSurfaceWidth, aSurfaceHeight);
}

mozilla::layers::APZCTreeManager*
nsWindow::GetAPZCTreeManager()
{
    if (!sApzcTreeManager) {
        CompositorParent* compositor = sCompositorParent;
        if (!compositor) {
            return nullptr;
        }
        uint64_t rootLayerTreeId = compositor->RootLayerTreeId();
        CompositorParent::SetControllerForLayerTree(rootLayerTreeId, AndroidBridge::Bridge());
        sApzcTreeManager = CompositorParent::GetAPZCTreeManager(rootLayerTreeId);
    }
    return sApzcTreeManager;
}

uint64_t
nsWindow::RootLayerTreeId()
{
    MOZ_ASSERT(sCompositorParent);
    return sCompositorParent->RootLayerTreeId();
}