summaryrefslogtreecommitdiff
path: root/widget/android/nsWindow.cpp
blob: 9423a4a2697a1ec5be133134af2e604029ed0d6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
/* -*- Mode: c++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: set sw=4 ts=4 expandtab:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <math.h>
#include <unistd.h>

#include "mozilla/IMEStateManager.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/TextComposition.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/TypeTraits.h"
#include "mozilla/WeakPtr.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 "nsWindow.h"

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

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

#include "WidgetUtils.h"

#include "nsIDOMSimpleGestureEvent.h"

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

#include "gfxContext.h"

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

#include "nsTArray.h"

#include "AndroidBridge.h"
#include "AndroidBridgeUtilities.h"
#include "android_npapi.h"
#include "FennecJNINatives.h"
#include "GeneratedJNINatives.h"
#include "KeyEvent.h"
#include "MotionEvent.h"

#include "imgIEncoder.h"

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

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

NS_IMPL_ISUPPORTS_INHERITED0(nsWindow, nsBaseWidget)

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

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

static bool sFailedToCreateGLContext = false;

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

// Sync with GeckoEditableView class
static const int IME_MONITOR_CURSOR_ONE_SHOT = 1;
static const int IME_MONITOR_CURSOR_START_MONITOR = 2;
static const int IME_MONITOR_CURSOR_END_MONITOR = 3;

static Modifiers GetModifiers(int32_t metaState);

template<typename Lambda, bool IsStatic, typename InstanceType, class Impl>
class nsWindow::WindowEvent : public nsAppShell::LambdaEvent<Lambda>
{
    typedef nsAppShell::Event Event;
    typedef nsAppShell::LambdaEvent<Lambda> Base;

    bool IsStaleCall()
    {
        if (IsStatic) {
            // Static calls are never stale.
            return false;
        }

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

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

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

    const InstanceType mInstance;
    const Event::Type mEventType;

public:
    WindowEvent(Lambda&& aLambda,
                InstanceType&& aInstance,
                Event::Type aEventType = Event::Type::kGeneralActivity)
        : Base(mozilla::Move(aLambda))
        , mInstance(mozilla::Move(aInstance))
        , mEventType(aEventType)
    {}

    WindowEvent(Lambda&& aLambda,
                Event::Type aEventType = Event::Type::kGeneralActivity)
        : Base(mozilla::Move(aLambda))
        , mInstance(Base::lambda.GetThisArg())
        , mEventType(aEventType)
    {}

    void Run() override
    {
        if (!IsStaleCall()) {
            return Base::Run();
        }
    }

    Event::Type ActivityType() const override
    {
        return mEventType;
    }
};

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

    auto impl = mozilla::MakeUnique<Impl>(
            this, aWindow, mozilla::Forward<Args>(aArgs)...);
    mImpl = impl.get();

    Impl::AttachNative(aInstance, mozilla::Move(impl));
}

template<class Impl> void
nsWindow::NativePtr<Impl>::Detach()
{
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mPtr && mImpl);

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

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

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

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

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

template<class Impl>
class nsWindow::WindowPtr final
{
    friend NativePtr<Impl>;

    NativePtr<Impl>* mPtr;
    nsWindow* mWindow;
    Mutex mWindowLock;

public:
    class Locked final : private MutexAutoLock
    {
        nsWindow* const mWindow;

    public:
        Locked(WindowPtr<Impl>& aPtr)
            : MutexAutoLock(aPtr.mWindowLock)
            , mWindow(aPtr.mWindow)
        {}

        operator nsWindow*() const { return mWindow; }
        nsWindow* operator->() const { return mWindow; }
    };

    WindowPtr(NativePtr<Impl>* aPtr, nsWindow* aWindow)
        : mPtr(aPtr)
        , mWindow(aWindow)
        , mWindowLock(NativePtr<Impl>::sName)
    {
        MOZ_ASSERT(NS_IsMainThread());
        mPtr->mPtr = this;
    }

    ~WindowPtr()
    {
        MOZ_ASSERT(NS_IsMainThread());
        if (!mPtr) {
            return;
        }
        mPtr->mPtr = nullptr;
        mPtr->mImpl = nullptr;
    }

    operator nsWindow*() const
    {
        MOZ_ASSERT(NS_IsMainThread());
        return mWindow;
    }

    nsWindow* operator->() const { return operator nsWindow*(); }
};


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

public:
    typedef GeckoView::Window::Natives<GeckoViewSupport> Base;
    typedef GeckoEditable::Natives<GeckoViewSupport> EditableBase;

    MOZ_DECLARE_WEAKREFERENCE_TYPENAME(GeckoViewSupport);

    template<typename Functor>
    static void OnNativeCall(Functor&& aCall)
    {
        if (aCall.IsTarget(&Open) && NS_IsMainThread()) {
            // Gecko state probably just switched to PROFILE_READY, and the
            // event loop is not running yet. Skip the event loop here so we
            // can get a head start on opening our window.
            return aCall();
        }

        const nsAppShell::Event::Type eventType =
                aCall.IsTarget(&GeckoViewSupport::OnKeyEvent) ||
                aCall.IsTarget(&GeckoViewSupport::OnImeReplaceText) ||
                aCall.IsTarget(&GeckoViewSupport::OnImeUpdateComposition) ?
                nsAppShell::Event::Type::kUIActivity :
                nsAppShell::Event::Type::kGeneralActivity;

        nsAppShell::PostEvent(mozilla::MakeUnique<WindowEvent<Functor>>(
                mozilla::Move(aCall), eventType));
    }

    GeckoViewSupport(nsWindow* aWindow,
                     const GeckoView::Window::LocalRef& aInstance,
                     GeckoView::Param aView)
        : window(*aWindow)
        , mEditable(GeckoEditable::New(aView))
        , mIMERanges(new TextRangeArray())
        , mIMEMaskEventsCount(1) // Mask IME events since there's no focus yet
        , mIMEUpdatingContext(false)
        , mIMESelectionChanged(false)
        , mIMETextChangedDuringFlush(false)
        , mIMEMonitorCursor(false)
    {
        Base::AttachNative(aInstance, this);
        EditableBase::AttachNative(mEditable, this);
    }

    ~GeckoViewSupport();

    using Base::DisposeNative;
    using EditableBase::DisposeNative;

    /**
     * GeckoView methods
     */
private:
    nsCOMPtr<nsPIDOMWindowOuter> mDOMWindow;

public:
    // Create and attach a window.
    static void Open(const jni::Class::LocalRef& aCls,
                     GeckoView::Window::Param aWindow,
                     GeckoView::Param aView, jni::Object::Param aCompositor,
                     jni::String::Param aChromeURI,
                     int32_t screenId);

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

    // Reattach this nsWindow to a new GeckoView.
    void Reattach(const GeckoView::Window::LocalRef& inst,
                  GeckoView::Param aView, jni::Object::Param aCompositor);

    void LoadUri(jni::String::Param aUri, int32_t aFlags);

    /**
     * GeckoEditable methods
     */
private:
    /*
        Rules for managing IME between Gecko and Java:

        * Gecko controls the text content, and Java shadows the Gecko text
           through text updates
        * Gecko and Java maintain separate selections, and synchronize when
           needed through selection updates and set-selection events
        * Java controls the composition, and Gecko shadows the Java
           composition through update composition events
    */

    struct IMETextChange final {
        int32_t mStart, mOldEnd, mNewEnd;

        IMETextChange() :
            mStart(-1), mOldEnd(-1), mNewEnd(-1) {}

        IMETextChange(const IMENotification& aIMENotification)
            : mStart(aIMENotification.mTextChangeData.mStartOffset)
            , mOldEnd(aIMENotification.mTextChangeData.mRemovedEndOffset)
            , mNewEnd(aIMENotification.mTextChangeData.mAddedEndOffset)
        {
            MOZ_ASSERT(aIMENotification.mMessage == NOTIFY_IME_OF_TEXT_CHANGE,
                       "IMETextChange initialized with wrong notification");
            MOZ_ASSERT(aIMENotification.mTextChangeData.IsValid(),
                       "The text change notification isn't initialized");
            MOZ_ASSERT(aIMENotification.mTextChangeData.IsInInt32Range(),
                       "The text change notification is out of range");
        }

        bool IsEmpty() const { return mStart < 0; }
    };

    // GeckoEditable instance used by this nsWindow;
    java::GeckoEditable::GlobalRef mEditable;
    AutoTArray<mozilla::UniquePtr<mozilla::WidgetEvent>, 8> mIMEKeyEvents;
    AutoTArray<IMETextChange, 4> mIMETextChanges;
    InputContext mInputContext;
    RefPtr<mozilla::TextRangeArray> mIMERanges;
    int32_t mIMEMaskEventsCount; // Mask events when > 0.
    bool mIMEUpdatingContext;
    bool mIMESelectionChanged;
    bool mIMETextChangedDuringFlush;
    bool mIMEMonitorCursor;

    void SendIMEDummyKeyEvents();
    void AddIMETextChange(const IMETextChange& aChange);

    enum FlushChangesFlag {
        // Not retrying.
        FLUSH_FLAG_NONE,
        // Retrying due to IME text changes during flush.
        FLUSH_FLAG_RETRY,
        // Retrying due to IME sync exceptions during flush.
        FLUSH_FLAG_RECOVER
    };
    void PostFlushIMEChanges();
    void FlushIMEChanges(FlushChangesFlag aFlags = FLUSH_FLAG_NONE);
    void FlushIMEText(FlushChangesFlag aFlags = FLUSH_FLAG_NONE);
    void AsyncNotifyIME(int32_t aNotification);
    void UpdateCompositionRects();

