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

#include "EditorBase.h"               // for EditorBase
#include "EditorUtils.h"              // for AutoTransactionBatchExternal
#include "FilteredContentIterator.h"  // for FilteredContentIterator
#include "HTMLEditUtils.h"            // for HTMLEditUtils
#include "JoinSplitNodeDirection.h"   // for JoinNodesDirection

#include "mozilla/Assertions.h"    // for MOZ_ASSERT, etc
#include "mozilla/IntegerRange.h"  // for IntegerRange
#include "mozilla/mozalloc.h"      // for operator new, etc
#include "mozilla/OwningNonNull.h"
#include "mozilla/UniquePtr.h"          // for UniquePtr
#include "mozilla/dom/AbstractRange.h"  // for AbstractRange
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/StaticRange.h"  // for StaticRange
#include "mozilla/dom/Text.h"
#include "mozilla/intl/WordBreaker.h"  // for WordRange, WordBreaker

#include "nsAString.h"       // for nsAString::Length, etc
#include "nsContentUtils.h"  // for nsContentUtils
#include "nsComposeTxtSrvFilter.h"
#include "nsDebug.h"                 // for NS_ENSURE_TRUE, etc
#include "nsDependentSubstring.h"    // for Substring
#include "nsError.h"                 // for NS_OK, NS_ERROR_FAILURE, etc
#include "nsGenericHTMLElement.h"    // for nsGenericHTMLElement
#include "nsIContent.h"              // for nsIContent, etc
#include "nsID.h"                    // for NS_GET_IID
#include "nsIEditor.h"               // for nsIEditor, etc
#include "nsIEditorSpellCheck.h"     // for nsIEditorSpellCheck, etc
#include "nsINode.h"                 // for nsINode
#include "nsISelectionController.h"  // for nsISelectionController, etc
#include "nsISupports.h"             // for nsISupports
#include "nsISupportsUtils.h"        // for NS_IF_ADDREF, NS_ADDREF, etc
#include "nsRange.h"                 // for nsRange
#include "nsString.h"                // for nsString, nsAutoString
#include "nscore.h"                  // for nsresult, NS_IMETHODIMP, etc

namespace mozilla {

using namespace dom;

/**
 * OffsetEntry manages a range in a text node.  It stores 2 offset values,
 * one is offset in the text node, the other is offset in all text in
 * the ancestor block of the text node.  And the length is managing length
 * in the text node, starting from the offset in text node.
 * In other words, a text node may be managed by multiple instances of this
 * class.
 */
class OffsetEntry final {
 public:
  OffsetEntry() = delete;

  /**
   * @param aTextNode   The text node which will be manged by the instance.
   * @param aOffsetInTextInBlock
   *                    Start offset in the text node which will be managed by
   *                    the instance.
   * @param aLength     Length in the text node which will be managed by the
   *                    instance.
   */
  OffsetEntry(Text& aTextNode, uint32_t aOffsetInTextInBlock, uint32_t aLength)
      : mTextNode(aTextNode),
        mOffsetInTextNode(0),
        mOffsetInTextInBlock(aOffsetInTextInBlock),
        mLength(aLength),
        mIsInsertedText(false),
        mIsValid(true) {}

  /**
   * EndOffsetInTextNode() returns end offset in the text node, which is
   * managed by the instance.
   */
  uint32_t EndOffsetInTextNode() const { return mOffsetInTextNode + mLength; }

  /**
   * OffsetInTextNodeIsInRangeOrEndOffset() checks whether the offset in
   * the text node is managed by the instance or not.
   */
  bool OffsetInTextNodeIsInRangeOrEndOffset(uint32_t aOffsetInTextNode) const {
    return aOffsetInTextNode >= mOffsetInTextNode &&
           aOffsetInTextNode <= EndOffsetInTextNode();
  }

  /**
   * EndOffsetInTextInBlock() returns end offset in the all text in ancestor
   * block of the text node, which is managed by the instance.
   */
  uint32_t EndOffsetInTextInBlock() const {
    return mOffsetInTextInBlock + mLength;
  }

  /**
   * OffsetInTextNodeIsInRangeOrEndOffset() checks whether the offset in
   * the all text in ancestor block of the text node is managed by the instance
   * or not.
   */
  bool OffsetInTextInBlockIsInRangeOrEndOffset(
      uint32_t aOffsetInTextInBlock) const {
    return aOffsetInTextInBlock >= mOffsetInTextInBlock &&
           aOffsetInTextInBlock <= EndOffsetInTextInBlock();
  }

  OwningNonNull<Text> mTextNode;
  uint32_t mOffsetInTextNode;
  // Offset in all text in the closest ancestor block of mTextNode.
  uint32_t mOffsetInTextInBlock;
  uint32_t mLength;
  bool mIsInsertedText;
  bool mIsValid;
};

template <typename ElementType>
struct MOZ_STACK_CLASS ArrayLengthMutationGuard final {
  ArrayLengthMutationGuard() = delete;
  explicit ArrayLengthMutationGuard(const nsTArray<ElementType>& aArray)
      : mArray(aArray), mOldLength(aArray.Length()) {}
  ~ArrayLengthMutationGuard() {
    if (mArray.Length() != mOldLength) {
      MOZ_CRASH("The array length was changed unexpectedly");
    }
  }

 private:
  const nsTArray<ElementType>& mArray;
  size_t mOldLength;
};

#define LockOffsetEntryArrayLengthInDebugBuild(aName, aArray)               \
  DebugOnly<ArrayLengthMutationGuard<UniquePtr<OffsetEntry>>> const aName = \
      ArrayLengthMutationGuard<UniquePtr<OffsetEntry>>(aArray);

TextServicesDocument::TextServicesDocument()
    : mTxtSvcFilterType(0), mIteratorStatus(IteratorStatus::eDone) {}

NS_IMPL_CYCLE_COLLECTING_ADDREF(TextServicesDocument)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TextServicesDocument)

NS_INTERFACE_MAP_BEGIN(TextServicesDocument)
  NS_INTERFACE_MAP_ENTRY(nsIEditActionListener)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEditActionListener)
  NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(TextServicesDocument)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION(TextServicesDocument, mDocument, mSelCon, mEditorBase,
                         mFilteredIter, mPrevTextBlock, mNextTextBlock, mExtent)

nsresult TextServicesDocument::InitWithEditor(nsIEditor* aEditor) {
  nsCOMPtr<nsISelectionController> selCon;

  NS_ENSURE_TRUE(aEditor, NS_ERROR_NULL_POINTER);

  // Check to see if we already have an mSelCon. If we do, it
  // better be the same one the editor uses!

  nsresult rv = aEditor->GetSelectionController(getter_AddRefs(selCon));

  if (NS_FAILED(rv)) {
    return rv;
  }

  if (!selCon || (mSelCon && selCon != mSelCon)) {
    return NS_ERROR_FAILURE;
  }

  if (!mSelCon) {
    mSelCon = selCon;
  }

  // Check to see if we already have an mDocument. If we do, it
  // better be the same one the editor uses!

  RefPtr<Document> doc = aEditor->AsEditorBase()->GetDocument();
  if (!doc || (mDocument && doc != mDocument)) {
    return NS_ERROR_FAILURE;
  }

  if (!mDocument) {
    mDocument = doc;

    rv = CreateDocumentContentIterator(getter_AddRefs(mFilteredIter));

    if (NS_FAILED(rv)) {
      return rv;
    }

    mIteratorStatus = IteratorStatus::eDone;

    rv = FirstBlock();

    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  mEditorBase = aEditor->AsEditorBase();

  rv = aEditor->AddEditActionListener(this);

  return rv;
}

nsresult TextServicesDocument::SetExtent(const AbstractRange* aAbstractRange) {
  MOZ_ASSERT(aAbstractRange);

  if (NS_WARN_IF(!mDocument)) {
    return NS_ERROR_FAILURE;
  }

  // We need to store a copy of aAbstractRange since we don't know where it
  // came from.
  mExtent = nsRange::Create(aAbstractRange, IgnoreErrors());
  if (NS_WARN_IF(!mExtent)) {
    return NS_ERROR_FAILURE;
  }

  // Create a new iterator based on our new extent range.
  nsresult rv =
      CreateFilteredContentIterator(mExtent, getter_AddRefs(mFilteredIter));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Now position the iterator at the start of the first block
  // in the range.
  mIteratorStatus = IteratorStatus::eDone;

  rv = FirstBlock();
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "FirstBlock() failed");
  return rv;
}

nsresult TextServicesDocument::ExpandRangeToWordBoundaries(
    StaticRange* aStaticRange) {
  MOZ_ASSERT(aStaticRange);

  // Get the end points of the range.

  nsCOMPtr<nsINode> rngStartNode, rngEndNode;
  uint32_t rngStartOffset, rngEndOffset;

  nsresult rv = GetRangeEndPoints(aStaticRange, getter_AddRefs(rngStartNode),
                                  &rngStartOffset, getter_AddRefs(rngEndNode),
                                  &rngEndOffset);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Create a content iterator based on the range.
  RefPtr<FilteredContentIterator> filteredIter;
  rv =
      CreateFilteredContentIterator(aStaticRange, getter_AddRefs(filteredIter));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Find the first text node in the range.
  IteratorStatus iterStatus = IteratorStatus::eDone;
  rv = FirstTextNode(filteredIter, &iterStatus);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (iterStatus == IteratorStatus::eDone) {
    // No text was found so there's no adjustment necessary!
    return NS_OK;
  }

  nsINode* firstText = filteredIter->GetCurrentNode();
  if (NS_WARN_IF(!firstText)) {
    return NS_ERROR_FAILURE;
  }

  // Find the last text node in the range.

  rv = LastTextNode(filteredIter, &iterStatus);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (iterStatus == IteratorStatus::eDone) {
    // We should never get here because a first text block
    // was found above.
    NS_ASSERTION(false, "Found a first without a last!");
    return NS_ERROR_FAILURE;
  }

  nsINode* lastText = filteredIter->GetCurrentNode();
  if (NS_WARN_IF(!lastText)) {
    return NS_ERROR_FAILURE;
  }

  // Now make sure our end points are in terms of text nodes in the range!

  if (rngStartNode != firstText) {
    // The range includes the start of the first text node!
    rngStartNode = firstText;
    rngStartOffset = 0;
  }

  if (rngEndNode != lastText) {
    // The range includes the end of the last text node!
    rngEndNode = lastText;
    rngEndOffset = lastText->Length();
  }

  // Create a doc iterator so that we can scan beyond
  // the bounds of the extent range.

  RefPtr<FilteredContentIterator> docFilteredIter;
  rv = CreateDocumentContentIterator(getter_AddRefs(docFilteredIter));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Grab all the text in the block containing our
  // first text node.
  rv = docFilteredIter->PositionAt(firstText);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  iterStatus = IteratorStatus::eValid;

  OffsetEntryArray offsetTable;
  nsAutoString blockStr;
  Result<IteratorStatus, nsresult> result = offsetTable.Init(
      *docFilteredIter, IteratorStatus::eValid, nullptr, &blockStr);
  if (result.isErr()) {
    return result.unwrapErr();
  }

  Result<EditorDOMRangeInTexts, nsresult> maybeWordRange =
      offsetTable.FindWordRange(
          blockStr, EditorRawDOMPoint(rngStartNode, rngStartOffset));
  offsetTable.Clear();
  if (maybeWordRange.isErr()) {
    NS_WARNING(
        "TextServicesDocument::OffsetEntryArray::FindWordRange() failed");
    return maybeWordRange.unwrapErr();
  }
  rngStartNode = maybeWordRange.inspect().StartRef().GetContainerAs<Text>();
  rngStartOffset = maybeWordRange.inspect().StartRef().Offset();

  // Grab all the text in the block containing our
  // last text node.

  rv = docFilteredIter->PositionAt(lastText);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  result = offsetTable.Init(*docFilteredIter, IteratorStatus::eValid, nullptr,
                            &blockStr);
  if (result.isErr()) {
    return result.unwrapErr();
  }

  maybeWordRange = offsetTable.FindWordRange(
      blockStr, EditorRawDOMPoint(rngEndNode, rngEndOffset));
  offsetTable.Clear();
  if (maybeWordRange.isErr()) {
    NS_WARNING(
        "TextServicesDocument::OffsetEntryArray::FindWordRange() failed");
    return maybeWordRange.unwrapErr();
  }

  // To prevent expanding the range too much, we only change
  // rngEndNode and rngEndOffset if it isn't already at the start of the
  // word and isn't equivalent to rngStartNode and rngStartOffset.

  if (rngEndNode !=
          maybeWordRange.inspect().StartRef().GetContainerAs<Text>() ||
      rngEndOffset != maybeWordRange.inspect().StartRef().Offset() ||
      (rngEndNode == rngStartNode && rngEndOffset == rngStartOffset)) {
    rngEndNode = maybeWordRange.inspect().EndRef().GetContainerAs<Text>();
    rngEndOffset = maybeWordRange.inspect().EndRef().Offset();
  }

  // Now adjust the range so that it uses our new end points.
  rv = aStaticRange->SetStartAndEnd(rngStartNode, rngStartOffset, rngEndNode,
                                    rngEndOffset);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to update the given range");
  return rv;
}

