File: IMEContentObserver.cpp

package info (click to toggle)
firefox 143.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,617,328 kB
  • sloc: cpp: 7,478,492; javascript: 6,417,157; ansic: 3,720,058; python: 1,396,372; xml: 627,523; asm: 438,677; java: 186,156; sh: 63,477; makefile: 19,171; objc: 13,059; perl: 12,983; yacc: 4,583; cs: 3,846; pascal: 3,405; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (2997 lines) | stat: -rw-r--r-- 116,971 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
/* -*- 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 "IMEContentObserver.h"

#include "ContentEventHandler.h"
#include "WritingModes.h"
#include "mozilla/Assertions.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/Logging.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_test.h"
#include "mozilla/TextComposition.h"
#include "mozilla/TextControlElement.h"
#include "mozilla/TextEvents.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Selection.h"
#include "nsAtom.h"
#include "nsContentUtils.h"
#include "nsDocShell.h"
#include "nsGkAtoms.h"
#include "nsIContent.h"
#include "nsIFrame.h"
#include "nsINode.h"
#include "nsISelectionController.h"
#include "nsISupports.h"
#include "nsIWeakReferenceUtils.h"
#include "nsIWidget.h"
#include "nsPresContext.h"
#include "nsRange.h"
#include "nsRefreshDriver.h"
#include "nsString.h"

namespace mozilla {

using RawNodePosition = ContentEventHandler::RawNodePosition;

using namespace dom;
using namespace widget;

LazyLogModule sIMECOLog("IMEContentObserver");
LazyLogModule sCacheLog("IMEContentObserverCache");

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

/******************************************************************************
 * mozilla::IMEContentObserver
 ******************************************************************************/

NS_IMPL_CYCLE_COLLECTION_CLASS(IMEContentObserver)

// Note that we don't need to add mFirstAddedContainer nor
// mLastAddedContainer to cycle collection because they are non-null only
// during short time and shouldn't be touched while they are non-null.

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IMEContentObserver)
  nsAutoScriptBlocker scriptBlocker;

  tmp->NotifyIMEOfBlur();
  tmp->UnregisterObservers();

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelection)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mRootElement)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mEditableNode)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocShell)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mEditorBase)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentObserver)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mEndOfAddedTextCache.mContainerNode)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mEndOfAddedTextCache.mContent)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartOfRemovingTextRangeCache.mContainerNode)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartOfRemovingTextRangeCache.mContent)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE

  tmp->mIMENotificationRequests = nullptr;
  tmp->mESM = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IMEContentObserver)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWidget)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFocusedWidget)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelection)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRootElement)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEditableNode)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocShell)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEditorBase)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentObserver)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEndOfAddedTextCache.mContainerNode)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEndOfAddedTextCache.mContent)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(
      mStartOfRemovingTextRangeCache.mContainerNode)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartOfRemovingTextRangeCache.mContent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IMEContentObserver)
  NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
  NS_INTERFACE_MAP_ENTRY(nsIReflowObserver)
  NS_INTERFACE_MAP_ENTRY(nsIScrollObserver)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIReflowObserver)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(IMEContentObserver)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IMEContentObserver)

IMEContentObserver::IMEContentObserver() {
#ifdef DEBUG
  // TODO: Make this test as GTest.
  mTextChangeData.Test();
#endif
}

void IMEContentObserver::Init(nsIWidget& aWidget, nsPresContext& aPresContext,
                              Element* aElement, EditorBase& aEditorBase) {
  State state = GetState();
  if (NS_WARN_IF(state == eState_Observing)) {
    return;  // Nothing to do.
  }

  bool firstInitialization = state != eState_StoppedObserving;
  if (!firstInitialization) {
    // If this is now trying to initialize with new contents, all observers
    // should be registered again for simpler implementation.
    UnregisterObservers();
    Clear();
  }

  mESM = aPresContext.EventStateManager();
  mESM->OnStartToObserveContent(this);

  mWidget = &aWidget;
  mIMENotificationRequests = &mWidget->IMENotificationRequestsRef();

  if (!InitWithEditor(aPresContext, aElement, aEditorBase)) {
    MOZ_LOG(sIMECOLog, LogLevel::Error,
            ("0x%p   Init() FAILED, due to InitWithEditor() "
             "failure",
             this));
    Clear();
    return;
  }

  if (firstInitialization) {
    // Now, try to send NOTIFY_IME_OF_FOCUS to IME via the widget.
    MaybeNotifyIMEOfFocusSet();
    // When this is called first time, IME has not received NOTIFY_IME_OF_FOCUS
    // yet since NOTIFY_IME_OF_FOCUS will be sent to widget asynchronously.
    // So, we need to do nothing here.  After NOTIFY_IME_OF_FOCUS has been
    // sent, OnIMEReceivedFocus() will be called and content, selection and/or
    // position changes will be observed
    return;
  }

  // When this is called after editor reframing (i.e., the root editable node
  // is also recreated), IME has usually received NOTIFY_IME_OF_FOCUS.  In this
  // case, we need to restart to observe content, selection and/or position
  // changes in new root editable node.
  ObserveEditableNode();

  if (!NeedsToNotifyIMEOfSomething()) {
    return;
  }

  // Some change events may wait to notify IME because this was being
  // initialized.  It is the time to flush them.
  FlushMergeableNotifications();
}

void IMEContentObserver::OnIMEReceivedFocus() {
  // While Init() notifies IME of focus, pending layout may be flushed
  // because the notification may cause querying content.  Then, recursive
  // call of Init() with the latest content may occur.  In such case, we
  // shouldn't keep first initialization which notified IME of focus.
  if (GetState() != eState_Initializing) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   OnIMEReceivedFocus(), "
             "but the state is not \"initializing\", so does nothing",
             this));
    return;
  }

  // NOTIFY_IME_OF_FOCUS might cause recreating IMEContentObserver
  // instance via IMEStateManager::UpdateIMEState().  So, this
  // instance might already have been destroyed, check it.
  if (!mRootElement) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   OnIMEReceivedFocus(), "
             "but mRootElement has already been cleared, so does nothing",
             this));
    return;
  }

  // Start to observe which is needed by IME when IME actually has focus.
  ObserveEditableNode();

  if (!NeedsToNotifyIMEOfSomething()) {
    return;
  }

  // Some change events may wait to notify IME because this was being
  // initialized.  It is the time to flush them.
  FlushMergeableNotifications();
}

bool IMEContentObserver::InitWithEditor(nsPresContext& aPresContext,
                                        Element* aElement,
                                        EditorBase& aEditorBase) {
  // mEditableNode is one of
  // - Anonymous <div> in <input> or <textarea>
  // - Editing host if it's not in the design mode
  // - Document if it's in the design mode
  mEditableNode = IMEStateManager::GetRootEditableNode(aPresContext, aElement);
  if (NS_WARN_IF(!mEditableNode)) {
    return false;
  }

  mEditorBase = &aEditorBase;

  RefPtr<PresShell> presShell = aPresContext.GetPresShell();

  // get selection and root content
  nsCOMPtr<nsISelectionController> selCon;
  if (mEditableNode->IsContent()) {
    nsIFrame* frame = mEditableNode->AsContent()->GetPrimaryFrame();
    if (NS_WARN_IF(!frame)) {
      return false;
    }

    frame->GetSelectionController(&aPresContext, getter_AddRefs(selCon));
  } else {
    // mEditableNode is a document
    selCon = presShell;
  }

  if (NS_WARN_IF(!selCon)) {
    return false;
  }

  mSelection = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  if (NS_WARN_IF(!mSelection)) {
    return false;
  }

  if (mEditorBase->IsTextEditor()) {
    mRootElement = mEditorBase->GetRoot();  // The anonymous <div>
    MOZ_ASSERT(mRootElement);
    MOZ_ASSERT(mRootElement->GetFirstChild());
    if (auto* text = Text::FromNodeOrNull(
            mRootElement ? mRootElement->GetFirstChild() : nullptr)) {
      mTextControlValueLength = ContentEventHandler::GetNativeTextLength(*text);
    }
    mIsTextControl = true;
  } else if (const nsRange* selRange = mSelection->GetRangeAt(0)) {
    MOZ_ASSERT(!mIsTextControl);
    if (NS_WARN_IF(!selRange->GetStartContainer())) {
      return false;
    }

    // If an editing host has focus, mRootElement is it.
    // Otherwise, if we're in the design mode, mRootElement is the <body> if
    // there is and startContainer is not outside of the <body>.  Otherwise, the
    // document element is used instead.
    nsCOMPtr<nsINode> startContainer = selRange->GetStartContainer();
    mRootElement =
        Element::FromNodeOrNull(startContainer->GetSelectionRootContent(
            presShell,
            nsINode::IgnoreOwnIndependentSelection::No,  // XXX "Yes"?
            nsINode::AllowCrossShadowBoundary::No));
  } else {
    MOZ_ASSERT(!mIsTextControl);
    // If an editing host has focus, mRootElement is it.
    // Otherwise, if we're in the design mode, mRootElement is the <body> if
    // there is.  Otherwise, the document element is used instead.
    nsCOMPtr<nsINode> editableNode = mEditableNode;
    mRootElement =
        Element::FromNodeOrNull(editableNode->GetSelectionRootContent(
            presShell,
            nsINode::IgnoreOwnIndependentSelection::No,  // XXX "Yes"?
            nsINode::AllowCrossShadowBoundary::No));
  }
  if (!mRootElement && mEditableNode->IsDocument()) {
    // The document node is editable, but there are no contents, this document
    // is not editable.
    return false;
  }

  if (NS_WARN_IF(!mRootElement)) {
    return false;
  }

  mDocShell = aPresContext.GetDocShell();
  if (NS_WARN_IF(!mDocShell)) {
    return false;
  }

  mDocumentObserver = new DocumentObserver(*this);

  return true;
}

void IMEContentObserver::Clear() {
  mEditorBase = nullptr;
  mSelection = nullptr;
  mEditableNode = nullptr;
  mRootElement = nullptr;
  mDocShell = nullptr;
  // Should be safe to clear mDocumentObserver here even though it grabs
  // this instance in most cases because this is called by Init() or Destroy().
  // The callers of Init() grab this instance with local RefPtr.
  // The caller of Destroy() also grabs this instance with local RefPtr.
  // So, this won't cause refcount of this instance become 0.
  mDocumentObserver = nullptr;
}

void IMEContentObserver::ObserveEditableNode() {
  MOZ_RELEASE_ASSERT(mSelection);
  MOZ_RELEASE_ASSERT(mRootElement);
  MOZ_RELEASE_ASSERT(GetState() != eState_Observing);

  // If this is called before sending NOTIFY_IME_OF_FOCUS (it's possible when
  // the editor is reframed before sending NOTIFY_IME_OF_FOCUS asynchronously),
  // the notification requests of mWidget may be different from after the widget
  // receives NOTIFY_IME_OF_FOCUS.   So, this should be called again by
  // OnIMEReceivedFocus() which is called after sending NOTIFY_IME_OF_FOCUS.
  if (!mIMEHasFocus) {
    MOZ_ASSERT(!mWidget || mNeedsToNotifyIMEOfFocusSet ||
                   mSendingNotification == NOTIFY_IME_OF_FOCUS,
               "Wow, OnIMEReceivedFocus() won't be called?");
    return;
  }

  mIsObserving = true;
  if (mEditorBase) {
    mEditorBase->SetIMEContentObserver(this);
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p ObserveEditableNode(), starting to observe 0x%p (%s)", this,
           mRootElement.get(), ToString(*mRootElement).c_str()));

  mRootElement->AddMutationObserver(this);
  // If it's in a document (should be so), we can use document observer to
  // reduce redundant computation of text change offsets.
  Document* doc = mRootElement->GetComposedDoc();
  if (doc) {
    RefPtr<DocumentObserver> documentObserver = mDocumentObserver;
    documentObserver->Observe(doc);
  }

  if (mDocShell) {
    // Add scroll position listener and reflow observer to detect position
    // and size changes
    mDocShell->AddWeakScrollObserver(this);
    mDocShell->AddWeakReflowObserver(this);
  }
}

void IMEContentObserver::NotifyIMEOfBlur() {
  // Prevent any notifications to be sent IME.
  nsCOMPtr<nsIWidget> widget;
  mWidget.swap(widget);
  mIMENotificationRequests = nullptr;

  // If we hasn't been set focus, we shouldn't send blur notification to IME.
  if (!mIMEHasFocus) {
    return;
  }

  // mWidget must have been non-nullptr if IME has focus.
  MOZ_RELEASE_ASSERT(widget);

  RefPtr<IMEContentObserver> kungFuDeathGrip(this);

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p NotifyIMEOfBlur(), sending NOTIFY_IME_OF_BLUR", this));

  // For now, we need to send blur notification in any condition because
  // we don't have any simple ways to send blur notification asynchronously.
  // After this call, Destroy() or Unlink() will stop observing the content
  // and forget everything.  Therefore, if it's not safe to send notification
  // when script blocker is unlocked, we cannot send blur notification after
  // that and before next focus notification.
  // Anyway, as far as we know, IME doesn't try to query content when it loses
  // focus.  So, this may not cause any problem.
  mIMEHasFocus = false;
  IMEStateManager::NotifyIME(IMENotification(NOTIFY_IME_OF_BLUR), widget);

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   NotifyIMEOfBlur(), sent NOTIFY_IME_OF_BLUR", this));
}

void IMEContentObserver::UnregisterObservers() {
  if (!mIsObserving) {
    return;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p UnregisterObservers(), stop observing 0x%p (%s)", this,
           mRootElement.get(),
           mRootElement ? ToString(*mRootElement).c_str() : "nullptr"));

  mIsObserving = false;

  if (mEditorBase) {
    mEditorBase->SetIMEContentObserver(nullptr);
  }

  if (mSelection) {
    mSelectionData.Clear();
    mFocusedWidget = nullptr;
  }

  if (mRootElement) {
    mRootElement->RemoveMutationObserver(this);
  }

  if (mDocumentObserver) {
    RefPtr<DocumentObserver> documentObserver = mDocumentObserver;
    documentObserver->StopObserving();
  }

  if (mDocShell) {
    mDocShell->RemoveWeakScrollObserver(this);
    mDocShell->RemoveWeakReflowObserver(this);
  }
}

nsPresContext* IMEContentObserver::GetPresContext() const {
  return mESM ? mESM->GetPresContext() : nullptr;
}

