summaryrefslogtreecommitdiffstats
path: root/dom/events/IMEStateManager.cpp
blob: 966b2f62f7a3f2fe081d0578b59279357c49d727 (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "IMEStateManager.h"

#include "IMEContentObserver.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/EditorBase.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/Logging.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PresShell.h"
#include "mozilla/RefPtr.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_intl.h"
#include "mozilla/TextComposition.h"
#include "mozilla/TextEvents.h"
#include "mozilla/ToString.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/BrowserBridgeChild.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLFormElement.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLTextAreaElement.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/widget/IMEData.h"

#include "nsCOMPtr.h"
#include "nsContentUtils.h"
#include "nsFocusManager.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsIFormControl.h"
#include "nsINode.h"
#include "nsISupports.h"
#include "nsIURI.h"
#include "nsIURIMutator.h"
#include "nsPresContext.h"
#include "nsThreadUtils.h"

namespace mozilla {

using namespace dom;
using namespace widget;

/**
 * When a method is called, log its arguments and/or related static variables
 * with LogLevel::Info.  However, if it puts too many logs like
 * OnDestroyPresContext(), should long only when the method actually does
 * something. In this case, the log should start with "<method name>".
 *
 * When a method quits due to unexpected situation, log the reason with
 * LogLevel::Error.  In this case, the log should start with
 * "<method name>(), FAILED".  The indent makes the log look easier.
 *
 * When a method does something only in some situations and it may be important
 * for debug, log the information with LogLevel::Debug.  In this case, the log
 * should start with "  <method name>(),".
 */
LazyLogModule sISMLog("IMEStateManager");

static const char* GetBoolName(bool aBool) { return aBool ? "true" : "false"; }

StaticRefPtr<Element> IMEStateManager::sFocusedElement;
StaticRefPtr<nsPresContext> IMEStateManager::sFocusedPresContext;
nsIWidget* IMEStateManager::sTextInputHandlingWidget = nullptr;
nsIWidget* IMEStateManager::sFocusedIMEWidget = nullptr;
StaticRefPtr<BrowserParent> IMEStateManager::sFocusedIMEBrowserParent;
nsIWidget* IMEStateManager::sActiveInputContextWidget = nullptr;
StaticRefPtr<IMEContentObserver> IMEStateManager::sActiveIMEContentObserver;
TextCompositionArray* IMEStateManager::sTextCompositions = nullptr;
InputContext::Origin IMEStateManager::sOrigin = InputContext::ORIGIN_MAIN;
InputContext IMEStateManager::sActiveChildInputContext;
bool IMEStateManager::sInstalledMenuKeyboardListener = false;
bool IMEStateManager::sIsGettingNewIMEState = false;
bool IMEStateManager::sCleaningUpForStoppingIMEStateManagement = false;
bool IMEStateManager::sIsActive = false;
Maybe<IMEStateManager::PendingFocusedBrowserSwitchingData>
    IMEStateManager::sPendingFocusedBrowserSwitchingData;

class PseudoFocusChangeRunnable : public Runnable {
 public:
  explicit PseudoFocusChangeRunnable(bool aInstallingMenuKeyboardListener)
      : Runnable("PseudoFocusChangeRunnable"),
        mFocusedPresContext(IMEStateManager::sFocusedPresContext),
        mFocusedElement(IMEStateManager::sFocusedElement),
        mInstallMenuKeyboardListener(aInstallingMenuKeyboardListener) {}

  MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
    IMEStateManager::SetMenubarPseudoFocus(this, mInstallMenuKeyboardListener,
                                           mFocusedPresContext);
    return NS_OK;
  }

 private:
  const RefPtr<nsPresContext> mFocusedPresContext;
  const RefPtr<Element> mFocusedElement;
  const bool mInstallMenuKeyboardListener;
};

StaticRefPtr<PseudoFocusChangeRunnable>
    IMEStateManager::sPseudoFocusChangeRunnable;

// static
void IMEStateManager::Init() {
  sOrigin = XRE_IsParentProcess() ? InputContext::ORIGIN_MAIN
                                  : InputContext::ORIGIN_CONTENT;
  ResetActiveChildInputContext();
}

// static
void IMEStateManager::Shutdown() {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("Shutdown(), sTextCompositions=0x%p, sTextCompositions->Length()=%zu, "
       "sPendingFocusedBrowserSwitchingData.isSome()=%s",
       sTextCompositions, sTextCompositions ? sTextCompositions->Length() : 0,
       GetBoolName(sPendingFocusedBrowserSwitchingData.isSome())));
  MOZ_LOG(sISMLog, LogLevel::Debug,
          ("  Shutdown(), sFocusedElement=0x%p, sFocusedPresContext=0x%p, "
           "sTextInputHandlingWidget=0x%p, sFocusedIMEWidget=0x%p, "
           "sFocusedIMEBrowserParent=0x%p, sActiveInputContextWidget=0x%p, "
           "sActiveIMEContentObserver=0x%p",
           sFocusedElement.get(), sFocusedPresContext.get(),
           sTextInputHandlingWidget, sFocusedIMEWidget,
           sFocusedIMEBrowserParent.get(), sActiveInputContextWidget,
           sActiveIMEContentObserver.get()));

  sPendingFocusedBrowserSwitchingData.reset();
  MOZ_ASSERT(!sTextCompositions || !sTextCompositions->Length());
  delete sTextCompositions;
  sTextCompositions = nullptr;
  // All string instances in the global space need to be empty after XPCOM
  // shutdown.
  sActiveChildInputContext.ShutDown();
}

// static
void IMEStateManager::OnFocusMovedBetweenBrowsers(BrowserParent* aBlur,
                                                  BrowserParent* aFocus) {
  MOZ_ASSERT(aBlur != aFocus);
  MOZ_ASSERT(XRE_IsParentProcess());

  if (sPendingFocusedBrowserSwitchingData.isSome()) {
    MOZ_ASSERT(aBlur ==
               sPendingFocusedBrowserSwitchingData.ref().mBrowserParentFocused);
    // If focus is not changed between browsers actually, we need to do
    // nothing here.  Let's cancel handling what this method does.
    if (sPendingFocusedBrowserSwitchingData.ref().mBrowserParentBlurred ==
        aFocus) {
      sPendingFocusedBrowserSwitchingData.reset();
      MOZ_LOG(sISMLog, LogLevel::Info,
              ("  OnFocusMovedBetweenBrowsers(), canceled all pending focus "
               "moves between browsers"));
      return;
    }
    aBlur = sPendingFocusedBrowserSwitchingData.ref().mBrowserParentBlurred;
    sPendingFocusedBrowserSwitchingData.ref().mBrowserParentFocused = aFocus;
    MOZ_ASSERT(aBlur != aFocus);
  }

  // If application was inactive, but is now activated, and the last focused
  // this is called by BrowserParent::UnsetTopLevelWebFocusAll() from
  // nsFocusManager::WindowRaised().  If a content has focus in a remote
  // process and it has composition, it may get focus back later and the
  // composition shouldn't be commited now.  Therefore, we should put off to
  // handle this until getting another call of this method or a call of
  //`OnFocusChangeInternal()`.
  if (aBlur && !aFocus && !sIsActive && sTextInputHandlingWidget &&
      sTextCompositions &&
      sTextCompositions->GetCompositionFor(sTextInputHandlingWidget)) {
    if (sPendingFocusedBrowserSwitchingData.isNothing()) {
      sPendingFocusedBrowserSwitchingData.emplace(aBlur, aFocus);
    }
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnFocusMovedBetweenBrowsers(), put off to handle it until "
             "next OnFocusChangeInternal() call"));
    return;
  }
  sPendingFocusedBrowserSwitchingData.reset();

  const nsCOMPtr<nsIWidget> oldWidget = sTextInputHandlingWidget;
  // In the chrome-process case, we'll get sTextInputHandlingWidget from a
  // PresShell later.
  sTextInputHandlingWidget =
      aFocus ? nsCOMPtr<nsIWidget>(aFocus->GetTextInputHandlingWidget()).get()
             : nullptr;
  if (oldWidget && sTextCompositions) {
    RefPtr<TextComposition> composition =
        sTextCompositions->GetCompositionFor(oldWidget);
    if (composition) {
      MOZ_LOG(
          sISMLog, LogLevel::Debug,
          ("  OnFocusMovedBetweenBrowsers(), requesting to commit "
           "composition to "
           "the (previous) focused widget (would request=%s)",
           GetBoolName(
               !oldWidget->IMENotificationRequestsRef().WantDuringDeactive())));
      NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, oldWidget,
                composition->GetBrowserParent());
    }
  }

  // The manager check is to avoid telling the content process to stop
  // IME state management after focus has already moved there between
  // two same-process-hosted out-of-process iframes.
  if (aBlur && (!aFocus || (aBlur->Manager() != aFocus->Manager()))) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnFocusMovedBetweenBrowsers(), notifying previous "
             "focused child process of parent process or another child process "
             "getting focus"));
    aBlur->StopIMEStateManagement();
  }

  if (sActiveIMEContentObserver) {
    DestroyIMEContentObserver();
  }

  if (sFocusedIMEWidget) {
    // sFocusedIMEBrowserParent can be null, if IME focus hasn't been
    // taken before BrowserParent blur.
    // aBlur can be null when keyboard focus moves not actually
    // between tabs but an open menu is involved.
    MOZ_ASSERT(!sFocusedIMEBrowserParent || !aBlur ||
               (sFocusedIMEBrowserParent == aBlur));
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnFocusMovedBetweenBrowsers(), notifying IME of blur"));
    NotifyIME(NOTIFY_IME_OF_BLUR, sFocusedIMEWidget, sFocusedIMEBrowserParent);

    MOZ_ASSERT(!sFocusedIMEBrowserParent);
    MOZ_ASSERT(!sFocusedIMEWidget);

  } else {
    MOZ_ASSERT(!sFocusedIMEBrowserParent);
  }

  // We deliberately don't null out sFocusedElement or sFocusedPresContext here.
  // When focus is in remote content, as far as layout in the chrome process is
  // concerned, the corresponding content is the top-level XUL browser. Changes
  // among out-of-process iframes don't change that, so dropping the pointer to
  // the XUL browser upon such a change would break IME handling.
}

// static
void IMEStateManager::WidgetDestroyed(nsIWidget* aWidget) {
  MOZ_LOG(sISMLog, LogLevel::Debug,
          ("WidgetDestroyed(aWidget=0x%p), sFocusedIMEWidget=0x%p, "
           "sActiveInputContextWidget=0x%p, sFocusedIMEBrowserParent=0x%p",
           aWidget, sFocusedIMEWidget, sActiveInputContextWidget,
           sFocusedIMEBrowserParent.get()));
  if (sTextInputHandlingWidget == aWidget) {
    sTextInputHandlingWidget = nullptr;
  }
  if (sFocusedIMEWidget == aWidget) {
    if (sFocusedIMEBrowserParent) {
      OnFocusMovedBetweenBrowsers(sFocusedIMEBrowserParent, nullptr);
      MOZ_ASSERT(!sFocusedIMEBrowserParent);
    }
    sFocusedIMEWidget = nullptr;
  }
  if (sActiveInputContextWidget == aWidget) {
    sActiveInputContextWidget = nullptr;
  }
}

// static
void IMEStateManager::WidgetOnQuit(nsIWidget* aWidget) {
  if (sFocusedIMEWidget == aWidget) {
    MOZ_LOG(
        sISMLog, LogLevel::Debug,
        ("WidgetOnQuit(aWidget=0x%p (available %s)), sFocusedIMEWidget=0x%p",
         aWidget, GetBoolName(aWidget && !aWidget->Destroyed()),
         sFocusedIMEWidget));
    // Notify IME of blur (which is done by IMEContentObserver::Destroy
    // automatically) when the widget still has IME focus before forgetting the
    // focused widget because the focused widget is required to clean up native
    // IME handler with sending blur notification.  Fortunately, the widget
    // has not been destroyed yet here since some methods to sending blur
    // notification won't work with destroyed widget.
    IMEStateManager::DestroyIMEContentObserver();
    // Finally, clean up the widget and related objects for avoiding to leak.
    IMEStateManager::WidgetDestroyed(aWidget);
  }
}