nsresult TextServicesDocument::SetFilterType(uint32_t aFilterType) {
  mTxtSvcFilterType = aFilterType;

  return NS_OK;
}

nsresult TextServicesDocument::GetCurrentTextBlock(nsAString& aStr) {
  aStr.Truncate();

  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  Result<IteratorStatus, nsresult> result =
      mOffsetTable.Init(*mFilteredIter, mIteratorStatus, mExtent, &aStr);
  if (result.isErr()) {
    NS_WARNING("OffsetEntryArray::Init() failed");
    return result.unwrapErr();
  }
  mIteratorStatus = result.unwrap();
  return NS_OK;
}

nsresult TextServicesDocument::FirstBlock() {
  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  nsresult rv = FirstTextNode(mFilteredIter, &mIteratorStatus);

  if (NS_FAILED(rv)) {
    return rv;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.

  if (mIteratorStatus == IteratorStatus::eValid) {
    mPrevTextBlock = nullptr;
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // There's no text block in the document!

    mPrevTextBlock = nullptr;
    mNextTextBlock = nullptr;
  }

  // XXX Result of FirstTextNode() or GetFirstTextNodeInNextBlock().
  return rv;
}

nsresult TextServicesDocument::LastSelectedBlock(
    BlockSelectionStatus* aSelStatus, uint32_t* aSelOffset,
    uint32_t* aSelLength) {
  NS_ENSURE_TRUE(aSelStatus && aSelOffset && aSelLength, NS_ERROR_NULL_POINTER);

  mIteratorStatus = IteratorStatus::eDone;

  *aSelStatus = BlockSelectionStatus::eBlockNotFound;
  *aSelOffset = *aSelLength = UINT32_MAX;

  if (!mSelCon || !mFilteredIter) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  if (NS_WARN_IF(!selection)) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<const nsRange> range;
  nsCOMPtr<nsINode> parent;

  if (selection->IsCollapsed()) {
    // We have a caret. Check if the caret is in a text node.
    // If it is, make the text node's block the current block.
    // If the caret isn't in a text node, search forwards in
    // the document, till we find a text node.

    range = selection->GetRangeAt(0);
    if (!range) {
      return NS_ERROR_FAILURE;
    }

    parent = range->GetStartContainer();
    if (!parent) {
      return NS_ERROR_FAILURE;
    }

    nsresult rv;
    if (parent->IsText()) {
      // The caret is in a text node. Find the beginning
      // of the text block containing this text node and
      // return.

      rv = mFilteredIter->PositionAt(parent->AsText());
      if (NS_FAILED(rv)) {
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mFilteredIter);
      if (NS_FAILED(rv)) {
        return rv;
      }

      Result<IteratorStatus, nsresult> result =
          mOffsetTable.Init(*mFilteredIter, IteratorStatus::eValid, mExtent);
      if (result.isErr()) {
        NS_WARNING("OffsetEntryArray::Init() failed");
        mIteratorStatus = IteratorStatus::eValid;  // XXX
        return result.unwrapErr();
      }
      mIteratorStatus = result.unwrap();

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);
      if (NS_FAILED(rv)) {
        return rv;
      }

      if (*aSelStatus == BlockSelectionStatus::eBlockContains) {
        rv = SetSelectionInternal(*aSelOffset, *aSelLength, false);
      }
    } else {
      // The caret isn't in a text node. Create an iterator
      // based on a range that extends from the current caret
      // position to the end of the document, then walk forwards
      // till you find a text node, then find the beginning of it's block.

      range = CreateDocumentContentRootToNodeOffsetRange(
          parent, range->StartOffset(), false);
      if (NS_WARN_IF(!range)) {
        return NS_ERROR_FAILURE;
      }

      if (range->Collapsed()) {
        // If we get here, the range is collapsed because there is nothing after
        // the caret! Just return NS_OK;
        return NS_OK;
      }

      RefPtr<FilteredContentIterator> filteredIter;
      rv = CreateFilteredContentIterator(range, getter_AddRefs(filteredIter));
      if (NS_FAILED(rv)) {
        return rv;
      }

      filteredIter->First();

      Text* textNode = nullptr;
      for (; !filteredIter->IsDone(); filteredIter->Next()) {
        nsINode* currentNode = filteredIter->GetCurrentNode();
        if (currentNode->IsText()) {
          textNode = currentNode->AsText();
          break;
        }
      }

      if (!textNode) {
        return NS_OK;
      }

      rv = mFilteredIter->PositionAt(textNode);
      if (NS_FAILED(rv)) {
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mFilteredIter);
      if (NS_FAILED(rv)) {
        return rv;
      }

      Result<IteratorStatus, nsresult> result = mOffsetTable.Init(
          *mFilteredIter, IteratorStatus::eValid, mExtent, nullptr);
      if (result.isErr()) {
        NS_WARNING("OffsetEntryArray::Init() failed");
        mIteratorStatus = IteratorStatus::eValid;  // XXX
        return result.unwrapErr();
      }
      mIteratorStatus = result.inspect();

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);
      if (NS_FAILED(rv)) {
        return rv;
      }
    }

    // Result of SetSelectionInternal() in the |if| block or NS_OK.
    return rv;
  }

  // If we get here, we have an uncollapsed selection!
  // Look backwards through each range in the selection till you
  // find the first text node. If you find one, find the
  // beginning of its text block, and make it the current
  // block.

  const uint32_t rangeCount = selection->RangeCount();
  MOZ_ASSERT(
      rangeCount,
      "Selection is not collapsed, so, the range count should be 1 or larger");

  // XXX: We may need to add some code here to make sure
  //      the ranges are sorted in document appearance order!

  for (const uint32_t i : Reversed(IntegerRange(rangeCount))) {
    MOZ_ASSERT(selection->RangeCount() == rangeCount);
    range = selection->GetRangeAt(i);
    if (MOZ_UNLIKELY(!range)) {
      return NS_OK;  // XXX Really?
    }

    // Create an iterator for the range.

    RefPtr<FilteredContentIterator> filteredIter;
    nsresult rv =
        CreateFilteredContentIterator(range, getter_AddRefs(filteredIter));
    if (NS_FAILED(rv)) {
      return rv;
    }

    filteredIter->Last();

    // Now walk through the range till we find a text node.

    for (; !filteredIter->IsDone(); filteredIter->Prev()) {
      if (filteredIter->GetCurrentNode()->NodeType() == nsINode::TEXT_NODE) {
        // We found a text node, so position the document's
        // iterator at the beginning of the block, then get
        // the selection in terms of the string offset.

        nsresult rv = mFilteredIter->PositionAt(filteredIter->GetCurrentNode());
        if (NS_FAILED(rv)) {
          return rv;
        }

        rv = FirstTextNodeInCurrentBlock(mFilteredIter);
        if (NS_FAILED(rv)) {
          return rv;
        }

        mIteratorStatus = IteratorStatus::eValid;

        Result<IteratorStatus, nsresult> result =
            mOffsetTable.Init(*mFilteredIter, IteratorStatus::eValid, mExtent);
        if (result.isErr()) {
          NS_WARNING("OffsetEntryArray::Init() failed");
          mIteratorStatus = IteratorStatus::eValid;  // XXX
          return result.unwrapErr();
        }
        mIteratorStatus = result.unwrap();

        return GetSelection(aSelStatus, aSelOffset, aSelLength);
      }
    }
  }

  // If we get here, we didn't find any text node in the selection!
  // Create a range that extends from the end of the selection,
  // to the end of the document, then iterate forwards through
  // it till you find a text node!
  range = rangeCount > 0 ? selection->GetRangeAt(rangeCount - 1) : nullptr;
  if (!range) {
    return NS_ERROR_FAILURE;
  }

  parent = range->GetEndContainer();
  if (!parent) {
    return NS_ERROR_FAILURE;
  }

  range = CreateDocumentContentRootToNodeOffsetRange(parent, range->EndOffset(),
                                                     false);
  if (NS_WARN_IF(!range)) {
    return NS_ERROR_FAILURE;
  }

  if (range->Collapsed()) {
    // If we get here, the range is collapsed because there is nothing after
    // the current selection! Just return NS_OK;
    return NS_OK;
  }

  RefPtr<FilteredContentIterator> filteredIter;
  nsresult rv =
      CreateFilteredContentIterator(range, getter_AddRefs(filteredIter));
  if (NS_FAILED(rv)) {
    return rv;
  }

  filteredIter->First();

  for (; !filteredIter->IsDone(); filteredIter->Next()) {
    if (filteredIter->GetCurrentNode()->NodeType() == nsINode::TEXT_NODE) {
      // We found a text node! Adjust the document's iterator to point
      // to the beginning of its text block, then get the current selection.
      nsresult rv = mFilteredIter->PositionAt(filteredIter->GetCurrentNode());
      if (NS_FAILED(rv)) {
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mFilteredIter);
      if (NS_FAILED(rv)) {
        return rv;
      }

      Result<IteratorStatus, nsresult> result =
          mOffsetTable.Init(*mFilteredIter, IteratorStatus::eValid, mExtent);
      if (result.isErr()) {
        NS_WARNING("OffsetEntryArray::Init() failed");
        mIteratorStatus = IteratorStatus::eValid;  // XXX
        return result.unwrapErr();
      }
      mIteratorStatus = result.unwrap();

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                           "TextServicesDocument::GetSelection() failed");
      return rv;
    }
  }

  // If we get here, we didn't find any block before or inside
  // the selection! Just return OK.
  return NS_OK;
}