void IMEContentObserver::Destroy() {
  // WARNING: When you change this method, you have to check Unlink() too.

  // Note that don't send any notifications later from here.  I.e., notify
  // IMEStateManager of the blur synchronously because IMEStateManager needs to
  // stop notifying the main process if this is requested by the main process.
  NotifyIMEOfBlur();
  UnregisterObservers();
  Clear();

  mWidget = nullptr;
  mIMENotificationRequests = nullptr;

  if (mESM) {
    mESM->OnStopObservingContent(this);
    mESM = nullptr;
  }
}

bool IMEContentObserver::Destroyed() const { return !mWidget; }

void IMEContentObserver::DisconnectFromEventStateManager() { mESM = nullptr; }

bool IMEContentObserver::MaybeReinitialize(nsIWidget& aWidget,
                                           nsPresContext& aPresContext,
                                           Element* aElement,
                                           EditorBase& aEditorBase) {
  if (!IsObservingContent(aPresContext, aElement)) {
    return false;
  }

  if (GetState() == eState_StoppedObserving) {
    Init(aWidget, aPresContext, aElement, aEditorBase);
  }
  return IsObserving(aPresContext, aElement);
}

bool IMEContentObserver::IsObserving(const nsPresContext& aPresContext,
                                     const Element* aElement) const {
  if (GetState() != eState_Observing) {
    return false;
  }
  // If aElement is not a text control, aElement is an editing host or entire
  // the document is editable in the design mode.  Therefore, return false if
  // we're observing an anonymous subtree of a text control.
  if (!aElement || !aElement->IsTextControlElement() ||
      !static_cast<const TextControlElement*>(aElement)
           ->IsSingleLineTextControlOrTextArea()) {
    if (mIsTextControl) {
      return false;
    }
  }
  // If aElement is a text control, return true if we're observing the anonymous
  // subtree of aElement.  Therefore, return false if we're observing with
  // HTMLEditor.
  else if (!mIsTextControl) {
    return false;
  }
  return IsObservingContent(aPresContext, aElement);
}

bool IMEContentObserver::IsBeingInitializedFor(
    const nsPresContext& aPresContext, const Element* aElement,
    const EditorBase& aEditorBase) const {
  return GetState() == eState_Initializing && mEditorBase == &aEditorBase &&
         IsObservingContent(aPresContext, aElement);
}

bool IMEContentObserver::IsObserving(
    const TextComposition& aTextComposition) const {
  if (GetState() != eState_Observing) {
    return false;
  }
  nsPresContext* const presContext = aTextComposition.GetPresContext();
  if (NS_WARN_IF(!presContext)) {
    return false;
  }
  if (presContext != GetPresContext()) {
    return false;  // observing different document
  }
  auto* const elementHavingComposition =
      Element::FromNodeOrNull(aTextComposition.GetEventTargetNode());
  bool isObserving = IsObservingContent(*presContext, elementHavingComposition);
#ifdef DEBUG
  if (isObserving) {
    if (mIsTextControl) {
      MOZ_ASSERT(elementHavingComposition);
      MOZ_ASSERT(elementHavingComposition->IsTextControlElement(),
                 "Should've never started to observe non-text-control element");
      // XXX Our fake focus move has not been implemented properly. So, the
      // following assertions may fail, but I don't like to make the failures
      // cause crash even in debug builds because it may block developers to
      // debug web-compat issues.  On the other hand, it'd be nice if we can
      // detect the bug with automated tests.  Therefore, the following
      // assertions are NS_ASSERTION.
      NS_ASSERTION(static_cast<TextControlElement*>(elementHavingComposition)
                       ->IsSingleLineTextControlOrTextArea(),
                   "Should've stopped observing when the type is changed");
      NS_ASSERTION(!elementHavingComposition->IsInDesignMode(),
                   "Should've stopped observing when the design mode started");
    } else if (elementHavingComposition) {
      NS_ASSERTION(
          !elementHavingComposition->IsTextControlElement() ||
              !static_cast<TextControlElement*>(elementHavingComposition)
                   ->IsSingleLineTextControlOrTextArea(),
          "Should've never started to observe text-control element or "
          "stopped observing it when the type is changed");
    } else {
      MOZ_ASSERT(presContext->GetPresShell());
      MOZ_ASSERT(presContext->GetPresShell()->GetDocument());
      NS_ASSERTION(
          presContext->GetPresShell()->GetDocument()->IsInDesignMode(),
          "Should be observing entire the document only in the design mode");
    }
  }
#endif  // #ifdef DEBUG
  return isObserving;
}

IMEContentObserver::State IMEContentObserver::GetState() const {
  if (!mSelection || !mRootElement || !mEditableNode) {
    return eState_NotObserving;  // failed to initialize or finalized.
  }
  if (!mRootElement->IsInComposedDoc()) {
    // the focused editor has already been reframed.
    return eState_StoppedObserving;
  }
  return mIsObserving ? eState_Observing : eState_Initializing;
}

bool IMEContentObserver::IsObservingContent(const nsPresContext& aPresContext,
                                            const Element* aElement) const {
  return mEditableNode ==
         IMEStateManager::GetRootEditableNode(aPresContext, aElement);
}

bool IMEContentObserver::IsEditorHandlingEventForComposition() const {
  if (!mWidget) {
    return false;
  }
  RefPtr<TextComposition> composition =
      IMEStateManager::GetTextCompositionFor(mWidget);
  if (!composition) {
    return false;
  }
  return composition->EditorIsHandlingLatestChange();
}

bool IMEContentObserver::IsEditorComposing() const {
  // Note that don't use TextComposition here. The important thing is,
  // whether the editor already started to handle composition because
  // web contents can change selection, text content and/or something from
  // compositionstart event listener which is run before EditorBase handles it.
  if (NS_WARN_IF(!mEditorBase)) {
    return false;
  }
  return mEditorBase->IsIMEComposing();
}

nsresult IMEContentObserver::GetSelectionAndRoot(Selection** aSelection,
                                                 Element** aRootElement) const {
  if (!mEditableNode || !mSelection) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  NS_ASSERTION(mSelection && mRootElement, "uninitialized content observer");
  NS_ADDREF(*aSelection = mSelection);
  NS_ADDREF(*aRootElement = mRootElement);
  return NS_OK;
}

void IMEContentObserver::OnSelectionChange(Selection& aSelection) {
  if (!mIsObserving) {
    return;
  }

  if (mWidget) {
    bool causedByComposition = IsEditorHandlingEventForComposition();
    bool causedBySelectionEvent = TextComposition::IsHandlingSelectionEvent();
    bool duringComposition = IsEditorComposing();
    MaybeNotifyIMEOfSelectionChange(causedByComposition, causedBySelectionEvent,
                                    duringComposition);
  }
}

void IMEContentObserver::ScrollPositionChanged() {
  if (!NeedsPositionChangeNotification()) {
    return;
  }

  MaybeNotifyIMEOfPositionChange();
}

NS_IMETHODIMP
IMEContentObserver::Reflow(DOMHighResTimeStamp aStart,
                           DOMHighResTimeStamp aEnd) {
  if (!NeedsPositionChangeNotification()) {
    return NS_OK;
  }

  MaybeNotifyIMEOfPositionChange();
  return NS_OK;
}

NS_IMETHODIMP
IMEContentObserver::ReflowInterruptible(DOMHighResTimeStamp aStart,
                                        DOMHighResTimeStamp aEnd) {
  if (!NeedsPositionChangeNotification()) {
    return NS_OK;
  }

  MaybeNotifyIMEOfPositionChange();
  return NS_OK;
}

nsresult IMEContentObserver::HandleQueryContentEvent(
    WidgetQueryContentEvent* aEvent) {
  // If the instance has normal selection cache and the query event queries
  // normal selection's range, it should use the cached selection which was
  // sent to the widget.  However, if this instance has already received new
  // selection change notification but hasn't updated the cache yet (i.e.,
  // not sending selection change notification to IME, don't use the cached
  // value.  Note that don't update selection cache here since if you update
  // selection cache here, IMENotificationSender won't notify IME of selection
  // change because it looks like that the selection isn't actually changed.
  const bool isSelectionCacheAvailable = aEvent->mUseNativeLineBreak &&
                                         mSelectionData.IsInitialized() &&
                                         !mNeedsToNotifyIMEOfSelectionChange;
  if (isSelectionCacheAvailable && aEvent->mMessage == eQuerySelectedText &&
      aEvent->mInput.mSelectionType == SelectionType::eNormal) {
    aEvent->EmplaceReply();
    if (mSelectionData.HasRange()) {
      aEvent->mReply->mOffsetAndData.emplace(mSelectionData.mOffset,
                                             mSelectionData.String(),
                                             OffsetAndDataFor::SelectedString);
      aEvent->mReply->mReversed = mSelectionData.mReversed;
    }
    aEvent->mReply->mContentsRoot = mRootElement;
    aEvent->mReply->mWritingMode = mSelectionData.GetWritingMode();
    // The selection cache in IMEContentObserver must always have been in
    // an editing host (or an editable anonymous <div> element).  Therefore,
    // we set mIsEditableContent to true here even though it's already been
    // blurred or changed its editable state but the selection cache has not
    // been invalidated yet.
    aEvent->mReply->mIsEditableContent = true;
    MOZ_LOG(sIMECOLog, LogLevel::Debug,
            ("0x%p HandleQueryContentEvent(aEvent={ "
             "mMessage=%s, mReply=%s })",
             this, ToChar(aEvent->mMessage), ToString(aEvent->mReply).c_str()));
    return NS_OK;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p HandleQueryContentEvent(aEvent={ mMessage=%s })", this,
           ToChar(aEvent->mMessage)));

  // If we can make the event's input offset absolute with TextComposition or
  // mSelection, we should set it here for reducing the cost of computing
  // selection start offset.  If ContentEventHandler receives a
  // WidgetQueryContentEvent whose input offset is relative to insertion point,
  // it computes current selection start offset (this may be expensive) and
  // make the offset absolute value itself.
  // Note that calling MakeOffsetAbsolute() makes the event a query event with
  // absolute offset.  So, ContentEventHandler doesn't pay any additional cost
  // after calling MakeOffsetAbsolute() here.
  if (aEvent->mInput.mRelativeToInsertionPoint &&
      aEvent->mInput.IsValidEventMessage(aEvent->mMessage)) {
    RefPtr<TextComposition> composition =
        IMEStateManager::GetTextCompositionFor(aEvent->mWidget);
    if (composition) {
      uint32_t compositionStart = composition->NativeOffsetOfStartComposition();
      if (NS_WARN_IF(!aEvent->mInput.MakeOffsetAbsolute(compositionStart))) {
        return NS_ERROR_FAILURE;
      }
    } else if (isSelectionCacheAvailable && mSelectionData.HasRange()) {
      const uint32_t selectionStart = mSelectionData.mOffset;
      if (NS_WARN_IF(!aEvent->mInput.MakeOffsetAbsolute(selectionStart))) {
        return NS_ERROR_FAILURE;
      }
    }
  }

  AutoRestore<bool> handling(mIsHandlingQueryContentEvent);
  mIsHandlingQueryContentEvent = true;
  ContentEventHandler handler(GetPresContext());
  nsresult rv = handler.HandleQueryContentEvent(aEvent);
  if (NS_WARN_IF(Destroyed())) {
    // If this has already destroyed during querying the content, the query
    // is outdated even if it's succeeded.  So, make the query fail.
    aEvent->mReply.reset();
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   HandleQueryContentEvent(), WARNING, "
             "IMEContentObserver has been destroyed during the query, "
             "making the query fail",
             this));
    return rv;
  }

  if (aEvent->Succeeded() &&
      NS_WARN_IF(aEvent->mReply->mContentsRoot != mRootElement)) {
    // Focus has changed unexpectedly, so make the query fail.
    aEvent->mReply.reset();
  }
  return rv;
}

nsresult IMEContentObserver::MaybeHandleSelectionEvent(
    nsPresContext* aPresContext, WidgetSelectionEvent* aEvent) {
  MOZ_ASSERT(aEvent);
  MOZ_ASSERT(aEvent->mMessage == eSetSelection);
  NS_ASSERTION(!mNeedsToNotifyIMEOfSelectionChange,
               "Selection cache has not been updated yet");

  MOZ_LOG(
      sIMECOLog, LogLevel::Debug,
      ("0x%p MaybeHandleSelectionEvent(aEvent={ "
       "mMessage=%s, mOffset=%u, mLength=%u, mReversed=%s, "
       "mExpandToClusterBoundary=%s, mUseNativeLineBreak=%s }), "
       "mSelectionData=%s",
       this, ToChar(aEvent->mMessage), aEvent->mOffset, aEvent->mLength,
       ToChar(aEvent->mReversed), ToChar(aEvent->mExpandToClusterBoundary),
       ToChar(aEvent->mUseNativeLineBreak), ToString(mSelectionData).c_str()));

  // When we have Selection cache, and the caller wants to set same selection
  // range, we shouldn't try to compute same range because it may be impossible
  // if the range boundary is around element boundaries which won't be
  // serialized with line breaks like close tags of inline elements.  In that
  // case, inserting new text at different point may be different from intention
  // of users or web apps which set current selection.
  // FIXME: We cache only selection data computed with native line breaker
  // lengths.  Perhaps, we should improve the struct to have both data of
  // offset and length.  E.g., adding line break counts for both offset and
  // length.
  if (!mNeedsToNotifyIMEOfSelectionChange && aEvent->mUseNativeLineBreak &&
      mSelectionData.IsInitialized() && mSelectionData.HasRange() &&
      mSelectionData.StartOffset() == aEvent->mOffset &&
      mSelectionData.Length() == aEvent->mLength) {
    if (RefPtr<Selection> selection = mSelection) {
      selection->ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION);
    }
    aEvent->mSucceeded = true;
    return NS_OK;
  }

  ContentEventHandler handler(aPresContext);
  return handler.OnSelectionEvent(aEvent);
}