// static
void IMEStateManager::StopIMEStateManagement() {
  MOZ_ASSERT(XRE_IsContentProcess());
  MOZ_LOG(sISMLog, LogLevel::Info, ("StopIMEStateManagement()"));

  // NOTE: Don't set input context from here since this has already lost
  //       the rights to change input context.

  // The requestee of this method in the main process must destroy its
  // active IMEContentObserver for making existing composition end and
  // make it be possible to start new composition in new focused process.
  // Therefore, we shouldn't notify the main process of any changes which
  // occurred after here.
  AutoRestore<bool> restoreStoppingIMEStateManagementState(
      sCleaningUpForStoppingIMEStateManagement);
  sCleaningUpForStoppingIMEStateManagement = true;

  if (sTextCompositions && sFocusedPresContext) {
    NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, sFocusedPresContext, nullptr);
  }
  sActiveInputContextWidget = nullptr;
  sFocusedPresContext = nullptr;
  sFocusedElement = nullptr;
  sIsActive = false;
  DestroyIMEContentObserver();
}

// static
void IMEStateManager::MaybeStartOffsetUpdatedInChild(nsIWidget* aWidget,
                                                     uint32_t aStartOffset) {
  if (NS_WARN_IF(!sTextCompositions)) {
    MOZ_LOG(sISMLog, LogLevel::Warning,
            ("MaybeStartOffsetUpdatedInChild(aWidget=0x%p, aStartOffset=%u), "
             "called when there is no composition",
             aWidget, aStartOffset));
    return;
  }

  TextComposition* const composition = GetTextCompositionFor(aWidget);
  if (NS_WARN_IF(!composition)) {
    MOZ_LOG(sISMLog, LogLevel::Warning,
            ("MaybeStartOffsetUpdatedInChild(aWidget=0x%p, aStartOffset=%u), "
             "called when there is no composition",
             aWidget, aStartOffset));
    return;
  }

  if (composition->NativeOffsetOfStartComposition() == aStartOffset) {
    return;
  }

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("MaybeStartOffsetUpdatedInChild(aWidget=0x%p, aStartOffset=%u), "
       "old offset=%u",
       aWidget, aStartOffset, composition->NativeOffsetOfStartComposition()));
  composition->OnStartOffsetUpdatedInChild(aStartOffset);
}

// static
nsresult IMEStateManager::OnDestroyPresContext(nsPresContext& aPresContext) {
  // First, if there is a composition in the aPresContext, clean up it.
  if (sTextCompositions) {
    TextCompositionArray::index_type i =
        sTextCompositions->IndexOf(&aPresContext);
    if (i != TextCompositionArray::NoIndex) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  OnDestroyPresContext(), "
               "removing TextComposition instance from the array (index=%zu)",
               i));
      // there should be only one composition per presContext object.
      sTextCompositions->ElementAt(i)->Destroy();
      sTextCompositions->RemoveElementAt(i);
      if (sTextCompositions->IndexOf(&aPresContext) !=
          TextCompositionArray::NoIndex) {
        MOZ_LOG(sISMLog, LogLevel::Error,
                ("  OnDestroyPresContext(), FAILED to remove "
                 "TextComposition instance from the array"));
        MOZ_CRASH("Failed to remove TextComposition instance from the array");
      }
    }
  }

  if (&aPresContext != sFocusedPresContext) {
    return NS_OK;
  }

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("OnDestroyPresContext(aPresContext=0x%p), "
       "sFocusedPresContext=0x%p, sFocusedElement=0x%p, sTextCompositions=0x%p",
       &aPresContext, sFocusedPresContext.get(), sFocusedElement.get(),
       sTextCompositions));

  DestroyIMEContentObserver();

  if (sTextInputHandlingWidget) {
    IMEState newState = GetNewIMEState(*sFocusedPresContext, nullptr);
    InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                              InputContextAction::LOST_FOCUS);
    InputContext::Origin origin =
        BrowserParent::GetFocused() ? InputContext::ORIGIN_CONTENT : sOrigin;
    OwningNonNull<nsIWidget> textInputHandlingWidget =
        *sTextInputHandlingWidget;
    SetIMEState(newState, nullptr, nullptr, textInputHandlingWidget, action,
                origin);
  }
  sTextInputHandlingWidget = nullptr;
  sFocusedElement = nullptr;
  sFocusedPresContext = nullptr;
  return NS_OK;
}

// static
nsresult IMEStateManager::OnRemoveContent(nsPresContext& aPresContext,
                                          Element& aElement) {
  // First, if there is a composition in the aElement, clean up it.
  if (sTextCompositions) {
    const RefPtr<TextComposition> compositionInContent =
        sTextCompositions->GetCompositionInContent(&aPresContext, &aElement);

    if (compositionInContent) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  OnRemoveContent(), "
               "composition is in the content"));

      // Try resetting the native IME state.  Be aware, typically, this method
      // is called during the content being removed.  Then, the native
      // composition events which are caused by following APIs are ignored due
      // to unsafe to run script (in PresShell::HandleEvent()).
      nsresult rv =
          compositionInContent->NotifyIME(REQUEST_TO_CANCEL_COMPOSITION);
      if (NS_FAILED(rv)) {
        compositionInContent->NotifyIME(REQUEST_TO_COMMIT_COMPOSITION);
      }
    }
  }

  if (!sFocusedPresContext || !sFocusedElement ||
      !sFocusedElement->IsInclusiveDescendantOf(&aElement)) {
    return NS_OK;
  }
  MOZ_ASSERT(sFocusedPresContext == &aPresContext);

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("OnRemoveContent(aPresContext=0x%p, aElement=0x%p), "
       "sFocusedPresContext=0x%p, sFocusedElement=0x%p, sTextCompositions=0x%p",
       &aPresContext, &aElement, sFocusedPresContext.get(),
       sFocusedElement.get(), sTextCompositions));

  DestroyIMEContentObserver();

  // FYI: Don't clear sTextInputHandlingWidget and sFocusedPresContext because
  // the window/document keeps having focus.
  sFocusedElement = nullptr;

  // Current IME transaction should commit
  if (!sTextInputHandlingWidget) {
    return NS_OK;
  }

  IMEState newState = GetNewIMEState(*sFocusedPresContext, nullptr);
  InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                            InputContextAction::LOST_FOCUS);
  InputContext::Origin origin =
      BrowserParent::GetFocused() ? InputContext::ORIGIN_CONTENT : sOrigin;
  OwningNonNull<nsIWidget> textInputHandlingWidget = *sTextInputHandlingWidget;
  SetIMEState(newState, &aPresContext, nullptr, textInputHandlingWidget, action,
              origin);
  if (sFocusedPresContext != &aPresContext || sFocusedElement) {
    return NS_OK;  // Some body must have set focus
  }

  if (IsIMEObserverNeeded(newState)) {
    if (RefPtr<HTMLEditor> htmlEditor =
            nsContentUtils::GetHTMLEditor(&aPresContext)) {
      CreateIMEContentObserver(*htmlEditor, nullptr);
    }
  }

  return NS_OK;
}

// static
bool IMEStateManager::CanHandleWith(const nsPresContext* aPresContext) {
  return aPresContext && aPresContext->GetPresShell() &&
         !aPresContext->PresShell()->IsDestroying();
}

// static
nsresult IMEStateManager::OnChangeFocus(nsPresContext* aPresContext,
                                        Element* aElement,
                                        InputContextAction::Cause aCause) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnChangeFocus(aPresContext=0x%p, aElement=0x%p, aCause=%s)",
           aPresContext, aElement, ToString(aCause).c_str()));

  InputContextAction action(aCause);
  return OnChangeFocusInternal(aPresContext, aElement, action);
}