nsresult TextServicesDocument::PrevBlock() {
  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  if (mIteratorStatus == IteratorStatus::eDone) {
    return NS_OK;
  }

  switch (mIteratorStatus) {
    case IteratorStatus::eValid:
    case IteratorStatus::eNext: {
      nsresult rv = FirstTextNodeInPrevBlock(mFilteredIter);

      if (NS_FAILED(rv)) {
        mIteratorStatus = IteratorStatus::eDone;
        return rv;
      }

      if (mFilteredIter->IsDone()) {
        mIteratorStatus = IteratorStatus::eDone;
        return NS_OK;
      }

      mIteratorStatus = IteratorStatus::eValid;
      break;
    }
    case IteratorStatus::ePrev:

      // The iterator already points to the previous
      // block, so don't do anything.

      mIteratorStatus = IteratorStatus::eValid;
      break;

    default:

      mIteratorStatus = IteratorStatus::eDone;
      break;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.
  nsresult rv = NS_OK;
  if (mIteratorStatus == IteratorStatus::eValid) {
    GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // We must be done!
    mPrevTextBlock = nullptr;
    mNextTextBlock = nullptr;
  }

  // XXX The result of GetFirstTextNodeInNextBlock() or NS_OK.
  return rv;
}

nsresult TextServicesDocument::NextBlock() {
  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  if (mIteratorStatus == IteratorStatus::eDone) {
    return NS_OK;
  }

  switch (mIteratorStatus) {
    case IteratorStatus::eValid: {
      // Advance the iterator to the next text block.

      nsresult rv = FirstTextNodeInNextBlock(mFilteredIter);

      if (NS_FAILED(rv)) {
        mIteratorStatus = IteratorStatus::eDone;
        return rv;
      }

      if (mFilteredIter->IsDone()) {
        mIteratorStatus = IteratorStatus::eDone;
        return NS_OK;
      }

      mIteratorStatus = IteratorStatus::eValid;
      break;
    }
    case IteratorStatus::eNext:

      // The iterator already points to the next block,
      // so don't do anything to it!

      mIteratorStatus = IteratorStatus::eValid;
      break;

    case IteratorStatus::ePrev:

      // If the iterator is pointing to the previous block,
      // we know that there is no next text block! Just
      // fall through to the default case!

    default:

      mIteratorStatus = IteratorStatus::eDone;
      break;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.
  nsresult rv = NS_OK;
  if (mIteratorStatus == IteratorStatus::eValid) {
    GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // We must be done.
    mPrevTextBlock = nullptr;
    mNextTextBlock = nullptr;
  }

  // The result of GetFirstTextNodeInNextBlock() or NS_OK.
  return rv;
}

nsresult TextServicesDocument::IsDone(bool* aIsDone) {
  NS_ENSURE_TRUE(aIsDone, NS_ERROR_NULL_POINTER);

  *aIsDone = false;

  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  *aIsDone = mIteratorStatus == IteratorStatus::eDone;

  return NS_OK;
}

nsresult TextServicesDocument::SetSelection(uint32_t aOffset,
                                            uint32_t aLength) {
  NS_ENSURE_TRUE(mSelCon, NS_ERROR_FAILURE);

  return SetSelectionInternal(aOffset, aLength, true);
}

nsresult TextServicesDocument::ScrollSelectionIntoView() {
  NS_ENSURE_TRUE(mSelCon, NS_ERROR_FAILURE);

  // After ScrollSelectionIntoView(), the pending notifications might be flushed
  // and PresShell/PresContext/Frames may be dead. See bug 418470.
  nsresult rv = mSelCon->ScrollSelectionIntoView(
      nsISelectionController::SELECTION_NORMAL,
      nsISelectionController::SELECTION_FOCUS_REGION,
      nsISelectionController::SCROLL_SYNCHRONOUS);

  return rv;
}

nsresult TextServicesDocument::OffsetEntryArray::WillDeleteSelection() {
  MOZ_ASSERT(mSelection.IsSet());
  MOZ_ASSERT(!mSelection.IsCollapsed());

  for (size_t i = mSelection.StartIndex(); i <= mSelection.EndIndex(); i++) {
    OffsetEntry* entry = ElementAt(i).get();
    if (i == mSelection.StartIndex()) {
      // Calculate the length of the selection. Note that the
      // selection length can be zero if the start of the selection
      // is at the very end of a text node entry.
      uint32_t selLength;
      if (entry->mIsInsertedText) {
        // Inserted text offset entries have no width when
        // talking in terms of string offsets! If the beginning
        // of the selection is in an inserted text offset entry,
        // the caret is always at the end of the entry!
        selLength = 0;
      } else {
        selLength = entry->EndOffsetInTextInBlock() -
                    mSelection.StartOffsetInTextInBlock();
      }

      if (selLength > 0) {
        if (mSelection.StartOffsetInTextInBlock() >
            entry->mOffsetInTextInBlock) {
          // Selection doesn't start at the beginning of the
          // text node entry. We need to split this entry into
          // two pieces, the piece before the selection, and
          // the piece inside the selection.
          nsresult rv = SplitElementAt(i, selLength);
          if (NS_FAILED(rv)) {
            NS_WARNING("selLength was invalid for the OffsetEntry");
            return rv;
          }

          // Adjust selection indexes to account for new entry:
          MOZ_DIAGNOSTIC_ASSERT(mSelection.StartIndex() + 1 < Length());
          MOZ_DIAGNOSTIC_ASSERT(mSelection.EndIndex() + 1 < Length());
          mSelection.SetIndexes(mSelection.StartIndex() + 1,
                                mSelection.EndIndex() + 1);
          entry = ElementAt(++i).get();
        }

        if (mSelection.StartIndex() < mSelection.EndIndex()) {
          // The entire entry is contained in the selection. Mark the
          // entry invalid.
          entry->mIsValid = false;
        }
      }
    }

    if (i == mSelection.EndIndex()) {
      if (entry->mIsInsertedText) {
        // Inserted text offset entries have no width when
        // talking in terms of string offsets! If the end
        // of the selection is in an inserted text offset entry,
        // the selection includes the entire entry!
        entry->mIsValid = false;
      } else {
        // Calculate the length of the selection. Note that the
        // selection length can be zero if the end of the selection
        // is at the very beginning of a text node entry.

        const uint32_t selLength =
            mSelection.EndOffsetInTextInBlock() - entry->mOffsetInTextInBlock;
        if (selLength) {
          if (mSelection.EndOffsetInTextInBlock() <
              entry->EndOffsetInTextInBlock()) {
            // mOffsetInTextInBlock is guaranteed to be inside the selection,
            // even when mSelection.IsInSameElement() is true.
            nsresult rv = SplitElementAt(i, entry->mLength - selLength);
            if (NS_FAILED(rv)) {
              NS_WARNING(
                  "entry->mLength - selLength was invalid for the OffsetEntry");
              return rv;
            }

            // Update the entry fields:
            ElementAt(i + 1)->mOffsetInTextNode = entry->mOffsetInTextNode;
          }

          if (mSelection.EndOffsetInTextInBlock() ==
              entry->EndOffsetInTextInBlock()) {
            // The entire entry is contained in the selection. Mark the
            // entry invalid.
            entry->mIsValid = false;
          }
        }
      }
    }

    if (i != mSelection.StartIndex() && i != mSelection.EndIndex()) {
      // The entire entry is contained in the selection. Mark the
      // entry invalid.
      entry->mIsValid = false;
    }
  }

  return NS_OK;
}

nsresult TextServicesDocument::DeleteSelection() {
  if (NS_WARN_IF(!mEditorBase) ||
      NS_WARN_IF(!mOffsetTable.mSelection.IsSet())) {
    return NS_ERROR_FAILURE;
  }

  if (mOffsetTable.mSelection.IsCollapsed()) {
    return NS_OK;
  }

  // If we have an mExtent, save off its current set of
  // end points so we can compare them against mExtent's
  // set after the deletion of the content.

  nsCOMPtr<nsINode> origStartNode, origEndNode;
  uint32_t origStartOffset = 0, origEndOffset = 0;

  if (mExtent) {
    nsresult rv = GetRangeEndPoints(
        mExtent, getter_AddRefs(origStartNode), &origStartOffset,
        getter_AddRefs(origEndNode), &origEndOffset);

    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  if (NS_FAILED(mOffsetTable.WillDeleteSelection())) {
    NS_WARNING(
        "TextServicesDocument::OffsetEntryTable::WillDeleteSelection() failed");
    return NS_ERROR_FAILURE;
  }

  // Make sure mFilteredIter always points to something valid!
  AdjustContentIterator();

  // Now delete the actual content!
  OwningNonNull<EditorBase> editorBase = *mEditorBase;
  nsresult rv = editorBase->DeleteSelectionAsAction(nsIEditor::ePrevious,
                                                    nsIEditor::eStrip);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Now that we've actually deleted the selected content,
  // check to see if our mExtent has changed, if so, then
  // we have to create a new content iterator!

  if (origStartNode && origEndNode) {
    nsCOMPtr<nsINode> curStartNode, curEndNode;
    uint32_t curStartOffset = 0, curEndOffset = 0;

    rv = GetRangeEndPoints(mExtent, getter_AddRefs(curStartNode),
                           &curStartOffset, getter_AddRefs(curEndNode),
                           &curEndOffset);

    if (NS_FAILED(rv)) {
      return rv;
    }

    if (origStartNode != curStartNode || origEndNode != curEndNode) {
      // The range has changed, so we need to create a new content
      // iterator based on the new range.
      nsCOMPtr<nsIContent> curContent;
      if (mIteratorStatus != IteratorStatus::eDone) {
        // The old iterator is still pointing to something valid,
        // so get its current node so we can restore it after we
        // create the new iterator!
        curContent = mFilteredIter->GetCurrentNode()
                         ? mFilteredIter->GetCurrentNode()->AsContent()
                         : nullptr;
      }

      // Create the new iterator.
      rv =
          CreateFilteredContentIterator(mExtent, getter_AddRefs(mFilteredIter));
      if (NS_FAILED(rv)) {
        return rv;
      }

      // Now make the new iterator point to the content node
      // the old one was pointing at.
      if (curContent) {
        rv = mFilteredIter->PositionAt(curContent);
        if (NS_FAILED(rv)) {
          mIteratorStatus = IteratorStatus::eDone;
        } else {
          mIteratorStatus = IteratorStatus::eValid;
        }
      }
    }
  }

  OffsetEntry* entry = mOffsetTable.DidDeleteSelection();
  if (entry) {
    SetSelection(mOffsetTable.mSelection.StartOffsetInTextInBlock(), 0);
  }

  // Now remove any invalid entries from the offset table.
  mOffsetTable.RemoveInvalidElements();
  return NS_OK;
}

OffsetEntry* TextServicesDocument::OffsetEntryArray::DidDeleteSelection() {
  MOZ_ASSERT(mSelection.IsSet());

  // Move the caret to the end of the first valid entry.
  // Start with SelectionStartIndex() since it may still be valid.
  OffsetEntry* entry = nullptr;
  for (size_t i = mSelection.StartIndex() + 1; !entry && i > 0; i--) {
    entry = ElementAt(i - 1).get();
    if (!entry->mIsValid) {
      entry = nullptr;
    } else {
      MOZ_DIAGNOSTIC_ASSERT(i - 1 < Length());
      mSelection.Set(i - 1, entry->EndOffsetInTextInBlock());
    }
  }

  // If we still don't have a valid entry, move the caret
  // to the next valid entry after the selection:
  for (size_t i = mSelection.EndIndex(); !entry && i < Length(); i++) {
    entry = ElementAt(i).get();
    if (!entry->mIsValid) {
      entry = nullptr;
    } else {
      MOZ_DIAGNOSTIC_ASSERT(i < Length());
      mSelection.Set(i, entry->mOffsetInTextInBlock);
    }
  }

  if (!entry) {
    // Uuughh we have no valid offset entry to place our
    // caret ... just mark the selection invalid.
    mSelection.Reset();
  }

  return entry;
}

nsresult TextServicesDocument::InsertText(const nsAString& aText) {
  if (NS_WARN_IF(!mEditorBase) ||
      NS_WARN_IF(!mOffsetTable.mSelection.IsSet())) {
    return NS_ERROR_FAILURE;
  }

  // If the selection is not collapsed, we need to save
  // off the selection offsets so we can restore the
  // selection and delete the selected content after we've
  // inserted the new text. This is necessary to try and
  // retain as much of the original style of the content
  // being deleted.

  const bool wasSelectionCollapsed = mOffsetTable.mSelection.IsCollapsed();
  const uint32_t savedSelOffset =
      mOffsetTable.mSelection.StartOffsetInTextInBlock();
  const uint32_t savedSelLength = mOffsetTable.mSelection.LengthInTextInBlock();

  if (!wasSelectionCollapsed) {
    // Collapse to the start of the current selection
    // for the insert!
    nsresult rv =
        SetSelection(mOffsetTable.mSelection.StartOffsetInTextInBlock(), 0);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // AutoTransactionBatchExternal grabs mEditorBase, so, we don't need to grab
  // the instance with local variable here.
  OwningNonNull<EditorBase> editorBase = *mEditorBase;
  AutoTransactionBatchExternal treatAsOneTransaction(editorBase);

  nsresult rv = editorBase->InsertTextAsAction(aText);
  if (NS_FAILED(rv)) {
    NS_WARNING("InsertTextAsAction() failed");
    return rv;
  }

  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  rv = mOffsetTable.DidInsertText(selection, aText);
  if (NS_FAILED(rv)) {
    NS_WARNING("TextServicesDocument::OffsetEntry::DidInsertText() failed");
    return rv;
  }

  if (!wasSelectionCollapsed) {
    nsresult rv = SetSelection(savedSelOffset, savedSelLength);
    if (NS_FAILED(rv)) {
      return rv;
    }

    rv = DeleteSelection();
    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  return NS_OK;
}

nsresult TextServicesDocument::OffsetEntryArray::DidInsertText(
    dom::Selection* aSelection, const nsAString& aInsertedString) {
  MOZ_ASSERT(mSelection.IsSet());

  // When you touch this method, please make sure that the entry instance
  // won't be deleted.  If you know it'll be deleted, you should set it to
  // `nullptr`.
  OffsetEntry* entry = ElementAt(mSelection.StartIndex()).get();
  OwningNonNull<Text> const textNodeAtStartEntry = entry->mTextNode;

  NS_ASSERTION((entry->mIsValid), "Invalid insertion point!");

  if (entry->mOffsetInTextInBlock == mSelection.StartOffsetInTextInBlock()) {
    if (entry->mIsInsertedText) {
      // If the caret is in an inserted text offset entry,
      // we simply insert the text at the end of the entry.
      entry->mLength += aInsertedString.Length();
    } else {
      // Insert an inserted text offset entry before the current
      // entry!
      UniquePtr<OffsetEntry> newInsertedTextEntry =
          MakeUnique<OffsetEntry>(entry->mTextNode, entry->mOffsetInTextInBlock,
                                  aInsertedString.Length());
      newInsertedTextEntry->mIsInsertedText = true;
      newInsertedTextEntry->mOffsetInTextNode = entry->mOffsetInTextNode;
      // XXX(Bug 1631371) Check if this should use a fallible operation as it
      // pretended earlier.
      InsertElementAt(mSelection.StartIndex(), std::move(newInsertedTextEntry));
    }
  } else if (entry->EndOffsetInTextInBlock() ==
             mSelection.EndOffsetInTextInBlock()) {
    // We are inserting text at the end of the current offset entry.
    // Look at the next valid entry in the table. If it's an inserted
    // text entry, add to its length and adjust its node offset. If
    // it isn't, add a new inserted text entry.
    uint32_t nextIndex = mSelection.StartIndex() + 1;
    OffsetEntry* insertedTextEntry = nullptr;
    if (Length() > nextIndex) {
      insertedTextEntry = ElementAt(nextIndex).get();
      if (!insertedTextEntry) {
        return NS_ERROR_FAILURE;
      }

      // Check if the entry is a match. If it isn't, set
      // iEntry to zero.
      if (!insertedTextEntry->mIsInsertedText ||
          insertedTextEntry->mOffsetInTextInBlock !=
              mSelection.StartOffsetInTextInBlock()) {
        insertedTextEntry = nullptr;
      }
    }

    if (!insertedTextEntry) {
      // We didn't find an inserted text offset entry, so
      // create one.
      UniquePtr<OffsetEntry> newInsertedTextEntry = MakeUnique<OffsetEntry>(
          entry->mTextNode, mSelection.StartOffsetInTextInBlock(), 0);
      newInsertedTextEntry->mOffsetInTextNode = entry->EndOffsetInTextNode();
      newInsertedTextEntry->mIsInsertedText = true;
      // XXX(Bug 1631371) Check if this should use a fallible operation as it
      // pretended earlier.
      insertedTextEntry =
          InsertElementAt(nextIndex, std::move(newInsertedTextEntry))->get();
    }

    // We have a valid inserted text offset entry. Update its
    // length, adjust the selection indexes, and make sure the
    // caret is properly placed!

    insertedTextEntry->mLength += aInsertedString.Length();

    MOZ_DIAGNOSTIC_ASSERT(nextIndex < Length());
    mSelection.SetIndex(nextIndex);

    if (!aSelection) {
      return NS_OK;
    }

    OwningNonNull<Text> textNode = insertedTextEntry->mTextNode;
    nsresult rv = aSelection->CollapseInLimiter(
        textNode, insertedTextEntry->EndOffsetInTextNode());
    if (NS_FAILED(rv)) {
      NS_WARNING("Selection::CollapseInLimiter() failed");
      return rv;
    }
  } else if (entry->EndOffsetInTextInBlock() >
             mSelection.StartOffsetInTextInBlock()) {
    // We are inserting text into the middle of the current offset entry.
    // split the current entry into two parts, then insert an inserted text
    // entry between them!
    nsresult rv = SplitElementAt(mSelection.StartIndex(),
                                 entry->EndOffsetInTextInBlock() -
                                     mSelection.StartOffsetInTextInBlock());
    if (NS_FAILED(rv)) {
      NS_WARNING(
          "entry->EndOffsetInTextInBlock() - "
          "mSelection.StartOffsetInTextInBlock() was invalid for the "
          "OffsetEntry");
      return rv;
    }

    // XXX(Bug 1631371) Check if this should use a fallible operation as it
    // pretended earlier.
    UniquePtr<OffsetEntry>& insertedTextEntry = *InsertElementAt(
        mSelection.StartIndex() + 1,
        MakeUnique<OffsetEntry>(entry->mTextNode,
                                mSelection.StartOffsetInTextInBlock(),
                                aInsertedString.Length()));
    LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
    insertedTextEntry->mIsInsertedText = true;
    insertedTextEntry->mOffsetInTextNode = entry->EndOffsetInTextNode();
    MOZ_DIAGNOSTIC_ASSERT(mSelection.StartIndex() + 1 < Length());
    mSelection.SetIndex(mSelection.StartIndex() + 1);
  }

  // We've just finished inserting an inserted text offset entry.
  // update all entries with the same mTextNode pointer that follow
  // it in the table!

  for (size_t i = mSelection.StartIndex() + 1; i < Length(); i++) {
    const UniquePtr<OffsetEntry>& entry = ElementAt(i);
    LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
    if (entry->mTextNode != textNodeAtStartEntry) {
      break;
    }
    if (entry->mIsValid) {
      entry->mOffsetInTextNode += aInsertedString.Length();
    }
  }

  return NS_OK;
}

void TextServicesDocument::DidDeleteContent(const nsIContent& aChildContent) {
  if (NS_WARN_IF(!mFilteredIter) || !aChildContent.IsText()) {
    return;
  }

  Maybe<size_t> maybeNodeIndex =
      mOffsetTable.FirstIndexOf(*aChildContent.AsText());
  if (maybeNodeIndex.isNothing()) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    return;
  }

  nsINode* node = mFilteredIter->GetCurrentNode();
  if (node && node == &aChildContent &&
      mIteratorStatus != IteratorStatus::eDone) {
    // XXX: This should never really happen because
    // AdjustContentIterator() should have been called prior
    // to the delete to try and position the iterator on the
    // next valid text node in the offset table, and if there
    // wasn't a next, it would've set mIteratorStatus to eIsDone.

    NS_ERROR("DeleteNode called for current iterator node.");
  }

  for (size_t nodeIndex = *maybeNodeIndex; nodeIndex < mOffsetTable.Length();
       nodeIndex++) {
    const UniquePtr<OffsetEntry>& entry = mOffsetTable[nodeIndex];
    LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
    if (!entry) {
      return;
    }

    if (entry->mTextNode == &aChildContent) {
      entry->mIsValid = false;
    }
  }
}

void TextServicesDocument::DidJoinContents(
    const EditorRawDOMPoint& aJoinedPoint, const nsIContent& aRemovedContent,
    JoinNodesDirection aJoinNodesDirection) {
  // Make sure that both nodes are text nodes -- otherwise we don't care.
  if (!aJoinedPoint.IsInTextNode() || !aRemovedContent.IsText()) {
    return;
  }

  // Note: The editor merges the contents of the left node into the
  //       contents of the right.

  Maybe<size_t> maybeRemovedIndex =
      mOffsetTable.FirstIndexOf(*aRemovedContent.AsText());
  if (maybeRemovedIndex.isNothing()) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    return;
  }

  Maybe<size_t> maybeJoinedIndex =
      mOffsetTable.FirstIndexOf(*aJoinedPoint.ContainerAs<Text>());
  if (maybeJoinedIndex.isNothing()) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    return;
  }

  const size_t removedIndex = *maybeRemovedIndex;
  const size_t joinedIndex = *maybeJoinedIndex;

  if (aJoinNodesDirection == JoinNodesDirection::LeftNodeIntoRightNode) {
    if (MOZ_UNLIKELY(removedIndex > joinedIndex)) {
      NS_ASSERTION(removedIndex < joinedIndex, "Indexes out of order.");
      return;
    }
    NS_ASSERTION(mOffsetTable[joinedIndex]->mOffsetInTextNode == 0,
                 "Unexpected offset value for joinedIndex.");
  } else {
    if (MOZ_UNLIKELY(joinedIndex > removedIndex)) {
      NS_ASSERTION(joinedIndex < removedIndex, "Indexes out of order.");
      return;
    }
    NS_ASSERTION(mOffsetTable[removedIndex]->mOffsetInTextNode == 0,
                 "Unexpected offset value for rightIndex.");
  }

  // Run through the table and change all entries referring to
  // the removed node so that they now refer to the joined node,
  // and adjust offsets if necessary.
  const uint32_t movedTextDataLength =
      aJoinNodesDirection == JoinNodesDirection::LeftNodeIntoRightNode
          ? aJoinedPoint.Offset()
          : aJoinedPoint.ContainerAs<Text>()->TextDataLength() -
                aJoinedPoint.Offset();
  for (uint32_t i = removedIndex; i < mOffsetTable.Length(); i++) {
    const UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
    LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
    if (entry->mTextNode != aRemovedContent.AsText()) {
      break;
    }
    if (entry->mIsValid) {
      entry->mTextNode = aJoinedPoint.ContainerAs<Text>();
      if (aJoinNodesDirection == JoinNodesDirection::RightNodeIntoLeftNode) {
        // The text was moved from aRemovedContent to end of the container of
        // aJoinedPoint.
        entry->mOffsetInTextNode += movedTextDataLength;
      }
    }
  }

  if (aJoinNodesDirection == JoinNodesDirection::LeftNodeIntoRightNode) {
    // The text was moved from aRemovedContent to start of the container of
    // aJoinedPoint.
    for (uint32_t i = joinedIndex; i < mOffsetTable.Length(); i++) {
      const UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
      LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
      if (entry->mTextNode != aJoinedPoint.ContainerAs<Text>()) {
        break;
      }
      if (entry->mIsValid) {
        entry->mOffsetInTextNode += movedTextDataLength;
      }
    }
  }

  // Now check to see if the iterator is pointing to the
  // left node. If it is, make it point to the joined node!
  if (mFilteredIter->GetCurrentNode() == aRemovedContent.AsText()) {
    mFilteredIter->PositionAt(aJoinedPoint.ContainerAs<Text>());
  }
}

nsresult TextServicesDocument::CreateFilteredContentIterator(
    const AbstractRange* aAbstractRange,
    FilteredContentIterator** aFilteredIter) {
  if (NS_WARN_IF(!aAbstractRange) || NS_WARN_IF(!aFilteredIter)) {
    return NS_ERROR_INVALID_ARG;
  }

  *aFilteredIter = nullptr;

  UniquePtr<nsComposeTxtSrvFilter> composeFilter;
  switch (mTxtSvcFilterType) {
    case nsIEditorSpellCheck::FILTERTYPE_NORMAL:
      composeFilter = nsComposeTxtSrvFilter::CreateNormalFilter();
      break;
    case nsIEditorSpellCheck::FILTERTYPE_MAIL:
      composeFilter = nsComposeTxtSrvFilter::CreateMailFilter();
      break;
  }

  // Create a FilteredContentIterator
  // This class wraps the ContentIterator in order to give itself a chance
  // to filter out certain content nodes
  RefPtr<FilteredContentIterator> filter =
      new FilteredContentIterator(std::move(composeFilter));
  nsresult rv = filter->Init(aAbstractRange);
  if (NS_FAILED(rv)) {
    return rv;
  }

  filter.forget(aFilteredIter);
  return NS_OK;
}

Element* TextServicesDocument::GetDocumentContentRootNode() const {
  if (NS_WARN_IF(!mDocument)) {
    return nullptr;
  }

  if (mDocument->IsHTMLOrXHTML()) {
    Element* rootElement = mDocument->GetRootElement();
    if (rootElement && rootElement->IsXULElement()) {
      // HTML documents with root XUL elements should eventually be transitioned
      // to a regular document structure, but for now the content root node will
      // be the document element.
      return mDocument->GetDocumentElement();
    }
    // For HTML documents, the content root node is the body.
    return mDocument->GetBody();
  }

  // For non-HTML documents, the content root node will be the document element.
  return mDocument->GetDocumentElement();
}

already_AddRefed<nsRange> TextServicesDocument::CreateDocumentContentRange() {
  nsCOMPtr<nsINode> node = GetDocumentContentRootNode();
  if (NS_WARN_IF(!node)) {
    return nullptr;
  }

  RefPtr<nsRange> range = nsRange::Create(node);
  IgnoredErrorResult ignoredError;
  range->SelectNodeContents(*node, ignoredError);
  NS_WARNING_ASSERTION(!ignoredError.Failed(), "SelectNodeContents() failed");
  return range.forget();
}

already_AddRefed<nsRange>
TextServicesDocument::CreateDocumentContentRootToNodeOffsetRange(
    nsINode* aParent, uint32_t aOffset, bool aToStart) {
  if (NS_WARN_IF(!aParent)) {
    return nullptr;
  }

  nsCOMPtr<nsINode> bodyNode = GetDocumentContentRootNode();
  if (NS_WARN_IF(!bodyNode)) {
    return nullptr;
  }

  nsCOMPtr<nsINode> startNode;
  nsCOMPtr<nsINode> endNode;
  uint32_t startOffset, endOffset;

  if (aToStart) {
    // The range should begin at the start of the document
    // and extend up until (aParent, aOffset).
    startNode = bodyNode;
    startOffset = 0;
    endNode = aParent;
    endOffset = aOffset;
  } else {
    // The range should begin at (aParent, aOffset) and
    // extend to the end of the document.
    startNode = aParent;
    startOffset = aOffset;
    endNode = bodyNode;
    endOffset = endNode ? endNode->GetChildCount() : 0;
  }

  RefPtr<nsRange> range = nsRange::Create(startNode, startOffset, endNode,
                                          endOffset, IgnoreErrors());
  NS_WARNING_ASSERTION(range,
                       "nsRange::Create() failed to create new valid range");
  return range.forget();
}

nsresult TextServicesDocument::CreateDocumentContentIterator(
    FilteredContentIterator** aFilteredIter) {
  NS_ENSURE_TRUE(aFilteredIter, NS_ERROR_NULL_POINTER);

  RefPtr<nsRange> range = CreateDocumentContentRange();
  if (NS_WARN_IF(!range)) {
    *aFilteredIter = nullptr;
    return NS_ERROR_FAILURE;
  }

  return CreateFilteredContentIterator(range, aFilteredIter);
}

nsresult TextServicesDocument::AdjustContentIterator() {
  NS_ENSURE_TRUE(mFilteredIter, NS_ERROR_FAILURE);

  nsCOMPtr<nsINode> node = mFilteredIter->GetCurrentNode();
  NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);

  Text* prevValidTextNode = nullptr;
  Text* nextValidTextNode = nullptr;
  bool foundEntry = false;

  const size_t tableLength = mOffsetTable.Length();
  for (size_t i = 0; i < tableLength && !nextValidTextNode; i++) {
    UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
    LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
    if (entry->mTextNode == node) {
      if (entry->mIsValid) {
        // The iterator is still pointing to something valid!
        // Do nothing!
        return NS_OK;
      }
      // We found an invalid entry that points to
      // the current iterator node. Stop looking for
      // a previous valid node!
      foundEntry = true;
    }

    if (entry->mIsValid) {
      if (!foundEntry) {
        prevValidTextNode = entry->mTextNode;
      } else {
        nextValidTextNode = entry->mTextNode;
      }
    }
  }

  Text* validTextNode = nullptr;
  if (prevValidTextNode) {
    validTextNode = prevValidTextNode;
  } else if (nextValidTextNode) {
    validTextNode = nextValidTextNode;
  }

  if (validTextNode) {
    nsresult rv = mFilteredIter->PositionAt(validTextNode);
    if (NS_FAILED(rv)) {
      mIteratorStatus = IteratorStatus::eDone;
    } else {
      mIteratorStatus = IteratorStatus::eValid;
    }
    return rv;
  }

  // If we get here, there aren't any valid entries
  // in the offset table! Try to position the iterator
  // on the next text block first, then previous if
  // one doesn't exist!

  if (mNextTextBlock) {
    nsresult rv = mFilteredIter->PositionAt(mNextTextBlock);
    if (NS_FAILED(rv)) {
      mIteratorStatus = IteratorStatus::eDone;
      return rv;
    }

    mIteratorStatus = IteratorStatus::eNext;
  } else if (mPrevTextBlock) {
    nsresult rv = mFilteredIter->PositionAt(mPrevTextBlock);
    if (NS_FAILED(rv)) {
      mIteratorStatus = IteratorStatus::eDone;
      return rv;
    }

    mIteratorStatus = IteratorStatus::ePrev;
  } else {
    mIteratorStatus = IteratorStatus::eDone;
  }
  return NS_OK;
}

// static
bool TextServicesDocument::DidSkip(FilteredContentIterator* aFilteredIter) {
  return aFilteredIter && aFilteredIter->DidSkip();
}

// static
void TextServicesDocument::ClearDidSkip(
    FilteredContentIterator* aFilteredIter) {
  // Clear filter's skip flag
  if (aFilteredIter) {
    aFilteredIter->ClearDidSkip();
  }
}

// static
bool TextServicesDocument::HasSameBlockNodeParent(Text& aTextNode1,
                                                  Text& aTextNode2) {
  // XXX How about the case that both text nodes are orphan nodes?
  if (aTextNode1.GetParent() == aTextNode2.GetParent()) {
    return true;
  }

  // I think that spellcheck should be available only in editable nodes.
  // So, we also need to check whether they are in same editing host.
  const Element* editableBlockElementOrInlineEditingHost1 =
      HTMLEditUtils::GetAncestorElement(
          aTextNode1,
          HTMLEditUtils::ClosestEditableBlockElementOrInlineEditingHost);
  const Element* editableBlockElementOrInlineEditingHost2 =
      HTMLEditUtils::GetAncestorElement(
          aTextNode2,
          HTMLEditUtils::ClosestEditableBlockElementOrInlineEditingHost);
  return editableBlockElementOrInlineEditingHost1 &&
         editableBlockElementOrInlineEditingHost1 ==
             editableBlockElementOrInlineEditingHost2;
}

Result<EditorRawDOMRangeInTexts, nsresult>
TextServicesDocument::OffsetEntryArray::WillSetSelection(
    uint32_t aOffsetInTextInBlock, uint32_t aLength) {
  // Find start of selection in node offset terms:
  EditorRawDOMPointInText newStart;
  for (size_t i = 0; !newStart.IsSet() && i < Length(); i++) {
    const UniquePtr<OffsetEntry>& entry = ElementAt(i);
    LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
    if (entry->mIsValid) {
      if (entry->mIsInsertedText) {
        // Caret can only be placed at the end of an
        // inserted text offset entry, if the offsets
        // match exactly!
        if (entry->mOffsetInTextInBlock == aOffsetInTextInBlock) {
          newStart.Set(entry->mTextNode, entry->EndOffsetInTextNode());
        }
      } else if (aOffsetInTextInBlock >= entry->mOffsetInTextInBlock) {
        bool foundEntry = false;
        if (aOffsetInTextInBlock < entry->EndOffsetInTextInBlock()) {
          foundEntry = true;
        } else if (aOffsetInTextInBlock == entry->EndOffsetInTextInBlock()) {
          // Peek after this entry to see if we have any
          // inserted text entries belonging to the same
          // entry->mTextNode. If so, we have to place the selection
          // after it!
          if (i + 1 < Length()) {
            const UniquePtr<OffsetEntry>& nextEntry = ElementAt(i + 1);
            LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
            if (!nextEntry->mIsValid ||
                nextEntry->mOffsetInTextInBlock != aOffsetInTextInBlock) {
              // Next offset entry isn't an exact match, so we'll
              // just use the current entry.
              foundEntry = true;
            }
          }
        }

        if (foundEntry) {
          newStart.Set(entry->mTextNode, entry->mOffsetInTextNode +
                                             aOffsetInTextInBlock -
                                             entry->mOffsetInTextInBlock);
        }
      }

      if (newStart.IsSet()) {
        MOZ_DIAGNOSTIC_ASSERT(i < Length());
        mSelection.Set(i, aOffsetInTextInBlock);
      }
    }
  }

  if (NS_WARN_IF(!newStart.IsSet())) {
    return Err(NS_ERROR_FAILURE);
  }

  if (!aLength) {
    mSelection.CollapseToStart();
    return EditorRawDOMRangeInTexts(newStart);
  }

  // Find the end of the selection in node offset terms:
  EditorRawDOMPointInText newEnd;
  const uint32_t endOffset = aOffsetInTextInBlock + aLength;
  for (uint32_t i = Length(); !newEnd.IsSet() && i > 0; i--) {
    const UniquePtr<OffsetEntry>& entry = ElementAt(i - 1);
    LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
    if (entry->mIsValid) {
      if (entry->mIsInsertedText) {
        if (entry->mOffsetInTextInBlock ==
            (newEnd.IsSet() ? newEnd.Offset() : 0)) {
          // If the selection ends on an inserted text offset entry,
          // the selection includes the entire entry!
          newEnd.Set(entry->mTextNode, entry->EndOffsetInTextNode());
        }
      } else if (entry->OffsetInTextInBlockIsInRangeOrEndOffset(endOffset)) {
        newEnd.Set(entry->mTextNode, entry->mOffsetInTextNode + endOffset -
                                         entry->mOffsetInTextInBlock);
      }

      if (newEnd.IsSet()) {
        MOZ_DIAGNOSTIC_ASSERT(mSelection.StartIndex() < Length());
        MOZ_DIAGNOSTIC_ASSERT(i - 1 < Length());
        mSelection.Set(mSelection.StartIndex(), i - 1,
                       mSelection.StartOffsetInTextInBlock(), endOffset);
      }
    }
  }

  return newEnd.IsSet() ? EditorRawDOMRangeInTexts(newStart, newEnd)
                        : EditorRawDOMRangeInTexts(newStart);
}

nsresult TextServicesDocument::SetSelectionInternal(
    uint32_t aOffsetInTextInBlock, uint32_t aLength, bool aDoUpdate) {
  if (NS_WARN_IF(!mSelCon)) {
    return NS_ERROR_INVALID_ARG;
  }

  Result<EditorRawDOMRangeInTexts, nsresult> newSelectionRange =
      mOffsetTable.WillSetSelection(aOffsetInTextInBlock, aLength);
  if (newSelectionRange.isErr()) {
    NS_WARNING(
        "TextServicesDocument::OffsetEntryArray::WillSetSelection() failed");
    return newSelectionRange.unwrapErr();
  }

  if (!aDoUpdate) {
    return NS_OK;
  }

  // XXX: If we ever get a SetSelection() method in nsIEditor, we should
  //      use it.
  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  if (NS_WARN_IF(!selection)) {
    return NS_ERROR_FAILURE;
  }

  if (newSelectionRange.inspect().Collapsed()) {
    nsresult rv =
        selection->CollapseInLimiter(newSelectionRange.inspect().StartRef());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                         "Selection::CollapseInLimiter() failed");
    return rv;
  }

  ErrorResult error;
  selection->SetStartAndEndInLimiter(newSelectionRange.inspect().StartRef(),
                                     newSelectionRange.inspect().EndRef(),
                                     error);
  NS_WARNING_ASSERTION(!error.Failed(),
                       "Selection::SetStartAndEndInLimiter() failed");
  return error.StealNSResult();
}