bool IMEContentObserver::OnMouseButtonEvent(nsPresContext& aPresContext,
                                            WidgetMouseEvent& aMouseEvent) {
  if (!mIMENotificationRequests ||
      !mIMENotificationRequests->WantMouseButtonEventOnChar()) {
    return false;
  }
  if (!aMouseEvent.IsTrusted() || aMouseEvent.DefaultPrevented() ||
      !aMouseEvent.mWidget) {
    return false;
  }
  // Now, we need to notify only mouse down and mouse up event.
  switch (aMouseEvent.mMessage) {
    case eMouseUp:
    case eMouseDown:
      break;
    default:
      return false;
  }
  if (NS_WARN_IF(!mWidget) || NS_WARN_IF(mWidget->Destroyed())) {
    return false;
  }

  WidgetQueryContentEvent queryCharAtPointEvent(true, eQueryCharacterAtPoint,
                                                aMouseEvent.mWidget);
  queryCharAtPointEvent.mRefPoint = aMouseEvent.mRefPoint;
  ContentEventHandler handler(&aPresContext);
  handler.OnQueryCharacterAtPoint(&queryCharAtPointEvent);
  if (NS_WARN_IF(queryCharAtPointEvent.Failed()) ||
      queryCharAtPointEvent.DidNotFindChar()) {
    return false;
  }

  // The widget might be destroyed during querying the content since it
  // causes flushing layout.
  if (!mWidget || NS_WARN_IF(mWidget->Destroyed())) {
    return false;
  }

  // The result character rect is relative to the top level widget.
  // We should notify it with offset in the widget.
  nsIWidget* topLevelWidget = mWidget->GetTopLevelWidget();
  if (topLevelWidget && topLevelWidget != mWidget) {
    queryCharAtPointEvent.mReply->mRect.MoveBy(
        topLevelWidget->WidgetToScreenOffset() -
        mWidget->WidgetToScreenOffset());
  }
  // The refPt is relative to its widget.
  // We should notify it with offset in the widget.
  if (aMouseEvent.mWidget != mWidget) {
    queryCharAtPointEvent.mRefPoint +=
        aMouseEvent.mWidget->WidgetToScreenOffset() -
        mWidget->WidgetToScreenOffset();
  }

  IMENotification notification(NOTIFY_IME_OF_MOUSE_BUTTON_EVENT);
  notification.mMouseButtonEventData.mEventMessage = aMouseEvent.mMessage;
  notification.mMouseButtonEventData.mOffset =
      queryCharAtPointEvent.mReply->StartOffset();
  notification.mMouseButtonEventData.mCursorPos =
      queryCharAtPointEvent.mRefPoint;
  notification.mMouseButtonEventData.mCharRect =
      queryCharAtPointEvent.mReply->mRect;
  notification.mMouseButtonEventData.mButton = aMouseEvent.mButton;
  notification.mMouseButtonEventData.mButtons = aMouseEvent.mButtons;
  notification.mMouseButtonEventData.mModifiers = aMouseEvent.mModifiers;

  nsresult rv = IMEStateManager::NotifyIME(notification, mWidget);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  bool consumed = (rv == NS_SUCCESS_EVENT_CONSUMED);
  if (consumed) {
    aMouseEvent.PreventDefault();
  }
  return consumed;
}

void IMEContentObserver::CharacterDataWillChange(
    nsIContent* aContent, const CharacterDataChangeInfo& aInfo) {
  if (!aContent->IsText()) {
    return;  // Ignore if it's a comment node or something other invisible data
             // node.
  }
  MOZ_ASSERT(mPreCharacterDataChangeLength < 0,
             "CharacterDataChanged() should've reset "
             "mPreCharacterDataChangeLength");

  if (!NeedsTextChangeNotification() ||
      !nsContentUtils::IsInSameAnonymousTree(mRootElement, aContent)) {
    return;
  }

  mEndOfAddedTextCache.Clear(__FUNCTION__);
  mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);

  // Although we don't assume this change occurs while this is storing
  // the range of added consecutive nodes, if it actually happens, we need to
  // flush them since this change may occur before or in the range.  So, it's
  // safe to flush pending computation of mTextChangeData before handling this.
  if (mAddedContentCache.HasCache()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }

  mPreCharacterDataChangeLength = ContentEventHandler::GetNativeTextLength(
      *aContent->AsText(), aInfo.mChangeStart, aInfo.mChangeEnd);
  MOZ_ASSERT(
      mPreCharacterDataChangeLength >= aInfo.mChangeEnd - aInfo.mChangeStart,
      "The computed length must be same as or larger than XP length");
}

void IMEContentObserver::CharacterDataChanged(
    nsIContent* aContent, const CharacterDataChangeInfo& aInfo) {
  if (!aContent->IsText()) {
    return;  // Ignore if it's a comment node or something other invisible data
             // node.
  }

  // Let TextComposition have a change to update composition string range in
  // the text node if the change is caused by the web apps.
  if (mWidget && !IsEditorHandlingEventForComposition()) {
    if (RefPtr<TextComposition> composition =
            IMEStateManager::GetTextCompositionFor(mWidget)) {
      composition->OnCharacterDataChanged(*aContent->AsText(), aInfo);
    }
  }

  if (!NeedsTextChangeNotification() ||
      !nsContentUtils::IsInSameAnonymousTree(mRootElement, aContent)) {
    return;
  }

  if (mAddedContentCache.HasCache()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }
  mEndOfAddedTextCache.Clear(__FUNCTION__);
  mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
  MOZ_ASSERT(
      !mAddedContentCache.HasCache(),
      "The stored range should be flushed before actually the data is changed");

  int64_t removedLength = mPreCharacterDataChangeLength;
  mPreCharacterDataChangeLength = -1;

  MOZ_ASSERT(removedLength >= 0,
             "mPreCharacterDataChangeLength should've been set by "
             "CharacterDataWillChange()");

  uint32_t offset = 0;
  if (mIsTextControl) {
    // If we're observing a text control, mRootElement is the anonymous <div>
    // element which has only one text node and/or invisible <br> element.
    // TextEditor assumes this structure when it handles editing commands.
    // Therefore, it's safe to assume same things here.
    MOZ_ASSERT(mRootElement->GetFirstChild() == aContent);
    if (aInfo.mChangeStart) {
      offset = ContentEventHandler::GetNativeTextLength(*aContent->AsText(), 0,
                                                        aInfo.mChangeStart);
    }
  } else {
    nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
        RawNodePosition::BeforeFirstContentOf(*mRootElement),
        RawNodePosition(aContent, aInfo.mChangeStart), mRootElement, &offset,
        LINE_BREAK_TYPE_NATIVE);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }
  }

  uint32_t newLength = ContentEventHandler::GetNativeTextLength(
      *aContent->AsText(), aInfo.mChangeStart,
      aInfo.mChangeStart + aInfo.mReplaceLength);

  uint32_t oldEnd = offset + static_cast<uint32_t>(removedLength);
  uint32_t newEnd = offset + newLength;

  TextChangeData data(offset, oldEnd, newEnd,
                      IsEditorHandlingEventForComposition(),
                      IsEditorComposing());
  MaybeNotifyIMEOfTextChange(data);
}

void IMEContentObserver::ContentAdded(nsINode* aContainer,
                                      nsIContent* aFirstContent,
                                      nsIContent* aLastContent) {
  if (!NeedsTextChangeNotification() ||
      !nsContentUtils::IsInSameAnonymousTree(mRootElement, aFirstContent)) {
    return;
  }

  // We can skip everything when a padding <br> element is added since its text
  // length is 0.
  if (aFirstContent == aLastContent) {
    if (const auto* brElement = HTMLBRElement::FromNode(aFirstContent)) {
      if (MOZ_LIKELY(!brElement->HasChildNodes()) &&
          (brElement->IsPaddingForEmptyEditor() ||
           brElement->IsPaddingForEmptyLastLine())) {
        return;
      }
    }
  }

  MOZ_ASSERT(IsInDocumentChange());
  MOZ_ASSERT_IF(aFirstContent, aFirstContent->GetParentNode() == aContainer);
  MOZ_ASSERT_IF(aLastContent, aLastContent->GetParentNode() == aContainer);

  // While a document change, new nodes should be added consecutively in a
  // container node.  Therefore, we can cache the first added node and the last
  // added node until ending the document change at least.  Then, we can avoid
  // to compute first added node offset in the flattened text repeatedly.
  bool needToCache = true;
  if (mAddedContentCache.HasCache()) {
    MOZ_DIAGNOSTIC_ASSERT(aFirstContent->GetParentNode() ==
                          aLastContent->GetParentNode());
    if (mAddedContentCache.IsInRange(*aFirstContent, mRootElement)) {
      // The new content nodes are in the range, we can include their text
      // length when we flush the cached range later.  Therefore, we need to
      // do nothing in this case.
      needToCache = false;
      MOZ_LOG(sCacheLog, LogLevel::Info,
              ("ContentAdded: mAddedContentCache already caches the give "
               "content nodes"));
      MOZ_ASSERT(mAddedContentCache.IsInRange(*aLastContent, mRootElement));
    }
    // When new nodes are inserted in a different container, let's flush the
    // preceding content first.  Then, we should restart to cache the new
    // inserted nodes.
    else if (!mAddedContentCache.CanMergeWith(*aFirstContent, *aLastContent,
                                              mRootElement)) {
      MOZ_LOG(sCacheLog, LogLevel::Info,
              ("ContentAdded: mAddedContentCache was cached not in current "
               "document change and new content nodes cannot be merged"));
      mEndOfAddedTextCache.Clear(__FUNCTION__);
      mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
      OffsetAndLengthAdjustments differences;
      Result<std::pair<uint32_t, uint32_t>, nsresult> offsetAndLength =
          mAddedContentCache.ComputeFlatTextRangeBeforeInsertingNewContent(
              *aFirstContent, *aLastContent, mRootElement, differences);
      if (NS_WARN_IF(offsetAndLength.isErr())) {
        MOZ_LOG(sCacheLog, LogLevel::Error,
                ("ContentAdded: "
                 "AddedContentCache::"
                 "ComputeFlatTextRangeExcludingInsertingNewContent() failed"));
        mAddedContentCache.Clear(__FUNCTION__);
        return;
      }
      NotifyIMEOfCachedConsecutiveNewNodes(
          __FUNCTION__, Some(offsetAndLength.inspect().first),
          Some(offsetAndLength.inspect().second), differences);
      mAddedContentCache.Clear(__FUNCTION__);
    }
  }

  mEndOfAddedTextCache.ContentAdded(__FUNCTION__, *aFirstContent, *aLastContent,
                                    Nothing(), mRootElement);
  mStartOfRemovingTextRangeCache.ContentAdded(
      __FUNCTION__, *aFirstContent, *aLastContent, Nothing(), mRootElement);

  if (!needToCache) {
    return;
  }

  // Okay, now, we can start to cache new nodes or merge the range of new
  // nodes with the cached range.
  if (!mAddedContentCache.TryToCache(*aFirstContent, *aLastContent,
                                     mRootElement)) {
    // Flush the old range first.
    MOZ_LOG(sCacheLog, LogLevel::Info,
            ("ContentAdded: called during a document change flushed "
             "previous added nodes (aFirstContent=%s, aLastContent=%s)",
             ToString(RefPtr<nsINode>(aFirstContent)).c_str(),
             ToString(RefPtr<nsINode>(aLastContent)).c_str()));
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
    MOZ_ASSERT(!mAddedContentCache.HasCache());
    MOZ_ALWAYS_TRUE(mAddedContentCache.TryToCache(*aFirstContent, *aLastContent,
                                                  mRootElement));
  }
}

void IMEContentObserver::NotifyIMEOfCachedConsecutiveNewNodes(
    const char* aCallerName,
    const Maybe<uint32_t>& aOffsetOfFirstContent /* = Nothing() */,
    const Maybe<uint32_t>& aLengthOfContentNNodes /* = Nothing() */,
    const OffsetAndLengthAdjustments& aAdjustments /* = Nothing() */) {
  MOZ_ASSERT(mAddedContentCache.HasCache());

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p "
           "IMEContentObserver::NotifyIMEOfCachedConsecutiveNewNodes(), "
           "flushing stored consecutive nodes",
           this));
  MOZ_LOG(sCacheLog, LogLevel::Info,
          ("NotifyIMEOfCachedConsecutiveNewNodes: called by %s "
           "(mAddedContentCache=%s)",
           aCallerName, ToString(mAddedContentCache).c_str()));

  // If 2 <div> elements are inserted into the DOM, we wan't the text length
  // from start of the first <div> (including line break caused by its open
  // tag) to end of the second <div>.  I.e., we want to compute:
  // ...{<div>.....</div><div>......</div>}...
  //    ^  ^               ^              ^
  //    |  mFirst          |              |
  //    |                  mLast          |
  //    offset                            (offset + length)
  Maybe<uint32_t> offset =
      aOffsetOfFirstContent.isSome()
          ? aOffsetOfFirstContent
          : mEndOfAddedTextCache.GetFlatTextLengthBeforeContent(
                *mAddedContentCache.mFirst, mRootElement);
  if (offset.isNothing()) {
    Result<uint32_t, nsresult> textLengthBeforeFirstContentOrError =
        FlatTextCache::ComputeTextLengthBeforeContent(
            *mAddedContentCache.mFirst, mRootElement);
    if (NS_WARN_IF(textLengthBeforeFirstContentOrError.isErr())) {
      mEndOfAddedTextCache.Clear(__FUNCTION__);
      mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
      MOZ_LOG(
          sCacheLog, LogLevel::Error,
          ("NotifyContentAdded: failed to compute text length before mFirst"));
      mAddedContentCache.Clear(__FUNCTION__);
      return;
    }
    offset = Some(textLengthBeforeFirstContentOrError.unwrap());
  }
  Maybe<uint32_t> length = aLengthOfContentNNodes;
  if (aLengthOfContentNNodes.isNothing()) {
    Result<uint32_t, nsresult> addingLengthOrError =
        FlatTextCache::ComputeTextLengthStartOfContentToEndOfContent(
            *mAddedContentCache.mFirst, *mAddedContentCache.mLast,
            mRootElement);
    if (NS_WARN_IF(addingLengthOrError.isErr())) {
      mEndOfAddedTextCache.Clear(__FUNCTION__);
      mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
      MOZ_LOG(sCacheLog, LogLevel::Error,
              ("NotifyContentAdded: failed to compute text length of added"));
      mAddedContentCache.Clear(__FUNCTION__);
      return;
    }
    length = Some(addingLengthOrError.inspect());
  }

  // If multiple lines are being inserted in an HTML editor, next call of
  // NotifyContentAdded() is for adding next node.  Therefore, caching the text
  // length can skip to compute the text length before the adding node and
  // before of it.
  mEndOfAddedTextCache.CacheFlatTextLengthBeforeEndOfContent(
      __FUNCTION__, *mAddedContentCache.mLast,
      aAdjustments.AdjustedEndOffset(*offset + *length), mRootElement);
  mStartOfRemovingTextRangeCache.ContentAdded(
      __FUNCTION__, *mAddedContentCache.mFirst, *mAddedContentCache.mLast,
      Some(aAdjustments.AdjustedEndOffset(*offset + *length)), mRootElement);

  mAddedContentCache.Clear(__FUNCTION__);

  if (*length == 0u) {
    return;
  }

  TextChangeData data(*offset, *offset, *offset + *length,
                      IsEditorHandlingEventForComposition(),
                      IsEditorComposing());
  MaybeNotifyIMEOfTextChange(data);
}