public:
    bool NotifyIME(const IMENotification& aIMENotification);
    void SetInputContext(const InputContext& aContext,
                         const InputContextAction& aAction);
    InputContext GetInputContext();

    // RAII helper class that automatically sends an event reply through
    // OnImeSynchronize, as required by events like OnImeReplaceText.
    class AutoIMESynchronize {
        GeckoViewSupport* const mGVS;
    public:
        AutoIMESynchronize(GeckoViewSupport* gvs) : mGVS(gvs) {}
        ~AutoIMESynchronize() { mGVS->OnImeSynchronize(); }
    };

    // Handle an Android KeyEvent.
    void OnKeyEvent(int32_t aAction, int32_t aKeyCode, int32_t aScanCode,
                    int32_t aMetaState, int64_t aTime, int32_t aUnicodeChar,
                    int32_t aBaseUnicodeChar, int32_t aDomPrintableKeyValue,
                    int32_t aRepeatCount, int32_t aFlags,
                    bool aIsSynthesizedImeKey, jni::Object::Param originalEvent);

    // Synchronize Gecko thread with the InputConnection thread.
    void OnImeSynchronize();

    // Replace a range of text with new text.
    void OnImeReplaceText(int32_t aStart, int32_t aEnd,
                          jni::String::Param aText);

    // Add styling for a range within the active composition.
    void OnImeAddCompositionRange(int32_t aStart, int32_t aEnd,
            int32_t aRangeType, int32_t aRangeStyle, int32_t aRangeLineStyle,
            bool aRangeBoldLine, int32_t aRangeForeColor,
            int32_t aRangeBackColor, int32_t aRangeLineColor);

    // Update styling for the active composition using previous-added ranges.
    void OnImeUpdateComposition(int32_t aStart, int32_t aEnd);

    // Set cursor mode whether IME requests
    void OnImeRequestCursorUpdates(int aRequestMode);
};

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

    WindowPtr<NPZCSupport> mWindow;
    NativePanZoomController::GlobalRef mNPZC;
    int mPreviousButtons;

public:
    typedef NativePanZoomController::Natives<NPZCSupport> Base;

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

    ~NPZCSupport()
    {}

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

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

        typedef NativePanZoomController::GlobalRef NPZCRef;
        auto callDestroy = [] (const NPZCRef& npzc) {
            npzc->Destroy();
        };

        NativePanZoomController::GlobalRef npzc = mNPZC;
        AndroidBridge::Bridge()->PostTaskToUiThread(NewRunnableFunction(
                static_cast<void(*)(const NPZCRef&)>(callDestroy),
                mozilla::Move(npzc)), 0);
    }

public:
    void AdjustScrollForSurfaceShift(float aX, float aY)
    {
        MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

        RefPtr<IAPZCTreeManager> controller;

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

        if (controller) {
            controller->AdjustScrollForSurfaceShift(
                ScreenPoint(aX, aY));
        }
    }

    void SetIsLongpressEnabled(bool aIsLongpressEnabled)
    {
        MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

        RefPtr<IAPZCTreeManager> controller;

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

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

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

        RefPtr<IAPZCTreeManager> controller;

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

        if (!controller) {
            return false;
        }

        ScreenPoint origin = ScreenPoint(aX, aY);

        ScrollWheelInput input(aTime, TimeStamp::Now(), GetModifiers(aMetaState),
                               ScrollWheelInput::SCROLLMODE_SMOOTH,
                               ScrollWheelInput::SCROLLDELTA_PIXEL,
                               origin,
                               aHScroll, aVScroll,
                               false);

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

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

        NativePanZoomController::GlobalRef npzc = mNPZC;
        nsAppShell::PostEvent([npzc, input, guid, blockId, status] {
            MOZ_ASSERT(NS_IsMainThread());

            JNIEnv* const env = jni::GetGeckoThreadEnv();
            NPZCSupport* npzcSupport = GetNative(
                    NativePanZoomController::LocalRef(env, npzc));

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

            nsWindow* const window = npzcSupport->mWindow;
            window->UserActivity();
            WidgetWheelEvent wheelEvent = input.ToWidgetWheelEvent(window);
            window->ProcessUntransformedAPZEvent(&wheelEvent, guid,
                                                 blockId, status);
        });

        return true;
    }

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

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

        return result;
    }

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

        if (buttons & java::sdk::MotionEvent::BUTTON_PRIMARY) {
            result |= WidgetMouseEventBase::eLeftButtonFlag;
        }
        if (buttons & java::sdk::MotionEvent::BUTTON_SECONDARY) {
            result |= WidgetMouseEventBase::eRightButtonFlag;
        }
        if (buttons & java::sdk::MotionEvent::BUTTON_TERTIARY) {
            result |= WidgetMouseEventBase::eMiddleButtonFlag;
        }
        if (buttons & java::sdk::MotionEvent::BUTTON_BACK) {
            result |= WidgetMouseEventBase::e4thButtonFlag;
        }
        if (buttons & java::sdk::MotionEvent::BUTTON_FORWARD) {
            result |= WidgetMouseEventBase::e5thButtonFlag;
        }

        return result;
    }

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

        RefPtr<IAPZCTreeManager> controller;

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

        if (!controller) {
            return false;
        }

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

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

        ScreenPoint origin = ScreenPoint(aX, aY);

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

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

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

        NativePanZoomController::GlobalRef npzc = mNPZC;
        nsAppShell::PostEvent([npzc, input, guid, blockId, status] {
            MOZ_ASSERT(NS_IsMainThread());

            JNIEnv* const env = jni::GetGeckoThreadEnv();
            NPZCSupport* npzcSupport = GetNative(
                    NativePanZoomController::LocalRef(env, npzc));

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

            nsWindow* const window = npzcSupport->mWindow;
            window->UserActivity();
            WidgetMouseEvent mouseEvent = input.ToWidgetMouseEvent(window);
            window->ProcessUntransformedAPZEvent(&mouseEvent, guid,
                                                 blockId, status);
        });

        return true;
    }

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

        RefPtr<IAPZCTreeManager> controller;

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

        if (!controller) {
            return false;
        }

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

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

        MultiTouchInput input(type, aTime, TimeStamp(), 0);
        input.modifiers = GetModifiers(aMetaState);
        input.mTouches.SetCapacity(endIndex - startIndex);

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

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

        for (size_t i = startIndex; i < endIndex; i++) {

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

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

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

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

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

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

        // Dispatch APZ input event on Gecko thread.
        NativePanZoomController::GlobalRef npzc = mNPZC;
        nsAppShell::PostEvent([npzc, input, guid, blockId, status] {
            MOZ_ASSERT(NS_IsMainThread());

            JNIEnv* const env = jni::GetGeckoThreadEnv();
            NPZCSupport* npzcSupport = GetNative(
                    NativePanZoomController::LocalRef(env, npzc));

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

            nsWindow* const window = npzcSupport->mWindow;
            window->UserActivity();
            WidgetTouchEvent touchEvent = input.ToWidgetTouchEvent(window);
            window->ProcessUntransformedAPZEvent(&touchEvent, guid,
                                                 blockId, status);
            window->DispatchHitTest(touchEvent);
        });
        return true;
    }

    void HandleMotionEventVelocity(int64_t aTime, float aSpeedY)
    {
        MOZ_ASSERT(AndroidBridge::IsJavaUiThread());

        RefPtr<IAPZCTreeManager> controller;

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

        if (controller) {
            controller->ProcessTouchVelocity((uint32_t)aTime, aSpeedY);
        }
    }

    void UpdateOverscrollVelocity(const float x, const float y)
    {
        mNPZC->UpdateOverscrollVelocity(x, y);
    }

    void UpdateOverscrollOffset(const float x, const float y)
    {
        mNPZC->UpdateOverscrollOffset(x, y);
    }

    void SetScrollingRootContent(const bool isRootContent)
    {
        mNPZC->SetScrollingRootContent(isRootContent);
    }

    void SetSelectionDragState(const bool aState)
    {
        mNPZC->OnSelectionDragState(aState);
    }
};

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

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

    WindowPtr<LayerViewSupport> mWindow;
    LayerView::Compositor::GlobalRef mCompositor;
    GeckoLayerClient::GlobalRef mLayerClient;
    Atomic<bool, ReleaseAcquire> mCompositorPaused;
    jni::Object::GlobalRef mSurface;

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

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

        LayerViewEvent(UniquePtr<Event>&& event)
            : nsAppShell::ProxyEvent(mozilla::Move(event))
        {}

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

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

    template<class Functor>
    static void OnNativeCall(Functor&& aCall)
    {
        if (aCall.IsTarget(&LayerViewSupport::CreateCompositor)) {
            // This call is blocking.
            nsAppShell::SyncRunEvent(nsAppShell::LambdaEvent<Functor>(
                    mozilla::Move(aCall)), &LayerViewEvent::MakeEvent);
            return;
        }
    }

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

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

    ~LayerViewSupport()
    {}

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

    void OnDetach()
    {
        mCompositor->Destroy();
    }

    const GeckoLayerClient::Ref& GetLayerClient() const
    {
        return mLayerClient;
    }

    bool CompositorPaused() const
    {
        return mCompositorPaused;
    }

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