// static
nsresult IMEStateManager::OnChangeFocusInternal(nsPresContext* aPresContext,
                                                Element* aElement,
                                                InputContextAction aAction) {
  NS_ASSERTION(!aElement || aElement->GetPresContext(
                                Element::PresContextFor::eForComposedDoc) ==
                                aPresContext,
               "aPresContext does not match with one of aElement");

  bool remoteHasFocus = EventStateManager::IsRemoteTarget(aElement);
  // If we've handled focused content, we were inactive but now active,
  // a remote process has focus, and setting focus to same content in the main
  // process, it means that we're restoring focus without changing DOM focus
  // both in the main process and the remote process.
  const bool restoringContextForRemoteContent =
      XRE_IsParentProcess() && remoteHasFocus && !sIsActive && aPresContext &&
      sFocusedPresContext && sFocusedElement &&
      sFocusedPresContext.get() == aPresContext &&
      sFocusedElement.get() == aElement &&
      aAction.mFocusChange != InputContextAction::MENU_GOT_PSEUDO_FOCUS;

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("OnChangeFocusInternal(aPresContext=0x%p (available: %s), "
       "aElement=0x%p (remote: %s), aAction={ mCause=%s, "
       "mFocusChange=%s }), sFocusedPresContext=0x%p (available: %s), "
       "sFocusedElement=0x%p, sTextInputHandlingWidget=0x%p (available: %s), "
       "BrowserParent::GetFocused()=0x%p, sActiveIMEContentObserver=0x%p, "
       "sInstalledMenuKeyboardListener=%s, sIsActive=%s, "
       "restoringContextForRemoteContent=%s",
       aPresContext, GetBoolName(CanHandleWith(aPresContext)), aElement,
       GetBoolName(remoteHasFocus), ToString(aAction.mCause).c_str(),
       ToString(aAction.mFocusChange).c_str(), sFocusedPresContext.get(),
       GetBoolName(CanHandleWith(sFocusedPresContext)), sFocusedElement.get(),
       sTextInputHandlingWidget,
       GetBoolName(sTextInputHandlingWidget &&
                   !sTextInputHandlingWidget->Destroyed()),
       BrowserParent::GetFocused(), sActiveIMEContentObserver.get(),
       GetBoolName(sInstalledMenuKeyboardListener), GetBoolName(sIsActive),
       GetBoolName(restoringContextForRemoteContent)));

  sIsActive = !!aPresContext;
  if (sPendingFocusedBrowserSwitchingData.isSome()) {
    MOZ_ASSERT(XRE_IsParentProcess());
    RefPtr<Element> focusedElement = sFocusedElement;
    RefPtr<nsPresContext> focusedPresContext = sFocusedPresContext;
    RefPtr<BrowserParent> browserParentBlurred =
        sPendingFocusedBrowserSwitchingData.ref().mBrowserParentBlurred;
    RefPtr<BrowserParent> browserParentFocused =
        sPendingFocusedBrowserSwitchingData.ref().mBrowserParentFocused;
    OnFocusMovedBetweenBrowsers(browserParentBlurred, browserParentFocused);
    // If another call of this method happens during the
    // OnFocusMovedBetweenBrowsers call, we shouldn't take back focus to
    // the old one.
    if (focusedElement != sFocusedElement.get() ||
        focusedPresContext != sFocusedPresContext.get()) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  OnChangeFocusInternal(aPresContext=0x%p, aElement=0x%p) "
               "stoped handling it because the focused content was changed to "
               "sFocusedPresContext=0x%p, sFocusedElement=0x%p by another call",
               aPresContext, aElement, sFocusedPresContext.get(),
               sFocusedElement.get()));
      return NS_OK;
    }
  }

  // If new aPresShell has been destroyed, this should handle the focus change
  // as nobody is getting focus.
  MOZ_ASSERT_IF(!aPresContext, !aElement);
  if (NS_WARN_IF(aPresContext && !CanHandleWith(aPresContext))) {
    MOZ_LOG(sISMLog, LogLevel::Warning,
            ("  OnChangeFocusInternal(), called with destroyed PresShell, "
             "handling this call as nobody getting focus"));
    aPresContext = nullptr;
    aElement = nullptr;
  } else if (!aPresContext) {
    aElement = nullptr;
  }

  const nsCOMPtr<nsIWidget> oldWidget = sTextInputHandlingWidget;
  const nsCOMPtr<nsIWidget> newWidget =
      aPresContext ? aPresContext->GetTextInputHandlingWidget() : nullptr;
  const bool focusActuallyChanging =
      (sFocusedElement != aElement || sFocusedPresContext != aPresContext ||
       oldWidget != newWidget ||
       (remoteHasFocus && !restoringContextForRemoteContent &&
        (aAction.mFocusChange != InputContextAction::MENU_GOT_PSEUDO_FOCUS)));

  // If old widget has composition, we may need to commit composition since
  // a native IME context is shared on all editors on some widgets or all
  // widgets (it depends on platforms).
  if (oldWidget && focusActuallyChanging && sTextCompositions) {
    RefPtr<TextComposition> composition =
        sTextCompositions->GetCompositionFor(oldWidget);
    if (composition) {
      // However, don't commit the composition if we're being inactivated
      // but the composition should be kept even during deactive.
      // Note that oldWidget and sFocusedIMEWidget may be different here (in
      // such case, sFocusedIMEWidget is perhaps nullptr).  For example, IME
      // may receive only blur notification but still has composition.
      // We need to clean up only the oldWidget's composition state here.
      if (aPresContext ||
          !oldWidget->IMENotificationRequestsRef().WantDuringDeactive()) {
        MOZ_LOG(
            sISMLog, LogLevel::Info,
            ("  OnChangeFocusInternal(), requesting to commit composition to "
             "the (previous) focused widget"));
        NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, oldWidget,
                  composition->GetBrowserParent());
      }
    }
  }

  if (sActiveIMEContentObserver) {
    MOZ_ASSERT(!remoteHasFocus || XRE_IsContentProcess(),
               "IMEContentObserver should have been destroyed by "
               "OnFocusMovedBetweenBrowsers.");
    if (!aPresContext) {
      if (!sActiveIMEContentObserver->KeepAliveDuringDeactive()) {
        DestroyIMEContentObserver();
      }
    }
    // Otherwise, i.e., new focused content is in this process, let's check
    // whether the editable content for aElement has already been being observed
    // by the active IMEContentObserver.  If not, let's stop observing the
    // editable content which is being blurred.
    else if (!sActiveIMEContentObserver->IsObserving(*aPresContext, aElement)) {
      DestroyIMEContentObserver();
    }
  }

  if (!aPresContext) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnChangeFocusInternal(), no nsPresContext is being activated"));
    return NS_OK;
  }

  if (NS_WARN_IF(!newWidget)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  OnChangeFocusInternal(), FAILED due to no widget to manage its "
             "IME state"));
    return NS_OK;
  }

  // Update the cached widget since root view of the presContext may be
  // changed to different view.
  sTextInputHandlingWidget = newWidget;

  // If a child process has focus, we should disable IME state until the child
  // process actually gets focus because if user types keys before that they
  // are handled by IME.
  IMEState newState = remoteHasFocus ? IMEState(IMEEnabled::Disabled)
                                     : GetNewIMEState(*aPresContext, aElement);
  bool setIMEState = true;

  if (remoteHasFocus && XRE_IsParentProcess()) {
    if (aAction.mFocusChange == InputContextAction::MENU_GOT_PSEUDO_FOCUS) {
      // If menu keyboard listener is installed, we need to disable IME now.
      setIMEState = true;
    } else if (aAction.mFocusChange ==
               InputContextAction::MENU_LOST_PSEUDO_FOCUS) {
      // If menu keyboard listener is uninstalled, we need to restore
      // input context which was set by the remote process.  However, if
      // the remote process hasn't been set input context yet, we need to
      // wait next SetInputContextForChildProcess() call.
      if (HasActiveChildSetInputContext()) {
        setIMEState = true;
        newState = sActiveChildInputContext.mIMEState;
      } else {
        setIMEState = false;
      }
    } else if (focusActuallyChanging) {
      InputContext context = newWidget->GetInputContext();
      if (context.mIMEState.mEnabled == IMEEnabled::Disabled &&
          context.mOrigin == InputContext::ORIGIN_CONTENT) {
        setIMEState = false;
        MOZ_LOG(sISMLog, LogLevel::Debug,
                ("  OnChangeFocusInternal(), doesn't set IME state because "
                 "focused element (or document) is in a child process and the "
                 "IME state is already disabled by a remote process"));
      } else {
        // When new remote process gets focus, we should forget input context
        // coming from old focused remote process.
        ResetActiveChildInputContext();
        MOZ_LOG(sISMLog, LogLevel::Debug,
                ("  OnChangeFocusInternal(), will disable IME until new "
                 "focused element (or document) in the child process will get "
                 "focus actually"));
      }
    } else if (newWidget->GetInputContext().mOrigin !=
               InputContext::ORIGIN_MAIN) {
      // When focus is NOT changed actually, we shouldn't set IME state if
      // current input context was set by a remote process since that means
      // that the window is being activated and the child process may have
      // composition.  Then, we shouldn't commit the composition with making
      // IME state disabled.
      setIMEState = false;
      MOZ_LOG(
          sISMLog, LogLevel::Debug,
          ("  OnChangeFocusInternal(), doesn't set IME state because focused "
           "element (or document) is already in the child process"));
    }
  } else {
    // When this process gets focus, we should forget input context coming
    // from remote process.
    ResetActiveChildInputContext();
  }

  if (setIMEState) {
    if (!focusActuallyChanging) {
      // actual focus isn't changing, but if IME enabled state is changing,
      // we should do it.
      InputContext context = newWidget->GetInputContext();
      if (context.mIMEState.mEnabled == newState.mEnabled) {
        MOZ_LOG(sISMLog, LogLevel::Debug,
                ("  OnChangeFocusInternal(), neither focus nor IME state is "
                 "changing"));
        return NS_OK;
      }
      aAction.mFocusChange = InputContextAction::FOCUS_NOT_CHANGED;

      // Even if focus isn't changing actually, we should commit current
      // composition here since the IME state is changing.
      if (sFocusedPresContext && oldWidget && !focusActuallyChanging) {
        NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, oldWidget,
                  sFocusedIMEBrowserParent);
      }
    } else if (aAction.mFocusChange == InputContextAction::FOCUS_NOT_CHANGED) {
      // If aElement isn't null or aElement is null but editable, somebody gets
      // focus.
      bool gotFocus = aElement || (newState.mEnabled == IMEEnabled::Enabled);
      aAction.mFocusChange = gotFocus ? InputContextAction::GOT_FOCUS
                                      : InputContextAction::LOST_FOCUS;
    }

    if (remoteHasFocus && HasActiveChildSetInputContext() &&
        aAction.mFocusChange == InputContextAction::MENU_LOST_PSEUDO_FOCUS) {
      // Restore the input context in the active remote process when
      // menu keyboard listener is uninstalled and active remote tab has
      // focus.
      SetInputContext(*newWidget, sActiveChildInputContext, aAction);
    } else {
      // Update IME state for new focus widget
      SetIMEState(newState, aPresContext, aElement, *newWidget, aAction,
                  remoteHasFocus ? InputContext::ORIGIN_CONTENT : sOrigin);
    }
  }

  sFocusedPresContext = aPresContext;
  sFocusedElement = aElement;

  // Don't call CreateIMEContentObserver() here  because it will be called from
  // the focus event handler of focused editor.

  MOZ_LOG(sISMLog, LogLevel::Debug,
          ("  OnChangeFocusInternal(), modified IME state for "
           "sFocusedPresContext=0x%p, sFocusedElement=0x%p",
           sFocusedPresContext.get(), sFocusedElement.get()));

  return NS_OK;
}

// static
void IMEStateManager::OnInstalledMenuKeyboardListener(bool aInstalling) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("OnInstalledMenuKeyboardListener(aInstalling=%s), "
       "nsContentUtils::IsSafeToRunScript()=%s, "
       "sInstalledMenuKeyboardListener=%s, BrowserParent::GetFocused()=0x%p, "
       "sActiveChildInputContext=%s, sFocusedPresContext=0x%p, "
       "sFocusedElement=0x%p, sPseudoFocusChangeRunnable=0x%p",
       GetBoolName(aInstalling),
       GetBoolName(nsContentUtils::IsSafeToRunScript()),
       GetBoolName(sInstalledMenuKeyboardListener), BrowserParent::GetFocused(),
       ToString(sActiveChildInputContext).c_str(), sFocusedPresContext.get(),
       sFocusedElement.get(), sPseudoFocusChangeRunnable.get()));

  // Update the state whether the menubar has pseudo focus or not immediately.
  // This will be referred by the runner which is created below.
  sInstalledMenuKeyboardListener = aInstalling;
  // However, this may be called when it's not safe to run script.  Therefore,
  // we need to create a runnable to notify IME of the pseudo focus change.
  if (sPseudoFocusChangeRunnable) {
    return;
  }
  sPseudoFocusChangeRunnable = new PseudoFocusChangeRunnable(aInstalling);
  nsContentUtils::AddScriptRunner(sPseudoFocusChangeRunnable);
}

// static
void IMEStateManager::SetMenubarPseudoFocus(
    PseudoFocusChangeRunnable* aCaller, bool aSetPseudoFocus,
    nsPresContext* aFocusedPresContextAtRequested) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("SetMenubarPseudoFocus(aCaller=0x%p, aSetPseudoFocus=%s, "
       "aFocusedPresContextAtRequested=0x%p), "
       "sInstalledMenuKeyboardListener=%s, sFocusedPresContext=0x%p, "
       "sFocusedElement=0x%p, sPseudoFocusChangeRunnable=0x%p",
       aCaller, GetBoolName(aSetPseudoFocus), aFocusedPresContextAtRequested,
       GetBoolName(sInstalledMenuKeyboardListener), sFocusedPresContext.get(),
       sFocusedElement.get(), sPseudoFocusChangeRunnable.get()));

  MOZ_ASSERT(sPseudoFocusChangeRunnable.get() == aCaller);

  // Clear the runnable first for nested call of
  // OnInstalledMenuKeyboardListener().
  RefPtr<PseudoFocusChangeRunnable> runningOne =
      sPseudoFocusChangeRunnable.forget();
  MOZ_ASSERT(!sPseudoFocusChangeRunnable);

  // If the requested state is still same, let's make the menubar get
  // pseudo focus with the latest focused PresContext and Element.
  // Note that this is no problem even after the focused element is changed
  // after aCaller is created because only sInstalledMenuKeyboardListener
  // manages the state and current focused PresContext and element should be
  // used only for restoring the focus from the menubar.  So, restoring
  // focus with the lasted one does make sense.
  if (sInstalledMenuKeyboardListener == aSetPseudoFocus) {
    InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                              aSetPseudoFocus
                                  ? InputContextAction::MENU_GOT_PSEUDO_FOCUS
                                  : InputContextAction::MENU_LOST_PSEUDO_FOCUS);
    RefPtr<nsPresContext> focusedPresContext = sFocusedPresContext;
    RefPtr<Element> focusedElement = sFocusedElement;
    OnChangeFocusInternal(focusedPresContext, focusedElement, action);
    return;
  }

  // If the requested state is different from current state, we don't need to
  // make the menubar get and lose pseudo focus because of redundant. However,
  // if there is a composition on the original focused element, we need to
  // commit it because pseudo focus move should've caused it.
  if (!aFocusedPresContextAtRequested) {
    return;
  }
  RefPtr<TextComposition> composition =
      GetTextCompositionFor(aFocusedPresContextAtRequested);
  if (!composition) {
    return;
  }
  if (nsCOMPtr<nsIWidget> widget =
          aFocusedPresContextAtRequested->GetTextInputHandlingWidget()) {
    composition->RequestToCommit(widget, false);
  }
}

// static
bool IMEStateManager::OnMouseButtonEventInEditor(
    nsPresContext& aPresContext, Element* aElement,
    WidgetMouseEvent& aMouseEvent) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnMouseButtonEventInEditor(aPresContext=0x%p (available: %s), "
           "aElement=0x%p, aMouseEvent=0x%p), sFocusedPresContext=0x%p, "
           "sFocusedElement=0x%p",
           &aPresContext, GetBoolName(CanHandleWith(&aPresContext)), aElement,
           &aMouseEvent, sFocusedPresContext.get(), sFocusedElement.get()));

  if (sFocusedPresContext != &aPresContext || sFocusedElement != aElement) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnMouseButtonEventInEditor(), "
             "the mouse event isn't fired on the editor managed by ISM"));
    return false;
  }

  if (!sActiveIMEContentObserver) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnMouseButtonEventInEditor(), "
             "there is no active IMEContentObserver"));
    return false;
  }

  if (!sActiveIMEContentObserver->IsObserving(aPresContext, aElement)) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnMouseButtonEventInEditor(), "
             "the active IMEContentObserver isn't managing the editor"));
    return false;
  }

  OwningNonNull<IMEContentObserver> observer = *sActiveIMEContentObserver;
  bool consumed = observer->OnMouseButtonEvent(aPresContext, aMouseEvent);
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("  OnMouseButtonEventInEditor(), "
           "mouse event (mMessage=%s, mButton=%d) is %s",
           ToChar(aMouseEvent.mMessage), aMouseEvent.mButton,
           consumed ? "consumed" : "not consumed"));
  return consumed;
}