void IMEContentObserver::ContentAppended(nsIContent* aFirstNewContent,
                                         const ContentAppendInfo&) {
  nsIContent* parent = aFirstNewContent->GetParent();
  MOZ_ASSERT(parent);
  ContentAdded(parent, aFirstNewContent, parent->GetLastChild());
}

void IMEContentObserver::ContentInserted(nsIContent* aChild,
                                         const ContentInsertInfo&) {
  MOZ_ASSERT(aChild);
  ContentAdded(aChild->GetParentNode(), aChild, aChild);
}

void IMEContentObserver::ContentWillBeRemoved(nsIContent* aChild,
                                              const ContentRemoveInfo&) {
  if (!NeedsTextChangeNotification() ||
      !nsContentUtils::IsInSameAnonymousTree(mRootElement, aChild)) {
    return;
  }

  // We can skip everything when padding <br> element is removed since its text
  // length is 0.
  if (const auto* brElement = HTMLBRElement::FromNode(aChild)) {
    if (MOZ_LIKELY(!brElement->HasChildNodes()) &&
        (brElement->IsPaddingForEmptyEditor() ||
         brElement->IsPaddingForEmptyLastLine())) {
      return;
    }
  }

  const Result<uint32_t, nsresult> textLengthOrError =
      FlatTextCache::ComputeTextLengthOfContent(*aChild, mRootElement,
                                                ForRemoval::Yes);
  if (NS_WARN_IF(textLengthOrError.isErr())) {
    mEndOfAddedTextCache.Clear(__FUNCTION__);
    mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
    mAddedContentCache.Clear(__FUNCTION__);
    return;
  }

  if (mAddedContentCache.HasCache()) {
    mEndOfAddedTextCache.Clear(__FUNCTION__);
    mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
    MOZ_DIAGNOSTIC_ASSERT(!mAddedContentCache.HasCache());
  }

  nsINode* containerNode = aChild->GetParentNode();
  MOZ_ASSERT(containerNode);

  mEndOfAddedTextCache.ContentWillBeRemoved(
      *aChild, textLengthOrError.inspect(), mRootElement);

  Maybe<uint32_t> offset =
      mStartOfRemovingTextRangeCache.GetFlatTextLengthBeforeContent(
          *aChild, mRootElement, ForRemoval::Yes);
  nsIContent* const prevSibling = aChild->GetPreviousSibling();
  if (offset.isSome()) {
    // Update the cache because next remove may be the previous or the next
    // sibling removal.  So, caching offset of currently removing content node
    // makes us skip computing offset of next removal.
    if (prevSibling) {
      mStartOfRemovingTextRangeCache.CacheFlatTextLengthBeforeEndOfContent(
          __FUNCTION__, *prevSibling, *offset, mRootElement);
    } else {
      mStartOfRemovingTextRangeCache.CacheFlatTextLengthBeforeFirstContent(
          __FUNCTION__, *containerNode, *offset, mRootElement);
    }
  } else {
    if (prevSibling) {
      // When we compute preceding text length of the removing content node, we
      // cannot make the range cross the removing node boundary because
      // containerNode->ComputeIndexOf(aChild) returns Nothing so that
      // ContentEventHandler fails to compute the length.  Therefore, if a <div>
      // is being removed, we want to compute the length of `...}<div>`.
      if (NS_WARN_IF(
              NS_FAILED(mStartOfRemovingTextRangeCache
                            .ComputeAndCacheFlatTextLengthBeforeEndOfContent(
                                __FUNCTION__, *prevSibling, mRootElement)))) {
        return;
      }
    } else {
      // At removing a child node of containerNode, we need the line break
      // caused by open tag of containerNode.
      if (NS_WARN_IF(
              NS_FAILED(mStartOfRemovingTextRangeCache
                            .ComputeAndCacheFlatTextLengthBeforeFirstContent(
                                __FUNCTION__, *containerNode, mRootElement)))) {
        return;
      }
    }
    offset = Some(mStartOfRemovingTextRangeCache.GetFlatTextLength());
  }

  // We do not need a text change notification since removing aChild does not
  // change flattened text and no pending added length.
  if (textLengthOrError.inspect() == 0u) {
    return;
  }

  TextChangeData data(*offset, *offset + textLengthOrError.inspect(), *offset,
                      IsEditorHandlingEventForComposition(),
                      IsEditorComposing());
  MaybeNotifyIMEOfTextChange(data);
}

MOZ_CAN_RUN_SCRIPT_BOUNDARY void IMEContentObserver::ParentChainChanged(
    nsIContent* aContent) {
  // When the observing element itself is directly removed from the document
  // without a focus move, i.e., it's the root of the removed document fragment
  // and the editor was handling the design mode, we have already stopped
  // observing the element because IMEStateManager::OnRemoveContent() should
  // have already been called for it and the instance which was observing the
  // node has already been destroyed.  Therefore, this is called only when
  // this is observing the <body> in the design mode and it's disconnected from
  // the tree by an <html> element removal.  Even in this case, IMEStateManager
  // never gets a focus change notification, but we need to notify IME of focus
  // change because we cannot interact with IME anymore due to no editable
  // content.  Therefore, this method notifies IMEStateManager of the
  // disconnection of the observing node to emulate a blur from the editable
  // content.
  MOZ_ASSERT(mIsObserving);
  OwningNonNull<IMEContentObserver> observer(*this);
  IMEStateManager::OnParentChainChangedOfObservingElement(observer);
}

void IMEContentObserver::OnTextControlValueChangedWhileNotObservable(
    const nsAString& aNewValue) {
  MOZ_ASSERT(mEditorBase);
  MOZ_ASSERT(mEditorBase->IsTextEditor());
  if (!mTextControlValueLength && aNewValue.IsEmpty()) {
    return;
  }
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p OnTextControlValueChangedWhileNotObservable()", this));
  uint32_t newLength = ContentEventHandler::GetNativeTextLength(aNewValue);
  TextChangeData data(0, mTextControlValueLength, newLength, false, false);
  MaybeNotifyIMEOfTextChange(data);
}

void IMEContentObserver::BeginDocumentUpdate() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug, ("0x%p BeginDocumentUpdate()", this));
}

void IMEContentObserver::EndDocumentUpdate() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug, ("0x%p EndDocumentUpdate()", this));

  if (mAddedContentCache.HasCache() && !EditorIsHandlingEditSubAction()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }
}

void IMEContentObserver::SuppressNotifyingIME() {
  mSuppressNotifications++;

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p SuppressNotifyingIME(), mSuppressNotifications=%u", this,
           mSuppressNotifications));
}

void IMEContentObserver::UnsuppressNotifyingIME() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p UnsuppressNotifyingIME(), mSuppressNotifications=%u", this,
           mSuppressNotifications));

  if (!mSuppressNotifications || --mSuppressNotifications) {
    return;
  }
  FlushMergeableNotifications();
}

void IMEContentObserver::OnEditActionHandled() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug, ("0x%p OnEditActionHandled()", this));

  if (mAddedContentCache.HasCache()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }
  mEndOfAddedTextCache.Clear(__FUNCTION__);
  mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
  FlushMergeableNotifications();
}

void IMEContentObserver::BeforeEditAction() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug, ("0x%p BeforeEditAction()", this));

  if (mAddedContentCache.HasCache()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }
  mEndOfAddedTextCache.Clear(__FUNCTION__);
  mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
}

void IMEContentObserver::CancelEditAction() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug, ("0x%p CancelEditAction()", this));

  if (mAddedContentCache.HasCache()) {
    NotifyIMEOfCachedConsecutiveNewNodes(__FUNCTION__);
  }
  mEndOfAddedTextCache.Clear(__FUNCTION__);
  mStartOfRemovingTextRangeCache.Clear(__FUNCTION__);
  FlushMergeableNotifications();
}

bool IMEContentObserver::EditorIsHandlingEditSubAction() const {
  return mEditorBase && mEditorBase->IsInEditSubAction();
}

void IMEContentObserver::PostFocusSetNotification() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p PostFocusSetNotification()", this));

  mNeedsToNotifyIMEOfFocusSet = true;
}

void IMEContentObserver::PostTextChangeNotification() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p PostTextChangeNotification(mTextChangeData=%s)", this,
           ToString(mTextChangeData).c_str()));

  MOZ_ASSERT(mTextChangeData.IsValid(),
             "mTextChangeData must have text change data");
  mNeedsToNotifyIMEOfTextChange = true;
  // Even if the observer hasn't received selection change, selection in the
  // flat text may have already been changed.  For example, when previous `<p>`
  // element of another `<p>` element which contains caret is removed by a DOM
  // mutation, selection change event won't be fired, but selection start offset
  // should be decreased by the length of removed `<p>` element.
  // In such case, HandleQueryContentEvent shouldn't use the selection cache
  // anymore.  Therefore, we also need to post selection change notification
  // too.  eQuerySelectedText event may be dispatched at sending a text change
  // notification.
  mNeedsToNotifyIMEOfSelectionChange = true;
}

void IMEContentObserver::PostSelectionChangeNotification() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p PostSelectionChangeNotification(), mSelectionData={ "
           "mCausedByComposition=%s, mCausedBySelectionEvent=%s }",
           this, ToChar(mSelectionData.mCausedByComposition),
           ToChar(mSelectionData.mCausedBySelectionEvent)));

  mNeedsToNotifyIMEOfSelectionChange = true;
}

void IMEContentObserver::MaybeNotifyIMEOfFocusSet() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p MaybeNotifyIMEOfFocusSet()", this));

  PostFocusSetNotification();
  FlushMergeableNotifications();
}

void IMEContentObserver::MaybeNotifyIMEOfTextChange(
    const TextChangeDataBase& aTextChangeData) {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p MaybeNotifyIMEOfTextChange(aTextChangeData=%s)", this,
           ToString(aTextChangeData).c_str()));

  if (mEditorBase && mEditorBase->IsTextEditor()) {
    MOZ_DIAGNOSTIC_ASSERT(static_cast<int64_t>(mTextControlValueLength) +
                              aTextChangeData.Difference() >=
                          0);
    mTextControlValueLength += aTextChangeData.Difference();
  }

  mTextChangeData += aTextChangeData;
  PostTextChangeNotification();
  FlushMergeableNotifications();
}

void IMEContentObserver::CancelNotifyingIMEOfTextChange() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p CancelNotifyingIMEOfTextChange()", this));
  mTextChangeData.Clear();
  mNeedsToNotifyIMEOfTextChange = false;
}

void IMEContentObserver::MaybeNotifyIMEOfSelectionChange(
    bool aCausedByComposition, bool aCausedBySelectionEvent,
    bool aOccurredDuringComposition) {
  MOZ_LOG(
      sIMECOLog, LogLevel::Debug,
      ("0x%p MaybeNotifyIMEOfSelectionChange(aCausedByComposition=%s, "
       "aCausedBySelectionEvent=%s, aOccurredDuringComposition)",
       this, ToChar(aCausedByComposition), ToChar(aCausedBySelectionEvent)));

  mSelectionData.AssignReason(aCausedByComposition, aCausedBySelectionEvent,
                              aOccurredDuringComposition);
  PostSelectionChangeNotification();
  FlushMergeableNotifications();
}

void IMEContentObserver::MaybeNotifyIMEOfPositionChange() {
  MOZ_LOG(sIMECOLog, LogLevel::Verbose,
          ("0x%p MaybeNotifyIMEOfPositionChange()", this));
  // If reflow is caused by ContentEventHandler during PositionChangeEvent
  // sending NOTIFY_IME_OF_POSITION_CHANGE, we don't need to notify IME of it
  // again since ContentEventHandler returns the result including this reflow's
  // result.
  if (mIsHandlingQueryContentEvent &&
      mSendingNotification == NOTIFY_IME_OF_POSITION_CHANGE) {
    MOZ_LOG(sIMECOLog, LogLevel::Verbose,
            ("0x%p   MaybeNotifyIMEOfPositionChange(), ignored since caused by "
             "ContentEventHandler during sending NOTIFY_IME_OF_POSITION_CHANGE",
             this));
    return;
  }
  PostPositionChangeNotification();
  FlushMergeableNotifications();
}

void IMEContentObserver::CancelNotifyingIMEOfPositionChange() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p CancelNotifyIMEOfPositionChange()", this));
  mNeedsToNotifyIMEOfPositionChange = false;
}

void IMEContentObserver::MaybeNotifyCompositionEventHandled() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p MaybeNotifyCompositionEventHandled()", this));

  PostCompositionEventHandledNotification();
  FlushMergeableNotifications();
}

bool IMEContentObserver::UpdateSelectionCache(bool aRequireFlush /* = true */) {
  MOZ_ASSERT(IsSafeToNotifyIME());

  mSelectionData.ClearSelectionData();

  // XXX Cannot we cache some information for reducing the cost to compute
  //     selection offset and writing mode?
  WidgetQueryContentEvent querySelectedTextEvent(true, eQuerySelectedText,
                                                 mWidget);
  querySelectedTextEvent.mNeedsToFlushLayout = aRequireFlush;
  ContentEventHandler handler(GetPresContext());
  handler.OnQuerySelectedText(&querySelectedTextEvent);
  if (NS_WARN_IF(querySelectedTextEvent.Failed()) ||
      NS_WARN_IF(querySelectedTextEvent.mReply->mContentsRoot !=
                 mRootElement)) {
    return false;
  }

  mFocusedWidget = querySelectedTextEvent.mReply->mFocusedWidget;
  mSelectionData.Assign(querySelectedTextEvent);

  // WARNING: Don't set the reason of selection change here because it should be
  //          set the reason at sending the notification.

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p UpdateSelectionCache(), mSelectionData=%s", this,
           ToString(mSelectionData).c_str()));

  return true;
}

void IMEContentObserver::PostPositionChangeNotification() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p PostPositionChangeNotification()", this));

  mNeedsToNotifyIMEOfPositionChange = true;
}

void IMEContentObserver::PostCompositionEventHandledNotification() {
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p PostCompositionEventHandledNotification()", this));

  mNeedsToNotifyIMEOfCompositionEventHandled = true;
}