nsresult TextServicesDocument::GetSelection(BlockSelectionStatus* aSelStatus,
                                            uint32_t* aSelOffset,
                                            uint32_t* aSelLength) {
  NS_ENSURE_TRUE(aSelStatus && aSelOffset && aSelLength, NS_ERROR_NULL_POINTER);

  *aSelStatus = BlockSelectionStatus::eBlockNotFound;
  *aSelOffset = UINT32_MAX;
  *aSelLength = UINT32_MAX;

  NS_ENSURE_TRUE(mDocument && mSelCon, NS_ERROR_FAILURE);

  if (mIteratorStatus == IteratorStatus::eDone) {
    return NS_OK;
  }

  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  if (selection->IsCollapsed()) {
    return GetCollapsedSelection(aSelStatus, aSelOffset, aSelLength);
  }

  return GetUncollapsedSelection(aSelStatus, aSelOffset, aSelLength);
}

nsresult TextServicesDocument::GetCollapsedSelection(
    BlockSelectionStatus* aSelStatus, uint32_t* aSelOffset,
    uint32_t* aSelLength) {
  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  // The calling function should have done the GetIsCollapsed()
  // check already. Just assume it's collapsed!
  *aSelStatus = BlockSelectionStatus::eBlockOutside;
  *aSelOffset = *aSelLength = UINT32_MAX;

  const uint32_t tableCount = mOffsetTable.Length();
  if (!tableCount) {
    return NS_OK;
  }

  // Get pointers to the first and last offset entries
  // in the table.

  UniquePtr<OffsetEntry>& eStart = mOffsetTable[0];
  UniquePtr<OffsetEntry>& eEnd =
      tableCount > 1 ? mOffsetTable[tableCount - 1] : eStart;
  LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);

  const uint32_t eStartOffset = eStart->mOffsetInTextNode;
  const uint32_t eEndOffset = eEnd->EndOffsetInTextNode();

  RefPtr<const nsRange> range = selection->GetRangeAt(0);
  NS_ENSURE_STATE(range);

  nsCOMPtr<nsINode> parent = range->GetStartContainer();
  MOZ_ASSERT(parent);

  uint32_t offset = range->StartOffset();

  const Maybe<int32_t> e1s1 = nsContentUtils::ComparePoints(
      eStart->mTextNode, eStartOffset, parent, offset);
  const Maybe<int32_t> e2s1 = nsContentUtils::ComparePoints(
      eEnd->mTextNode, eEndOffset, parent, offset);

  if (MOZ_UNLIKELY(NS_WARN_IF(!e1s1) || NS_WARN_IF(!e2s1))) {
    return NS_ERROR_FAILURE;
  }

  if (*e1s1 > 0 || *e2s1 < 0) {
    // We're done if the caret is outside the current text block.
    return NS_OK;
  }

  if (parent->IsText()) {
    // Good news, the caret is in a text node. Look
    // through the offset table for the entry that
    // matches its parent and offset.

    for (uint32_t i = 0; i < tableCount; i++) {
      const UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
      LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
      if (entry->mTextNode == parent->AsText() &&
          entry->OffsetInTextNodeIsInRangeOrEndOffset(offset)) {
        *aSelStatus = BlockSelectionStatus::eBlockContains;
        *aSelOffset =
            entry->mOffsetInTextInBlock + (offset - entry->mOffsetInTextNode);
        *aSelLength = 0;
        return NS_OK;
      }
    }

    // If we get here, we didn't find a text node entry
    // in our offset table that matched.
    return NS_ERROR_FAILURE;
  }

  // The caret is in our text block, but it's positioned in some
  // non-text node (ex. <b>). Create a range based on the start
  // and end of the text block, then create an iterator based on
  // this range, with its initial position set to the closest
  // child of this non-text node. Then look for the closest text
  // node.

  range = nsRange::Create(eStart->mTextNode, eStartOffset, eEnd->mTextNode,
                          eEndOffset, IgnoreErrors());
  if (NS_WARN_IF(!range)) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<FilteredContentIterator> filteredIter;
  nsresult rv =
      CreateFilteredContentIterator(range, getter_AddRefs(filteredIter));
  NS_ENSURE_SUCCESS(rv, rv);

  nsIContent* saveNode;
  if (parent->HasChildren()) {
    // XXX: We need to make sure that all of parent's
    //      children are in the text block.

    // If the parent has children, position the iterator
    // on the child that is to the left of the offset.

    nsIContent* content = range->GetChildAtStartOffset();
    if (content && parent->GetFirstChild() != content) {
      content = content->GetPreviousSibling();
    }
    NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);

    nsresult rv = filteredIter->PositionAt(content);
    NS_ENSURE_SUCCESS(rv, rv);

    saveNode = content;
  } else {
    // The parent has no children, so position the iterator
    // on the parent.
    NS_ENSURE_TRUE(parent->IsContent(), NS_ERROR_FAILURE);
    nsCOMPtr<nsIContent> content = parent->AsContent();

    nsresult rv = filteredIter->PositionAt(content);
    NS_ENSURE_SUCCESS(rv, rv);

    saveNode = content;
  }

  // Now iterate to the left, towards the beginning of
  // the text block, to find the first text node you
  // come across.

  Text* textNode = nullptr;
  for (; !filteredIter->IsDone(); filteredIter->Prev()) {
    nsINode* current = filteredIter->GetCurrentNode();
    if (current->IsText()) {
      textNode = current->AsText();
      break;
    }
  }

  if (textNode) {
    // We found a node, now set the offset to the end
    // of the text node.
    offset = textNode->TextLength();
  } else {
    // We should never really get here, but I'm paranoid.

    // We didn't find a text node above, so iterate to
    // the right, towards the end of the text block, looking
    // for a text node.

    nsresult rv = filteredIter->PositionAt(saveNode);
    NS_ENSURE_SUCCESS(rv, rv);

    textNode = nullptr;
    for (; !filteredIter->IsDone(); filteredIter->Next()) {
      nsINode* current = filteredIter->GetCurrentNode();
      if (current->IsText()) {
        textNode = current->AsText();
        break;
      }
    }
    NS_ENSURE_TRUE(textNode, NS_ERROR_FAILURE);

    // We found a text node, so set the offset to
    // the beginning of the node.
    offset = 0;
  }

  for (size_t i = 0; i < tableCount; i++) {
    const UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
    LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
    if (entry->mTextNode == textNode &&
        entry->OffsetInTextNodeIsInRangeOrEndOffset(offset)) {
      *aSelStatus = BlockSelectionStatus::eBlockContains;
      *aSelOffset =
          entry->mOffsetInTextInBlock + (offset - entry->mOffsetInTextNode);
      *aSelLength = 0;

      // Now move the caret so that it is actually in the text node.
      // We do this to keep things in sync.
      //
      // In most cases, the user shouldn't see any movement in the caret
      // on screen.
      return SetSelectionInternal(*aSelOffset, *aSelLength, true);
    }
  }

  return NS_ERROR_FAILURE;
}