private:
    void OnResumedCompositor()
    {
        MOZ_ASSERT(NS_IsMainThread());

        // 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 (!mCompositorPaused) {
            mWindow->RedrawAll();
        }
    }

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

        const auto& layerClient = GeckoLayerClient::Ref::From(aClient);

        // If resetting is true, Android destroyed our GeckoApp activity and we
        // had to recreate it, but all the Gecko-side things were not
        // destroyed.  We therefore need to link up the new java objects to
        // Gecko, and that's what we do here.
        const bool resetting = !!mLayerClient;
        mLayerClient = layerClient;

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

        layerClient->OnGeckoReady();

        if (resetting) {
            // Since we are re-linking the new java objects to Gecko, we need
            // to get the viewport from the compositor (since the Java copy was
            // thrown away) and we do that by setting the first-paint flag.
            if (RefPtr<CompositorBridgeParent> bridge = mWindow->GetCompositorBridgeParent()) {
                bridge->ForceIsFirstPaint();
            }
        }
    }

    void OnSizeChanged(int32_t aWindowWidth, int32_t aWindowHeight,
                       int32_t aScreenWidth, int32_t aScreenHeight)
    {
        MOZ_ASSERT(NS_IsMainThread());
        if (!mWindow) {
            return; // Already shut down.
        }

        if (aWindowWidth != mWindow->mBounds.width ||
            aWindowHeight != mWindow->mBounds.height) {

            mWindow->Resize(aWindowWidth, aWindowHeight, /* repaint */ false);
        }
    }

    void CreateCompositor(int32_t aWidth, int32_t aHeight,
                          jni::Object::Param aSurface)
    {
        MOZ_ASSERT(NS_IsMainThread());
        MOZ_ASSERT(mWindow);

        mSurface = aSurface;
        mWindow->CreateLayerManager(aWidth, aHeight);

        mCompositorPaused = false;
        OnResumedCompositor();
    }

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

        RefPtr<CompositorBridgeParent> bridge;

        if (LockedWindowPtr window{mWindow}) {
            bridge = window->GetCompositorBridgeParent();
        }

        if (bridge) {
            mCompositorPaused = true;
            bridge->SchedulePauseOnCompositorThread();
        }
    }

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

        RefPtr<CompositorBridgeParent> bridge;

        if (LockedWindowPtr window{mWindow}) {
            bridge = window->GetCompositorBridgeParent();
        }

        if (bridge && bridge->ScheduleResumeOnCompositorThread()) {
            mCompositorPaused = false;
        }
    }

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

        RefPtr<CompositorBridgeParent> bridge;

        if (LockedWindowPtr window{mWindow}) {
            bridge = window->GetCompositorBridgeParent();
        }

        mSurface = aSurface;

        if (!bridge || !bridge->ScheduleResumeOnCompositorThread(aWidth,
                                                                 aHeight)) {
            return;
        }

        mCompositorPaused = false;

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

        public:
            OnResumedEvent(LayerView::Compositor::GlobalRef&& aCompositor)
                : mCompositor(mozilla::Move(aCompositor))
            {}

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

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

                lvs->OnResumedCompositor();
            }
        };

        nsAppShell::PostEvent(MakeUnique<LayerViewEvent>(
                MakeUnique<OnResumedEvent>(aObj)));
    }

    void SyncInvalidateAndScheduleComposite()
    {
        RefPtr<CompositorBridgeParent> bridge;

        if (LockedWindowPtr window{mWindow}) {
            bridge = window->GetCompositorBridgeParent();
        }

        if (bridge) {
            bridge->InvalidateOnCompositorThread();
            bridge->ScheduleRenderOnCompositorThread();
        }
    }
};

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

/* PresentationMediaPlayerManager native calls access inner nsWindow functionality so PMPMSupport is a child class of nsWindow */
class nsWindow::PMPMSupport final
    : public PresentationMediaPlayerManager::Natives<PMPMSupport>
{
    PMPMSupport() = delete;

    static LayerViewSupport* GetLayerViewSupport(jni::Object::Param aView)
    {
        const auto& layerView = LayerView::Ref::From(aView);

        LayerView::Compositor::LocalRef compositor = layerView->GetCompositor();
        if (!layerView->CompositorCreated() || !compositor) {
            return nullptr;
        }

        LayerViewSupport* const lvs = LayerViewSupport::FromNative(compositor);
        if (!lvs) {
            // There is a pending exception whenever FromNative returns nullptr.
            compositor.Env()->ExceptionClear();
        }
        return lvs;
    }

public:
    static ANativeWindow* sWindow;
    static EGLSurface sSurface;

    static void InvalidateAndScheduleComposite(jni::Object::Param aView)
    {
        LayerViewSupport* const lvs = GetLayerViewSupport(aView);
        if (lvs) {
            lvs->SyncInvalidateAndScheduleComposite();
        }
    }

    static void AddPresentationSurface(const jni::Class::LocalRef& aCls,
                                       jni::Object::Param aView,
                                       jni::Object::Param aSurface)
    {
        RemovePresentationSurface();

        LayerViewSupport* const lvs = GetLayerViewSupport(aView);
        if (!lvs) {
            return;
        }

        ANativeWindow* const window = ANativeWindow_fromSurface(
                aCls.Env(), aSurface.Get());
        if (!window) {
            return;
        }

        sWindow = window;

        const bool wasAlreadyPaused = lvs->CompositorPaused();
        if (!wasAlreadyPaused) {
            lvs->SyncPauseCompositor();
        }

        if (sSurface) {
            // Destroy the EGL surface! The compositor is paused so it should
            // be okay to destroy the surface here.
            mozilla::gl::GLContextProvider::DestroyEGLSurface(sSurface);
            sSurface = nullptr;
        }

        if (!wasAlreadyPaused) {
            lvs->SyncResumeCompositor();
        }

        lvs->SyncInvalidateAndScheduleComposite();
    }

    static void RemovePresentationSurface()
    {
        if (sWindow) {
            ANativeWindow_release(sWindow);
            sWindow = nullptr;
        }
    }
};

ANativeWindow* nsWindow::PMPMSupport::sWindow;
EGLSurface nsWindow::PMPMSupport::sSurface;


nsWindow::GeckoViewSupport::~GeckoViewSupport()
{
    // Disassociate our GeckoEditable instance with our native object.
    // OnDestroy will call disposeNative after any pending native calls have
    // been made.
    MOZ_ASSERT(mEditable);
    mEditable->OnViewChange(nullptr);

    if (window.mNPZCSupport) {
        window.mNPZCSupport.Detach();
    }

    if (window.mLayerViewSupport) {
        window.mLayerViewSupport.Detach();
    }
}