// static
void IMEStateManager::OnClickInEditor(nsPresContext& aPresContext,
                                      Element* aElement,
                                      const WidgetMouseEvent& aMouseEvent) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnClickInEditor(aPresContext=0x%p (available: %s), aElement=0x%p, "
           "aMouseEvent=0x%p), sFocusedPresContext=0x%p, sFocusedElement=0x%p, "
           "sTextInputHandlingWidget=0x%p (available: %s)",
           &aPresContext, GetBoolName(CanHandleWith(&aPresContext)), aElement,
           &aMouseEvent, sFocusedPresContext.get(), sFocusedElement.get(),
           sTextInputHandlingWidget,
           GetBoolName(sTextInputHandlingWidget &&
                       !sTextInputHandlingWidget->Destroyed())));

  if (sFocusedPresContext != &aPresContext || sFocusedElement != aElement ||
      NS_WARN_IF(!sFocusedPresContext) ||
      NS_WARN_IF(!sTextInputHandlingWidget) ||
      NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnClickInEditor(), "
             "the mouse event isn't fired on the editor managed by ISM"));
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;
  MOZ_ASSERT_IF(sFocusedPresContext->GetTextInputHandlingWidget(),
                sFocusedPresContext->GetTextInputHandlingWidget() ==
                    textInputHandlingWidget.get());

  if (!aMouseEvent.IsTrusted()) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnClickInEditor(), "
             "the mouse event isn't a trusted event"));
    return;  // ignore untrusted event.
  }

  if (aMouseEvent.mButton) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnClickInEditor(), "
             "the mouse event isn't a left mouse button event"));
    return;  // not a left click event.
  }

  if (aMouseEvent.mClickCount != 1) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnClickInEditor(), "
             "the mouse event isn't a single click event"));
    return;  // should notify only first click event.
  }

  MOZ_ASSERT_IF(aElement, !EventStateManager::IsRemoteTarget(aElement));
  InputContextAction::Cause cause =
      aMouseEvent.mInputSource == MouseEvent_Binding::MOZ_SOURCE_TOUCH
          ? InputContextAction::CAUSE_TOUCH
          : InputContextAction::CAUSE_MOUSE;

  InputContextAction action(cause, InputContextAction::FOCUS_NOT_CHANGED);
  IMEState newState = GetNewIMEState(aPresContext, aElement);
  // If the state is not editable, there should be no active IMEContentObserver.
  // However, if this click sets focus to the editor, IMEContentObserver may
  // have not been created yet.  Instead, if there is active IMEContentObserver,
  // it should be editable.
  MOZ_ASSERT_IF(!newState.IsEditable(), !sActiveIMEContentObserver);
  MOZ_ASSERT_IF(sActiveIMEContentObserver, newState.IsEditable());
  SetIMEState(newState, &aPresContext, aElement, textInputHandlingWidget,
              action, sOrigin);
}

// static
Element* IMEStateManager::GetFocusedElement() { return sFocusedElement; }

// static
bool IMEStateManager::IsFocusedElement(const nsPresContext& aPresContext,
                                       const Element* aFocusedElement) {
  if (!sFocusedPresContext || &aPresContext != sFocusedPresContext) {
    return false;
  }

  if (sFocusedElement == aFocusedElement) {
    return true;
  }

  // If sFocusedElement is not nullptr, but aFocusedElement is nullptr, it does
  // not have focus from point of view of IMEStateManager.
  if (sFocusedElement) {
    return false;
  }

  // If the caller does not think that nobody has focus, but we know there is
  // a focused content, the caller must be called with wrong content.
  if (!aFocusedElement) {
    return false;
  }

  // If the aFocusedElement is in design mode, sFocusedElement may be nullptr.
  if (aFocusedElement->IsInDesignMode()) {
    MOZ_ASSERT(&aPresContext == sFocusedPresContext && !sFocusedElement);
    return true;
  }

  // Otherwise, only when aFocusedElement is the root element, it can have
  // focus, but IMEStateManager::OnChangeFocus is called with nullptr for
  // aFocusedElement if it was not editable.
  // XXX In this case, should the caller update sFocusedElement?
  return aFocusedElement->IsEditable() && sFocusedPresContext->Document() &&
         sFocusedPresContext->Document()->GetRootElement() == aFocusedElement;
}

// static
void IMEStateManager::OnFocusInEditor(nsPresContext& aPresContext,
                                      Element* aElement,
                                      EditorBase& aEditorBase) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnFocusInEditor(aPresContext=0x%p (available: %s), aElement=0x%p, "
           "aEditorBase=0x%p), sFocusedPresContext=0x%p, sFocusedElement=0x%p, "
           "sActiveIMEContentObserver=0x%p",
           &aPresContext, GetBoolName(CanHandleWith(&aPresContext)), aElement,
           &aEditorBase, sFocusedPresContext.get(), sFocusedElement.get(),
           sActiveIMEContentObserver.get()));

  if (!IsFocusedElement(aPresContext, aElement)) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnFocusInEditor(), "
             "an editor not managed by ISM gets focus"));
    return;
  }
  MOZ_ASSERT(sTextInputHandlingWidget);

  // If the IMEContentObserver instance isn't observing the editable content for
  // aElement, we need to recreate the instance because the active observer is
  // observing different content even if aElement keeps being focused.  E.g.,
  // it's an <input> and editing host but was not a text control, but now, it's
  // a text control.
  if (sActiveIMEContentObserver) {
    if (sActiveIMEContentObserver->IsObserving(aPresContext, aElement)) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  OnFocusInEditor(), "
               "the editable content for aEditorBase has already been being "
               "observed by sActiveIMEContentObserver"));
      return;
    }
    // If the IMEContentObserver has not finished initializing itself yet,
    // we don't need to recreate it because the following
    // TryToFlushPendingNotifications call must make it initialized.
    const nsCOMPtr<nsIWidget> textInputHandlingWidget =
        sTextInputHandlingWidget;
    if (!sActiveIMEContentObserver->IsBeingInitializedFor(
            aPresContext, aElement, aEditorBase)) {
      DestroyIMEContentObserver();
    }
    if (NS_WARN_IF(!IsFocusedElement(aPresContext, aElement)) ||
        NS_WARN_IF(!sTextInputHandlingWidget) ||
        NS_WARN_IF(sTextInputHandlingWidget != textInputHandlingWidget)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  OnFocusInEditor(), detected unexpected focus change with "
               "re-initializing active IMEContentObserver"));
      return;
    }
  }

  if (!sActiveIMEContentObserver && sTextInputHandlingWidget &&
      IsIMEObserverNeeded(
          sTextInputHandlingWidget->GetInputContext().mIMEState)) {
    CreateIMEContentObserver(aEditorBase, aElement);
    if (sActiveIMEContentObserver) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  OnFocusInEditor(), new IMEContentObserver is created (0x%p)",
               sActiveIMEContentObserver.get()));
    }
  }

  if (sActiveIMEContentObserver) {
    sActiveIMEContentObserver->TryToFlushPendingNotifications(false);
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnFocusInEditor(), trying to send pending notifications in "
             "the active IMEContentObserver (0x%p)...",
             sActiveIMEContentObserver.get()));
  }
}

// static
void IMEStateManager::OnEditorInitialized(EditorBase& aEditorBase) {
  if (!sActiveIMEContentObserver ||
      !sActiveIMEContentObserver->WasInitializedWith(aEditorBase)) {
    return;
  }

  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnEditorInitialized(aEditorBase=0x%p)", &aEditorBase));

  sActiveIMEContentObserver->UnsuppressNotifyingIME();
}

// static
void IMEStateManager::OnEditorDestroying(EditorBase& aEditorBase) {
  if (!sActiveIMEContentObserver ||
      !sActiveIMEContentObserver->WasInitializedWith(aEditorBase)) {
    return;
  }

  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnEditorDestroying(aEditorBase=0x%p)", &aEditorBase));

  // The IMEContentObserver shouldn't notify IME of anything until reframing
  // is finished.
  sActiveIMEContentObserver->SuppressNotifyingIME();
}

void IMEStateManager::OnReFocus(nsPresContext& aPresContext,
                                Element& aElement) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("OnReFocus(aPresContext=0x%p (available: %s), aElement=0x%p), "
           "sActiveIMEContentObserver=0x%p, aElement=0x%p",
           &aPresContext, GetBoolName(CanHandleWith(&aPresContext)), &aElement,
           sActiveIMEContentObserver.get(), sFocusedElement.get()));

  if (NS_WARN_IF(!sTextInputHandlingWidget) ||
      NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    return;
  }

  // Check if IME has focus.  If and only if IME has focus, we may need to
  // update IME state of the widget to re-open VKB.  Otherwise, IME will open
  // VKB at getting focus.
  if (!sActiveIMEContentObserver ||
      !sActiveIMEContentObserver->IsObserving(aPresContext, &aElement)) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  OnReFocus(), editable content for aElement was not being "
             "observed by the sActiveIMEContentObserver"));
    return;
  }

  MOZ_ASSERT(&aElement == sFocusedElement.get());

  if (!UserActivation::IsHandlingUserInput() ||
      UserActivation::IsHandlingKeyboardInput()) {
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;

  // Don't update IME state during composition.
  if (sTextCompositions) {
    if (const TextComposition* composition =
            sTextCompositions->GetCompositionFor(textInputHandlingWidget)) {
      if (composition->IsComposing()) {
        return;
      }
    }
  }

  InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                            InputContextAction::FOCUS_NOT_CHANGED);
  IMEState newState = GetNewIMEState(aPresContext, &aElement);
  MOZ_ASSERT(newState.IsEditable());
  SetIMEState(newState, &aPresContext, &aElement, textInputHandlingWidget,
              action, sOrigin);
}

// static
void IMEStateManager::MaybeOnEditableStateDisabled(nsPresContext& aPresContext,
                                                   dom::Element* aElement) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("MaybeOnEditableStateDisabled(aPresContext=0x%p, aElement=0x%p), "
       "sFocusedPresContext=0x%p (available: %s), "
       "sFocusedElement=0x%p, sTextInputHandlingWidget=0x%p (available: %s), "
       "sActiveIMEContentObserver=0x%p, sIsGettingNewIMEState=%s",
       &aPresContext, aElement, sFocusedPresContext.get(),
       GetBoolName(CanHandleWith(sFocusedPresContext)), sFocusedElement.get(),
       sTextInputHandlingWidget,
       GetBoolName(sTextInputHandlingWidget &&
                   !sTextInputHandlingWidget->Destroyed()),
       sActiveIMEContentObserver.get(), GetBoolName(sIsGettingNewIMEState)));

  if (sIsGettingNewIMEState) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  MaybeOnEditableStateDisabled(), "
             "does nothing because of called while getting new IME state"));
    return;
  }

  if (&aPresContext != sFocusedPresContext || aElement != sFocusedElement) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  MaybeOnEditableStateDisabled(), "
             "does nothing because of another element already has focus"));
    return;
  }

  if (NS_WARN_IF(!sTextInputHandlingWidget) ||
      NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  MaybeOnEditableStateDisabled(), FAILED due to "
             "the widget for the managing the nsPresContext has gone"));
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;
  MOZ_ASSERT_IF(sFocusedPresContext->GetTextInputHandlingWidget(),
                sFocusedPresContext->GetTextInputHandlingWidget() ==
                    textInputHandlingWidget.get());

  const IMEState newIMEState = GetNewIMEState(aPresContext, aElement);
  // If IME state becomes editable, HTMLEditor should also be initialized with
  // same path as it gets focus.  Therefore, IMEStateManager::UpdateIMEState
  // should be called by HTMLEditor instead.
  if (newIMEState.IsEditable()) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  MaybeOnEditableStateDisabled(), "
             "does nothing because IME state does not become disabled"));
    return;
  }

  // Otherwise, disable IME on the widget and destroy active IMEContentObserver
  // if there is.
  const InputContext inputContext = textInputHandlingWidget->GetInputContext();
  if (inputContext.mIMEState.mEnabled == newIMEState.mEnabled) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  MaybeOnEditableStateDisabled(), "
             "does nothing because IME state is not changed"));
    return;
  }

  if (sActiveIMEContentObserver) {
    DestroyIMEContentObserver();
  }

  InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                            InputContextAction::FOCUS_NOT_CHANGED);
  SetIMEState(newIMEState, &aPresContext, aElement, textInputHandlingWidget,
              action, sOrigin);
}