bool IMEContentObserver::IsReflowLocked() const {
  nsPresContext* presContext = GetPresContext();
  if (NS_WARN_IF(!presContext)) {
    return false;
  }
  PresShell* presShell = presContext->GetPresShell();
  if (NS_WARN_IF(!presShell)) {
    return false;
  }
  // During reflow, we shouldn't notify IME because IME may query content
  // synchronously.  Then, it causes ContentEventHandler will try to flush
  // pending notifications during reflow.
  return presShell->IsReflowLocked();
}

bool IMEContentObserver::IsSafeToNotifyIME() const {
  // If this is already detached from the widget, this doesn't need to notify
  // anything.
  if (!mWidget) {
    MOZ_LOG(sIMECOLog, LogLevel::Debug,
            ("0x%p   IsSafeToNotifyIME(), it's not safe because of no widget",
             this));
    return false;
  }

  // Don't notify IME of anything if it's not good time to do it.
  if (mSuppressNotifications) {
    MOZ_LOG(sIMECOLog, LogLevel::Debug,
            ("0x%p   IsSafeToNotifyIME(), it's not safe because of no widget",
             this));
    return false;
  }

  if (!mESM || NS_WARN_IF(!GetPresContext())) {
    MOZ_LOG(sIMECOLog, LogLevel::Debug,
            ("0x%p   IsSafeToNotifyIME(), it's not safe because of no "
             "EventStateManager and/or PresContext",
             this));
    return false;
  }

  // If it's in reflow, we should wait to finish the reflow.
  // FYI: This should be called again from Reflow() or ReflowInterruptible().
  if (IsReflowLocked()) {
    MOZ_LOG(
        sIMECOLog, LogLevel::Debug,
        ("0x%p   IsSafeToNotifyIME(), it's not safe because of reflow locked",
         this));
    return false;
  }

  // If we're in handling an edit action, this method will be called later.
  if (EditorIsHandlingEditSubAction()) {
    MOZ_LOG(sIMECOLog, LogLevel::Debug,
            ("0x%p   IsSafeToNotifyIME(), it's not safe because of focused "
             "editor handling somethings",
             this));
    return false;
  }

  return true;
}

void IMEContentObserver::FlushMergeableNotifications() {
  if (!IsSafeToNotifyIME()) {
    // So, if this is already called, this should do nothing.
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   FlushMergeableNotifications(), Warning, do nothing due to "
             "unsafe to notify IME",
             this));
    return;
  }

  // Notifying something may cause nested call of this method.  For example,
  // when somebody notified one of the notifications may dispatch query content
  // event. Then, it causes flushing layout which may cause another layout
  // change notification.

  if (mQueuedSender) {
    // So, if this is already called, this should do nothing.
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   FlushMergeableNotifications(), Warning, do nothing due to "
             "already flushing pending notifications",
             this));
    return;
  }

  // If text change notification and/or position change notification becomes
  // unnecessary, let's cancel them.
  if (mNeedsToNotifyIMEOfTextChange && !NeedsTextChangeNotification()) {
    CancelNotifyingIMEOfTextChange();
  }
  if (mNeedsToNotifyIMEOfPositionChange && !NeedsPositionChangeNotification()) {
    CancelNotifyingIMEOfPositionChange();
  }

  if (!NeedsToNotifyIMEOfSomething()) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   FlushMergeableNotifications(), Warning, due to no pending "
             "notifications",
             this));
    return;
  }

  // NOTE: Reset each pending flag because sending notification may cause
  //       another change.

  MOZ_LOG(
      sIMECOLog, LogLevel::Info,
      ("0x%p FlushMergeableNotifications(), creating IMENotificationSender...",
       this));

  // If contents in selection range is modified, the selection range still
  // has removed node from the tree.  In such case, ContentIterator won't
  // work well.  Therefore, we shouldn't use AddScriptRunner() here since
  // it may kick runnable event immediately after DOM tree is changed but
  // the selection range isn't modified yet.
  mQueuedSender = new IMENotificationSender(this);
  mQueuedSender->Dispatch(mDocShell);
  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   FlushMergeableNotifications(), finished", this));
}

void IMEContentObserver::TryToFlushPendingNotifications(bool aAllowAsync) {
  // If a sender instance is sending notifications, we shouldn't try to create
  // a new sender again because the sender will recreate by itself if there are
  // new pending notifications.
  if (mSendingNotification != NOTIFY_IME_OF_NOTHING) {
    return;
  }

  // When the caller allows to put off notifying IME, we can wait the next
  // call of this method or to run the queued sender.
  if (mQueuedSender && XRE_IsContentProcess() && aAllowAsync) {
    return;
  }

  if (!mQueuedSender) {
    // If it was not safe to dispatch notifications when the pending
    // notifications are posted, this may not have IMENotificationSender
    // instance because it couldn't dispatch it, e.g., when an edit sub-action
    // is being handled in the editor, we shouldn't do it even if it's safe to
    // run script.  Therefore, we need to create the sender instance here in the
    // case.
    if (!NeedsToNotifyIMEOfSomething()) {
      return;
    }
    mQueuedSender = new IMENotificationSender(this);
  }

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p TryToFlushPendingNotifications(), performing queued "
           "IMENotificationSender forcibly",
           this));
  RefPtr<IMENotificationSender> queuedSender = mQueuedSender;
  queuedSender->Run();
}

/******************************************************************************
 * mozilla::IMEContentObserver::AChangeEvent
 ******************************************************************************/

bool IMEContentObserver::AChangeEvent::CanNotifyIME(
    ChangeEventType aChangeEventType) const {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (NS_WARN_IF(!observer)) {
    return false;
  }

  const LogLevel debugOrVerbose =
      aChangeEventType == ChangeEventType::eChangeEventType_Position
          ? LogLevel::Verbose
          : LogLevel::Debug;

  if (aChangeEventType == eChangeEventType_CompositionEventHandled) {
    if (observer->mWidget) {
      return true;
    }
    MOZ_LOG(sIMECOLog, debugOrVerbose,
            ("0x%p   AChangeEvent::CanNotifyIME(), Cannot notify IME of "
             "composition event handled because of no widget",
             this));
    return false;
  }
  State state = observer->GetState();
  // If it's not initialized, we should do nothing.
  if (state == eState_NotObserving) {
    MOZ_LOG(sIMECOLog, debugOrVerbose,
            ("0x%p   AChangeEvent::CanNotifyIME(), Cannot notify IME because "
             "of not observing",
             this));
    return false;
  }
  // If setting focus, just check the state.
  if (aChangeEventType == eChangeEventType_Focus) {
    if (!observer->mIMEHasFocus) {
      return true;
    }
    MOZ_LOG(sIMECOLog, debugOrVerbose,
            ("0x%p   AChangeEvent::CanNotifyIME(), Cannot notify IME of focus "
             "change because of already focused",
             this));
    NS_WARNING("IME already has focus");
    return false;
  }
  // If we've not notified IME of focus yet, we shouldn't notify anything.
  if (!observer->mIMEHasFocus) {
    MOZ_LOG(sIMECOLog, debugOrVerbose,
            ("0x%p   AChangeEvent::CanNotifyIME(), Cannot notify IME because "
             "of not focused",
             this));
    return false;
  }

  // If IME has focus, IMEContentObserver must hold the widget.
  MOZ_ASSERT(observer->mWidget);

  return true;
}

bool IMEContentObserver::AChangeEvent::IsSafeToNotifyIME(
    ChangeEventType aChangeEventType) const {
  const LogLevel warningOrVerbose =
      aChangeEventType == ChangeEventType::eChangeEventType_Position
          ? LogLevel::Verbose
          : LogLevel::Warning;

  if (NS_WARN_IF(!nsContentUtils::IsSafeToRunScript())) {
    MOZ_LOG(sIMECOLog, warningOrVerbose,
            ("0x%p   AChangeEvent::IsSafeToNotifyIME(), Warning, Cannot notify "
             "IME because of not safe to run script",
             this));
    return false;
  }

  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    MOZ_LOG(sIMECOLog, warningOrVerbose,
            ("0x%p   AChangeEvent::IsSafeToNotifyIME(), Warning, Cannot notify "
             "IME because of no observer",
             this));
    return false;
  }

  // While we're sending a notification, we shouldn't send another notification
  // recursively.
  if (observer->mSendingNotification != NOTIFY_IME_OF_NOTHING) {
    MOZ_LOG(sIMECOLog, warningOrVerbose,
            ("0x%p   AChangeEvent::IsSafeToNotifyIME(), Warning, Cannot notify "
             "IME because of the observer sending another notification",
             this));
    return false;
  }
  State state = observer->GetState();
  if (aChangeEventType == eChangeEventType_Focus) {
    if (NS_WARN_IF(state != eState_Initializing && state != eState_Observing)) {
      MOZ_LOG(sIMECOLog, warningOrVerbose,
              ("0x%p   AChangeEvent::IsSafeToNotifyIME(), Warning, Cannot "
               "notify IME of focus because of not observing",
               this));
      return false;
    }
  } else if (aChangeEventType == eChangeEventType_CompositionEventHandled) {
    // It doesn't need to check the observing status.
  } else if (state != eState_Observing) {
    MOZ_LOG(sIMECOLog, warningOrVerbose,
            ("0x%p   AChangeEvent::IsSafeToNotifyIME(), Warning, Cannot notify "
             "IME because of not observing",
             this));
    return false;
  }
  return observer->IsSafeToNotifyIME();
}

/******************************************************************************
 * mozilla::IMEContentObserver::IMENotificationSender
 ******************************************************************************/

void IMEContentObserver::IMENotificationSender::Dispatch(
    nsIDocShell* aDocShell) {
  if (XRE_IsContentProcess() && aDocShell) {
    if (RefPtr<nsPresContext> presContext = aDocShell->GetPresContext()) {
      if (nsRefreshDriver* refreshDriver = presContext->RefreshDriver()) {
        refreshDriver->AddEarlyRunner(this);
        return;
      }
    }
  }
  NS_DispatchToCurrentThread(this);
}

NS_IMETHODIMP
IMEContentObserver::IMENotificationSender::Run() {
  if (NS_WARN_IF(mIsRunning)) {
    MOZ_LOG(
        sIMECOLog, LogLevel::Error,
        ("0x%p IMENotificationSender::Run(), FAILED, due to called recursively",
         this));
    return NS_OK;
  }

  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return NS_OK;
  }

  AutoRestore<bool> running(mIsRunning);
  mIsRunning = true;

  // This instance was already performed forcibly.
  if (observer->mQueuedSender != this) {
    return NS_OK;
  }

  // NOTE: Reset each pending flag because sending notification may cause
  //       another change.

  if (observer->mNeedsToNotifyIMEOfFocusSet) {
    observer->mNeedsToNotifyIMEOfFocusSet = false;
    SendFocusSet();
    observer->mQueuedSender = nullptr;
    // If it's not safe to notify IME of focus, SendFocusSet() sets
    // mNeedsToNotifyIMEOfFocusSet true again.  For guaranteeing to send the
    // focus notification later,  we should put a new sender into the queue but
    // this case must be rare.  Note that if mIMEContentObserver is already
    // destroyed, mNeedsToNotifyIMEOfFocusSet is never set true again.
    if (observer->mNeedsToNotifyIMEOfFocusSet) {
      MOZ_ASSERT(!observer->mIMEHasFocus);
      MOZ_LOG(sIMECOLog, LogLevel::Debug,
              ("0x%p IMENotificationSender::Run(), posting "
               "IMENotificationSender to current thread",
               this));
      observer->mQueuedSender = new IMENotificationSender(observer);
      observer->mQueuedSender->Dispatch(observer->mDocShell);
      return NS_OK;
    }
    // This is the first notification to IME. So, we don't need to notify
    // anymore since IME starts to query content after it gets focus.
    observer->ClearPendingNotifications();
    return NS_OK;
  }

  if (observer->mNeedsToNotifyIMEOfTextChange) {
    observer->mNeedsToNotifyIMEOfTextChange = false;
    SendTextChange();
  }

  // If a text change notification causes another text change again, we should
  // notify IME of that before sending a selection change notification.
  if (!observer->mNeedsToNotifyIMEOfTextChange) {
    // Be aware, PuppetWidget depends on the order of this. A selection change
    // notification should not be sent before a text change notification because
    // PuppetWidget shouldn't query new text content every selection change.
    if (observer->mNeedsToNotifyIMEOfSelectionChange) {
      observer->mNeedsToNotifyIMEOfSelectionChange = false;
      SendSelectionChange();
    }
  }

  // If a text change notification causes another text change again or a
  // selection change notification causes either a text change or another
  // selection change, we should notify IME of those before sending a position
  // change notification.
  if (!observer->mNeedsToNotifyIMEOfTextChange &&
      !observer->mNeedsToNotifyIMEOfSelectionChange) {
    if (observer->mNeedsToNotifyIMEOfPositionChange) {
      observer->mNeedsToNotifyIMEOfPositionChange = false;
      SendPositionChange();
    }
  }

  // Composition event handled notification should be sent after all the
  // other notifications because this notifies widget of finishing all pending
  // events are handled completely.
  if (!observer->mNeedsToNotifyIMEOfTextChange &&
      !observer->mNeedsToNotifyIMEOfSelectionChange &&
      !observer->mNeedsToNotifyIMEOfPositionChange) {
    if (observer->mNeedsToNotifyIMEOfCompositionEventHandled) {
      observer->mNeedsToNotifyIMEOfCompositionEventHandled = false;
      SendCompositionEventHandled();
    }
  }

  observer->mQueuedSender = nullptr;

  // If notifications caused some new change, we should notify them now.
  if (observer->NeedsToNotifyIMEOfSomething()) {
    if (observer->GetState() == eState_StoppedObserving) {
      MOZ_LOG(sIMECOLog, LogLevel::Debug,
              ("0x%p IMENotificationSender::Run(), waiting "
               "IMENotificationSender to be reinitialized",
               this));
    } else {
      MOZ_LOG(sIMECOLog, LogLevel::Debug,
              ("0x%p IMENotificationSender::Run(), posting "
               "IMENotificationSender to current thread",
               this));
      observer->mQueuedSender = new IMENotificationSender(observer);
      observer->mQueuedSender->Dispatch(observer->mDocShell);
    }
  }
  return NS_OK;
}