/* static */ void
nsWindow::GeckoViewSupport::Open(const jni::Class::LocalRef& aCls,
                                 GeckoView::Window::Param aWindow,
                                 GeckoView::Param aView,
                                 jni::Object::Param aCompositor,
                                 jni::String::Param aChromeURI,
                                 int32_t aScreenId)
{
    MOZ_ASSERT(NS_IsMainThread());

    PROFILER_LABEL("nsWindow", "GeckoViewSupport::Open",
                   js::ProfileEntry::Category::OTHER);

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

    nsAdoptingCString url;
    if (aChromeURI) {
        url = aChromeURI->ToCString();
    } else {
        url = Preferences::GetCString("toolkit.defaultChromeURI");
        if (!url) {
            url = NS_LITERAL_CSTRING("chrome://browser/content/browser.xul");
        }
    }

    nsCOMPtr<mozIDOMWindowProxy> domWindow;
    ww->OpenWindow(nullptr, url, nullptr, "chrome,dialog=0,resizable,scrollbars=yes",
                   nullptr, getter_AddRefs(domWindow));
    MOZ_RELEASE_ASSERT(domWindow);

    nsCOMPtr<nsPIDOMWindowOuter> pdomWindow =
            nsPIDOMWindowOuter::From(domWindow);
    nsCOMPtr<nsIWidget> widget = WidgetUtils::DOMWindowToWidget(pdomWindow);
    MOZ_ASSERT(widget);

    const auto window = static_cast<nsWindow*>(widget.get());
    window->SetScreenId(aScreenId);

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

    window->mGeckoViewSupport->mDOMWindow = pdomWindow;

    // Attach the Compositor to the new window.
    auto compositor = LayerView::Compositor::LocalRef(
            aCls.Env(), LayerView::Compositor::Ref::From(aCompositor));
    window->mLayerViewSupport.Attach(compositor, window, compositor);

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

void
nsWindow::GeckoViewSupport::Close()
{
    if (!mDOMWindow) {
        return;
    }

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

void
nsWindow::GeckoViewSupport::Reattach(const GeckoView::Window::LocalRef& inst,
                                     GeckoView::Param aView,
                                     jni::Object::Param aCompositor)
{
    // Associate our previous GeckoEditable with the new GeckoView.
    mEditable->OnViewChange(aView);

    // mNPZCSupport might have already been detached through the Java side calling
    // NativePanZoomController.destroy().
    if (window.mNPZCSupport) {
        window.mNPZCSupport.Detach();
    }

    MOZ_ASSERT(window.mLayerViewSupport);
    window.mLayerViewSupport.Detach();

    auto compositor = LayerView::Compositor::LocalRef(
            inst.Env(), LayerView::Compositor::Ref::From(aCompositor));
    window.mLayerViewSupport.Attach(compositor, &window, compositor);
    compositor->Reattach();
}

void
nsWindow::GeckoViewSupport::LoadUri(jni::String::Param aUri, int32_t aFlags)
{
    if (!mDOMWindow) {
        return;
    }

    nsCOMPtr<nsIURI> uri = nsAppShell::ResolveURI(aUri->ToCString());
    if (NS_WARN_IF(!uri)) {
        return;
    }

    nsCOMPtr<nsIDOMChromeWindow> chromeWin = do_QueryInterface(mDOMWindow);
    nsCOMPtr<nsIBrowserDOMWindow> browserWin;

    if (NS_WARN_IF(!chromeWin) || NS_WARN_IF(NS_FAILED(
            chromeWin->GetBrowserDOMWindow(getter_AddRefs(browserWin))))) {
        return;
    }

    const int flags = aFlags == GeckoView::LOAD_NEW_TAB ?
                        nsIBrowserDOMWindow::OPEN_NEWTAB :
                      aFlags == GeckoView::LOAD_SWITCH_TAB ?
                        nsIBrowserDOMWindow::OPEN_SWITCHTAB :
                        nsIBrowserDOMWindow::OPEN_CURRENTWINDOW;
    nsCOMPtr<mozIDOMWindowProxy> newWin;

    if (NS_FAILED(browserWin->OpenURI(
            uri, nullptr, flags, nsIBrowserDOMWindow::OPEN_EXTERNAL,
            getter_AddRefs(newWin)))) {
        NS_WARNING("Failed to open URI");
    }
}

void
nsWindow::InitNatives()
{
    nsWindow::GeckoViewSupport::Base::Init();
    nsWindow::GeckoViewSupport::EditableBase::Init();
    nsWindow::LayerViewSupport::Init();
    nsWindow::NPZCSupport::Init();
    if (jni::IsFennec()) {
        nsWindow::PMPMSupport::Init();
    }
}

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() :
    mScreenId(0), // Use 0 (primary screen) as the default value.
    mIsVisible(false),
    mParent(nullptr),
    mAwaitingFullScreen(false),
    mIsFullScreen(false)
{
}

nsWindow::~nsWindow()
{
    gTopLevelWindows.RemoveElement(this);
    ALOG("nsWindow %p destructor", (void*)this);
}

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

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

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

    mBounds = aRect;

    BaseCreate(nullptr, aInitData);

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

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

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

#ifdef DEBUG_ANDROID_WIDGET
    DumpWindows();
#endif

    return NS_OK;
}

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

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

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

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

    nsBaseWidget::Destroy();

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

    SetParent(nullptr);

    nsBaseWidget::OnDestroy();

#ifdef DEBUG_ANDROID_WIDGET
    DumpWindows();
#endif
}

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

    return NS_OK;
}

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

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

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

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

double
nsWindow::GetDefaultScaleInternal()
{

    nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
    MOZ_ASSERT(screen);
    RefPtr<nsScreenAndroid> screenAndroid = (nsScreenAndroid*) screen.get();
    return screenAndroid->GetDensity();
}

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 eMouseExitFromWidget (for old top
        // window)/eMouseEnterIntoWidget (for new top window) since we need
        // to pretend that the top window always has focus.  Not sure
        // if Show() is the right place to do this, though.

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

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

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

#ifdef DEBUG_ANDROID_WIDGET
    DumpWindows();
#endif

    return NS_OK;
}

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

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

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

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(gfx::IntSize::Truncate(aWidth, aHeight));
    }

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

    nsIWidgetListener* listener = GetWidgetListener();
    if (mAwaitingFullScreen && listener) {
      listener->FullscreenChanged(mIsFullScreen);
      mAwaitingFullScreen = false;
    }

    return NS_OK;
}

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

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

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 LayoutDeviceIntRect& aRect)
{
    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)
{
    nsWindow *top = FindTopLevel();
    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<mozIDOMWindowProxy> existingTopWindow;
    fm->GetActiveWindow(getter_AddRefs(existingTopWindow));
    if (existingTopWindow && FindTopLevel() == nsWindow::TopWindow())
        return;

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

    RefPtr<nsWindow> kungFuDeathGrip(this);

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

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

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

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

    RedrawAll();
}

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

LayoutDeviceIntPoint
nsWindow::WidgetToScreenOffset()
{
    LayoutDeviceIntPoint p(0, 0);
    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(WidgetGUIEvent* aEvent,
                        nsEventStatus& aStatus)
{
    aStatus = DispatchEvent(aEvent);
    return NS_OK;
}

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

nsresult
nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen*)
{
    mIsFullScreen = aFullScreen;
    mAwaitingFullScreen = true;
    GeckoAppShell::SetFullScreen(aFullScreen);
    return NS_OK;
}

mozilla::layers::LayerManager*
nsWindow::GetLayerManager(PLayerTransactionChild*, LayersBackend, LayerManagerPersistence)
{
    if (mLayerManager) {
        return mLayerManager;
    }
    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;
    }

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

    if (ShouldUseOffMainThreadCompositing()) {
        CreateCompositor(aCompositorWidth, aCompositorHeight);
        if (mLayerManager) {
            return;
        }

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

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

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

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

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

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

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

    event.mTime = PR_Now() / 1000;
}

void
nsWindow::UpdateOverscrollVelocity(const float aX, const float aY)
{
    if (NativePtr<NPZCSupport>::Locked npzcs{mNPZCSupport}) {
        npzcs->UpdateOverscrollVelocity(aX, aY);
    }
}

void
nsWindow::UpdateOverscrollOffset(const float aX, const float aY)
{
    if (NativePtr<NPZCSupport>::Locked npzcs{mNPZCSupport}) {
        npzcs->UpdateOverscrollOffset(aX, aY);
    }
}

void
nsWindow::SetScrollingRootContent(const bool isRootContent)
{
    // On Android, the Controller thread and UI thread are the same.
    MOZ_ASSERT(APZThreadUtils::IsControllerThread(), "nsWindow::SetScrollingRootContent must be called from the controller thread");

    if (NativePtr<NPZCSupport>::Locked npzcs{mNPZCSupport}) {
        npzcs->SetScrollingRootContent(isRootContent);
    }
}

void
nsWindow::SetSelectionDragState(bool aState)
{
    if (NativePtr<NPZCSupport>::Locked npzcs{mNPZCSupport}) {
        npzcs->SetSelectionDragState(aState);
    }
}

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

        case NS_NATIVE_WIDGET:
            return (void *) this;

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

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

        case NS_PRESENTATION_WINDOW:
            return PMPMSupport::sWindow;

        case NS_PRESENTATION_SURFACE:
            return PMPMSupport::sSurface;
    }

    return nullptr;
}