// static
void IMEStateManager::UpdateIMEState(const IMEState& aNewIMEState,
                                     Element* aElement, EditorBase& aEditorBase,
                                     const UpdateIMEStateOptions& aOptions) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("UpdateIMEState(aNewIMEState=%s, aElement=0x%p, aEditorBase=0x%p, "
       "aOptions=0x%0x), sFocusedPresContext=0x%p (available: %s), "
       "sFocusedElement=0x%p, sTextInputHandlingWidget=0x%p (available: %s), "
       "sActiveIMEContentObserver=0x%p, sIsGettingNewIMEState=%s",
       ToString(aNewIMEState).c_str(), aElement, &aEditorBase,
       aOptions.serialize(), sFocusedPresContext.get(),
       GetBoolName(CanHandleWith(sFocusedPresContext)), sFocusedElement.get(),
       sTextInputHandlingWidget,
       GetBoolName(sTextInputHandlingWidget &&
                   !sTextInputHandlingWidget->Destroyed()),
       sActiveIMEContentObserver.get(), GetBoolName(sIsGettingNewIMEState)));

  if (sIsGettingNewIMEState) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  UpdateIMEState(), "
             "does nothing because of called while getting new IME state"));
    return;
  }

  RefPtr<PresShell> presShell(aEditorBase.GetPresShell());
  if (NS_WARN_IF(!presShell)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  UpdateIMEState(), FAILED due to "
             "editor doesn't have PresShell"));
    return;
  }

  const RefPtr<nsPresContext> presContext =
      aElement
          ? aElement->GetPresContext(Element::PresContextFor::eForComposedDoc)
          : aEditorBase.GetPresContext();
  if (NS_WARN_IF(!presContext)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  UpdateIMEState(), FAILED due to "
             "editor doesn't have PresContext"));
    return;
  }

  // IMEStateManager::UpdateIMEState() should be called after
  // IMEStateManager::OnChangeFocus() is called for setting focus to aElement
  // and aEditorBase.  However, when aEditorBase is an HTMLEditor, this may be
  // called by nsIEditor::PostCreate() before IMEStateManager::OnChangeFocus().
  // Similarly, when aEditorBase is a TextEditor, this may be called by
  // nsIEditor::SetFlags().  In such cases, this method should do nothing
  // because input context should be updated when
  // IMEStateManager::OnChangeFocus() is called later.
  if (sFocusedPresContext != presContext) {
    MOZ_LOG(sISMLog, LogLevel::Warning,
            ("  UpdateIMEState(), does nothing due to "
             "the editor hasn't managed by IMEStateManager yet"));
    return;
  }

  // If IMEStateManager doesn't manage any document, this cannot update IME
  // state of any widget.
  if (NS_WARN_IF(!sFocusedPresContext)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  UpdateIMEState(), FAILED due to "
             "no managing nsPresContext"));
    return;
  }

  if (NS_WARN_IF(!sTextInputHandlingWidget) ||
      NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  UpdateIMEState(), FAILED due to "
             "the widget for the managing nsPresContext has gone"));
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;
  MOZ_ASSERT_IF(sFocusedPresContext->GetTextInputHandlingWidget(),
                sFocusedPresContext->GetTextInputHandlingWidget() ==
                    textInputHandlingWidget.get());

  // TODO: Investigate if we could put off to initialize IMEContentObserver
  //       later because a lot of callers need to be marked as
  //       MOZ_CAN_RUN_SCRIPT otherwise.

  // If there is an active observer and we need an observer, we want to keep
  // using the observer as far as possible because it's already notified IME of
  // focus.  However, between the call of OnChangeFocus() and UpdateIMEState(),
  // focus and/or IME state may have been changed.  If so, we need to update
  // the observer for current situation.
  const bool hasActiveObserverAndNeedObserver =
      sActiveIMEContentObserver && IsIMEObserverNeeded(aNewIMEState);

  // If the active observer was not initialized with aEditorBase, it means
  // that the old editor lost focus but new editor gets focus **without**
  // focus move in the DOM tree.  This may happen with changing the type of
  // <input> element, etc.  In this case, we need to let IME know a focus move
  // with recreating IMEContentObserver because editable target has been
  // changed.
  const bool needToRecreateObserver =
      hasActiveObserverAndNeedObserver &&
      !sActiveIMEContentObserver->WasInitializedWith(aEditorBase);

  // If the active observer was initialized with same editor, we can/should
  // keep using it for avoiding to notify IME of a focus change.  However, we
  // may need to re-initialize it because it may have temporarily stopped
  // observing the content.
  if (hasActiveObserverAndNeedObserver && !needToRecreateObserver) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  UpdateIMEState(), try to reinitialize the active "
             "IMEContentObserver"));
    OwningNonNull<IMEContentObserver> contentObserver =
        *sActiveIMEContentObserver;
    OwningNonNull<nsPresContext> presContext = *sFocusedPresContext;
    if (!contentObserver->MaybeReinitialize(
            textInputHandlingWidget, presContext, aElement, aEditorBase)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), failed to reinitialize the active "
               "IMEContentObserver"));
    }
    if (NS_WARN_IF(textInputHandlingWidget->Destroyed())) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), widget has gone during re-initializing "
               "the active IMEContentObserver"));
      return;
    }
  }

  // If there is no active IMEContentObserver or it isn't observing the
  // editable content for aElement, we should recreate an observer.  E.g.,
  // aElement which is an editing host may have been changed from/to a text
  // control.
  const bool createNewObserver =
      IsIMEObserverNeeded(aNewIMEState) &&
      (!sActiveIMEContentObserver || needToRecreateObserver ||
       !sActiveIMEContentObserver->IsObserving(*sFocusedPresContext, aElement));
  // If we're recreating new IMEContentObserver or new state does not need
  // IMEContentObserver, destroy the active one.
  const bool destroyCurrentObserver =
      sActiveIMEContentObserver &&
      (createNewObserver || !IsIMEObserverNeeded(aNewIMEState));

  // If IME state is changed, e.g., from "enabled" or "password" to "disabled",
  // we cannot keep the composing state because the new "disabled" state does
  // not support composition, and also from "enabled" to "password" and vice
  // versa, IME may use different composing rules.  Therefore, for avoiding
  // IME to be confused, we should fix the composition first.
  const bool updateIMEState =
      aOptions.contains(UpdateIMEStateOption::ForceUpdate) ||
      (textInputHandlingWidget->GetInputContext().mIMEState.mEnabled !=
       aNewIMEState.mEnabled);
  if (NS_WARN_IF(textInputHandlingWidget->Destroyed())) {
    MOZ_LOG(
        sISMLog, LogLevel::Error,
        ("  UpdateIMEState(), widget has gone during getting input context"));
    return;
  }

  if (updateIMEState &&
      !aOptions.contains(UpdateIMEStateOption::DontCommitComposition)) {
    NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, textInputHandlingWidget,
              sFocusedIMEBrowserParent);
    if (NS_WARN_IF(textInputHandlingWidget->Destroyed())) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), widget has gone during committing "
               "composition"));
      return;
    }
    // FIXME: If committing composition changes IME state recursively, we should
    //        not keep updating IME state here.  However, how can we manage it?
    //        Is a generation of the state is required?
  }

  // Notify IME of blur first.
  if (destroyCurrentObserver) {
    DestroyIMEContentObserver();
    if (NS_WARN_IF(textInputHandlingWidget->Destroyed()) ||
        NS_WARN_IF(sTextInputHandlingWidget != textInputHandlingWidget)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), has set input context, but the widget is "
               "not focused"));
      return;
    }
  }

  // Then, notify our IME handler of new IME state.
  if (updateIMEState) {
    InputContextAction action(InputContextAction::CAUSE_UNKNOWN,
                              InputContextAction::FOCUS_NOT_CHANGED);
    RefPtr<nsPresContext> editorPresContext = aEditorBase.GetPresContext();
    if (NS_WARN_IF(!editorPresContext)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), nsPresContext for editor has already been "
               "lost"));
      return;
    }
    SetIMEState(aNewIMEState, editorPresContext, aElement,
                textInputHandlingWidget, action, sOrigin);
    if (NS_WARN_IF(textInputHandlingWidget->Destroyed()) ||
        NS_WARN_IF(sTextInputHandlingWidget != textInputHandlingWidget)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), has set input context, but the widget is "
               "not focused"));
      return;
    }
    if (NS_WARN_IF(
            sTextInputHandlingWidget->GetInputContext().mIMEState.mEnabled !=
            aNewIMEState.mEnabled)) {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), has set input context, but IME enabled "
               "state was overridden by somebody else"));
      return;
    }
  }

  NS_ASSERTION(IsFocusedElement(*presContext, aElement),
               "aElement does not match with sFocusedElement");

  // Finally, create new observer if required.
  if (createNewObserver) {
    if (!sActiveIMEContentObserver && sFocusedPresContext &&
        sTextInputHandlingWidget) {
      // XXX In this case, it might not be enough safe to notify IME of
      //     anything.  So, don't try to flush pending notifications of
      //     IMEContentObserver here.
      CreateIMEContentObserver(aEditorBase, aElement);
    } else {
      MOZ_LOG(sISMLog, LogLevel::Error,
              ("  UpdateIMEState(), wanted to create IMEContentObserver, but "
               "lost focus"));
    }
  }
}

// static
IMEState IMEStateManager::GetNewIMEState(const nsPresContext& aPresContext,
                                         Element* aElement) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("GetNewIMEState(aPresContext=0x%p, aElement=0x%p), "
       "sInstalledMenuKeyboardListener=%s",
       &aPresContext, aElement, GetBoolName(sInstalledMenuKeyboardListener)));

  if (!CanHandleWith(&aPresContext)) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  GetNewIMEState() returns IMEEnabled::Disabled because "
             "the nsPresContext has been destroyed"));
    return IMEState(IMEEnabled::Disabled);
  }

  // On Printing or Print Preview, we don't need IME.
  if (aPresContext.Type() == nsPresContext::eContext_PrintPreview ||
      aPresContext.Type() == nsPresContext::eContext_Print) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  GetNewIMEState() returns IMEEnabled::Disabled because "
             "the nsPresContext is for print or print preview"));
    return IMEState(IMEEnabled::Disabled);
  }

  if (sInstalledMenuKeyboardListener) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  GetNewIMEState() returns IMEEnabled::Disabled because "
             "menu keyboard listener was installed"));
    return IMEState(IMEEnabled::Disabled);
  }

  if (!aElement) {
    // Even if there are no focused content, the focused document might be
    // editable, such case is design mode.
    if (aPresContext.Document() && aPresContext.Document()->IsInDesignMode()) {
      MOZ_LOG(sISMLog, LogLevel::Debug,
              ("  GetNewIMEState() returns IMEEnabled::Enabled because "
               "design mode editor has focus"));
      return IMEState(IMEEnabled::Enabled);
    }
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  GetNewIMEState() returns IMEEnabled::Disabled because "
             "no content has focus"));
    return IMEState(IMEEnabled::Disabled);
  }

  // If aElement is in designMode, aElement should be the root node of the
  // document.
  if (aElement && aElement->IsInDesignMode()) {
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  GetNewIMEState() returns IMEEnabled::Enabled because "
             "a content node in design mode editor has focus"));
    return IMEState(IMEEnabled::Enabled);
  }

  // nsIContent::GetDesiredIMEState() may cause a call of UpdateIMEState()
  // from EditorBase::PostCreate() because GetDesiredIMEState() needs to
  // retrieve an editor instance for the element if it's editable element.
  // For avoiding such nested IME state updates, we should set
  // sIsGettingNewIMEState here and UpdateIMEState() should check it.
  GettingNewIMEStateBlocker blocker;

  IMEState newIMEState = aElement->GetDesiredIMEState();
  MOZ_LOG(sISMLog, LogLevel::Debug,
          ("  GetNewIMEState() returns %s", ToString(newIMEState).c_str()));
  return newIMEState;
}

// static
void IMEStateManager::ResetActiveChildInputContext() {
  sActiveChildInputContext.mIMEState.mEnabled = IMEEnabled::Unknown;
}

// static
bool IMEStateManager::HasActiveChildSetInputContext() {
  return sActiveChildInputContext.mIMEState.mEnabled != IMEEnabled::Unknown;
}