void IMEContentObserver::IMENotificationSender::SendFocusSet() {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return;
  }

  if (!CanNotifyIME(eChangeEventType_Focus)) {
    // If IMEContentObserver has already gone, we don't need to notify IME of
    // focus.
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendFocusSet(), Warning, does not "
             "send notification due to impossible to notify IME of focus",
             this));
    observer->ClearPendingNotifications();
    return;
  }

  if (!IsSafeToNotifyIME(eChangeEventType_Focus)) {
    MOZ_LOG(
        sIMECOLog, LogLevel::Warning,
        ("0x%p   IMENotificationSender::SendFocusSet(), Warning, does not send "
         "notification due to unsafe, retrying to send NOTIFY_IME_OF_FOCUS...",
         this));
    observer->PostFocusSetNotification();
    return;
  }

  observer->mIMEHasFocus = true;
  // Initialize selection cache with the first selection data.  However, this
  // may be handled synchronously when the editor gets focus.  In that case,
  // some frames may be dirty and they may be required to get caret frame in
  // ContentEventHandler::Init() to get the nearest widget from the selection.
  // Therefore, we need to update selection cache with flushing the pending
  // notifications.
  observer->UpdateSelectionCache(true);
  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p IMENotificationSender::SendFocusSet(), sending "
           "NOTIFY_IME_OF_FOCUS...",
           this));

  MOZ_RELEASE_ASSERT(observer->mSendingNotification == NOTIFY_IME_OF_NOTHING);
  observer->mSendingNotification = NOTIFY_IME_OF_FOCUS;
  IMEStateManager::NotifyIME(IMENotification(NOTIFY_IME_OF_FOCUS),
                             observer->mWidget);
  observer->mSendingNotification = NOTIFY_IME_OF_NOTHING;

  // IMENotificationRequests referred by ObserveEditableNode() may be different
  // before or after widget receives NOTIFY_IME_OF_FOCUS.  Therefore, we need
  // to guarantee to call ObserveEditableNode() after sending
  // NOTIFY_IME_OF_FOCUS.
  observer->OnIMEReceivedFocus();

  MOZ_LOG(
      sIMECOLog, LogLevel::Debug,
      ("0x%p   IMENotificationSender::SendFocusSet(), sent NOTIFY_IME_OF_FOCUS",
       this));
}

void IMEContentObserver::IMENotificationSender::SendSelectionChange() {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return;
  }

  if (!CanNotifyIME(eChangeEventType_Selection)) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendSelectionChange(), Warning, "
             "does not send notification due to impossible to notify IME of "
             "selection change",
             this));
    return;
  }

  if (!IsSafeToNotifyIME(eChangeEventType_Selection)) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendSelectionChange(), Warning, "
             "does not send notification due to unsafe, retrying to send "
             "NOTIFY_IME_OF_SELECTION_CHANGE...",
             this));
    observer->PostSelectionChangeNotification();
    return;
  }

  SelectionChangeData lastSelChangeData = observer->mSelectionData;
  if (NS_WARN_IF(!observer->UpdateSelectionCache())) {
    MOZ_LOG(sIMECOLog, LogLevel::Error,
            ("0x%p   IMENotificationSender::SendSelectionChange(), FAILED, due "
             "to UpdateSelectionCache() failure",
             this));
    return;
  }

  // The state may be changed since querying content causes flushing layout.
  if (!CanNotifyIME(eChangeEventType_Selection)) {
    MOZ_LOG(sIMECOLog, LogLevel::Error,
            ("0x%p   IMENotificationSender::SendSelectionChange(), FAILED, due "
             "to flushing layout having changed something",
             this));
    return;
  }

  // If the selection isn't changed actually, we shouldn't notify IME of
  // selection change.
  SelectionChangeData& newSelChangeData = observer->mSelectionData;
  if (lastSelChangeData.IsInitialized() &&
      lastSelChangeData.EqualsRangeAndDirectionAndWritingMode(
          newSelChangeData)) {
    MOZ_LOG(
        sIMECOLog, LogLevel::Debug,
        ("0x%p IMENotificationSender::SendSelectionChange(), not notifying IME "
         "of NOTIFY_IME_OF_SELECTION_CHANGE due to not changed actually",
         this));
    return;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p IMENotificationSender::SendSelectionChange(), sending "
           "NOTIFY_IME_OF_SELECTION_CHANGE... newSelChangeData=%s",
           this, ToString(newSelChangeData).c_str()));

  IMENotification notification(NOTIFY_IME_OF_SELECTION_CHANGE);
  notification.SetData(observer->mSelectionData);

  MOZ_RELEASE_ASSERT(observer->mSendingNotification == NOTIFY_IME_OF_NOTHING);
  observer->mSendingNotification = NOTIFY_IME_OF_SELECTION_CHANGE;
  IMEStateManager::NotifyIME(notification, observer->mWidget);
  observer->mSendingNotification = NOTIFY_IME_OF_NOTHING;

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   IMENotificationSender::SendSelectionChange(), sent "
           "NOTIFY_IME_OF_SELECTION_CHANGE",
           this));
}

void IMEContentObserver::IMENotificationSender::SendTextChange() {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return;
  }

  if (!CanNotifyIME(eChangeEventType_Text)) {
    MOZ_LOG(
        sIMECOLog, LogLevel::Warning,
        ("0x%p   IMENotificationSender::SendTextChange(), Warning, does not "
         "send notification due to impossible to notify IME of text change",
         this));
    return;
  }

  if (!IsSafeToNotifyIME(eChangeEventType_Text)) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendTextChange(), Warning, does "
             "not send notification due to unsafe, retrying to send "
             "NOTIFY_IME_OF_TEXT_CHANGE...",
             this));
    observer->PostTextChangeNotification();
    return;
  }

  // If text change notification is unnecessary anymore, just cancel it.
  if (!observer->NeedsTextChangeNotification()) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendTextChange(), Warning, "
             "canceling sending NOTIFY_IME_OF_TEXT_CHANGE",
             this));
    observer->CancelNotifyingIMEOfTextChange();
    return;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p IMENotificationSender::SendTextChange(), sending "
           "NOTIFY_IME_OF_TEXT_CHANGE... mIMEContentObserver={ "
           "mTextChangeData=%s }",
           this, ToString(observer->mTextChangeData).c_str()));

  IMENotification notification(NOTIFY_IME_OF_TEXT_CHANGE);
  notification.SetData(observer->mTextChangeData);
  observer->mTextChangeData.Clear();

  MOZ_RELEASE_ASSERT(observer->mSendingNotification == NOTIFY_IME_OF_NOTHING);
  observer->mSendingNotification = NOTIFY_IME_OF_TEXT_CHANGE;
  IMEStateManager::NotifyIME(notification, observer->mWidget);
  observer->mSendingNotification = NOTIFY_IME_OF_NOTHING;

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   IMENotificationSender::SendTextChange(), sent "
           "NOTIFY_IME_OF_TEXT_CHANGE",
           this));
}

void IMEContentObserver::IMENotificationSender::SendPositionChange() {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return;
  }

  if (!CanNotifyIME(eChangeEventType_Position)) {
    MOZ_LOG(sIMECOLog, LogLevel::Verbose,
            ("0x%p   IMENotificationSender::SendPositionChange(), Warning, "
             "does not send notification due to impossible to notify IME of "
             "position change",
             this));
    return;
  }

  if (!IsSafeToNotifyIME(eChangeEventType_Position)) {
    MOZ_LOG(sIMECOLog, LogLevel::Verbose,
            ("0x%p   IMENotificationSender::SendPositionChange(), Warning, "
             "does not send notification due to unsafe, retrying to send "
             "NOTIFY_IME_OF_POSITION_CHANGE...",
             this));
    observer->PostPositionChangeNotification();
    return;
  }

  // If position change notification is unnecessary anymore, just cancel it.
  if (!observer->NeedsPositionChangeNotification()) {
    MOZ_LOG(sIMECOLog, LogLevel::Verbose,
            ("0x%p   IMENotificationSender::SendPositionChange(), Warning, "
             "canceling sending NOTIFY_IME_OF_POSITION_CHANGE",
             this));
    observer->CancelNotifyingIMEOfPositionChange();
    return;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p IMENotificationSender::SendPositionChange(), sending "
           "NOTIFY_IME_OF_POSITION_CHANGE...",
           this));

  MOZ_RELEASE_ASSERT(observer->mSendingNotification == NOTIFY_IME_OF_NOTHING);
  observer->mSendingNotification = NOTIFY_IME_OF_POSITION_CHANGE;
  IMEStateManager::NotifyIME(IMENotification(NOTIFY_IME_OF_POSITION_CHANGE),
                             observer->mWidget);
  observer->mSendingNotification = NOTIFY_IME_OF_NOTHING;

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   IMENotificationSender::SendPositionChange(), sent "
           "NOTIFY_IME_OF_POSITION_CHANGE",
           this));
}

void IMEContentObserver::IMENotificationSender::SendCompositionEventHandled() {
  RefPtr<IMEContentObserver> observer = GetObserver();
  if (!observer) {
    return;
  }

  if (!CanNotifyIME(eChangeEventType_CompositionEventHandled)) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendCompositionEventHandled(), "
             "Warning, does not send notification due to impossible to notify "
             "IME of composition event handled",
             this));
    return;
  }

  if (!IsSafeToNotifyIME(eChangeEventType_CompositionEventHandled)) {
    MOZ_LOG(sIMECOLog, LogLevel::Warning,
            ("0x%p   IMENotificationSender::SendCompositionEventHandled(), "
             "Warning, does not send notification due to unsafe, retrying to "
             "send NOTIFY_IME_OF_POSITION_CHANGE...",
             this));
    observer->PostCompositionEventHandledNotification();
    return;
  }

  MOZ_LOG(sIMECOLog, LogLevel::Info,
          ("0x%p IMENotificationSender::SendCompositionEventHandled(), sending "
           "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED...",
           this));

  MOZ_RELEASE_ASSERT(observer->mSendingNotification == NOTIFY_IME_OF_NOTHING);
  observer->mSendingNotification = NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED;
  IMEStateManager::NotifyIME(
      IMENotification(NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED),
      observer->mWidget);
  observer->mSendingNotification = NOTIFY_IME_OF_NOTHING;

  MOZ_LOG(sIMECOLog, LogLevel::Debug,
          ("0x%p   IMENotificationSender::SendCompositionEventHandled(), sent "
           "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED",
           this));
}

/******************************************************************************
 * mozilla::IMEContentObserver::DocumentObservingHelper
 ******************************************************************************/

NS_IMPL_CYCLE_COLLECTION_CLASS(IMEContentObserver::DocumentObserver)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IMEContentObserver::DocumentObserver)
  // StopObserving() releases mIMEContentObserver and mDocument.
  tmp->StopObserving();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IMEContentObserver::DocumentObserver)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIMEContentObserver)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IMEContentObserver::DocumentObserver)
  NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver)
  NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(IMEContentObserver::DocumentObserver)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IMEContentObserver::DocumentObserver)

void IMEContentObserver::DocumentObserver::Observe(Document* aDocument) {
  MOZ_ASSERT(aDocument);

  // Guarantee that aDocument won't be destroyed during a call of
  // StopObserving().
  RefPtr<Document> newDocument = aDocument;

  StopObserving();

  mDocument = std::move(newDocument);
  mDocument->AddObserver(this);
}

void IMEContentObserver::DocumentObserver::StopObserving() {
  if (!IsObserving()) {
    return;
  }

  // Grab IMEContentObserver which could be destroyed during method calls.
  RefPtr<IMEContentObserver> observer = std::move(mIMEContentObserver);

  // Stop observing the document first.
  RefPtr<Document> document = std::move(mDocument);
  document->RemoveObserver(this);

  // Notify IMEContentObserver of ending of document updates if this already
  // notified it of beginning of document updates.
  for (; IsUpdating(); --mDocumentUpdating) {
    // FYI: IsUpdating() returns true until mDocumentUpdating becomes 0.
    //      However, IsObserving() returns false now because mDocument was
    //      already cleared above.  Therefore, this method won't be called
    //      recursively.
    observer->EndDocumentUpdate();
  }
}

void IMEContentObserver::DocumentObserver::Destroy() {
  StopObserving();
  mIMEContentObserver = nullptr;
}

void IMEContentObserver::DocumentObserver::BeginUpdate(Document* aDocument) {
  if (NS_WARN_IF(Destroyed()) || NS_WARN_IF(!IsObserving())) {
    return;
  }
  mIMEContentObserver->BeginDocumentUpdate();
  mDocumentUpdating++;
}

void IMEContentObserver::DocumentObserver::EndUpdate(Document* aDocument) {
  if (NS_WARN_IF(Destroyed()) || NS_WARN_IF(!IsObserving()) ||
      NS_WARN_IF(!IsUpdating())) {
    return;
  }
  mDocumentUpdating--;
  mIMEContentObserver->EndDocumentUpdate();
}

/******************************************************************************
 * mozilla::IMEContentObserver::FlatTextCache
 ******************************************************************************/

void IMEContentObserver::FlatTextCache::Clear(const char* aCallerName) {
  if (!HasCache()) {
    return;
  }
  MOZ_LOG(sCacheLog, LogLevel::Info,
          ("%s.Clear: called by %s", mInstanceName, aCallerName));
  mContainerNode = nullptr;
  mContent = nullptr;
  mFlatTextLength = 0;
}

nsresult IMEContentObserver::FlatTextCache::
    ComputeAndCacheFlatTextLengthBeforeEndOfContent(
        const char* aCallerName, const nsIContent& aContent,
        const Element* aRootElement) {
  MOZ_ASSERT(aRootElement);
  MOZ_ASSERT(aContent.GetParentNode());

  uint32_t length = 0;
  nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
      RawNodePosition::BeforeFirstContentOf(*aRootElement),
      RawNodePosition::After(aContent), aRootElement, &length,
      LineBreakType::LINE_BREAK_TYPE_NATIVE);
  if (NS_FAILED(rv)) {
    Clear(aCallerName);
    return rv;
  }

  CacheFlatTextLengthBeforeEndOfContent(aCallerName, aContent, length,
                                        aRootElement);
  return NS_OK;
}

void IMEContentObserver::FlatTextCache::CacheFlatTextLengthBeforeEndOfContent(
    const char* aCallerName, const nsIContent& aContent,
    uint32_t aFlatTextLength, const dom::Element* aRootElement) {
  mContainerNode = aContent.GetParentNode();
  mContent = const_cast<nsIContent*>(&aContent);
  mFlatTextLength = aFlatTextLength;
  MOZ_ASSERT(IsCachingToEndOfContent());
  MOZ_LOG(sCacheLog, LogLevel::Info,
          ("%s.%s: called by %s -> %s", mInstanceName, __FUNCTION__,
           aCallerName, ToString(*this).c_str()));
  AssertValidCache(aRootElement);
}