nsresult TextServicesDocument::GetUncollapsedSelection(
    BlockSelectionStatus* aSelStatus, uint32_t* aSelOffset,
    uint32_t* aSelLength) {
  RefPtr<const nsRange> range;
  RefPtr<Selection> selection =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL);
  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  // It is assumed that the calling function has made sure that the
  // selection is not collapsed, and that the input params to this
  // method are initialized to some defaults.

  nsCOMPtr<nsINode> startContainer, endContainer;

  const size_t tableCount = mOffsetTable.Length();

  // Get pointers to the first and last offset entries
  // in the table.

  UniquePtr<OffsetEntry>& eStart = mOffsetTable[0];
  UniquePtr<OffsetEntry>& eEnd =
      tableCount > 1 ? mOffsetTable[tableCount - 1] : eStart;
  LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);

  const uint32_t eStartOffset = eStart->mOffsetInTextNode;
  const uint32_t eEndOffset = eEnd->EndOffsetInTextNode();

  const uint32_t rangeCount = selection->RangeCount();
  MOZ_ASSERT(rangeCount);

  // Find the first range in the selection that intersects
  // the current text block.
  Maybe<int32_t> e1s2;
  Maybe<int32_t> e2s1;
  uint32_t startOffset, endOffset;
  for (const uint32_t i : IntegerRange(rangeCount)) {
    MOZ_ASSERT(selection->RangeCount() == rangeCount);
    range = selection->GetRangeAt(i);
    if (MOZ_UNLIKELY(NS_WARN_IF(!range))) {
      return NS_ERROR_FAILURE;
    }

    nsresult rv =
        GetRangeEndPoints(range, getter_AddRefs(startContainer), &startOffset,
                          getter_AddRefs(endContainer), &endOffset);

    NS_ENSURE_SUCCESS(rv, rv);

    e1s2 = nsContentUtils::ComparePoints(eStart->mTextNode, eStartOffset,
                                         endContainer, endOffset);
    if (NS_WARN_IF(!e1s2)) {
      return NS_ERROR_FAILURE;
    }

    e2s1 = nsContentUtils::ComparePoints(eEnd->mTextNode, eEndOffset,
                                         startContainer, startOffset);
    if (NS_WARN_IF(!e2s1)) {
      return NS_ERROR_FAILURE;
    }

    // Break out of the loop if the text block intersects the current range.

    if (*e1s2 <= 0 && *e2s1 >= 0) {
      break;
    }
  }

  // We're done if we didn't find an intersecting range.

  if (rangeCount < 1 || *e1s2 > 0 || *e2s1 < 0) {
    *aSelStatus = BlockSelectionStatus::eBlockOutside;
    *aSelOffset = *aSelLength = UINT32_MAX;
    return NS_OK;
  }

  // Now that we have an intersecting range, find out more info:
  const Maybe<int32_t> e1s1 = nsContentUtils::ComparePoints(
      eStart->mTextNode, eStartOffset, startContainer, startOffset);
  if (NS_WARN_IF(!e1s1)) {
    return NS_ERROR_FAILURE;
  }

  const Maybe<int32_t> e2s2 = nsContentUtils::ComparePoints(
      eEnd->mTextNode, eEndOffset, endContainer, endOffset);
  if (NS_WARN_IF(!e2s2)) {
    return NS_ERROR_FAILURE;
  }

  if (rangeCount > 1) {
    // There are multiple selection ranges, we only deal
    // with the first one that intersects the current,
    // text block, so mark this a as a partial.
    *aSelStatus = BlockSelectionStatus::eBlockPartial;
  } else if (*e1s1 > 0 && *e2s2 < 0) {
    // The range extends beyond the start and
    // end of the current text block.
    *aSelStatus = BlockSelectionStatus::eBlockInside;
  } else if (*e1s1 <= 0 && *e2s2 >= 0) {
    // The current text block contains the entire
    // range.
    *aSelStatus = BlockSelectionStatus::eBlockContains;
  } else {
    // The range partially intersects the block.
    *aSelStatus = BlockSelectionStatus::eBlockPartial;
  }

  // Now create a range based on the intersection of the
  // text block and range:

  nsCOMPtr<nsINode> p1, p2;
  uint32_t o1, o2;

  // The start of the range will be the rightmost
  // start node.

  if (*e1s1 >= 0) {
    p1 = eStart->mTextNode;
    o1 = eStartOffset;
  } else {
    p1 = startContainer;
    o1 = startOffset;
  }

  // The end of the range will be the leftmost
  // end node.

  if (*e2s2 <= 0) {
    p2 = eEnd->mTextNode;
    o2 = eEndOffset;
  } else {
    p2 = endContainer;
    o2 = endOffset;
  }

  range = nsRange::Create(p1, o1, p2, o2, IgnoreErrors());
  if (NS_WARN_IF(!range)) {
    return NS_ERROR_FAILURE;
  }

  // Now iterate over this range to figure out the selection's
  // block offset and length.

  RefPtr<FilteredContentIterator> filteredIter;
  nsresult rv =
      CreateFilteredContentIterator(range, getter_AddRefs(filteredIter));
  NS_ENSURE_SUCCESS(rv, rv);

  // Find the first text node in the range.
  nsCOMPtr<nsIContent> content;
  filteredIter->First();
  if (!p1->IsText()) {
    bool found = false;
    for (; !filteredIter->IsDone(); filteredIter->Next()) {
      nsINode* node = filteredIter->GetCurrentNode();
      if (node->IsText()) {
        p1 = node->AsText();
        o1 = 0;
        found = true;
        break;
      }
    }
    NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
  }

  // Find the last text node in the range.
  filteredIter->Last();
  if (!p2->IsText()) {
    bool found = false;
    for (; !filteredIter->IsDone(); filteredIter->Prev()) {
      nsINode* node = filteredIter->GetCurrentNode();
      if (node->IsText()) {
        p2 = node->AsText();
        o2 = p2->AsText()->Length();
        found = true;

        break;
      }
    }
    NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
  }

  bool found = false;
  *aSelLength = 0;

  for (size_t i = 0; i < tableCount; i++) {
    const UniquePtr<OffsetEntry>& entry = mOffsetTable[i];
    LockOffsetEntryArrayLengthInDebugBuild(observer, mOffsetTable);
    if (!found) {
      if (entry->mTextNode == p1.get() &&
          entry->OffsetInTextNodeIsInRangeOrEndOffset(o1)) {
        *aSelOffset =
            entry->mOffsetInTextInBlock + (o1 - entry->mOffsetInTextNode);
        if (p1 == p2 && entry->OffsetInTextNodeIsInRangeOrEndOffset(o2)) {
          // The start and end of the range are in the same offset
          // entry. Calculate the length of the range then we're done.
          *aSelLength = o2 - o1;
          break;
        }
        // Add the length of the sub string in this offset entry
        // that follows the start of the range.
        *aSelLength = entry->EndOffsetInTextNode() - o1;
        found = true;
      }
    } else {  // Found.
      if (entry->mTextNode == p2.get() &&
          entry->OffsetInTextNodeIsInRangeOrEndOffset(o2)) {
        // We found the end of the range. Calculate the length of the
        // sub string that is before the end of the range, then we're done.
        *aSelLength += o2 - entry->mOffsetInTextNode;
        break;
      }
      // The entire entry must be in the range.
      *aSelLength += entry->mLength;
    }
  }

  return NS_OK;
}