// static
void IMEStateManager::SetInputContextForChildProcess(
    BrowserParent* aBrowserParent, const InputContext& aInputContext,
    const InputContextAction& aAction) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("SetInputContextForChildProcess(aBrowserParent=0x%p, "
       "aInputContext=%s , aAction={ mCause=%s, mAction=%s }), "
       "sFocusedPresContext=0x%p (available: %s), "
       "sTextInputHandlingWidget=0x%p (available: %s), "
       "BrowserParent::GetFocused()=0x%p, sInstalledMenuKeyboardListener=%s",
       aBrowserParent, ToString(aInputContext).c_str(),
       ToString(aAction.mCause).c_str(), ToString(aAction.mFocusChange).c_str(),
       sFocusedPresContext.get(),
       GetBoolName(CanHandleWith(sFocusedPresContext)),
       sTextInputHandlingWidget,
       GetBoolName(sTextInputHandlingWidget &&
                   !sTextInputHandlingWidget->Destroyed()),
       BrowserParent::GetFocused(),
       GetBoolName(sInstalledMenuKeyboardListener)));

  if (aBrowserParent != BrowserParent::GetFocused()) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  SetInputContextForChildProcess(), FAILED, "
             "because non-focused tab parent tries to set input context"));
    return;
  }

  if (NS_WARN_IF(!CanHandleWith(sFocusedPresContext))) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  SetInputContextForChildProcess(), FAILED, "
             "due to no focused presContext"));
    return;
  }

  if (NS_WARN_IF(!sTextInputHandlingWidget) ||
      NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  SetInputContextForChildProcess(), FAILED, "
             "due to the widget for the nsPresContext has gone"));
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;
  MOZ_ASSERT_IF(sFocusedPresContext->GetTextInputHandlingWidget(),
                sFocusedPresContext->GetTextInputHandlingWidget() ==
                    textInputHandlingWidget.get());
  MOZ_ASSERT(aInputContext.mOrigin == InputContext::ORIGIN_CONTENT);

  sActiveChildInputContext = aInputContext;
  MOZ_ASSERT(HasActiveChildSetInputContext());

  // If input context is changed in remote process while menu keyboard listener
  // is installed, this process shouldn't set input context now.  When it's
  // uninstalled, input context should be restored from
  // sActiveChildInputContext.
  if (sInstalledMenuKeyboardListener) {
    MOZ_LOG(sISMLog, LogLevel::Info,
            ("  SetInputContextForChildProcess(), waiting to set input context "
             "until menu keyboard listener is uninstalled"));
    return;
  }

  SetInputContext(textInputHandlingWidget, aInputContext, aAction);
}

MOZ_CAN_RUN_SCRIPT static bool IsNextFocusableElementTextControl(
    const Element* aInputContent) {
  RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager();
  if (MOZ_UNLIKELY(!fm)) {
    return false;
  }
  nsCOMPtr<nsIContent> nextContent;
  const RefPtr<Element> inputContent = const_cast<Element*>(aInputContent);
  const nsCOMPtr<nsPIDOMWindowOuter> outerWindow =
      aInputContent->OwnerDoc()->GetWindow();
  nsresult rv = fm->DetermineElementToMoveFocus(
      outerWindow, inputContent, nsIFocusManager::MOVEFOCUS_FORWARD, true,
      false, getter_AddRefs(nextContent));
  if (NS_WARN_IF(NS_FAILED(rv)) || !nextContent) {
    return false;
  }
  nextContent = nextContent->FindFirstNonChromeOnlyAccessContent();
  nsCOMPtr<nsIFormControl> nextControl = do_QueryInterface(nextContent);
  if (!nextControl || !nextControl->IsTextControl(false)) {
    return false;
  }

  // XXX We don't consider next element is date/time control yet.
  nsGenericHTMLElement* nextElement =
      nsGenericHTMLElement::FromNodeOrNull(nextContent);
  if (!nextElement) {
    return false;
  }

  // FIXME: Should probably use nsIFrame::IsFocusable if possible, to account
  // for things like visibility: hidden or so.
  if (!nextElement->IsFocusableWithoutStyle(false)) {
    return false;
  }

  // Check readonly attribute.
  if (nextElement->IsHTMLElement(nsGkAtoms::textarea)) {
    auto* textAreaElement = HTMLTextAreaElement::FromNode(nextElement);
    return !textAreaElement->ReadOnly();
  }

  // If neither textarea nor input, what element type?
  MOZ_DIAGNOSTIC_ASSERT(nextElement->IsHTMLElement(nsGkAtoms::input));

  auto* inputElement = HTMLInputElement::FromNode(nextElement);
  return !inputElement->ReadOnly();
}

static void GetInputType(const IMEState& aState, const nsIContent& aContent,
                         nsAString& aInputType) {
  // NOTE: If you change here, you may need to update
  //       widget::InputContext::GatNativeKeyBindings too.
  if (aContent.IsHTMLElement(nsGkAtoms::input)) {
    const HTMLInputElement* inputElement =
        HTMLInputElement::FromNode(&aContent);
    if (inputElement->HasBeenTypePassword() && aState.IsEditable()) {
      aInputType.AssignLiteral("password");
    } else {
      inputElement->GetType(aInputType);
    }
  } else if (aContent.IsHTMLElement(nsGkAtoms::textarea)) {
    aInputType.Assign(nsGkAtoms::textarea->GetUTF16String());
  }
}

MOZ_CAN_RUN_SCRIPT static void GetActionHint(const IMEState& aState,
                                             const nsIContent& aContent,
                                             nsAString& aActionHint) {
  MOZ_ASSERT(aContent.IsHTMLElement());

  if (aState.IsEditable()) {
    nsGenericHTMLElement::FromNode(&aContent)->GetEnterKeyHint(aActionHint);

    // If enterkeyhint is set, we don't infer action hint.
    if (!aActionHint.IsEmpty()) {
      return;
    }
  }

  if (!aContent.IsHTMLElement(nsGkAtoms::input)) {
    return;
  }

  // Get the input content corresponding to the focused node,
  // which may be an anonymous child of the input content.
  MOZ_ASSERT(&aContent == aContent.FindFirstNonChromeOnlyAccessContent());
  const HTMLInputElement* inputElement = HTMLInputElement::FromNode(aContent);
  if (!inputElement) {
    return;
  }

  // If we don't have an action hint and
  // return won't submit the form, use "maybenext".
  bool willSubmit = false;
  bool isLastElement = false;
  HTMLFormElement* formElement = inputElement->GetForm();
  // is this a form and does it have a default submit element?
  if (formElement) {
    if (formElement->IsLastActiveElement(inputElement)) {
      isLastElement = true;
    }

    if (formElement->GetDefaultSubmitElement()) {
      willSubmit = true;
      // is this an html form...
    } else {
      // ... and does it only have a single text input element ?
      if (!formElement->ImplicitSubmissionIsDisabled() ||
          // ... or is this the last non-disabled element?
          isLastElement) {
        willSubmit = true;
      }
    }
  }

  if (!isLastElement && formElement) {
    // If next tabbable content in form is text control, hint should be "next"
    // even there is submit in form.
    // MOZ_KnownLive(inputElement) because it's an alias of aContent.
    if (IsNextFocusableElementTextControl(MOZ_KnownLive(inputElement))) {
      // This is focusable text control
      // XXX What good hint for read only field?
      aActionHint.AssignLiteral("maybenext");
      return;
    }
  }

  if (!willSubmit) {
    aActionHint.Truncate();
    return;
  }

  if (inputElement->ControlType() == FormControlType::InputSearch) {
    aActionHint.AssignLiteral("search");
    return;
  }

  aActionHint.AssignLiteral("go");
}

static void GetInputMode(const IMEState& aState, const nsIContent& aContent,
                         nsAString& aInputMode) {
  if (aState.IsEditable()) {
    aContent.AsElement()->GetAttr(nsGkAtoms::inputmode, aInputMode);
    if (aContent.IsHTMLElement(nsGkAtoms::input) &&
        aInputMode.EqualsLiteral("mozAwesomebar")) {
      if (!nsContentUtils::IsChromeDoc(aContent.OwnerDoc())) {
        // mozAwesomebar should be allowed only in chrome
        aInputMode.Truncate();
      }
    } else {
      ToLowerCase(aInputMode);
    }
  }
}

static void GetAutocapitalize(const IMEState& aState, const Element& aElement,
                              const InputContext& aInputContext,
                              nsAString& aAutocapitalize) {
  if (aElement.IsHTMLElement() && aState.IsEditable() &&
      aInputContext.IsAutocapitalizeSupported()) {
    nsGenericHTMLElement::FromNode(&aElement)->GetAutocapitalize(
        aAutocapitalize);
  }
}

// static
void IMEStateManager::SetIMEState(const IMEState& aState,
                                  const nsPresContext* aPresContext,
                                  Element* aElement, nsIWidget& aWidget,
                                  InputContextAction aAction,
                                  InputContext::Origin aOrigin) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("SetIMEState(aState=%s, nsPresContext=0x%p, aElement=0x%p "
           "(BrowserParent=0x%p), aWidget=0x%p, aAction={ mCause=%s, "
           "mFocusChange=%s }, aOrigin=%s)",
           ToString(aState).c_str(), aPresContext, aElement,
           BrowserParent::GetFrom(aElement), &aWidget,
           ToString(aAction.mCause).c_str(),
           ToString(aAction.mFocusChange).c_str(), ToChar(aOrigin)));

  InputContext context;
  context.mIMEState = aState;
  if (aPresContext) {
    if (nsIURI* uri = aPresContext->Document()->GetDocumentURI()) {
      // We don't need to and should not expose special URLs such as:
      // about: Any apps like IME should work normally and constantly in any
      //        default pages such as about:blank, about:home, etc in either
      //        the main process or a content process.
      // blob: This may contain big data.  If we copy it to the main process,
      //       it may make the heap dirty which makes the process slower.
      // chrome: Same as about, any apps should work normally and constantly in
      //         any chrome documents.
      // data: Any native apps in the environment shouldn't change the behavior
      //       with the data URL's content and it may contain too big data.
      // file: The file path may contain private things and we shouldn't let
      //       other apps like IME know which one is touched by the user because
      //       malicious text services may like files which are explicitly used
      //       by the user better.
      if (uri->SchemeIs("http") || uri->SchemeIs("https")) {
        // Note that we don't need to expose UserPass, Query and Reference to
        // IME since they may contain sensitive data, but non-malicious text
        // services must not require these data.
        nsCOMPtr<nsIURI> exposableURL;
        if (NS_SUCCEEDED(NS_MutateURI(uri)
                             .SetQuery(""_ns)
                             .SetRef(""_ns)
                             .SetUserPass(""_ns)
                             .Finalize(exposableURL))) {
          context.mURI = std::move(exposableURL);
        }
      }
    }
  }
  context.mOrigin = aOrigin;

  context.mHasHandledUserInput =
      aPresContext && aPresContext->PresShell()->HasHandledUserInput();

  context.mInPrivateBrowsing =
      aPresContext &&
      nsContentUtils::IsInPrivateBrowsing(aPresContext->Document());

  const RefPtr<Element> focusedElement =
      aElement ? Element::FromNodeOrNull(
                     aElement->FindFirstNonChromeOnlyAccessContent())
               : nullptr;

  if (focusedElement && focusedElement->IsHTMLElement()) {
    GetInputType(aState, *focusedElement, context.mHTMLInputType);
    GetActionHint(aState, *focusedElement, context.mActionHint);
    GetInputMode(aState, *focusedElement, context.mHTMLInputMode);
    GetAutocapitalize(aState, *focusedElement, context,
                      context.mAutocapitalize);
  }

  if (aAction.mCause == InputContextAction::CAUSE_UNKNOWN &&
      nsContentUtils::LegacyIsCallerChromeOrNativeCode()) {
    aAction.mCause = InputContextAction::CAUSE_UNKNOWN_CHROME;
  }

  if ((aAction.mCause == InputContextAction::CAUSE_UNKNOWN ||
       aAction.mCause == InputContextAction::CAUSE_UNKNOWN_CHROME) &&
      UserActivation::IsHandlingUserInput()) {
    aAction.mCause =
        UserActivation::IsHandlingKeyboardInput()
            ? InputContextAction::CAUSE_UNKNOWN_DURING_KEYBOARD_INPUT
            : InputContextAction::CAUSE_UNKNOWN_DURING_NON_KEYBOARD_INPUT;
  }

  SetInputContext(aWidget, context, aAction);
}