void
nsWindow::SetNativeData(uint32_t aDataType, uintptr_t aVal)
{
    switch (aDataType) {
        case NS_PRESENTATION_SURFACE:
            PMPMSupport::sSurface = reinterpret_cast<EGLSurface>(aVal);
            break;
    }
}

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

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

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;

        // the A key is the action key for gamepad devices.
        case AKEYCODE_BUTTON_A:          return NS_VK_RETURN;

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

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

    if (keyCode >= AKEYCODE_0 && keyCode <= AKEYCODE_9) {
        return KEY_NAME_INDEX_USE_STRING;
    }

    switch (keyCode) {

#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_SPACE:
        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_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_DIVIDE:
        case AKEYCODE_NUMPAD_MULTIPLY:
        case AKEYCODE_NUMPAD_SUBTRACT:
        case AKEYCODE_NUMPAD_ADD:
        case AKEYCODE_NUMPAD_DOT:
        case AKEYCODE_NUMPAD_COMMA:
        case AKEYCODE_NUMPAD_EQUALS:
        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_USE_STRING;

        case AKEYCODE_ENDCALL:
        case AKEYCODE_NUM:                // XXX Not sure
        case AKEYCODE_HEADSETHOOK:
        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_DVR:

        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_MANNER_MODE:
        case AKEYCODE_3D_MODE:
        case AKEYCODE_CONTACTS:
            return KEY_NAME_INDEX_Unidentified;

        case AKEYCODE_UNKNOWN:
            MOZ_ASSERT(
                action != AKEY_EVENT_ACTION_MULTIPLE,
                "Don't call this when action is AKEY_EVENT_ACTION_MULTIPLE!");
            // It's actually an unknown key if the action isn't ACTION_MULTIPLE.
            // However, it might cause text input.  So, let's check the value.
            return domPrintableKeyValue ?
                KEY_NAME_INDEX_USE_STRING : KEY_NAME_INDEX_Unidentified;

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

static CodeNameIndex
ConvertAndroidScanCodeToCodeNameIndex(int scanCode)
{
    switch (scanCode) {

#define NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX(aNativeKey, aCodeNameIndex) \
        case aNativeKey: return aCodeNameIndex;

#include "NativeKeyToDOMCodeName.h"

#undef NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX

        default:
          return CODE_NAME_INDEX_UNKNOWN;
    }
}

static bool
IsModifierKey(int32_t keyCode)
{
    using mozilla::java::sdk::KeyEvent;
    return keyCode == KeyEvent::KEYCODE_ALT_LEFT ||
           keyCode == KeyEvent::KEYCODE_ALT_RIGHT ||
           keyCode == KeyEvent::KEYCODE_SHIFT_LEFT ||
           keyCode == KeyEvent::KEYCODE_SHIFT_RIGHT ||
           keyCode == KeyEvent::KEYCODE_CTRL_LEFT ||
           keyCode == KeyEvent::KEYCODE_CTRL_RIGHT ||
           keyCode == KeyEvent::KEYCODE_META_LEFT ||
           keyCode == KeyEvent::KEYCODE_META_RIGHT;
}

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

static void
InitKeyEvent(WidgetKeyboardEvent& event,
             int32_t action, int32_t keyCode, int32_t scanCode,
             int32_t metaState, int64_t time, int32_t unicodeChar,
             int32_t baseUnicodeChar, int32_t domPrintableKeyValue,
             int32_t repeatCount, int32_t flags)
{
    const uint32_t domKeyCode = ConvertAndroidKeyCodeToDOMKeyCode(keyCode);
    const int32_t charCode = unicodeChar ? unicodeChar : baseUnicodeChar;

    event.mModifiers = GetModifiers(metaState);

    if (event.mMessage == eKeyPress) {
        // Android gives us \n, so filter out some control characters.
        event.mIsChar = (charCode >= ' ');
        event.mCharCode = event.mIsChar ? charCode : 0;
        event.mKeyCode = event.mIsChar ? 0 : domKeyCode;
        event.mPluginEvent.Clear();

        // 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.
        // Note that on Android 4.x, Alt modifier isn't set when the key input
        // causes text input even while right Alt key is pressed.  However,
        // this is necessary for Android 2.3 compatibility.
        if (unicodeChar && unicodeChar != baseUnicodeChar) {
            event.mModifiers &= ~(MODIFIER_ALT | MODIFIER_CONTROL
                                               | MODIFIER_META);
        }

    } else {
        event.mIsChar = false;
        event.mCharCode = 0;
        event.mKeyCode = domKeyCode;

        ANPEvent pluginEvent;
        pluginEvent.inSize = sizeof(pluginEvent);
        pluginEvent.eventType = kKey_ANPEventType;
        pluginEvent.data.key.action = event.mMessage == eKeyDown
                ? kDown_ANPKeyAction : kUp_ANPKeyAction;
        pluginEvent.data.key.nativeCode = keyCode;
        pluginEvent.data.key.virtualCode = domKeyCode;
        pluginEvent.data.key.unichar = charCode;
        pluginEvent.data.key.modifiers =
                (metaState & sdk::KeyEvent::META_SHIFT_MASK
                        ? kShift_ANPKeyModifier : 0) |
                (metaState & sdk::KeyEvent::META_ALT_MASK
                        ? kAlt_ANPKeyModifier : 0);
        pluginEvent.data.key.repeatCount = repeatCount;
        event.mPluginEvent.Copy(pluginEvent);
    }

    event.mIsRepeat =
        (event.mMessage == eKeyDown || event.mMessage == eKeyPress) &&
        ((flags & sdk::KeyEvent::FLAG_LONG_PRESS) || repeatCount);

    event.mKeyNameIndex = ConvertAndroidKeyCodeToKeyNameIndex(
            keyCode, action, domPrintableKeyValue);
    event.mCodeNameIndex = ConvertAndroidScanCodeToCodeNameIndex(scanCode);

    if (event.mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
            domPrintableKeyValue) {
        event.mKeyValue = char16_t(domPrintableKeyValue);
    }

    event.mLocation =
        WidgetKeyboardEvent::ComputeLocationFromCodeValue(event.mCodeNameIndex);
    event.mTime = time;
}

void
nsWindow::GeckoViewSupport::OnKeyEvent(int32_t aAction, int32_t aKeyCode,
        int32_t aScanCode, int32_t aMetaState, int64_t aTime,
        int32_t aUnicodeChar, int32_t aBaseUnicodeChar,
        int32_t aDomPrintableKeyValue, int32_t aRepeatCount, int32_t aFlags,
        bool aIsSynthesizedImeKey, jni::Object::Param originalEvent)
{
    RefPtr<nsWindow> kungFuDeathGrip(&window);
    if (!aIsSynthesizedImeKey) {
        window.UserActivity();
        window.RemoveIMEComposition();
    }

    EventMessage msg;
    if (aAction == sdk::KeyEvent::ACTION_DOWN) {
        msg = eKeyDown;
    } else if (aAction == sdk::KeyEvent::ACTION_UP) {
        msg = eKeyUp;
    } else if (aAction == sdk::KeyEvent::ACTION_MULTIPLE) {
        // Keys with multiple action are handled in Java,
        // and we should never see one here
        MOZ_CRASH("Cannot handle key with multiple action");
    } else {
        ALOG("Unknown key action event!");
        return;
    }

    nsEventStatus status = nsEventStatus_eIgnore;
    WidgetKeyboardEvent event(true, msg, &window);
    window.InitEvent(event, nullptr);
    InitKeyEvent(event, aAction, aKeyCode, aScanCode, aMetaState, aTime,
                 aUnicodeChar, aBaseUnicodeChar, aDomPrintableKeyValue,
                 aRepeatCount, aFlags);

    if (aIsSynthesizedImeKey) {
        // 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.
        mIMEKeyEvents.AppendElement(
                mozilla::UniquePtr<WidgetEvent>(event.Duplicate()));

    } else {
        window.DispatchEvent(&event, status);

        if (window.Destroyed() || status == nsEventStatus_eConsumeNoDefault) {
            // Skip default processing.
            return;
        }

        mEditable->OnDefaultKeyEvent(originalEvent);
    }

    if (msg != eKeyDown || IsModifierKey(aKeyCode)) {
        // Skip sending key press event.
        return;
    }

    WidgetKeyboardEvent pressEvent(true, eKeyPress, &window);
    window.InitEvent(pressEvent, nullptr);
    InitKeyEvent(pressEvent, aAction, aKeyCode, aScanCode, aMetaState, aTime,
                 aUnicodeChar, aBaseUnicodeChar, aDomPrintableKeyValue,
                 aRepeatCount, aFlags);

    if (aIsSynthesizedImeKey) {
        mIMEKeyEvents.AppendElement(
                mozilla::UniquePtr<WidgetEvent>(pressEvent.Duplicate()));
    } else {
        window.DispatchEvent(&pressEvent, status);
    }
}

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

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

/*
 * Get the current composition object, if any.
 */
RefPtr<mozilla::TextComposition>
nsWindow::GetIMEComposition()
{
    MOZ_ASSERT(this == FindTopLevel());
    return mozilla::IMEStateManager::GetTextCompositionFor(this);
}

/*
    Remove the composition but leave the text content as-is
*/
void
nsWindow::RemoveIMEComposition(RemoveIMECompositionFlag aFlag)
{
    // Remove composition on Gecko side
    const RefPtr<mozilla::TextComposition> composition(GetIMEComposition());
    if (!composition) {
        return;
    }

    RefPtr<nsWindow> kungFuDeathGrip(this);

    WidgetCompositionEvent compositionCommitEvent(
            true, eCompositionCommit, this);
    if (aFlag == COMMIT_IME_COMPOSITION) {
        compositionCommitEvent.mMessage = eCompositionCommitAsIs;
    }
    InitEvent(compositionCommitEvent, nullptr);
    DispatchEvent(&compositionCommitEvent);
}

/*
 * Send dummy key events for pages that are unaware of input events,
 * to provide web compatibility for pages that depend on key events.
 * Our dummy key events have 0 as the keycode.
 */
void
nsWindow::GeckoViewSupport::SendIMEDummyKeyEvents()
{
    WidgetKeyboardEvent downEvent(true, eKeyDown, &window);
    window.InitEvent(downEvent, nullptr);
    MOZ_ASSERT(downEvent.mKeyCode == 0);
    window.DispatchEvent(&downEvent);

    WidgetKeyboardEvent upEvent(true, eKeyUp, &window);
    window.InitEvent(upEvent, nullptr);
    MOZ_ASSERT(upEvent.mKeyCode == 0);
    window.DispatchEvent(&upEvent);
}

void
nsWindow::GeckoViewSupport::AddIMETextChange(const IMETextChange& aChange)
{
    mIMETextChanges.AppendElement(aChange);

    // We may not be in the middle of flushing,
    // in which case this flag is meaningless.
    mIMETextChangedDuringFlush = true;

    // 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
    const int32_t delta = aChange.mNewEnd - aChange.mOldEnd;
    for (int32_t i = mIMETextChanges.Length() - 2; i >= 0; i--) {
        IMETextChange& previousChange = mIMETextChanges[i];
        if (previousChange.mStart > aChange.mOldEnd) {
            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) {
        IMETextChange& src = mIMETextChanges[srcIndex];
        IMETextChange& 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;
    }
}

void
nsWindow::GeckoViewSupport::PostFlushIMEChanges()
{
    if (!mIMETextChanges.IsEmpty() || mIMESelectionChanged) {
        // Already posted
        return;
    }

    // Keep a strong reference to the window to keep 'this' alive.
    RefPtr<nsWindow> window(&this->window);

    nsAppShell::PostEvent([this, window] {
        if (!window->Destroyed()) {
            FlushIMEChanges();
        }
    });
}

void
nsWindow::GeckoViewSupport::FlushIMEChanges(FlushChangesFlag aFlags)
{
    // Only send change notifications if we are *not* masking events,
    // i.e. if we have a focused editor,
    NS_ENSURE_TRUE_VOID(!mIMEMaskEventsCount);

    nsCOMPtr<nsISelection> imeSelection;
    nsCOMPtr<nsIContent> imeRoot;

    // If we are receiving notifications, we must have selection/root content.
    MOZ_ALWAYS_SUCCEEDS(IMEStateManager::GetFocusSelectionAndRoot(
            getter_AddRefs(imeSelection), getter_AddRefs(imeRoot)));

    // Make sure we still have a valid selection/root. We can potentially get
    // a stale selection/root if the editor becomes hidden, for example.
    NS_ENSURE_TRUE_VOID(imeRoot->IsInComposedDoc());

    RefPtr<nsWindow> kungFuDeathGrip(&window);
    window.UserActivity();

    struct TextRecord {
        nsString text;
        int32_t start;
        int32_t oldEnd;
        int32_t newEnd;
    };
    AutoTArray<TextRecord, 4> textTransaction;
    if (mIMETextChanges.Length() > textTransaction.Capacity()) {
        textTransaction.SetCapacity(mIMETextChanges.Length());
    }

    mIMETextChangedDuringFlush = false;

    auto shouldAbort = [=] () -> bool {
        if (!mIMETextChangedDuringFlush) {
            return false;
        }
        // A query event could have triggered more text changes to come in, as
        // indicated by our flag. If that happens, try flushing IME changes
        // again.
        if (aFlags == FLUSH_FLAG_NONE) {
            FlushIMEChanges(FLUSH_FLAG_RETRY);
        } else {
            // Don't retry if already retrying, to avoid infinite loops.
            __android_log_print(ANDROID_LOG_WARN, "GeckoViewSupport",
                    "Already retrying IME flush");
        }
        return true;
    };

    for (const IMETextChange &change : mIMETextChanges) {
        if (change.mStart == change.mOldEnd &&
                change.mStart == change.mNewEnd) {
            continue;
        }

        WidgetQueryContentEvent event(true, eQueryTextContent, &window);

        if (change.mNewEnd != change.mStart) {
            window.InitEvent(event, nullptr);
            event.InitForQueryTextContent(change.mStart,
                                          change.mNewEnd - change.mStart);
            window.DispatchEvent(&event);
            NS_ENSURE_TRUE_VOID(event.mSucceeded);
            NS_ENSURE_TRUE_VOID(event.mReply.mContentsRoot == imeRoot.get());
        }

        if (shouldAbort()) {
            return;
        }

        textTransaction.AppendElement(
                TextRecord{event.mReply.mString, change.mStart,
                           change.mOldEnd, change.mNewEnd});
    }

    int32_t selStart = -1;
    int32_t selEnd = -1;

    if (mIMESelectionChanged) {
        WidgetQueryContentEvent event(true, eQuerySelectedText, &window);
        window.InitEvent(event, nullptr);
        window.DispatchEvent(&event);

        NS_ENSURE_TRUE_VOID(event.mSucceeded);
        NS_ENSURE_TRUE_VOID(event.mReply.mContentsRoot == imeRoot.get());

        if (shouldAbort()) {
            return;
        }

        selStart = int32_t(event.GetSelectionStart());
        selEnd = int32_t(event.GetSelectionEnd());
    }

    JNIEnv* const env = jni::GetGeckoThreadEnv();
    auto flushOnException = [=] () -> bool {
        if (!env->ExceptionCheck()) {
            return false;
        }
        if (aFlags != FLUSH_FLAG_RECOVER) {
            // First time seeing an exception; try flushing text.
            env->ExceptionClear();
            __android_log_print(ANDROID_LOG_WARN, "GeckoViewSupport",
                    "Recovering from IME exception");
            FlushIMEText(FLUSH_FLAG_RECOVER);
        } else {
            // Give up because we've already tried.
            MOZ_CATCH_JNI_EXCEPTION(env);
        }
        return true;
    };

    // Commit the text change and selection change transaction.
    mIMETextChanges.Clear();

    for (const TextRecord& record : textTransaction) {
        mEditable->OnTextChange(record.text, record.start,
                                record.oldEnd, record.newEnd);
        if (flushOnException()) {
            return;
        }
    }

    if (mIMESelectionChanged) {
        mIMESelectionChanged = false;
        mEditable->OnSelectionChange(selStart, selEnd);
        flushOnException();
    }
}

void
nsWindow::GeckoViewSupport::FlushIMEText(FlushChangesFlag aFlags)
{
    // Notify Java of the newly focused content
    mIMETextChanges.Clear();
    mIMESelectionChanged = true;

    // 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.
    IMENotification notification(NOTIFY_IME_OF_TEXT_CHANGE);
    notification.mTextChangeData.mStartOffset = 0;
    notification.mTextChangeData.mRemovedEndOffset = INT32_MAX / 2;
    notification.mTextChangeData.mAddedEndOffset = INT32_MAX / 2;
    NotifyIME(notification);

    FlushIMEChanges(aFlags);
}

static jni::ObjectArray::LocalRef
ConvertRectArrayToJavaRectFArray(JNIEnv* aJNIEnv, const nsTArray<LayoutDeviceIntRect>& aRects, const LayoutDeviceIntPoint& aOffset, const CSSToLayoutDeviceScale aScale)
{
    size_t length = aRects.Length();
    jobjectArray rects = aJNIEnv->NewObjectArray(length, sdk::RectF::Context().ClassRef(), nullptr);
    auto rectsRef = jni::ObjectArray::LocalRef::Adopt(aJNIEnv, rects);
    for (size_t i = 0; i < length; i++) {
        sdk::RectF::LocalRef rect(aJNIEnv);
        LayoutDeviceIntRect tmp = aRects[i] + aOffset;
        sdk::RectF::New(tmp.x / aScale.scale, tmp.y / aScale.scale,
                        (tmp.x + tmp.width) / aScale.scale,
                        (tmp.y + tmp.height) / aScale.scale,
                        &rect);
        rectsRef->SetElement(i, rect);
    }
    return rectsRef;
}

void
nsWindow::GeckoViewSupport::UpdateCompositionRects()
{
    const auto composition(window.GetIMEComposition());
    if (NS_WARN_IF(!composition)) {
        return;
    }

    uint32_t offset = composition->NativeOffsetOfStartComposition();
    WidgetQueryContentEvent textRects(true, eQueryTextRectArray, &window);
    textRects.InitForQueryTextRectArray(offset, composition->String().Length());
    window.DispatchEvent(&textRects);

    auto rects =
        ConvertRectArrayToJavaRectFArray(jni::GetGeckoThreadEnv(),
                                         textRects.mReply.mRectArray,
                                         window.WidgetToScreenOffset(),
                                         window.GetDefaultScale());

    mEditable->UpdateCompositionRects(rects);
}

void
nsWindow::GeckoViewSupport::AsyncNotifyIME(int32_t aNotification)
{
    // Keep a strong reference to the window to keep 'this' alive.
    RefPtr<nsWindow> window(&this->window);

    nsAppShell::PostEvent([this, window, aNotification] {
        if (mIMEMaskEventsCount) {
            return;
        }

        mEditable->NotifyIME(aNotification);
    });
}

bool
nsWindow::GeckoViewSupport::NotifyIME(const IMENotification& aIMENotification)
{
    MOZ_ASSERT(mEditable);

    switch (aIMENotification.mMessage) {
        case REQUEST_TO_COMMIT_COMPOSITION: {
            ALOGIME("IME: REQUEST_TO_COMMIT_COMPOSITION");

            window.RemoveIMEComposition();

            AsyncNotifyIME(GeckoEditableListener::
                           NOTIFY_IME_TO_COMMIT_COMPOSITION);
            return true;
        }

        case REQUEST_TO_CANCEL_COMPOSITION: {
            ALOGIME("IME: REQUEST_TO_CANCEL_COMPOSITION");

            window.RemoveIMEComposition(CANCEL_IME_COMPOSITION);

            AsyncNotifyIME(GeckoEditableListener::
                           NOTIFY_IME_TO_CANCEL_COMPOSITION);
            return true;
        }

        case NOTIFY_IME_OF_FOCUS: {
            ALOGIME("IME: NOTIFY_IME_OF_FOCUS");
            // Keep a strong reference to the window to keep 'this' alive.
            RefPtr<nsWindow> window(&this->window);

            // Post an event because we have to flush the text before sending a
            // focus event, and we may not be able to flush text during the
            // NotifyIME call.
            nsAppShell::PostEvent([this, window] {
                --mIMEMaskEventsCount;
                if (mIMEMaskEventsCount || window->Destroyed()) {
                    return;
                }

                FlushIMEText();

                // IME will call requestCursorUpdates after getting context.
                // So reset cursor update mode before getting context.
                mIMEMonitorCursor = false;

                MOZ_ASSERT(mEditable);
                mEditable->NotifyIME(GeckoEditableListener::NOTIFY_IME_OF_FOCUS);
            });
            return true;
        }

        case NOTIFY_IME_OF_BLUR: {
            ALOGIME("IME: NOTIFY_IME_OF_BLUR");

            if (!mIMEMaskEventsCount) {
                mEditable->NotifyIME(GeckoEditableListener::NOTIFY_IME_OF_BLUR);
            }

            // Mask events because we lost focus. Unmask on the next focus.
            mIMEMaskEventsCount++;
            return true;
        }

        case NOTIFY_IME_OF_SELECTION_CHANGE: {
            ALOGIME("IME: NOTIFY_IME_OF_SELECTION_CHANGE");

            PostFlushIMEChanges();
            mIMESelectionChanged = true;
            return true;
        }

        case NOTIFY_IME_OF_TEXT_CHANGE: {
            ALOGIME("IME: NotifyIMEOfTextChange: s=%d, oe=%d, ne=%d",
                    aIMENotification.mTextChangeData.mStartOffset,
                    aIMENotification.mTextChangeData.mRemovedEndOffset,
                    aIMENotification.mTextChangeData.mAddedEndOffset);

            /* Make sure Java's selection is up-to-date */
            PostFlushIMEChanges();
            mIMESelectionChanged = true;
            AddIMETextChange(IMETextChange(aIMENotification));
            return true;
        }

        case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED: {
            ALOGIME("IME: NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED");

            // Hardware keyboard support requires each string rect.
            if (AndroidBridge::Bridge() && AndroidBridge::Bridge()->GetAPIVersion() >= 21 && mIMEMonitorCursor) {
                UpdateCompositionRects();
            }
            return true;
        }

        default:
            return false;
    }
}

void
nsWindow::GeckoViewSupport::SetInputContext(const InputContext& aContext,
                                            const InputContextAction& aAction)
{
    MOZ_ASSERT(mEditable);

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

    // 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 = aContext;
    mInputContext.mIMEState.mEnabled = enabled;

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

    if (mIMEUpdatingContext) {
        return;
    }

    // Keep a strong reference to the window to keep 'this' alive.
    RefPtr<nsWindow> window(&this->window);
    mIMEUpdatingContext = true;

    nsAppShell::PostEvent([this, window] {
        mIMEUpdatingContext = false;
        if (window->Destroyed()) {
            return;
        }
        MOZ_ASSERT(mEditable);
        mEditable->NotifyIMEContext(mInputContext.mIMEState.mEnabled,
                                    mInputContext.mHTMLInputType,
                                    mInputContext.mHTMLInputInputmode,
                                    mInputContext.mActionHint);
    });
}

InputContext
nsWindow::GeckoViewSupport::GetInputContext()
{
    InputContext context = mInputContext;
    context.mIMEState.mOpen = IMEState::OPEN_STATE_NOT_SUPPORTED;
    return context;
}

void
nsWindow::GeckoViewSupport::OnImeSynchronize()
{
    if (!mIMEMaskEventsCount) {
        FlushIMEChanges();
    }
    mEditable->NotifyIME(GeckoEditableListener::NOTIFY_IME_REPLY_EVENT);
}

void
nsWindow::GeckoViewSupport::OnImeReplaceText(int32_t aStart, int32_t aEnd,
                                             jni::String::Param aText)
{
    AutoIMESynchronize as(this);

    if (mIMEMaskEventsCount > 0) {
        // Not focused; still reply to events, but don't do anything else.
        return;
    }

    /*
        Replace text in Gecko thread from aStart to aEnd with the string text.
    */
    RefPtr<nsWindow> kungFuDeathGrip(&window);
    nsString string(aText->ToString());

    const auto composition(window.GetIMEComposition());
    MOZ_ASSERT(!composition || !composition->IsEditorHandlingEvent());

    const bool composing = !mIMERanges->IsEmpty();

    if (!mIMEKeyEvents.IsEmpty() || !composition ||
        uint32_t(aStart) != composition->NativeOffsetOfStartComposition() ||
        uint32_t(aEnd) != composition->NativeOffsetOfStartComposition() +
                          composition->String().Length())
    {
        // Only start a new composition if we have key events,
        // if we don't have an existing composition, or
        // the replaced text does not match our composition.
        window.RemoveIMEComposition();

        {
            // Use text selection to set target postion(s) for
            // insert, or replace, of text.
            WidgetSelectionEvent event(true, eSetSelection, &window);
            window.InitEvent(event, nullptr);
            event.mOffset = uint32_t(aStart);
            event.mLength = uint32_t(aEnd - aStart);
            event.mExpandToClusterBoundary = false;
            event.mReason = nsISelectionListener::IME_REASON;
            window.DispatchEvent(&event);
        }

        if (!mIMEKeyEvents.IsEmpty()) {
            nsEventStatus status;
            for (uint32_t i = 0; i < mIMEKeyEvents.Length(); i++) {
                const auto event = static_cast<WidgetGUIEvent*>(
                        mIMEKeyEvents[i].get());
                if (event->mMessage == eKeyPress &&
                        status == nsEventStatus_eConsumeNoDefault) {
                    MOZ_ASSERT(i > 0 &&
                            mIMEKeyEvents[i - 1]->mMessage == eKeyDown);
                    // The previous key down event resulted in eConsumeNoDefault
                    // so we should not dispatch the current key press event.
                    continue;
                }
                // widget for duplicated events is initially nullptr.
                event->mWidget = &window;
                window.DispatchEvent(event, status);
            }
            mIMEKeyEvents.Clear();
            return;
        }

        if (aStart != aEnd) {
            // Perform a deletion first.
            WidgetContentCommandEvent event(
                    true, eContentCommandDelete, &window);
            window.InitEvent(event, nullptr);
            window.DispatchEvent(&event);
        }

        // Start a composition if we're not just performing a deletion.
        if (composing || !string.IsEmpty()) {
            WidgetCompositionEvent event(true, eCompositionStart, &window);
            window.InitEvent(event, nullptr);
            window.DispatchEvent(&event);
        }

    } else if (composition->String().Equals(string)) {
        /* If the new text is the same as the existing composition text,
         * the NS_COMPOSITION_CHANGE event does not generate a text
         * change notification. However, the Java side still expects
         * one, so we manually generate a notification. */
        IMETextChange dummyChange;
        dummyChange.mStart = aStart;
        dummyChange.mOldEnd = dummyChange.mNewEnd = aEnd;
        AddIMETextChange(dummyChange);
    }

    // Check composition again because previous events may have destroyed our
    // composition; in which case we should just skip the next event.
    if (window.GetIMEComposition()) {
        WidgetCompositionEvent event(true, eCompositionChange, &window);
        window.InitEvent(event, nullptr);
        event.mData = string;

        if (composing) {
            event.mRanges = new TextRangeArray();
            mIMERanges.swap(event.mRanges);
        } else {
            event.mMessage = eCompositionCommit;
        }

        window.DispatchEvent(&event);

    } else if (composing) {
        // Ensure IME ranges are empty.
        mIMERanges->Clear();
    }

    if (mInputContext.mMayBeIMEUnaware) {
        SendIMEDummyKeyEvents();
    }
}

void
nsWindow::GeckoViewSupport::OnImeAddCompositionRange(
        int32_t aStart, int32_t aEnd, int32_t aRangeType, int32_t aRangeStyle,
        int32_t aRangeLineStyle, bool aRangeBoldLine, int32_t aRangeForeColor,
        int32_t aRangeBackColor, int32_t aRangeLineColor)
{
    if (mIMEMaskEventsCount > 0) {
        // Not focused.
        return;
    }

    TextRange range;
    range.mStartOffset = aStart;
    range.mEndOffset = aEnd;
    range.mRangeType = ToTextRangeType(aRangeType);
    range.mRangeStyle.mDefinedStyles = aRangeStyle;
    range.mRangeStyle.mLineStyle = aRangeLineStyle;
    range.mRangeStyle.mIsBoldLine = aRangeBoldLine;
    range.mRangeStyle.mForegroundColor =
            ConvertAndroidColor(uint32_t(aRangeForeColor));
    range.mRangeStyle.mBackgroundColor =
            ConvertAndroidColor(uint32_t(aRangeBackColor));
    range.mRangeStyle.mUnderlineColor =
            ConvertAndroidColor(uint32_t(aRangeLineColor));
    mIMERanges->AppendElement(range);
}

void
nsWindow::GeckoViewSupport::OnImeUpdateComposition(int32_t aStart, int32_t aEnd)
{
    if (mIMEMaskEventsCount > 0) {
        // Not focused.
        return;
    }

    RefPtr<nsWindow> kungFuDeathGrip(&window);

    // A composition with no ranges means we want to set the selection.
    if (mIMERanges->IsEmpty()) {
        MOZ_ASSERT(aStart >= 0 && aEnd >= 0);
        window.RemoveIMEComposition();

        WidgetSelectionEvent selEvent(true, eSetSelection, &window);
        window.InitEvent(selEvent, nullptr);

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

        window.DispatchEvent(&selEvent);
        return;
    }

    /*
        Update the composition from aStart to aEnd 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.
    */
    const auto composition(window.GetIMEComposition());
    MOZ_ASSERT(!composition || !composition->IsEditorHandlingEvent());

    WidgetCompositionEvent event(true, eCompositionChange, &window);
    window.InitEvent(event, nullptr);

    event.mRanges = new TextRangeArray();
    mIMERanges.swap(event.mRanges);

    if (!composition ||
        uint32_t(aStart) != composition->NativeOffsetOfStartComposition() ||
        uint32_t(aEnd) != composition->NativeOffsetOfStartComposition() +
                          composition->String().Length())
    {
        // Only start new composition if we don't have an existing one,
        // or if the existing composition doesn't match the new one.
        window.RemoveIMEComposition();

        {
            WidgetSelectionEvent event(true, eSetSelection, &window);
            window.InitEvent(event, nullptr);
            event.mOffset = uint32_t(aStart);
            event.mLength = uint32_t(aEnd - aStart);
            event.mExpandToClusterBoundary = false;
            event.mReason = nsISelectionListener::IME_REASON;
            window.DispatchEvent(&event);
        }

        {
            WidgetQueryContentEvent queryEvent(true, eQuerySelectedText,
                                               &window);
            window.InitEvent(queryEvent, nullptr);
            window.DispatchEvent(&queryEvent);
            MOZ_ASSERT(queryEvent.mSucceeded);
            event.mData = queryEvent.mReply.mString;
        }

        {
            WidgetCompositionEvent event(true, eCompositionStart, &window);
            window.InitEvent(event, nullptr);
            window.DispatchEvent(&event);
        }

    } else {
        // If the new composition matches the existing composition,
        // reuse the old composition.
        event.mData = composition->String();
    }

#ifdef DEBUG_ANDROID_IME
    const NS_ConvertUTF16toUTF8 data(event.mData);
    const char* text = data.get();
    ALOGIME("IME: IME_SET_TEXT: text=\"%s\", length=%u, range=%u",
            text, event.mData.Length(), event.mRanges->Length());
#endif // DEBUG_ANDROID_IME

    // Previous events may have destroyed our composition; bail in that case.
    if (window.GetIMEComposition()) {
        window.DispatchEvent(&event);
    }
}

void
nsWindow::GeckoViewSupport::OnImeRequestCursorUpdates(int aRequestMode)
{
    if (aRequestMode == IME_MONITOR_CURSOR_ONE_SHOT) {
        UpdateCompositionRects();
        return;
    }

    mIMEMonitorCursor = (aRequestMode == IME_MONITOR_CURSOR_START_MONITOR);
}

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

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

nsresult
nsWindow::NotifyIMEInternal(const IMENotification& aIMENotification)
{
    MOZ_ASSERT(this == FindTopLevel());

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

    if (mGeckoViewSupport->NotifyIME(aIMENotification)) {
        return NS_OK;
    }
    return NS_ERROR_NOT_IMPLEMENTED;
}

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

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

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

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

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

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

nsIMEUpdatePreference
nsWindow::GetIMEUpdatePreference()
{
    // While a plugin has focus, nsWindow for Android doesn't need any
    // notifications.
    if (GetInputContext().mIMEState.mEnabled == IMEState::PLUGIN) {
      return nsIMEUpdatePreference();
    }
    return nsIMEUpdatePreference(nsIMEUpdatePreference::NOTIFY_TEXT_CHANGE);
}

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

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

    MOZ_ASSERT(mLayerViewSupport);
    GeckoLayerClient::LocalRef client = mLayerViewSupport->GetLayerClient();
    client->SynthesizeNativeTouchPoint(aPointerId, eventType,
        aPoint.x, aPoint.y, aPointerPressure, aPointerOrientation);

    return NS_OK;
}

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

    MOZ_ASSERT(mLayerViewSupport);
    GeckoLayerClient::LocalRef client = mLayerViewSupport->GetLayerClient();
    client->SynthesizeNativeMouseEvent(aNativeMessage, aPoint.x, aPoint.y);

    return NS_OK;
}

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

    MOZ_ASSERT(mLayerViewSupport);
    GeckoLayerClient::LocalRef client = mLayerViewSupport->GetLayerClient();
    client->SynthesizeNativeMouseEvent(sdk::MotionEvent::ACTION_HOVER_MOVE, aPoint.x, aPoint.y);

    return NS_OK;
}