nsresult IMEContentObserver::FlatTextCache::
    ComputeAndCacheFlatTextLengthBeforeFirstContent(
        const char* aCallerName, const nsINode& aContainer,
        const Element* aRootElement) {
  MOZ_ASSERT(aRootElement);

  const Result<uint32_t, nsresult>
      lengthIncludingLineBreakCausedByOpenTagOfContainer =
          FlatTextCache::ComputeTextLengthBeforeFirstContentOf(aContainer,
                                                               aRootElement);
  if (MOZ_UNLIKELY(
          lengthIncludingLineBreakCausedByOpenTagOfContainer.isErr())) {
    Clear(__FUNCTION__);
    return lengthIncludingLineBreakCausedByOpenTagOfContainer.inspectErr();
  }

  CacheFlatTextLengthBeforeFirstContent(
      aCallerName, aContainer,
      lengthIncludingLineBreakCausedByOpenTagOfContainer.inspect(),
      aRootElement);
  return NS_OK;
}

void IMEContentObserver::FlatTextCache::CacheFlatTextLengthBeforeFirstContent(
    const char* aCallerName, const nsINode& aContainer,
    uint32_t aFlatTextLength, const dom::Element* aRootElement) {
  mContainerNode = const_cast<nsINode*>(&aContainer);
  mContent = nullptr;
  mFlatTextLength = aFlatTextLength;
  MOZ_ASSERT(IsCachingToStartOfContainer());
  MOZ_LOG(sCacheLog, LogLevel::Info,
          ("%s.%s: called by %s -> %s", mInstanceName, __FUNCTION__,
           aCallerName, ToString(*this).c_str()));
  AssertValidCache(aRootElement);
}

Maybe<uint32_t>
IMEContentObserver::FlatTextCache::GetFlatTextLengthBeforeContent(
    const nsIContent& aContent, const dom::Element* aRootElement,
    ForRemoval aForRemoval) const {
  MOZ_ASSERT(aRootElement);
  if (!mContainerNode) {
    return Nothing();
  }

  nsIContent* const prevSibling = aContent.GetPreviousSibling();
  if (IsCachingToStartOfContainer()) {
    MOZ_ASSERT(!mContent);
    // If aContent is the first child of mContainerNode and we're caching text
    // length before first child of mContainerNode, we're caching the result
    // as-is..
    if (!prevSibling && mContainerNode == aContent.GetParentNode()) {
      return Some(mFlatTextLength);
    }
    return Nothing();
  }

  MOZ_ASSERT(IsCachingToEndOfContent());
  MOZ_ASSERT(mContent);

  // If we're caching text length before end of previous sibling of aContent,
  // the cached length is the result of this call.
  if (mContent == prevSibling) {
    return Some(mFlatTextLength);
  }

  // If we're caching text length before end of aContent, aContent siblings
  // may be being removed backward because aContent is the previous sibling of
  // previously removed node.  We should return the length with computing the
  // text length of aContent because it's much faster than computing the length
  // starting from the root element especially when there are a lot of preceding
  // content.
  if (mContent == &aContent) {
    const Result<uint32_t, nsresult> textLength =
        FlatTextCache::ComputeTextLengthOfContent(aContent, aRootElement,
                                                  aForRemoval);
    if (NS_WARN_IF(textLength.isErr()) ||
        NS_WARN_IF(mFlatTextLength < textLength.inspect())) {
      return Nothing();
    }
    return Some(mFlatTextLength - textLength.inspect());
  }
  return Nothing();
}

Maybe<uint32_t> IMEContentObserver::FlatTextCache::GetFlatTextOffsetOnInsertion(
    const nsIContent& aFirstContent, const nsIContent& aLastContent,
    const dom::Element* aRootElement) const {
  MOZ_ASSERT(aRootElement);
  MOZ_ASSERT(aFirstContent.GetParentNode() == aLastContent.GetParentNode());
  MOZ_ASSERT(!aFirstContent.IsBeingRemoved());
  MOZ_ASSERT(!aLastContent.IsBeingRemoved());

  if (!mContainerNode || mContainerNode != aFirstContent.GetParentNode()) {
    return Nothing();
  }

  if (IsCachingToStartOfContainer()) {
    MOZ_ASSERT(!mContent);
    // If aFirstContent is the first child of mContainerNode, we're caching the
    // result as-is.
    if (mContainerNode->GetFirstChild() == &aFirstContent) {
      return Some(mFlatTextLength);
    }
    return Nothing();
  }

  MOZ_ASSERT(IsCachingToEndOfContent());
  MOZ_ASSERT(mContent);
  MOZ_ASSERT(mContent != &aFirstContent);
  MOZ_ASSERT(mContent != &aLastContent);

  // When the content nodes are inserted forward, we may cache text length
  // before end of last inserted content.  If so, mContent should be the
  // previous sibling of aFirstContent.  Then, we can return the cached length
  // simply.
  if (mContent == aFirstContent.GetPreviousSibling()) {
    return Some(mFlatTextLength);
  }
  // When the content nodes inserted backward, we may cache text length before
  // the end of the last inserted content which is next or latter sibling of
  // aLastContent.  In this case, we can compute the length with the cache with
  // computing text length starting from the next sibling of aLastContent to
  // mContent which were previously inserted.  That must be faster than
  // computing the length starting from the root element.
  if (mContent == aLastContent.GetNextSibling() ||
      aLastContent.ComputeIndexInParentNode().valueOr(UINT32_MAX) <
          mContent->ComputeIndexInParentNode().valueOr(0u)) {
    Result<uint32_t, nsresult> previouslyInsertedTextLengthOrError =
        FlatTextCache::ComputeTextLengthStartOfContentToEndOfContent(
            *aLastContent.GetNextSibling(), *mContent, aRootElement);
    if (NS_WARN_IF(previouslyInsertedTextLengthOrError.isErr()) ||
        NS_WARN_IF(mFlatTextLength <
                   previouslyInsertedTextLengthOrError.inspect())) {
      return Nothing();
    }
    // mFlatTextLength contains the last inserted text length, but it does not
    // contain text length starting from aFirstContent to aLastContent.
    // Therefore, subtracting the last inserted text length from mFlatTextLength
    // equals the text length before aFirstContent.
    return Some(mFlatTextLength - previouslyInsertedTextLengthOrError.unwrap());
  }
  return Nothing();
}

/* static */
Result<uint32_t, nsresult>
IMEContentObserver::FlatTextCache::ComputeTextLengthOfContent(
    const nsIContent& aContent, const dom::Element* aRootElement,
    ForRemoval aForRemoval) {
  MOZ_ASSERT(aRootElement);

  if (const Text* textNode = Text::FromNode(aContent)) {
    return ContentEventHandler::GetNativeTextLength(*textNode);
  }

  if (aForRemoval == ForRemoval::Yes) {
    // When we compute the text length of the removing content node, we need to
    // select all children in the removing node because of the same reason
    // above.  Therefore, if a <div> is being removed, we want to compute
    // `{<div>...}</div>`.  In this case, we want to include the open tag of
    // aRemovingContent if it's an element to add the line break if it's caused
    // by the open tag.  However, we have no way to specify it with
    // RawNodePosition, but ContentEventHandler::GetFlatTextLengthInRange()
    // treats the range as the start container is selected.  Therefore, we
    // should use a RawNodePosition setting its container to the removed node.
    uint32_t textLength = 0;
    RawNodePosition start(const_cast<nsIContent*>(&aContent), 0u);
    start.mAfterOpenTag = false;
    nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
        start, RawNodePosition::AtEndOf(aContent), aRootElement, &textLength,
        LineBreakType::LINE_BREAK_TYPE_NATIVE, /* aIsRemovingNode = */ true);
    if (NS_FAILED(rv)) {
      return Err(rv);
    }
    return textLength;
  }

  return ComputeTextLengthStartOfContentToEndOfContent(aContent, aContent,
                                                       aRootElement);
}

/* static */
Result<uint32_t, nsresult>
IMEContentObserver::FlatTextCache::ComputeTextLengthBeforeContent(
    const nsIContent& aContent, const dom::Element* aRootElement) {
  uint32_t textLengthBeforeContent = 0;
  nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
      RawNodePosition::BeforeFirstContentOf(*aRootElement),
      RawNodePosition::Before(aContent), aRootElement, &textLengthBeforeContent,
      LineBreakType::LINE_BREAK_TYPE_NATIVE);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }
  return textLengthBeforeContent;
}

/* static */
Result<uint32_t, nsresult> IMEContentObserver::FlatTextCache::
    ComputeTextLengthStartOfContentToEndOfContent(
        const nsIContent& aStartContent, const nsIContent& aEndContent,
        const dom::Element* aRootElement) {
  uint32_t textLength = 0;
  nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
      RawNodePosition::Before(aStartContent),
      RawNodePosition::After(aEndContent), aRootElement, &textLength,
      LineBreakType::LINE_BREAK_TYPE_NATIVE);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }
  return textLength;
}

/* static */
Result<uint32_t, nsresult>
IMEContentObserver::FlatTextCache::ComputeTextLengthBeforeFirstContentOf(
    const nsINode& aContainer, const dom::Element* aRootElement) {
  uint32_t lengthIncludingLineBreakCausedByOpenTagOfContent = 0;
  nsresult rv = ContentEventHandler::GetFlatTextLengthInRange(
      RawNodePosition::BeforeFirstContentOf(*aRootElement),
      // Include the line break caused by open tag of aContainer if it's an
      // element when we cache text length before first content of aContainer.
      RawNodePosition(const_cast<nsINode*>(&aContainer), nullptr), aRootElement,
      &lengthIncludingLineBreakCausedByOpenTagOfContent,
      LineBreakType::LINE_BREAK_TYPE_NATIVE);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }
  return lengthIncludingLineBreakCausedByOpenTagOfContent;
}

void IMEContentObserver::FlatTextCache::AssertValidCache(
    const Element* aRootElement) const {
#ifdef DEBUG
  if (MOZ_LIKELY(
          !StaticPrefs::test_ime_content_observer_assert_valid_cache())) {
    return;
  }
  MOZ_ASSERT(aRootElement);
  if (!mContainerNode) {
    return;
  }
  MOZ_ASSERT(mContainerNode->IsInclusiveDescendantOf(aRootElement));
  MOZ_ASSERT_IF(mContent, mContent->IsInclusiveDescendantOf(aRootElement));

  if (IsCachingToEndOfContent()) {
    MOZ_ASSERT(mContent);
    Result<uint32_t, nsresult> offset =
        FlatTextCache::ComputeTextLengthBeforeContent(*mContent, aRootElement);
    MOZ_ASSERT(offset.isOk());
    Result<uint32_t, nsresult> length =
        FlatTextCache::ComputeTextLengthStartOfContentToEndOfContent(
            *mContent, *mContent, aRootElement);
    MOZ_ASSERT(length.isOk());
    if (mFlatTextLength != offset.inspect() + length.inspect()) {
      nsAutoString innerHTMLOfEditable;
      const_cast<Element*>(aRootElement)
          ->GetInnerHTML(innerHTMLOfEditable, IgnoreErrors());
      NS_WARNING(
          nsPrintfCString(
              "mFlatTextLength=%u, offset: %u, length: %u, mContainerNode:%s, "
              "mContent=%s (%s)",
              mFlatTextLength, offset.inspect(), length.inspect(),
              ToString(mContainerNode).c_str(), ToString(*mContent).c_str(),
              NS_ConvertUTF16toUTF8(innerHTMLOfEditable).get())
              .get());
    }
    MOZ_ASSERT(mFlatTextLength == offset.inspect() + length.inspect());
    return;
  }

  MOZ_ASSERT(!mContent);
  MOZ_ASSERT(mContainerNode->IsContent());
  Result<uint32_t, nsresult> offset =
      ComputeTextLengthBeforeFirstContentOf(*mContainerNode, aRootElement);
  MOZ_ASSERT(offset.isOk());
  if (mFlatTextLength != offset.inspect()) {
    nsAutoString innerHTMLOfEditable;
    const_cast<Element*>(aRootElement)
        ->GetInnerHTML(innerHTMLOfEditable, IgnoreErrors());
    NS_WARNING(nsPrintfCString(
                   "mFlatTextLength=%u, offset: %u, mContainerNode:%s (%s)",
                   mFlatTextLength, offset.inspect(),
                   ToString(mContainerNode).c_str(),
                   NS_ConvertUTF16toUTF8(innerHTMLOfEditable).get())
                   .get());
  }
  MOZ_ASSERT(mFlatTextLength == offset.inspect());
#endif  // #ifdef DEBUG
}

void IMEContentObserver::FlatTextCache::ContentAdded(
    const char* aCallerName, const nsIContent& aFirstContent,
    const nsIContent& aLastContent, const Maybe<uint32_t>& aAddedFlatTextLength,
    const Element* aRootElement) {
  MOZ_ASSERT(nsContentUtils::ComparePoints(
                 RawRangeBoundary(aFirstContent.GetParentNode(),
                                  aFirstContent.GetPreviousSibling()),
                 RawRangeBoundary(aLastContent.GetParentNode(),
                                  aLastContent.GetPreviousSibling()))
                 .value() <= 0);
  if (!mContainerNode) {
    return;  // No cache.
  }

  // We can keep cache without anything if the next sibling is the first added
  // content.
  if (mContent && &aFirstContent == mContent->GetNextSibling()) {
    return;
  }

  if (IsCachingToStartOfContainer()) {
    MOZ_ASSERT(!mContent);
    // We can keep the cache if added nodes are children of mContainerNode since
    // we cache the text length before its first child.
    if (mContainerNode == aFirstContent.GetParentNode()) {
      AssertValidCache(aRootElement);
      return;
    }

    // Let's clear the cache for avoiding to do anything expensive for a hot
    // path only for not frequent cases.  Be aware, this is a hot code path
    // here.  Therefore, expensive computation would make the DOM mutation
    // slower.
    Clear(aCallerName);
    return;
  }

  MOZ_ASSERT(IsCachingToEndOfContent());
  MOZ_ASSERT(mContent);
  if (aAddedFlatTextLength.isSome() &&
      aLastContent.GetNextSibling() == mContent) {
    // If we cache test length before end of next sibling of the last added
    // content node, we can update the cached text simply.
    CacheFlatTextLengthBeforeEndOfContent(
        aCallerName, *mContent, mFlatTextLength + *aAddedFlatTextLength,
        aRootElement);
    return;
  }
  // Let's clear the cache for avoiding to do anything expensive for a hot
  // path only for not frequent cases.  Be aware, this is a hot code path here.
  // Therefore, expensive computation would make the DOM mutation slower.
  Clear(aCallerName);
}