// static
nsresult TextServicesDocument::GetRangeEndPoints(
    const AbstractRange* aAbstractRange, nsINode** aStartContainer,
    uint32_t* aStartOffset, nsINode** aEndContainer, uint32_t* aEndOffset) {
  if (NS_WARN_IF(!aAbstractRange) || NS_WARN_IF(!aStartContainer) ||
      NS_WARN_IF(!aEndContainer) || NS_WARN_IF(!aEndOffset)) {
    return NS_ERROR_INVALID_ARG;
  }

  nsCOMPtr<nsINode> startContainer = aAbstractRange->GetStartContainer();
  if (NS_WARN_IF(!startContainer)) {
    return NS_ERROR_FAILURE;
  }
  nsCOMPtr<nsINode> endContainer = aAbstractRange->GetEndContainer();
  if (NS_WARN_IF(!endContainer)) {
    return NS_ERROR_FAILURE;
  }

  startContainer.forget(aStartContainer);
  endContainer.forget(aEndContainer);
  *aStartOffset = aAbstractRange->StartOffset();
  *aEndOffset = aAbstractRange->EndOffset();
  return NS_OK;
}

// static
nsresult TextServicesDocument::FirstTextNode(
    FilteredContentIterator* aFilteredIter, IteratorStatus* aIteratorStatus) {
  if (aIteratorStatus) {
    *aIteratorStatus = IteratorStatus::eDone;
  }

  for (aFilteredIter->First(); !aFilteredIter->IsDone();
       aFilteredIter->Next()) {
    if (aFilteredIter->GetCurrentNode()->NodeType() == nsINode::TEXT_NODE) {
      if (aIteratorStatus) {
        *aIteratorStatus = IteratorStatus::eValid;
      }
      break;
    }
  }

  return NS_OK;
}