// static
void IMEStateManager::SetInputContext(nsIWidget& aWidget,
                                      const InputContext& aInputContext,
                                      const InputContextAction& aAction) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("SetInputContext(aWidget=0x%p, aInputContext=%s, "
       "aAction={ mCause=%s, mAction=%s }), BrowserParent::GetFocused()=0x%p",
       &aWidget, ToString(aInputContext).c_str(),
       ToString(aAction.mCause).c_str(), ToString(aAction.mFocusChange).c_str(),
       BrowserParent::GetFocused()));

  OwningNonNull<nsIWidget> widget = aWidget;
  widget->SetInputContext(aInputContext, aAction);
  sActiveInputContextWidget = widget;
}

// static
void IMEStateManager::EnsureTextCompositionArray() {
  if (sTextCompositions) {
    return;
  }
  sTextCompositions = new TextCompositionArray();
}

// static
void IMEStateManager::DispatchCompositionEvent(
    nsINode* aEventTargetNode, nsPresContext* aPresContext,
    BrowserParent* aBrowserParent, WidgetCompositionEvent* aCompositionEvent,
    nsEventStatus* aStatus, EventDispatchingCallback* aCallBack,
    bool aIsSynthesized) {
  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("DispatchCompositionEvent(aNode=0x%p, "
       "aPresContext=0x%p, aCompositionEvent={ mMessage=%s, "
       "mNativeIMEContext={ mRawNativeIMEContext=0x%" PRIXPTR ", "
       "mOriginProcessID=0x%" PRIX64 " }, mWidget(0x%p)={ "
       "GetNativeIMEContext()={ mRawNativeIMEContext=0x%" PRIXPTR ", "
       "mOriginProcessID=0x%" PRIX64 " }, Destroyed()=%s }, "
       "mFlags={ mIsTrusted=%s, mPropagationStopped=%s } }, "
       "aIsSynthesized=%s), browserParent=%p",
       aEventTargetNode, aPresContext, ToChar(aCompositionEvent->mMessage),
       aCompositionEvent->mNativeIMEContext.mRawNativeIMEContext,
       aCompositionEvent->mNativeIMEContext.mOriginProcessID,
       aCompositionEvent->mWidget.get(),
       aCompositionEvent->mWidget->GetNativeIMEContext().mRawNativeIMEContext,
       aCompositionEvent->mWidget->GetNativeIMEContext().mOriginProcessID,
       GetBoolName(aCompositionEvent->mWidget->Destroyed()),
       GetBoolName(aCompositionEvent->mFlags.mIsTrusted),
       GetBoolName(aCompositionEvent->mFlags.mPropagationStopped),
       GetBoolName(aIsSynthesized), aBrowserParent));

  if (NS_WARN_IF(!aCompositionEvent->IsTrusted()) ||
      NS_WARN_IF(aCompositionEvent->PropagationStopped())) {
    return;
  }

  MOZ_ASSERT(aCompositionEvent->mMessage != eCompositionUpdate,
             "compositionupdate event shouldn't be dispatched manually");

  EnsureTextCompositionArray();

  RefPtr<TextComposition> composition =
      sTextCompositions->GetCompositionFor(aCompositionEvent);
  if (!composition) {
    // If synthesized event comes after delayed native composition events
    // for request of commit or cancel, we should ignore it.
    if (NS_WARN_IF(aIsSynthesized)) {
      return;
    }
    MOZ_LOG(sISMLog, LogLevel::Debug,
            ("  DispatchCompositionEvent(), "
             "adding new TextComposition to the array"));
    MOZ_ASSERT(aCompositionEvent->mMessage == eCompositionStart);
    composition = new TextComposition(aPresContext, aEventTargetNode,
                                      aBrowserParent, aCompositionEvent);
    sTextCompositions->AppendElement(composition);
  }
#ifdef DEBUG
  else {
    MOZ_ASSERT(aCompositionEvent->mMessage != eCompositionStart);
  }
#endif  // #ifdef DEBUG

  // Dispatch the event on composing target.
  composition->DispatchCompositionEvent(aCompositionEvent, aStatus, aCallBack,
                                        aIsSynthesized);

  // WARNING: the |composition| might have been destroyed already.

  // Remove the ended composition from the array.
  // NOTE: When TextComposition is synthesizing compositionend event for
  //       emulating a commit, the instance shouldn't be removed from the array
  //       because IME may perform it later.  Then, we need to ignore the
  //       following commit events in TextComposition::DispatchEvent().
  //       However, if commit or cancel for a request is performed synchronously
  //       during not safe to dispatch events, PresShell must have discarded
  //       compositionend event.  Then, the synthesized compositionend event is
  //       the last event for the composition.  In this case, we need to
  //       destroy the TextComposition with synthesized compositionend event.
  if ((!aIsSynthesized ||
       composition->WasNativeCompositionEndEventDiscarded()) &&
      aCompositionEvent->CausesDOMCompositionEndEvent()) {
    TextCompositionArray::index_type i =
        sTextCompositions->IndexOf(aCompositionEvent->mWidget);
    if (i != TextCompositionArray::NoIndex) {
      MOZ_LOG(
          sISMLog, LogLevel::Debug,
          ("  DispatchCompositionEvent(), "
           "removing TextComposition from the array since NS_COMPOSTION_END "
           "was dispatched"));
      sTextCompositions->ElementAt(i)->Destroy();
      sTextCompositions->RemoveElementAt(i);
    }
  }
}

// static
IMEContentObserver* IMEStateManager::GetActiveContentObserver() {
  return sActiveIMEContentObserver;
}

// static
nsIContent* IMEStateManager::GetRootContent(nsPresContext* aPresContext) {
  Document* doc = aPresContext->Document();
  if (NS_WARN_IF(!doc)) {
    return nullptr;
  }
  return doc->GetRootElement();
}

// static
void IMEStateManager::HandleSelectionEvent(
    nsPresContext* aPresContext, nsIContent* aEventTargetContent,
    WidgetSelectionEvent* aSelectionEvent) {
  RefPtr<BrowserParent> browserParent = GetActiveBrowserParent();
  if (!browserParent) {
    browserParent = BrowserParent::GetFrom(aEventTargetContent
                                               ? aEventTargetContent
                                               : GetRootContent(aPresContext));
  }

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("HandleSelectionEvent(aPresContext=0x%p, "
       "aEventTargetContent=0x%p, aSelectionEvent={ mMessage=%s, "
       "mFlags={ mIsTrusted=%s } }), browserParent=%p",
       aPresContext, aEventTargetContent, ToChar(aSelectionEvent->mMessage),
       GetBoolName(aSelectionEvent->mFlags.mIsTrusted), browserParent.get()));

  if (!aSelectionEvent->IsTrusted()) {
    return;
  }

  RefPtr<TextComposition> composition =
      sTextCompositions
          ? sTextCompositions->GetCompositionFor(aSelectionEvent->mWidget)
          : nullptr;
  if (composition) {
    // When there is a composition, TextComposition should guarantee that the
    // selection event will be handled in same target as composition events.
    composition->HandleSelectionEvent(aSelectionEvent);
  } else {
    // When there is no composition, the selection event should be handled
    // in the aPresContext or browserParent.
    TextComposition::HandleSelectionEvent(aPresContext, browserParent,
                                          aSelectionEvent);
  }
}

// static
void IMEStateManager::OnCompositionEventDiscarded(
    WidgetCompositionEvent* aCompositionEvent) {
  // Note that this method is never called for synthesized events for emulating
  // commit or cancel composition.

  MOZ_LOG(
      sISMLog, LogLevel::Info,
      ("OnCompositionEventDiscarded(aCompositionEvent={ "
       "mMessage=%s, mNativeIMEContext={ mRawNativeIMEContext=0x%" PRIXPTR ", "
       "mOriginProcessID=0x%" PRIX64 " }, mWidget(0x%p)={ "
       "GetNativeIMEContext()={ mRawNativeIMEContext=0x%" PRIXPTR ", "
       "mOriginProcessID=0x%" PRIX64 " }, Destroyed()=%s }, "
       "mFlags={ mIsTrusted=%s } })",
       ToChar(aCompositionEvent->mMessage),
       aCompositionEvent->mNativeIMEContext.mRawNativeIMEContext,
       aCompositionEvent->mNativeIMEContext.mOriginProcessID,
       aCompositionEvent->mWidget.get(),
       aCompositionEvent->mWidget->GetNativeIMEContext().mRawNativeIMEContext,
       aCompositionEvent->mWidget->GetNativeIMEContext().mOriginProcessID,
       GetBoolName(aCompositionEvent->mWidget->Destroyed()),
       GetBoolName(aCompositionEvent->mFlags.mIsTrusted)));

  if (!aCompositionEvent->IsTrusted()) {
    return;
  }

  // Ignore compositionstart for now because sTextCompositions may not have
  // been created yet.
  if (aCompositionEvent->mMessage == eCompositionStart) {
    return;
  }

  RefPtr<TextComposition> composition =
      sTextCompositions->GetCompositionFor(aCompositionEvent->mWidget);
  if (!composition) {
    // If the PresShell has been being destroyed during composition,
    // a TextComposition instance for the composition was already removed from
    // the array and destroyed in OnDestroyPresContext().  Therefore, we may
    // fail to retrieve a TextComposition instance here.
    MOZ_LOG(sISMLog, LogLevel::Info,
            ("  OnCompositionEventDiscarded(), "
             "TextComposition instance for the widget has already gone"));
    return;
  }
  composition->OnCompositionEventDiscarded(aCompositionEvent);
}

// static
nsresult IMEStateManager::NotifyIME(IMEMessage aMessage, nsIWidget* aWidget,
                                    BrowserParent* aBrowserParent) {
  return IMEStateManager::NotifyIME(IMENotification(aMessage), aWidget,
                                    aBrowserParent);
}