void IMEContentObserver::FlatTextCache::ContentWillBeRemoved(
    const nsIContent& aContent, uint32_t aFlatTextLengthOfContent,
    const Element* aRootElement) {
  if (!mContainerNode) {
    return;  // No cache.
  }

  // We can keep the cache without anything if the next sibling is removed.
  if (mContent && mContent == aContent.GetPreviousSibling()) {
    return;
  }

  if (IsCachingToStartOfContainer()) {
    MOZ_ASSERT(!mContent);
    // We're caching text length before first child of mContainerNode.
    // Therefore, if a child of mContainerNode is being removed, we can keep the
    // cache.
    if (mContainerNode == aContent.GetParentNode()) {
      AssertValidCache(aRootElement);
      return;
    }

    // Let's clear the cache for avoiding to do anything expensive for a hot
    // path only for not frequent cases.  Be aware, this is a hot code path
    // here.  Therefore, expensive computation would make the DOM mutation
    // slower.
    Clear("FlatTextCache::ContentRemoved");
    return;
  }

  MOZ_ASSERT(IsCachingToEndOfContent());
  if (&aContent == mContent) {
    MOZ_ASSERT(mFlatTextLength >= aFlatTextLengthOfContent);
    if (NS_WARN_IF(mFlatTextLength < aFlatTextLengthOfContent)) {
      Clear("FlatTextCache::ContentRemoved");
      return;
    }
    // We're caching text length before end of aContent.  So, if there is a
    // previous sibling, we can cache text length before aContent with
    // subtracting the text length caused by aContent from the cached value.
    if (nsIContent* prevSibling = aContent.GetPreviousSibling()) {
      CacheFlatTextLengthBeforeEndOfContent(
          "FlatTextCache::ContentRemoved", *prevSibling,
          mFlatTextLength - aFlatTextLengthOfContent, aRootElement);
      return;
    }
    // Otherwise, i.e., if aContent is first child of mContainerNode, we can
    // cache text length before first content of mContainerNode with subtracting
    // the text length caused by aContent from the cached value.
    CacheFlatTextLengthBeforeFirstContent(
        "FlatTextCache::ContentRemoved", *mContainerNode,
        mFlatTextLength - aFlatTextLengthOfContent, aRootElement);
    return;
  }
  // Let's clear the cache for avoiding to do anything expensive for a hot
  // path only for not frequent cases.  Be aware, this is a hot code path here.
  // Therefore, expensive computation would make the DOM mutation slower.
  Clear("FlatTextCache::ContentRemoved");
}

/******************************************************************************
 * mozilla::IMEContentObserver::AddedContentCache
 ******************************************************************************/

void IMEContentObserver::AddedContentCache::Clear(const char* aCallerName) {
  mFirst = nullptr;
  mLast = nullptr;
  MOZ_LOG(sCacheLog, LogLevel::Info,
          ("AddedContentCache::Clear: called by %s", aCallerName));
}

bool IMEContentObserver::AddedContentCache::IsInRange(
    const nsIContent& aContent, const dom::Element* aRootElement) const {
  MOZ_ASSERT(HasCache());

  // First, try to find sibling of mFirst from the ancestor chain of aContent.
  const nsIContent* sibling = [&]() -> const nsIContent* {
    const nsIContent* maybeSibling = &aContent;
    const nsIContent* const container = mFirst->GetParent();
    for (const nsIContent* ancestor : aContent.AncestorsOfType<nsIContent>()) {
      if (ancestor == container) {
        return maybeSibling;
      }
      if (ancestor == aRootElement) {
        return nullptr;
      }
      maybeSibling = ancestor;
    }
    return nullptr;
  }();
  if (!sibling) {
    return false;  // Not in same container node
  }
  // Let's avoid to compute indices...
  if (mFirst == sibling || mLast == sibling ||
      (mFirst != mLast && (mFirst->GetNextSibling() == sibling ||
                           sibling->GetNextSibling() == mLast))) {
    return true;
  }
  if (mFirst == mLast || sibling->GetNextSibling() == mFirst ||
      mLast->GetNextSibling() == sibling || !sibling->GetPreviousSibling() ||
      !sibling->GetNextSibling()) {
    return false;
  }
  const Maybe<uint32_t> index = aContent.ComputeIndexInParentNode();
  MOZ_ASSERT(index.isSome());
  const Maybe<uint32_t> firstIndex = mFirst->ComputeIndexInParentNode();
  MOZ_ASSERT(firstIndex.isSome());
  const Maybe<uint32_t> lastIndex = mLast->ComputeIndexInParentNode();
  MOZ_ASSERT(lastIndex.isSome());
  return firstIndex.value() < index.value() &&
         index.value() < lastIndex.value();
}

bool IMEContentObserver::AddedContentCache::CanMergeWith(
    const nsIContent& aFirstContent, const nsIContent& aLastContent,
    const dom::Element* aRootElement) const {
  MOZ_ASSERT(HasCache());
  if (aLastContent.GetNextSibling() == mFirst ||
      mLast->GetNextSibling() == &aFirstContent) {
    return true;
  }
  MOZ_DIAGNOSTIC_ASSERT(aFirstContent.GetParentNode() ==
                        aLastContent.GetParentNode());
  if (mFirst->GetParentNode() != aFirstContent.GetParentNode()) {
    return false;
  }
  const Maybe<uint32_t> newFirstIndex =
      aFirstContent.ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(newFirstIndex.isSome());
  const Maybe<uint32_t> newLastIndex =
      &aFirstContent == &aLastContent ? newFirstIndex
                                      : aLastContent.ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(newLastIndex.isSome());
  const Maybe<uint32_t> currentFirstIndex = mFirst->ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(currentFirstIndex.isSome());
  const Maybe<uint32_t> currentLastIndex =
      mFirst == mLast ? currentFirstIndex : mLast->ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(currentLastIndex.isSome());
  MOZ_ASSERT(!(newFirstIndex.value() < currentFirstIndex.value() &&
               newLastIndex.value() > currentLastIndex.value()),
             "New content nodes shouldn't contain mFirst nor mLast");
  MOZ_ASSERT(!(newFirstIndex.value() < currentFirstIndex.value() &&
               newLastIndex.value() > currentFirstIndex.value()),
             "New content nodes shouldn't contain mFirst");
  MOZ_ASSERT(!(newFirstIndex.value() < currentLastIndex.value() &&
               newLastIndex.value() > currentLastIndex.value()),
             "New content nodes shouldn't contain mLast");
  return *newFirstIndex > *currentFirstIndex &&
         *newLastIndex < *currentLastIndex;
}

bool IMEContentObserver::AddedContentCache::TryToCache(
    const nsIContent& aFirstContent, const nsIContent& aLastContent,
    const dom::Element* aRootElement) {
  if (!HasCache()) {
    mFirst = const_cast<nsIContent*>(&aFirstContent);
    mLast = const_cast<nsIContent*>(&aLastContent);
    MOZ_LOG(
        sCacheLog, LogLevel::Info,
        ("AddedContentCache::TryToCache: Starting to cache the range: %s - %s",
         ToString(mFirst).c_str(), ToString(mLast).c_str()));
    return true;
  }
  MOZ_ASSERT(mFirst != &aFirstContent);
  MOZ_ASSERT(mLast != &aLastContent);
  if (aLastContent.GetNextSibling() == mFirst) {
    MOZ_ASSERT(CanMergeWith(aFirstContent, aLastContent, aRootElement));
    mFirst = const_cast<nsIContent*>(&aFirstContent);
    MOZ_LOG(
        sCacheLog, LogLevel::Info,
        ("AddedContentCache::TryToCache: Extending the range backward (to %s)",
         ToString(mFirst).c_str()));
    return true;
  }
  if (mLast->GetNextSibling() == &aFirstContent) {
    MOZ_ASSERT(CanMergeWith(aFirstContent, aLastContent, aRootElement));
    mLast = const_cast<nsIContent*>(&aLastContent);
    MOZ_LOG(
        sCacheLog, LogLevel::Info,
        ("AddedContentCache::TryToCache: Extending the range forward (to %s)",
         ToString(mLast).c_str()));
    return true;
  }

  MOZ_DIAGNOSTIC_ASSERT(aFirstContent.GetParentNode() ==
                        aLastContent.GetParentNode());
  if (mFirst->GetParentNode() != aFirstContent.GetParentNode()) {
    MOZ_ASSERT(!CanMergeWith(aFirstContent, aLastContent, aRootElement));
    return false;
  }
  const Maybe<uint32_t> newFirstIndex =
      aFirstContent.ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(newFirstIndex.isSome());
  const Maybe<uint32_t> newLastIndex =
      &aFirstContent == &aLastContent ? newFirstIndex
                                      : aLastContent.ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(newLastIndex.isSome());
  const Maybe<uint32_t> currentFirstIndex = mFirst->ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(currentFirstIndex.isSome());
  const Maybe<uint32_t> currentLastIndex =
      mFirst == mLast ? currentFirstIndex : mLast->ComputeIndexInParentNode();
  MOZ_RELEASE_ASSERT(currentLastIndex.isSome());
  MOZ_ASSERT(!(newFirstIndex.value() < currentFirstIndex.value() &&
               newLastIndex.value() > currentLastIndex.value()),
             "New content nodes shouldn't contain mFirst nor mLast");
  MOZ_ASSERT(!(newFirstIndex.value() < currentFirstIndex.value() &&
               newLastIndex.value() > currentFirstIndex.value()),
             "New content nodes shouldn't contain mFirst");
  MOZ_ASSERT(!(newFirstIndex.value() < currentLastIndex.value() &&
               newLastIndex.value() > currentLastIndex.value()),
             "New content nodes shouldn't contain mLast");
  if (*newFirstIndex > *currentFirstIndex &&
      *newLastIndex < *currentLastIndex) {
    MOZ_ASSERT(CanMergeWith(aFirstContent, aLastContent, aRootElement));
    MOZ_LOG(sCacheLog, LogLevel::Info,
            ("AddedContentCache::TryToCache: New nodes in the range"));
    return true;
  }
  MOZ_ASSERT(!CanMergeWith(aFirstContent, aLastContent, aRootElement));
  return false;
}

Result<std::pair<uint32_t, uint32_t>, nsresult> IMEContentObserver::
    AddedContentCache::ComputeFlatTextRangeBeforeInsertingNewContent(
        const nsIContent& aNewFirstContent, const nsIContent& aNewLastContent,
        const dom::Element* aRootElement,
        OffsetAndLengthAdjustments& aDifferences) const {
  MOZ_ASSERT(HasCache());
  const Maybe<int32_t> newLastContentComparedWithCachedFirstContent =
      nsContentUtils::ComparePoints(
          RawRangeBoundary(aNewLastContent.GetParentNode(),
                           aNewLastContent.GetPreviousSibling()),
          RawRangeBoundary(mFirst->GetParentNode(),
                           mFirst->GetPreviousSibling()));
  MOZ_RELEASE_ASSERT(newLastContentComparedWithCachedFirstContent.isSome());
  MOZ_ASSERT(*newLastContentComparedWithCachedFirstContent != 0);
  MOZ_ASSERT((*nsContentUtils::ComparePoints(
                  RawRangeBoundary(aNewFirstContent.GetParentNode(),
                                   aNewFirstContent.GetPreviousSibling()),
                  RawRangeBoundary(mFirst->GetParentNode(),
                                   mFirst->GetPreviousSibling())) > 0) ==
                 (*newLastContentComparedWithCachedFirstContent > 0),
             "New nodes shouldn't contain mFirst");
  const Maybe<int32_t> newFirstContentComparedWithCachedLastContent =
      mLast->GetNextSibling() == &aNewFirstContent
          ? Some(1)
          : nsContentUtils::ComparePoints(
                RawRangeBoundary(aNewFirstContent.GetParentNode(),
                                 aNewFirstContent.GetPreviousSibling()),
                // aNewFirstContent and aNewLastContent may be descendants of
                // mLast. Then, we need to ignore the new length.  Therefore,
                // we need to compare aNewFirstContent position with next
                // sibling of mLast.
                RawRangeBoundary(mLast->GetParentNode(), mLast));
  MOZ_RELEASE_ASSERT(newFirstContentComparedWithCachedLastContent.isSome());
  MOZ_ASSERT(*newFirstContentComparedWithCachedLastContent != 0);
  MOZ_ASSERT((*newFirstContentComparedWithCachedLastContent > 0) ==
                 (*nsContentUtils::ComparePoints(
                      RawRangeBoundary(aNewLastContent.GetParentNode(),
                                       aNewLastContent.GetPreviousSibling()),
                      RawRangeBoundary(mLast->GetParentNode(), mLast)) > 0),
             "New nodes shouldn't contain mLast");

  Result<uint32_t, nsresult> length =
      FlatTextCache::ComputeTextLengthStartOfContentToEndOfContent(
          *mFirst, *mLast, aRootElement);
  if (NS_WARN_IF(length.isErr())) {
    return length.propagateErr();
  }
  Result<uint32_t, nsresult> offset =
      FlatTextCache::ComputeTextLengthBeforeContent(*mFirst, aRootElement);
  if (NS_WARN_IF(offset.isErr())) {
    return offset.propagateErr();
  }

  // If new content nodes are after the cached range, we can just ignore the
  // new content nodes.
  if (*newFirstContentComparedWithCachedLastContent == 1u) {
    aDifferences = OffsetAndLengthAdjustments{0, 0};
    return std::make_pair(offset.inspect(), length.inspect());
  }

  Result<uint32_t, nsresult> newLength =
      FlatTextCache::ComputeTextLengthStartOfContentToEndOfContent(
          aNewFirstContent, aNewLastContent, aRootElement);
  if (NS_WARN_IF(newLength.isErr())) {
    return newLength.propagateErr();
  }

  // If new content nodes are in the cached range, we need to subtract the new
  // content length from cached content length.
  if (*newLastContentComparedWithCachedFirstContent == 1u) {
    MOZ_RELEASE_ASSERT(length.inspect() >= newLength.inspect());
    aDifferences = OffsetAndLengthAdjustments{0, newLength.inspect()};
    return std::make_pair(offset.inspect(),
                          length.inspect() - newLength.inspect());
  }

  // If new content nodes are before the cached range, we need to subtract the
  // new content length from cached offset.
  MOZ_RELEASE_ASSERT(offset.inspect() >= newLength.inspect());
  aDifferences = OffsetAndLengthAdjustments{newLength.inspect(), 0};
  return std::make_pair(offset.inspect() - newLength.inspect(),
                        length.inspect());
}

}  // namespace mozilla