// static
nsresult TextServicesDocument::LastTextNode(
    FilteredContentIterator* aFilteredIter, IteratorStatus* aIteratorStatus) {
  if (aIteratorStatus) {
    *aIteratorStatus = IteratorStatus::eDone;
  }

  for (aFilteredIter->Last(); !aFilteredIter->IsDone(); aFilteredIter->Prev()) {
    if (aFilteredIter->GetCurrentNode()->NodeType() == nsINode::TEXT_NODE) {
      if (aIteratorStatus) {
        *aIteratorStatus = IteratorStatus::eValid;
      }
      break;
    }
  }

  return NS_OK;
}

// static
nsresult TextServicesDocument::FirstTextNodeInCurrentBlock(
    FilteredContentIterator* aFilteredIter) {
  NS_ENSURE_TRUE(aFilteredIter, NS_ERROR_NULL_POINTER);

  ClearDidSkip(aFilteredIter);

  // Walk backwards over adjacent text nodes until
  // we hit a block boundary:
  RefPtr<Text> lastTextNode;
  while (!aFilteredIter->IsDone()) {
    nsCOMPtr<nsIContent> content =
        aFilteredIter->GetCurrentNode()->IsContent()
            ? aFilteredIter->GetCurrentNode()->AsContent()
            : nullptr;
    if (lastTextNode && content &&
        (HTMLEditUtils::IsBlockElement(*content) ||
         content->IsHTMLElement(nsGkAtoms::br))) {
      break;
    }
    if (content && content->IsText()) {
      if (lastTextNode && !TextServicesDocument::HasSameBlockNodeParent(
                              *content->AsText(), *lastTextNode)) {
        // We're done, the current text node is in a
        // different block.
        break;
      }
      lastTextNode = content->AsText();
    }

    aFilteredIter->Prev();

    if (DidSkip(aFilteredIter)) {
      break;
    }
  }

  if (lastTextNode) {
    aFilteredIter->PositionAt(lastTextNode);
  }

  // XXX: What should we return if last is null?

  return NS_OK;
}

// static
nsresult TextServicesDocument::FirstTextNodeInPrevBlock(
    FilteredContentIterator* aFilteredIter) {
  NS_ENSURE_TRUE(aFilteredIter, NS_ERROR_NULL_POINTER);

  // XXX: What if mFilteredIter is not currently on a text node?

  // Make sure mFilteredIter is pointing to the first text node in the
  // current block:

  nsresult rv = FirstTextNodeInCurrentBlock(aFilteredIter);

  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Point mFilteredIter to the first node before the first text node:

  aFilteredIter->Prev();

  if (aFilteredIter->IsDone()) {
    return NS_ERROR_FAILURE;
  }

  // Now find the first text node of the next block:

  return FirstTextNodeInCurrentBlock(aFilteredIter);
}

// static
nsresult TextServicesDocument::FirstTextNodeInNextBlock(
    FilteredContentIterator* aFilteredIter) {
  bool crossedBlockBoundary = false;

  NS_ENSURE_TRUE(aFilteredIter, NS_ERROR_NULL_POINTER);

  ClearDidSkip(aFilteredIter);

  RefPtr<Text> previousTextNode;
  while (!aFilteredIter->IsDone()) {
    if (nsCOMPtr<nsIContent> content =
            aFilteredIter->GetCurrentNode()->IsContent()
                ? aFilteredIter->GetCurrentNode()->AsContent()
                : nullptr) {
      if (content->IsText()) {
        if (crossedBlockBoundary ||
            (previousTextNode && !TextServicesDocument::HasSameBlockNodeParent(
                                     *previousTextNode, *content->AsText()))) {
          break;
        }
        previousTextNode = content->AsText();
      } else if (!crossedBlockBoundary &&
                 (HTMLEditUtils::IsBlockElement(*content) ||
                  content->IsHTMLElement(nsGkAtoms::br))) {
        crossedBlockBoundary = true;
      }
    }

    aFilteredIter->Next();

    if (!crossedBlockBoundary && DidSkip(aFilteredIter)) {
      crossedBlockBoundary = true;
    }
  }

  return NS_OK;
}

nsresult TextServicesDocument::GetFirstTextNodeInPrevBlock(
    nsIContent** aContent) {
  NS_ENSURE_TRUE(aContent, NS_ERROR_NULL_POINTER);

  *aContent = 0;

  // Save the iterator's current content node so we can restore
  // it when we are done:

  nsINode* node = mFilteredIter->GetCurrentNode();

  nsresult rv = FirstTextNodeInPrevBlock(mFilteredIter);

  if (NS_FAILED(rv)) {
    // Try to restore the iterator before returning.
    mFilteredIter->PositionAt(node);
    return rv;
  }

  if (!mFilteredIter->IsDone()) {
    nsCOMPtr<nsIContent> current =
        mFilteredIter->GetCurrentNode()->IsContent()
            ? mFilteredIter->GetCurrentNode()->AsContent()
            : nullptr;
    current.forget(aContent);
  }

  // Restore the iterator:

  return mFilteredIter->PositionAt(node);
}

nsresult TextServicesDocument::GetFirstTextNodeInNextBlock(
    nsIContent** aContent) {
  NS_ENSURE_TRUE(aContent, NS_ERROR_NULL_POINTER);

  *aContent = 0;

  // Save the iterator's current content node so we can restore
  // it when we are done:

  nsINode* node = mFilteredIter->GetCurrentNode();

  nsresult rv = FirstTextNodeInNextBlock(mFilteredIter);

  if (NS_FAILED(rv)) {
    // Try to restore the iterator before returning.
    mFilteredIter->PositionAt(node);
    return rv;
  }

  if (!mFilteredIter->IsDone()) {
    nsCOMPtr<nsIContent> current =
        mFilteredIter->GetCurrentNode()->IsContent()
            ? mFilteredIter->GetCurrentNode()->AsContent()
            : nullptr;
    current.forget(aContent);
  }

  // Restore the iterator:
  return mFilteredIter->PositionAt(node);
}