// static
nsresult IMEStateManager::NotifyIME(const IMENotification& aNotification,
                                    nsIWidget* aWidget,
                                    BrowserParent* aBrowserParent) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("NotifyIME(aNotification={ mMessage=%s }, "
           "aWidget=0x%p, aBrowserParent=0x%p), sFocusedIMEWidget=0x%p, "
           "BrowserParent::GetFocused()=0x%p, sFocusedIMEBrowserParent=0x%p, "
           "aBrowserParent == BrowserParent::GetFocused()=%s, "
           "aBrowserParent == sFocusedIMEBrowserParent=%s, "
           "CanSendNotificationToWidget()=%s",
           ToChar(aNotification.mMessage), aWidget, aBrowserParent,
           sFocusedIMEWidget, BrowserParent::GetFocused(),
           sFocusedIMEBrowserParent.get(),
           GetBoolName(aBrowserParent == BrowserParent::GetFocused()),
           GetBoolName(aBrowserParent == sFocusedIMEBrowserParent),
           GetBoolName(CanSendNotificationToWidget())));

  if (NS_WARN_IF(!aWidget)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  NotifyIME(), FAILED due to no widget"));
    return NS_ERROR_INVALID_ARG;
  }

  switch (aNotification.mMessage) {
    case NOTIFY_IME_OF_FOCUS: {
      MOZ_ASSERT(CanSendNotificationToWidget());

      // If focus notification comes from a remote browser which already lost
      // focus, we shouldn't accept the focus notification.  Then, following
      // notifications from the process will be ignored.
      if (aBrowserParent != BrowserParent::GetFocused()) {
        MOZ_LOG(sISMLog, LogLevel::Warning,
                ("  NotifyIME(), WARNING, the received focus notification is "
                 "ignored, because its associated BrowserParent did not match"
                 "the focused BrowserParent."));
        return NS_OK;
      }
      // If IME focus is already set, first blur the currently-focused
      // IME widget
      if (sFocusedIMEWidget) {
        // XXX Why don't we first request the previously-focused IME
        // widget to commit the composition?
        MOZ_ASSERT(
            sFocusedIMEBrowserParent || aBrowserParent,
            "This case shouldn't be caused by focus move in this process");
        MOZ_LOG(sISMLog, LogLevel::Warning,
                ("  NotifyIME(), WARNING, received focus notification with ")
                 "non-null sFocusedIMEWidget. How come "
                 "OnFocusMovedBetweenBrowsers did not blur it already?");
        nsCOMPtr<nsIWidget> focusedIMEWidget(sFocusedIMEWidget);
        sFocusedIMEWidget = nullptr;
        sFocusedIMEBrowserParent = nullptr;
        focusedIMEWidget->NotifyIME(IMENotification(NOTIFY_IME_OF_BLUR));
      }
#ifdef DEBUG
      if (aBrowserParent) {
        nsCOMPtr<nsIWidget> browserParentWidget =
            aBrowserParent->GetTextInputHandlingWidget();
        MOZ_ASSERT(browserParentWidget == aWidget);
      } else {
        MOZ_ASSERT(sFocusedPresContext);
        MOZ_ASSERT_IF(
            sFocusedPresContext->GetTextInputHandlingWidget(),
            sFocusedPresContext->GetTextInputHandlingWidget() == aWidget);
      }
#endif
      sFocusedIMEBrowserParent = aBrowserParent;
      sFocusedIMEWidget = aWidget;
      nsCOMPtr<nsIWidget> widget(aWidget);
      MOZ_LOG(
          sISMLog, LogLevel::Info,
          ("  NotifyIME(), about to call widget->NotifyIME() for IME focus"));
      return widget->NotifyIME(aNotification);
    }
    case NOTIFY_IME_OF_BLUR: {
      if (aBrowserParent != sFocusedIMEBrowserParent) {
        MOZ_LOG(sISMLog, LogLevel::Warning,
                ("  NotifyIME(), WARNING, the received blur notification is "
                 "ignored "
                 "because it's not from current focused IME browser"));
        return NS_OK;
      }
      if (!sFocusedIMEWidget) {
        MOZ_LOG(
            sISMLog, LogLevel::Error,
            ("  NotifyIME(), WARNING, received blur notification but there is "
             "no focused IME widget"));
        return NS_OK;
      }
      if (NS_WARN_IF(sFocusedIMEWidget != aWidget)) {
        MOZ_LOG(sISMLog, LogLevel::Warning,
                ("  NotifyIME(), WARNING, the received blur notification is "
                 "ignored "
                 "because it's not for current focused IME widget"));
        return NS_OK;
      }
      nsCOMPtr<nsIWidget> focusedIMEWidget(sFocusedIMEWidget);
      sFocusedIMEWidget = nullptr;
      sFocusedIMEBrowserParent = nullptr;
      return CanSendNotificationToWidget()
                 ? focusedIMEWidget->NotifyIME(
                       IMENotification(NOTIFY_IME_OF_BLUR))
                 : NS_OK;
    }
    case NOTIFY_IME_OF_SELECTION_CHANGE:
    case NOTIFY_IME_OF_TEXT_CHANGE:
    case NOTIFY_IME_OF_POSITION_CHANGE:
    case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
    case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED: {
      if (aBrowserParent != sFocusedIMEBrowserParent) {
        MOZ_LOG(
            sISMLog, LogLevel::Warning,
            ("  NotifyIME(), WARNING, the received content change notification "
             "is ignored because it's not from current focused IME browser"));
        return NS_OK;
      }
      if (!sFocusedIMEWidget) {
        MOZ_LOG(
            sISMLog, LogLevel::Warning,
            ("  NotifyIME(), WARNING, the received content change notification "
             "is ignored because there is no focused IME widget"));
        return NS_OK;
      }
      if (NS_WARN_IF(sFocusedIMEWidget != aWidget)) {
        MOZ_LOG(
            sISMLog, LogLevel::Warning,
            ("  NotifyIME(), WARNING, the received content change notification "
             "is ignored because it's not for current focused IME widget"));
        return NS_OK;
      }
      if (!CanSendNotificationToWidget()) {
        return NS_OK;
      }
      nsCOMPtr<nsIWidget> widget(aWidget);
      return widget->NotifyIME(aNotification);
    }
    default:
      // Other notifications should be sent only when there is composition.
      // So, we need to handle the others below.
      break;
  }

  if (!sTextCompositions) {
    MOZ_LOG(sISMLog, LogLevel::Info,
            ("  NotifyIME(), the request to IME is ignored because "
             "there have been no compositions yet"));
    return NS_OK;
  }

  RefPtr<TextComposition> composition =
      sTextCompositions->GetCompositionFor(aWidget);
  if (!composition) {
    MOZ_LOG(sISMLog, LogLevel::Info,
            ("  NotifyIME(), the request to IME is ignored because "
             "there is no active composition"));
    return NS_OK;
  }

  if (aBrowserParent != composition->GetBrowserParent()) {
    MOZ_LOG(
        sISMLog, LogLevel::Warning,
        ("  NotifyIME(), WARNING, the request to IME is ignored because "
         "it does not come from the remote browser which has the composition "
         "on aWidget"));
    return NS_OK;
  }

  switch (aNotification.mMessage) {
    case REQUEST_TO_COMMIT_COMPOSITION:
      return composition->RequestToCommit(aWidget, false);
    case REQUEST_TO_CANCEL_COMPOSITION:
      return composition->RequestToCommit(aWidget, true);
    default:
      MOZ_CRASH("Unsupported notification");
  }
  MOZ_CRASH(
      "Failed to handle the notification for non-synthesized composition");
  return NS_ERROR_FAILURE;
}

// static
nsresult IMEStateManager::NotifyIME(IMEMessage aMessage,
                                    nsPresContext* aPresContext,
                                    BrowserParent* aBrowserParent) {
  MOZ_LOG(sISMLog, LogLevel::Info,
          ("NotifyIME(aMessage=%s, aPresContext=0x%p, aBrowserParent=0x%p)",
           ToChar(aMessage), aPresContext, aBrowserParent));
  // This assertion is just for clarify which message may be set, so feel free
  // to add other messages if you want.
  MOZ_ASSERT(aMessage == REQUEST_TO_CANCEL_COMPOSITION ||
             aMessage == REQUEST_TO_COMMIT_COMPOSITION ||
             aMessage == NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED);
  // However, these messages require additional information.  Therefore, this
  // overload shouldn't be used for them.
  MOZ_ASSERT(aMessage != NOTIFY_IME_OF_FOCUS &&
             aMessage != NOTIFY_IME_OF_BLUR &&
             aMessage != NOTIFY_IME_OF_TEXT_CHANGE &&
             aMessage != NOTIFY_IME_OF_SELECTION_CHANGE &&
             aMessage != NOTIFY_IME_OF_MOUSE_BUTTON_EVENT);

  if (NS_WARN_IF(!CanHandleWith(aPresContext))) {
    return NS_ERROR_INVALID_ARG;
  }

  nsCOMPtr<nsIWidget> widget =
      aPresContext == sFocusedPresContext && sTextInputHandlingWidget
          ? sTextInputHandlingWidget
          : aPresContext->GetTextInputHandlingWidget();
  if (NS_WARN_IF(!widget)) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  NotifyIME(), FAILED due to no widget for the nsPresContext"));
    return NS_ERROR_NOT_AVAILABLE;
  }
  return NotifyIME(aMessage, widget, aBrowserParent);
}

// static
bool IMEStateManager::IsEditable(nsINode* node) {
  if (node->IsEditable()) {
    return true;
  }
  // |node| might be readwrite (for example, a text control)
  if (node->IsElement() &&
      node->AsElement()->State().HasState(ElementState::READWRITE)) {
    return true;
  }
  return false;
}

// static
nsINode* IMEStateManager::GetRootEditableNode(const nsPresContext& aPresContext,
                                              const Element* aElement) {
  if (aElement) {
    // If the focused content is in design mode, return is composed document
    // because aElement may be in UA widget shadow tree.
    if (aElement->IsInDesignMode()) {
      return aElement->GetComposedDoc();
    }

    nsINode* candidateRootNode = const_cast<Element*>(aElement);
    for (nsINode* node = candidateRootNode; node && IsEditable(node);
         node = node->GetParentNode()) {
      // If the node has independent selection like <input type="text"> or
      // <textarea>, the node should be the root editable node for aElement.
      // FYI: <select> element also has independent selection but IsEditable()
      //      returns false.
      // XXX: If somebody adds new editable element which has independent
      //      selection but doesn't own editor, we'll need more checks here.
      // XXX: If aElement is not in native anonymous subtree, checking
      //      independent selection must be wrong, see bug 1731005.
      if (node->IsContent() && node->AsContent()->HasIndependentSelection()) {
        return node;
      }
      candidateRootNode = node;
    }
    return candidateRootNode;
  }

  return aPresContext.Document() && aPresContext.Document()->IsInDesignMode()
             ? aPresContext.Document()
             : nullptr;
}

// static
bool IMEStateManager::IsIMEObserverNeeded(const IMEState& aState) {
  return aState.IsEditable();
}

// static
void IMEStateManager::DestroyIMEContentObserver() {
  if (!sActiveIMEContentObserver) {
    MOZ_LOG(sISMLog, LogLevel::Verbose,
            ("DestroyIMEContentObserver() does nothing"));
    return;
  }

  MOZ_LOG(sISMLog, LogLevel::Info,
          ("DestroyIMEContentObserver(), destroying "
           "the active IMEContentObserver..."));
  RefPtr<IMEContentObserver> tsm = sActiveIMEContentObserver.get();
  sActiveIMEContentObserver = nullptr;
  tsm->Destroy();
}

// static
void IMEStateManager::CreateIMEContentObserver(EditorBase& aEditorBase,
                                               Element* aFocusedElement) {
  MOZ_ASSERT(!sActiveIMEContentObserver);
  MOZ_ASSERT(sTextInputHandlingWidget);
  MOZ_ASSERT(sFocusedPresContext);
  MOZ_ASSERT(IsIMEObserverNeeded(
      sTextInputHandlingWidget->GetInputContext().mIMEState));

  MOZ_LOG(sISMLog, LogLevel::Info,
          ("CreateIMEContentObserver(aEditorBase=0x%p, aFocusedElement=0x%p), "
           "sFocusedPresContext=0x%p, sFocusedElement=0x%p, "
           "sTextInputHandlingWidget=0x%p (available: %s), "
           "sActiveIMEContentObserver=0x%p, "
           "sActiveIMEContentObserver->IsObserving(sFocusedPresContext, "
           "sFocusedElement)=%s",
           &aEditorBase, aFocusedElement, sFocusedPresContext.get(),
           sFocusedElement.get(), sTextInputHandlingWidget,
           GetBoolName(sTextInputHandlingWidget &&
                       !sTextInputHandlingWidget->Destroyed()),
           sActiveIMEContentObserver.get(),
           GetBoolName(sActiveIMEContentObserver && sFocusedPresContext &&
                       sActiveIMEContentObserver->IsObserving(
                           *sFocusedPresContext, sFocusedElement))));

  if (NS_WARN_IF(sTextInputHandlingWidget->Destroyed())) {
    MOZ_LOG(sISMLog, LogLevel::Error,
            ("  CreateIMEContentObserver(), FAILED due to "
             "the widget for the nsPresContext has gone"));
    return;
  }

  const OwningNonNull<nsIWidget> textInputHandlingWidget =
      *sTextInputHandlingWidget;
  MOZ_ASSERT_IF(sFocusedPresContext->GetTextInputHandlingWidget(),
                sFocusedPresContext->GetTextInputHandlingWidget() ==
                    textInputHandlingWidget.get());

  MOZ_LOG(sISMLog, LogLevel::Debug,
          ("  CreateIMEContentObserver() is creating an "
           "IMEContentObserver instance..."));
  sActiveIMEContentObserver = new IMEContentObserver();

  // IMEContentObserver::Init() might create another IMEContentObserver
  // instance.  So, sActiveIMEContentObserver would be replaced with new one.
  // We should hold the current instance here.
  OwningNonNull<IMEContentObserver> activeIMEContentObserver =
      *sActiveIMEContentObserver;
  OwningNonNull<nsPresContext> focusedPresContext = *sFocusedPresContext;
  RefPtr<Element> focusedElement = aFocusedElement;
  activeIMEContentObserver->Init(textInputHandlingWidget, focusedPresContext,
                                 focusedElement, aEditorBase);
}

// static
nsresult IMEStateManager::GetFocusSelectionAndRootElement(
    Selection** aSelection, Element** aRootElement) {
  if (!sActiveIMEContentObserver) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  return sActiveIMEContentObserver->GetSelectionAndRoot(aSelection,
                                                        aRootElement);
}

// static
TextComposition* IMEStateManager::GetTextCompositionFor(nsIWidget* aWidget) {
  return sTextCompositions ? sTextCompositions->GetCompositionFor(aWidget)
                           : nullptr;
}

// static
TextComposition* IMEStateManager::GetTextCompositionFor(
    const WidgetCompositionEvent* aCompositionEvent) {
  return sTextCompositions
             ? sTextCompositions->GetCompositionFor(aCompositionEvent)
             : nullptr;
}

// static
TextComposition* IMEStateManager::GetTextCompositionFor(
    nsPresContext* aPresContext) {
  return sTextCompositions ? sTextCompositions->GetCompositionFor(aPresContext)
                           : nullptr;
}

}  // namespace mozilla