bool
nsWindow::PreRender(WidgetRenderingContext* aContext)
{
    if (Destroyed()) {
        return true;
    }

    layers::Compositor* compositor = aContext->mCompositor;

    GeckoLayerClient::LocalRef client;

    if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
        client = lvs->GetLayerClient();
    }

    if (compositor && client) {
        // Android Color is ARGB which is apparently unusual.
        compositor->SetDefaultClearColor(gfx::Color::UnusualFromARGB((uint32_t)client->ClearColor()));
    }

    return true;
}
void
nsWindow::DrawWindowUnderlay(WidgetRenderingContext* aContext,
                             LayoutDeviceIntRect aRect)
{
    if (Destroyed()) {
        return;
    }

    GeckoLayerClient::LocalRef client;

    if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
        client = lvs->GetLayerClient();
    }

    if (!client) {
        return;
    }

    LayerRenderer::Frame::LocalRef frame = client->CreateFrame();
    mLayerRendererFrame = frame;
    if (NS_WARN_IF(!mLayerRendererFrame)) {
        return;
    }

    if (!WidgetPaintsBackground()) {
        return;
    }

    frame->BeginDrawing();
}

void
nsWindow::DrawWindowOverlay(WidgetRenderingContext* aContext,
                            LayoutDeviceIntRect aRect)
{
    PROFILER_LABEL("nsWindow", "DrawWindowOverlay",
        js::ProfileEntry::Category::GRAPHICS);

    if (Destroyed() || NS_WARN_IF(!mLayerRendererFrame)) {
        return;
    }

    mLayerRendererFrame->EndDrawing();
    mLayerRendererFrame = nullptr;
}

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 (!mLayerViewSupport || mLayerViewSupport->CompositorPaused() ||
            // FindTopLevel() != nsWindow::TopWindow() ||
            !GetLayerManager(nullptr)) {
        return false;
    }
    return nsIWidget::NeedsPaint();
}

void
nsWindow::ConfigureAPZControllerThread()
{
    APZThreadUtils::SetControllerThread(nullptr);
}

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

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

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

CompositorBridgeParent*
nsWindow::GetCompositorBridgeParent() const
{
    return mCompositorSession ? mCompositorSession->GetInProcessBridge() : nullptr;
}

already_AddRefed<nsIScreen>
nsWindow::GetWidgetScreen()
{
    nsCOMPtr<nsIScreenManager> screenMgr =
        do_GetService("@mozilla.org/gfx/screenmanager;1");
    MOZ_ASSERT(screenMgr, "Failed to get nsIScreenManager");

    nsCOMPtr<nsIScreen> screen;
    screenMgr->ScreenForId(mScreenId, getter_AddRefs(screen));

    return screen.forget();
}

jni::DependentRef<java::GeckoLayerClient>
nsWindow::GetLayerClient()
{
    if (NativePtr<LayerViewSupport>::Locked lvs{mLayerViewSupport}) {
        return lvs->GetLayerClient().Get();
    }
    return nullptr;
}