Result<TextServicesDocument::IteratorStatus, nsresult>
TextServicesDocument::OffsetEntryArray::Init(
    FilteredContentIterator& aFilteredIter, IteratorStatus aIteratorStatus,
    nsRange* aIterRange, nsAString* aAllTextInBlock /* = nullptr */) {
  Clear();

  if (aAllTextInBlock) {
    aAllTextInBlock->Truncate();
  }

  if (aIteratorStatus == IteratorStatus::eDone) {
    return IteratorStatus::eDone;
  }

  // If we have an aIterRange, retrieve the endpoints so
  // they can be used in the while loop below to trim entries
  // for text nodes that are partially selected by aIterRange.

  nsCOMPtr<nsINode> rngStartNode, rngEndNode;
  uint32_t rngStartOffset = 0, rngEndOffset = 0;
  if (aIterRange) {
    nsresult rv = TextServicesDocument::GetRangeEndPoints(
        aIterRange, getter_AddRefs(rngStartNode), &rngStartOffset,
        getter_AddRefs(rngEndNode), &rngEndOffset);
    if (NS_FAILED(rv)) {
      NS_WARNING("TextServicesDocument::GetRangeEndPoints() failed");
      return Err(rv);
    }
  }

  // The text service could have added text nodes to the beginning
  // of the current block and called this method again. Make sure
  // we really are at the beginning of the current block:

  nsresult rv =
      TextServicesDocument::FirstTextNodeInCurrentBlock(&aFilteredIter);
  if (NS_FAILED(rv)) {
    NS_WARNING("TextServicesDocument::FirstTextNodeInCurrentBlock() failed");
    return Err(rv);
  }

  TextServicesDocument::ClearDidSkip(&aFilteredIter);

  uint32_t offset = 0;
  RefPtr<Text> firstTextNode, previousTextNode;
  while (!aFilteredIter.IsDone()) {
    if (nsCOMPtr<nsIContent> content =
            aFilteredIter.GetCurrentNode()->IsContent()
                ? aFilteredIter.GetCurrentNode()->AsContent()
                : nullptr) {
      if (HTMLEditUtils::IsBlockElement(*content) ||
          content->IsHTMLElement(nsGkAtoms::br)) {
        break;
      }
      if (content->IsText()) {
        if (previousTextNode && !TextServicesDocument::HasSameBlockNodeParent(
                                    *previousTextNode, *content->AsText())) {
          break;
        }

        nsString str;
        content->AsText()->GetNodeValue(str);

        // Add an entry for this text node into the offset table:

        UniquePtr<OffsetEntry>& entry = *AppendElement(
            MakeUnique<OffsetEntry>(*content->AsText(), offset, str.Length()));
        LockOffsetEntryArrayLengthInDebugBuild(observer, *this);

        // If one or both of the endpoints of the iteration range
        // are in the text node for this entry, make sure the entry
        // only accounts for the portion of the text node that is
        // in the range.

        uint32_t startOffset = 0;
        uint32_t endOffset = str.Length();
        bool adjustStr = false;

        if (entry->mTextNode == rngStartNode) {
          entry->mOffsetInTextNode = startOffset = rngStartOffset;
          adjustStr = true;
        }

        if (entry->mTextNode == rngEndNode) {
          endOffset = rngEndOffset;
          adjustStr = true;
        }

        if (adjustStr) {
          entry->mLength = endOffset - startOffset;
          str = Substring(str, startOffset, entry->mLength);
        }

        offset += str.Length();

        if (aAllTextInBlock) {
          // Append the text node's string to the output string:
          if (!firstTextNode) {
            *aAllTextInBlock = str;
          } else {
            *aAllTextInBlock += str;
          }
        }

        previousTextNode = content->AsText();

        if (!firstTextNode) {
          firstTextNode = content->AsText();
        }
      }
    }

    aFilteredIter.Next();

    if (TextServicesDocument::DidSkip(&aFilteredIter)) {
      break;
    }
  }

  if (firstTextNode) {
    // Always leave the iterator pointing at the first
    // text node of the current block!
    aFilteredIter.PositionAt(firstTextNode);
    return aIteratorStatus;
  }

  // If we never ran across a text node, the iterator
  // might have been pointing to something invalid to
  // begin with.
  return IteratorStatus::eDone;
}

void TextServicesDocument::OffsetEntryArray::RemoveInvalidElements() {
  for (size_t i = 0; i < Length();) {
    if (ElementAt(i)->mIsValid) {
      i++;
      continue;
    }

    RemoveElementAt(i);
    if (!mSelection.IsSet()) {
      continue;
    }
    if (mSelection.StartIndex() == i) {
      NS_ASSERTION(false, "What should we do in this case?");
      mSelection.Reset();
    } else if (mSelection.StartIndex() > i) {
      MOZ_DIAGNOSTIC_ASSERT(mSelection.StartIndex() - 1 < Length());
      MOZ_DIAGNOSTIC_ASSERT(mSelection.EndIndex() - 1 < Length());
      mSelection.SetIndexes(mSelection.StartIndex() - 1,
                            mSelection.EndIndex() - 1);
    } else if (mSelection.EndIndex() >= i) {
      MOZ_DIAGNOSTIC_ASSERT(mSelection.EndIndex() - 1 < Length());
      mSelection.SetIndexes(mSelection.StartIndex(), mSelection.EndIndex() - 1);
    }
  }
}

nsresult TextServicesDocument::OffsetEntryArray::SplitElementAt(
    size_t aIndex, uint32_t aOffsetInTextNode) {
  OffsetEntry* leftEntry = ElementAt(aIndex).get();
  MOZ_ASSERT(leftEntry);
  NS_ASSERTION((aOffsetInTextNode > 0), "aOffsetInTextNode == 0");
  NS_ASSERTION((aOffsetInTextNode < leftEntry->mLength),
               "aOffsetInTextNode >= mLength");

  if (aOffsetInTextNode < 1 || aOffsetInTextNode >= leftEntry->mLength) {
    return NS_ERROR_FAILURE;
  }

  const uint32_t oldLength = leftEntry->mLength - aOffsetInTextNode;

  // XXX(Bug 1631371) Check if this should use a fallible operation as it
  // pretended earlier.
  UniquePtr<OffsetEntry>& rightEntry = *InsertElementAt(
      aIndex + 1,
      MakeUnique<OffsetEntry>(leftEntry->mTextNode,
                              leftEntry->mOffsetInTextInBlock + oldLength,
                              aOffsetInTextNode));
  LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
  leftEntry->mLength = oldLength;
  rightEntry->mOffsetInTextNode = leftEntry->mOffsetInTextNode + oldLength;

  return NS_OK;
}

Maybe<size_t> TextServicesDocument::OffsetEntryArray::FirstIndexOf(
    const Text& aTextNode) const {
  for (size_t i = 0; i < Length(); i++) {
    if (ElementAt(i)->mTextNode == &aTextNode) {
      return Some(i);
    }
  }
  return Nothing();
}

// Spellchecker code has this. See bug 211343
#define IS_NBSP_CHAR(c) (((unsigned char)0xa0) == (c))

Result<EditorDOMRangeInTexts, nsresult>
TextServicesDocument::OffsetEntryArray::FindWordRange(
    nsAString& aAllTextInBlock, const EditorRawDOMPoint& aStartPointToScan) {
  MOZ_ASSERT(aStartPointToScan.IsInTextNode());
  // It's assumed that aNode is a text node. The first thing
  // we do is get its index in the offset table so we can
  // calculate the dom point's string offset.
  Maybe<size_t> maybeEntryIndex =
      FirstIndexOf(*aStartPointToScan.ContainerAs<Text>());
  if (NS_WARN_IF(maybeEntryIndex.isNothing())) {
    NS_WARNING(
        "TextServicesDocument::OffsetEntryArray::FirstIndexOf() didn't find "
        "entries");
    return Err(NS_ERROR_FAILURE);
  }

  // Next we map offset into a string offset.

  const UniquePtr<OffsetEntry>& entry = ElementAt(*maybeEntryIndex);
  LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
  uint32_t strOffset = entry->mOffsetInTextInBlock +
                       aStartPointToScan.Offset() - entry->mOffsetInTextNode;

  // Now we use the word breaker to find the beginning and end
  // of the word from our calculated string offset.

  const char16_t* str = aAllTextInBlock.BeginReading();
  uint32_t strLen = aAllTextInBlock.Length();
  MOZ_ASSERT(strOffset <= strLen,
             "The string offset shouldn't be greater than the string length!");

  intl::WordRange res = intl::WordBreaker::FindWord(str, strLen, strOffset);

  // Strip out the NBSPs at the ends
  while (res.mBegin <= res.mEnd && IS_NBSP_CHAR(str[res.mBegin])) {
    res.mBegin++;
  }
  if (str[res.mEnd] == static_cast<char16_t>(0x20)) {
    uint32_t realEndWord = res.mEnd - 1;
    while (realEndWord > res.mBegin && IS_NBSP_CHAR(str[realEndWord])) {
      realEndWord--;
    }
    if (realEndWord < res.mEnd - 1) {
      res.mEnd = realEndWord + 1;
    }
  }

  // Now that we have the string offsets for the beginning
  // and end of the word, run through the offset table and
  // convert them back into dom points.

  EditorDOMPointInText wordStart, wordEnd;
  size_t lastIndex = Length() - 1;
  for (size_t i = 0; i <= lastIndex; i++) {
    // Check to see if res.mBegin is within the range covered
    // by this entry. Note that if res.mBegin is after the last
    // character covered by this entry, we will use the next
    // entry if there is one.
    const UniquePtr<OffsetEntry>& entry = ElementAt(i);
    LockOffsetEntryArrayLengthInDebugBuild(observer, *this);
    if (entry->mOffsetInTextInBlock <= res.mBegin &&
        (res.mBegin < entry->EndOffsetInTextInBlock() ||
         (res.mBegin == entry->EndOffsetInTextInBlock() && i == lastIndex))) {
      wordStart.Set(entry->mTextNode, entry->mOffsetInTextNode + res.mBegin -
                                          entry->mOffsetInTextInBlock);
    }

    // Check to see if res.mEnd is within the range covered
    // by this entry.
    if (entry->mOffsetInTextInBlock <= res.mEnd &&
        res.mEnd <= entry->EndOffsetInTextInBlock()) {
      if (res.mBegin == res.mEnd &&
          res.mEnd == entry->EndOffsetInTextInBlock() && i != lastIndex) {
        // Wait for the next round so that we use the same entry
        // we did for aWordStartNode.
        continue;
      }

      wordEnd.Set(entry->mTextNode, entry->mOffsetInTextNode + res.mEnd -
                                        entry->mOffsetInTextInBlock);
      break;
    }
  }

  return EditorDOMRangeInTexts(wordStart, wordEnd);
}

/**
 * nsIEditActionListener implementation:
 *   Don't implement the behavior directly here.  The methods won't be called
 *   if the instance is created for inline spell checker created for editor.
 *   If you need to listen a new edit action, you need to add similar
 *   non-virtual method and you need to call it from EditorBase directly.
 */

NS_IMETHODIMP
TextServicesDocument::DidDeleteNode(nsINode* aChild, nsresult aResult) {
  if (NS_WARN_IF(NS_FAILED(aResult)) || NS_WARN_IF(!aChild) ||
      !aChild->IsContent()) {
    return NS_OK;
  }
  DidDeleteContent(*aChild->AsContent());
  return NS_OK;
}

NS_IMETHODIMP TextServicesDocument::DidJoinContents(
    const EditorRawDOMPoint& aJoinedPoint, const nsINode* aRemovedNode,
    bool aLeftNodeWasRemoved) {
  if (MOZ_UNLIKELY(NS_WARN_IF(!aJoinedPoint.IsSetAndValid()) ||
                   NS_WARN_IF(!aRemovedNode->IsContent()))) {
    return NS_OK;
  }
  DidJoinContents(aJoinedPoint, *aRemovedNode->AsContent(),
                  aLeftNodeWasRemoved
                      ? JoinNodesDirection::LeftNodeIntoRightNode
                      : JoinNodesDirection::RightNodeIntoLeftNode);
  return NS_OK;
}

NS_IMETHODIMP
TextServicesDocument::DidInsertText(CharacterData* aTextNode, int32_t aOffset,
                                    const nsAString& aString,
                                    nsresult aResult) {
  return NS_OK;
}

NS_IMETHODIMP
TextServicesDocument::WillDeleteText(CharacterData* aTextNode, int32_t aOffset,
                                     int32_t aLength) {
  return NS_OK;
}

NS_IMETHODIMP
TextServicesDocument::WillDeleteRanges(
    const nsTArray<RefPtr<nsRange>>& aRangesToDelete) {
  return NS_OK;
}

#undef LockOffsetEntryArrayLengthInDebugBuild

}  // namespace mozilla