1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
|
/* -*- 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 "EditorBase.h"
#include <stdio.h> // for nullptr, stdout
#include <string.h> // for strcmp
#include "AutoRangeArray.h" // for AutoRangeArray
#include "ChangeAttributeTransaction.h"
#include "CompositionTransaction.h"
#include "DeleteContentTransactionBase.h"
#include "DeleteMultipleRangesTransaction.h"
#include "DeleteNodeTransaction.h"
#include "DeleteRangeTransaction.h"
#include "DeleteTextTransaction.h"
#include "EditAction.h" // for EditSubAction
#include "EditorDOMPoint.h" // for EditorDOMPoint
#include "EditorUtils.h" // for various helper classes.
#include "EditTransactionBase.h" // for EditTransactionBase
#include "EditorEventListener.h" // for EditorEventListener
#include "HTMLEditor.h" // for HTMLEditor
#include "HTMLEditorInlines.h"
#include "HTMLEditUtils.h" // for HTMLEditUtils
#include "InsertNodeTransaction.h" // for InsertNodeTransaction
#include "InsertTextTransaction.h" // for InsertTextTransaction
#include "JoinNodesTransaction.h" // for JoinNodesTransaction
#include "PlaceholderTransaction.h" // for PlaceholderTransaction
#include "SplitNodeTransaction.h" // for SplitNodeTransaction
#include "TextEditor.h" // for TextEditor
#include "ErrorList.h"
#include "gfxFontUtils.h" // for gfxFontUtils
#include "mozilla/Assertions.h"
#include "mozilla/intl/BidiEmbeddingLevel.h"
#include "mozilla/BasePrincipal.h" // for BasePrincipal
#include "mozilla/CheckedInt.h" // for CheckedInt
#include "mozilla/ComposerCommandsUpdater.h" // for ComposerCommandsUpdater
#include "mozilla/ContentEvents.h" // for InternalClipboardEvent
#include "mozilla/DebugOnly.h" // for DebugOnly
#include "mozilla/EditorSpellCheck.h" // for EditorSpellCheck
#include "mozilla/Encoding.h" // for Encoding (used in Document::GetDocumentCharacterSet)
#include "mozilla/EventDispatcher.h" // for EventChainPreVisitor, etc.
#include "mozilla/FlushType.h" // for FlushType::Frames
#include "mozilla/IMEContentObserver.h" // for IMEContentObserver
#include "mozilla/IMEStateManager.h" // for IMEStateManager
#include "mozilla/InputEventOptions.h" // for InputEventOptions
#include "mozilla/IntegerRange.h" // for IntegerRange
#include "mozilla/InternalMutationEvent.h" // for NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED
#include "mozilla/mozalloc.h" // for operator new, etc.
#include "mozilla/mozInlineSpellChecker.h" // for mozInlineSpellChecker
#include "mozilla/mozSpellChecker.h" // for mozSpellChecker
#include "mozilla/Preferences.h" // for Preferences
#include "mozilla/PresShell.h" // for PresShell
#include "mozilla/RangeBoundary.h" // for RawRangeBoundary, RangeBoundary
#include "mozilla/Services.h" // for GetObserverService
#include "mozilla/StaticPrefs_bidi.h" // for StaticPrefs::bidi_*
#include "mozilla/StaticPrefs_dom.h" // for StaticPrefs::dom_*
#include "mozilla/StaticPrefs_editor.h" // for StaticPrefs::editor_*
#include "mozilla/StaticPrefs_layout.h" // for StaticPrefs::layout_*
#include "mozilla/TextComposition.h" // for TextComposition
#include "mozilla/TextControlElement.h" // for TextControlElement
#include "mozilla/TextInputListener.h" // for TextInputListener
#include "mozilla/TextServicesDocument.h" // for TextServicesDocument
#include "mozilla/TextEvents.h"
#include "mozilla/TransactionManager.h" // for TransactionManager
#include "mozilla/dom/AbstractRange.h" // for AbstractRange
#include "mozilla/dom/Attr.h" // for Attr
#include "mozilla/dom/BrowsingContext.h" // for BrowsingContext
#include "mozilla/dom/CharacterData.h" // for CharacterData
#include "mozilla/dom/DataTransfer.h" // for DataTransfer
#include "mozilla/dom/Document.h" // for Document
#include "mozilla/dom/DocumentInlines.h" // for GetObservingPresShell
#include "mozilla/dom/DragEvent.h" // for DragEvent
#include "mozilla/dom/Element.h" // for Element, nsINode::AsElement
#include "mozilla/dom/EventTarget.h" // for EventTarget
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/HTMLBRElement.h"
#include "mozilla/dom/Selection.h" // for Selection, etc.
#include "mozilla/dom/StaticRange.h" // for StaticRange
#include "mozilla/dom/Text.h"
#include "mozilla/dom/Event.h"
#include "nsAString.h" // for nsAString::Length, etc.
#include "nsCCUncollectableMarker.h" // for nsCCUncollectableMarker
#include "nsCaret.h" // for nsCaret
#include "nsCaseTreatment.h"
#include "nsCharTraits.h" // for NS_IS_HIGH_SURROGATE, etc.
#include "nsContentUtils.h" // for nsContentUtils
#include "nsCopySupport.h" // for nsCopySupport
#include "nsDOMString.h" // for DOMStringIsNull
#include "nsDebug.h" // for NS_WARNING, etc.
#include "nsError.h" // for NS_OK, etc.
#include "nsFocusManager.h" // for nsFocusManager
#include "nsFrameSelection.h" // for nsFrameSelection
#include "nsGenericHTMLElement.h" // for nsGenericHTMLElement
#include "nsGkAtoms.h" // for nsGkAtoms, nsGkAtoms::dir
#include "nsIClipboard.h" // for nsIClipboard
#include "nsIContent.h" // for nsIContent
#include "nsIContentInlines.h" // for nsINode::IsInDesignMode()
#include "nsIDocumentEncoder.h" // for nsIDocumentEncoder
#include "nsIDocumentStateListener.h" // for nsIDocumentStateListener
#include "nsIDocShell.h" // for nsIDocShell
#include "nsIEditActionListener.h" // for nsIEditActionListener
#include "nsIFrame.h" // for nsIFrame
#include "nsIInlineSpellChecker.h" // for nsIInlineSpellChecker, etc.
#include "nsNameSpaceManager.h" // for kNameSpaceID_None, etc.
#include "nsINode.h" // for nsINode, etc.
#include "nsISelectionController.h" // for nsISelectionController, etc.
#include "nsISelectionDisplay.h" // for nsISelectionDisplay, etc.
#include "nsISupports.h" // for nsISupports
#include "nsISupportsUtils.h" // for NS_ADDREF, NS_IF_ADDREF
#include "nsITransferable.h" // for nsITransferable
#include "nsIWeakReference.h" // for nsISupportsWeakReference
#include "nsIWidget.h" // for nsIWidget, IMEState, etc.
#include "nsPIDOMWindow.h" // for nsPIDOMWindow
#include "nsPresContext.h" // for nsPresContext
#include "nsRange.h" // for nsRange
#include "nsReadableUtils.h" // for EmptyString, ToNewCString
#include "nsString.h" // for nsAutoString, nsString, etc.
#include "nsStringFwd.h" // for nsString
#include "nsStyleConsts.h" // for StyleDirection::Rtl, etc.
#include "nsStyleStruct.h" // for nsStyleDisplay, nsStyleText, etc.
#include "nsStyleStructFwd.h" // for nsIFrame::StyleUIReset, etc.
#include "nsTextNode.h" // for nsTextNode
#include "nsThreadUtils.h" // for nsRunnable
#include "prtime.h" // for PR_Now
class nsIOutputStream;
class nsITransferable;
namespace mozilla {
using namespace dom;
using namespace widget;
using EmptyCheckOption = HTMLEditUtils::EmptyCheckOption;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
using LeafNodeTypes = HTMLEditUtils::LeafNodeTypes;
using WalkTreeOption = HTMLEditUtils::WalkTreeOption;
/*****************************************************************************
* mozilla::EditorBase
*****************************************************************************/
template EditorDOMPoint EditorBase::GetFirstIMESelectionStartPoint() const;
template EditorRawDOMPoint EditorBase::GetFirstIMESelectionStartPoint() const;
template EditorDOMPoint EditorBase::GetLastIMESelectionEndPoint() const;
template EditorRawDOMPoint EditorBase::GetLastIMESelectionEndPoint() const;
template Result<CreateContentResult, nsresult>
EditorBase::InsertNodeWithTransaction(nsIContent& aContentToInsert,
const EditorDOMPoint& aPointToInsert);
template Result<CreateElementResult, nsresult>
EditorBase::InsertNodeWithTransaction(Element& aContentToInsert,
const EditorDOMPoint& aPointToInsert);
template Result<CreateTextResult, nsresult>
EditorBase::InsertNodeWithTransaction(Text& aContentToInsert,
const EditorDOMPoint& aPointToInsert);
template EditorDOMPoint EditorBase::GetFirstSelectionStartPoint() const;
template EditorRawDOMPoint EditorBase::GetFirstSelectionStartPoint() const;
template EditorDOMPoint EditorBase::GetFirstSelectionEndPoint() const;
template EditorRawDOMPoint EditorBase::GetFirstSelectionEndPoint() const;
template EditorBase::AutoCaretBidiLevelManager::AutoCaretBidiLevelManager(
const EditorBase& aEditorBase, nsIEditor::EDirection aDirectionAndAmount,
const EditorDOMPoint& aPointAtCaret);
template EditorBase::AutoCaretBidiLevelManager::AutoCaretBidiLevelManager(
const EditorBase& aEditorBase, nsIEditor::EDirection aDirectionAndAmount,
const EditorRawDOMPoint& aPointAtCaret);
EditorBase::EditorBase(EditorType aEditorType)
: mEditActionData(nullptr),
mPlaceholderName(nullptr),
mModCount(0),
mFlags(0),
mUpdateCount(0),
mPlaceholderBatch(0),
mNewlineHandling(StaticPrefs::editor_singleLine_pasteNewlines()),
mCaretStyle(StaticPrefs::layout_selection_caret_style()),
mDocDirtyState(-1),
mSpellcheckCheckboxState(eTriUnset),
mInitSucceeded(false),
mAllowsTransactionsToChangeSelection(true),
mDidPreDestroy(false),
mDidPostCreate(false),
mDispatchInputEvent(true),
mIsInEditSubAction(false),
mHidingCaret(false),
mSpellCheckerDictionaryUpdated(true),
mIsHTMLEditorClass(aEditorType == EditorType::HTML) {
#ifdef XP_WIN
if (!mCaretStyle && !IsTextEditor()) {
// Wordpad-like caret behavior.
mCaretStyle = 1;
}
#endif // #ifdef XP_WIN
if (mNewlineHandling < nsIEditor::eNewlinesPasteIntact ||
mNewlineHandling > nsIEditor::eNewlinesStripSurroundingWhitespace) {
mNewlineHandling = nsIEditor::eNewlinesPasteToFirst;
}
}
EditorBase::~EditorBase() {
MOZ_ASSERT(!IsInitialized() || mDidPreDestroy,
"Why PreDestroy hasn't been called?");
if (mComposition) {
mComposition->OnEditorDestroyed();
mComposition = nullptr;
}
// If this editor is still hiding the caret, we need to restore it.
HideCaret(false);
mTransactionManager = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(EditorBase)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(EditorBase)
// Remove event listeners first since EditorEventListener may need
// mDocument, mEventTarget, etc.
if (tmp->mEventListener) {
tmp->mEventListener->Disconnect();
tmp->mEventListener = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mRootElement)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionController)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocument)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mIMEContentObserver)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mInlineSpellChecker)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTextServicesDocument)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTextInputListener)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTransactionManager)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mActionListeners)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocStateListeners)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mEventTarget)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPlaceholderTransaction)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCachedDocumentEncoder)
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(EditorBase)
Document* currentDoc =
tmp->mRootElement ? tmp->mRootElement->GetUncomposedDoc() : nullptr;
if (currentDoc && nsCCUncollectableMarker::InGeneration(
cb, currentDoc->GetMarkedCCGeneration())) {
return NS_SUCCESS_INTERRUPTED_TRAVERSE;
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRootElement)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionController)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIMEContentObserver)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInlineSpellChecker)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTextServicesDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTextInputListener)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTransactionManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActionListeners)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocStateListeners)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEventTarget)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEventListener)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPlaceholderTransaction)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCachedDocumentEncoder)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(EditorBase)
NS_INTERFACE_MAP_ENTRY(nsISelectionListener)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsIEditor)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEditor)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(EditorBase)
NS_IMPL_CYCLE_COLLECTING_RELEASE(EditorBase)
nsresult EditorBase::InitInternal(Document& aDocument, Element* aRootElement,
nsISelectionController& aSelectionController,
uint32_t aFlags) {
MOZ_ASSERT_IF(
!mEditActionData ||
!mEditActionData->HasEditorDestroyedDuringHandlingEditAction(),
GetTopLevelEditSubAction() == EditSubAction::eNone);
// First only set flags, but other stuff shouldn't be initialized now.
// Note that SetFlags() will be called by PostCreate().
mFlags = aFlags;
mDocument = &aDocument;
// nsISelectionController should be stored only when we're a `TextEditor`.
// Otherwise, in `HTMLEditor`, it's `PresShell`, and grabbing it causes
// a circular reference and memory leak.
// XXX Should we move `mSelectionController to `TextEditor`?
MOZ_ASSERT_IF(!IsTextEditor(), &aSelectionController == GetPresShell());
if (IsTextEditor()) {
MOZ_ASSERT(&aSelectionController != GetPresShell());
mSelectionController = &aSelectionController;
}
if (mEditActionData) {
// During edit action, selection is cached. But this selection is invalid
// now since selection controller is updated, so we have to update this
// cache.
Selection* selection = aSelectionController.GetSelection(
nsISelectionController::SELECTION_NORMAL);
NS_WARNING_ASSERTION(selection,
"SelectionController::GetSelection() failed");
if (selection) {
mEditActionData->UpdateSelectionCache(*selection);
}
}
// set up root element if we are passed one.
if (aRootElement) {
mRootElement = aRootElement;
}
// If this is an editor for <input> or <textarea>, the text node which
// has composition string is always recreated with same content. Therefore,
// we need to nodify mComposition of text node destruction and replacing
// composing string when this receives eCompositionChange event next time.
if (mComposition && mComposition->GetContainerTextNode() &&
!mComposition->GetContainerTextNode()->IsInComposedDoc()) {
mComposition->OnTextNodeRemoved();
}
// Show the caret.
DebugOnly<nsresult> rvIgnored = aSelectionController.SetCaretReadOnly(false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetCaretReadOnly(false) failed, but ignored");
// Show all the selection reflected to user.
rvIgnored =
aSelectionController.SetSelectionFlags(nsISelectionDisplay::DISPLAY_ALL);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetSelectionFlags("
"nsISelectionDisplay::DISPLAY_ALL) failed, but ignored");
// Make sure that the editor will be destroyed properly
mDidPreDestroy = false;
// Make sure that the editor will be created properly
mDidPostCreate = false;
MOZ_ASSERT(IsBeingInitialized());
AutoEditActionDataSetter editActionData(*this, EditAction::eInitializing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
SelectionRef().AddSelectionListener(this);
return NS_OK;
}
nsresult EditorBase::EnsureEmptyTextFirstChild() {
MOZ_ASSERT(IsTextEditor());
RefPtr<Element> root = GetRoot();
nsIContent* firstChild = root->GetFirstChild();
if (!firstChild || !firstChild->IsText()) {
RefPtr<nsTextNode> newTextNode = CreateTextNode(u""_ns);
if (!newTextNode) {
NS_WARNING("EditorBase::CreateTextNode() failed");
return NS_ERROR_UNEXPECTED;
}
IgnoredErrorResult ignoredError;
root->InsertChildBefore(newTextNode, root->GetFirstChild(), true,
ignoredError);
MOZ_ASSERT(!ignoredError.Failed());
}
return NS_OK;
}
nsresult EditorBase::PostCreateInternal() {
MOZ_ASSERT(IsEditActionDataAvailable());
// Synchronize some stuff for the flags. SetFlags() will initialize
// something by the flag difference. This is first time of that, so, all
// initializations must be run. For such reason, we need to invert mFlags
// value first.
mFlags = ~mFlags;
nsresult rv = SetFlags(~mFlags);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::SetFlags() failed");
return EditorBase::ToGenericNSResult(rv);
}
// These operations only need to happen on the first PostCreate call
if (!mDidPostCreate) {
mDidPostCreate = true;
// Set up listeners
CreateEventListeners();
nsresult rv = InstallEventListeners();
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::InstallEventListeners() failed");
return EditorBase::ToGenericNSResult(rv);
}
// nuke the modification count, so the doc appears unmodified
// do this before we notify listeners
DebugOnly<nsresult> rvIgnored = ResetModificationCount();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::ResetModificationCount() failed, but ignored");
// update the UI with our state
rvIgnored = NotifyDocumentListeners(eDocumentCreated);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::NotifyDocumentListeners(eDocumentCreated)"
" failed, but ignored");
rvIgnored = NotifyDocumentListeners(eDocumentStateChanged);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::NotifyDocumentListeners("
"eDocumentStateChanged) failed, but ignored");
}
// update nsTextStateManager and caret if we have focus
if (RefPtr<Element> focusedElement = GetFocusedElement()) {
DebugOnly<nsresult> rvIgnored = InitializeSelection(*focusedElement);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::InitializeSelection() failed, but ignored");
// If the text control gets reframed during focus, Focus() would not be
// called, so take a chance here to see if we need to spell check the text
// control.
nsresult rv = FlushPendingSpellCheck();
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::FlushPendingSpellCheck() caused destroying the editor");
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::FlushPendingSpellCheck() failed, but ignored");
IMEState newState;
rv = GetPreferredIMEState(&newState);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::GetPreferredIMEState() failed");
return NS_OK;
}
IMEStateManager::UpdateIMEState(newState, focusedElement, *this);
}
// FYI: This call might cause destroying this editor.
IMEStateManager::OnEditorInitialized(*this);
return NS_OK;
}
void EditorBase::SetTextInputListener(TextInputListener* aTextInputListener) {
MOZ_ASSERT(!mTextInputListener || !aTextInputListener ||
mTextInputListener == aTextInputListener);
mTextInputListener = aTextInputListener;
}
void EditorBase::SetIMEContentObserver(
IMEContentObserver* aIMEContentObserver) {
MOZ_ASSERT(!mIMEContentObserver || !aIMEContentObserver ||
mIMEContentObserver == aIMEContentObserver);
mIMEContentObserver = aIMEContentObserver;
}
void EditorBase::CreateEventListeners() {
// Don't create the handler twice
if (!mEventListener) {
mEventListener = new EditorEventListener();
}
}
nsresult EditorBase::InstallEventListeners() {
// FIXME InstallEventListeners() should not be called if we failed to set
// document or create an event listener. So, these checks should be
// MOZ_DIAGNOSTIC_ASSERT instead.
MOZ_ASSERT(GetDocument());
if (MOZ_UNLIKELY(!GetDocument()) || NS_WARN_IF(!mEventListener)) {
return NS_ERROR_NOT_INITIALIZED;
}
// Initialize the event target.
mEventTarget = GetExposedRoot();
if (NS_WARN_IF(!mEventTarget)) {
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv = mEventListener->Connect(this);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorEventListener::Connect() failed");
if (mComposition) {
// If mComposition has already been destroyed, we should forget it.
// This may happen if it ended while we don't listen to composition
// events.
if (mComposition->Destroyed()) {
// XXX We may need to fix existing composition transaction here.
// However, this may be called when it's not safe.
// Perhaps, we should stop handling composition with events.
mComposition = nullptr;
}
// Otherwise, Restart to handle composition with new editor contents.
else {
mComposition->StartHandlingComposition(this);
}
}
return rv;
}
void EditorBase::RemoveEventListeners() {
if (!mEventListener) {
return;
}
mEventListener->Disconnect();
if (mComposition) {
// Even if this is called, don't release mComposition because this is
// may be reused after reframing.
mComposition->EndHandlingComposition(this);
}
mEventTarget = nullptr;
}
bool EditorBase::IsListeningToEvents() const {
return mEventListener && !mEventListener->DetachedFromEditor();
}
bool EditorBase::GetDesiredSpellCheckState() {
// Check user override on this element
if (mSpellcheckCheckboxState != eTriUnset) {
return (mSpellcheckCheckboxState == eTriTrue);
}
// Check user preferences
int32_t spellcheckLevel = Preferences::GetInt("layout.spellcheckDefault", 1);
if (!spellcheckLevel) {
return false; // Spellchecking forced off globally
}
if (!CanEnableSpellCheck()) {
return false;
}
PresShell* presShell = GetPresShell();
if (presShell) {
nsPresContext* context = presShell->GetPresContext();
if (context && !context->IsDynamic()) {
return false;
}
}
// Check DOM state
nsCOMPtr<nsIContent> content = GetExposedRoot();
if (!content) {
return false;
}
auto element = nsGenericHTMLElement::FromNode(content);
if (!element) {
return false;
}
// XXX I'm not sure whether we don't use this path when we're a plaintext mail
// composer.
if (IsHTMLEditor() && !AsHTMLEditor()->IsPlaintextMailComposer()) {
// Some of the page content might be editable and some not, if spellcheck=
// is explicitly set anywhere, so if there's anything editable on the page,
// return true and let the spellchecker figure it out.
Document* doc = content->GetComposedDoc();
return doc && doc->IsEditingOn();
}
return element->Spellcheck();
}
void EditorBase::PreDestroyInternal() {
MOZ_ASSERT(!mDidPreDestroy);
mInitSucceeded = false;
Selection* selection = GetSelection();
if (selection) {
selection->RemoveSelectionListener(this);
}
IMEStateManager::OnEditorDestroying(*this);
// Let spellchecker clean up its observers etc. It is important not to
// actually free the spellchecker here, since the spellchecker could have
// caused flush notifications, which could have gotten here if a textbox
// is being removed. Setting the spellchecker to nullptr could free the
// object that is still in use! It will be freed when the editor is
// destroyed.
if (mInlineSpellChecker) {
DebugOnly<nsresult> rvIgnored =
mInlineSpellChecker->Cleanup(IsTextEditor());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"mozInlineSpellChecker::Cleanup() failed, but ignored");
}
// tell our listeners that the doc is going away
DebugOnly<nsresult> rvIgnored =
NotifyDocumentListeners(eDocumentToBeDestroyed);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::NotifyDocumentListeners("
"eDocumentToBeDestroyed) failed, but ignored");
// Unregister event listeners
RemoveEventListeners();
// If this editor is still hiding the caret, we need to restore it.
HideCaret(false);
mActionListeners.Clear();
mDocStateListeners.Clear();
mInlineSpellChecker = nullptr;
mTextServicesDocument = nullptr;
mTextInputListener = nullptr;
mSpellcheckCheckboxState = eTriUnset;
mRootElement = nullptr;
// Transaction may grab this instance. Therefore, they should be released
// here for stopping the circular reference with this instance.
if (mTransactionManager) {
DebugOnly<bool> disabledUndoRedo = DisableUndoRedo();
NS_WARNING_ASSERTION(disabledUndoRedo,
"EditorBase::DisableUndoRedo() failed, but ignored");
mTransactionManager = nullptr;
}
if (mEditActionData) {
mEditActionData->OnEditorDestroy();
}
mDidPreDestroy = true;
}
NS_IMETHODIMP EditorBase::GetFlags(uint32_t* aFlags) {
// NOTE: If you need to override this method, you need to make Flags()
// virtual.
*aFlags = Flags();
return NS_OK;
}
NS_IMETHODIMP EditorBase::SetFlags(uint32_t aFlags) {
if (mFlags == aFlags) {
return NS_OK;
}
// If we're a `TextEditor` instance, it's always a plaintext editor.
// Therefore, `eEditorPlaintextMask` is not necessary and should not be set
// for the performance reason.
MOZ_ASSERT_IF(IsTextEditor(), !(aFlags & nsIEditor::eEditorPlaintextMask));
// If we're an `HTMLEditor` instance, we cannot treat it as a single line
// editor. So, eEditorSingleLineMask is available only when we're a
// `TextEditor` instance.
MOZ_ASSERT_IF(IsHTMLEditor(), !(aFlags & nsIEditor::eEditorSingleLineMask));
// If we're an `HTMLEditor` instance, we cannot treat it as a password editor.
// So, eEditorPasswordMask is available only when we're a `TextEditor`
// instance.
MOZ_ASSERT_IF(IsHTMLEditor(), !(aFlags & nsIEditor::eEditorPasswordMask));
// eEditorAllowInteraction changes the behavior of `HTMLEditor`. So, it's
// not available with `TextEditor` instance.
MOZ_ASSERT_IF(IsTextEditor(), !(aFlags & nsIEditor::eEditorAllowInteraction));
const bool isCalledByPostCreate = (mFlags == ~aFlags);
// We don't support dynamic password flag change.
MOZ_ASSERT_IF(!isCalledByPostCreate,
!((mFlags ^ aFlags) & nsIEditor::eEditorPasswordMask));
bool spellcheckerWasEnabled = !isCalledByPostCreate && CanEnableSpellCheck();
mFlags = aFlags;
if (!IsInitialized()) {
// If we're initializing, we shouldn't do anything now.
// SetFlags() will be called by PostCreate(),
// we should synchronize some stuff for the flags at that time.
return NS_OK;
}
// The flag change may cause the spellchecker state change
if (CanEnableSpellCheck() != spellcheckerWasEnabled) {
SyncRealTimeSpell();
}
// If this is called from PostCreate(), it will update the IME state if it's
// necessary.
if (!mDidPostCreate) {
return NS_OK;
}
// Might be changing editable state, so, we need to reset current IME state
// if we're focused and the flag change causes IME state change.
if (RefPtr<Element> focusedElement = GetFocusedElement()) {
IMEState newState;
nsresult rv = GetPreferredIMEState(&newState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::GetPreferredIMEState() failed, but ignored");
if (NS_SUCCEEDED(rv)) {
// NOTE: When the enabled state isn't going to be modified, this method
// is going to do nothing.
IMEStateManager::UpdateIMEState(newState, focusedElement, *this);
}
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetIsSelectionEditable(bool* aIsSelectionEditable) {
if (NS_WARN_IF(!aIsSelectionEditable)) {
return NS_ERROR_INVALID_ARG;
}
*aIsSelectionEditable = IsSelectionEditable();
return NS_OK;
}
bool EditorBase::IsSelectionEditable() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return false;
}
if (IsTextEditor()) {
// XXX we just check that the anchor node is editable at the moment
// we should check that all nodes in the selection are editable
const nsINode* anchorNode = SelectionRef().GetAnchorNode();
return anchorNode && anchorNode->IsContent() && anchorNode->IsEditable();
}
const nsINode* anchorNode = SelectionRef().GetAnchorNode();
const nsINode* focusNode = SelectionRef().GetFocusNode();
if (!anchorNode || !focusNode) {
return false;
}
// if anchorNode or focusNode is in a native anonymous subtree, HTMLEditor
// shouldn't edit content in it.
// XXX This must be a bug of Selection API.
if (MOZ_UNLIKELY(anchorNode->IsInNativeAnonymousSubtree() ||
focusNode->IsInNativeAnonymousSubtree())) {
return false;
}
// Per the editing spec as of June 2012: we have to have a selection whose
// start and end nodes are editable, and which share an ancestor editing
// host. (Bug 766387.)
bool isSelectionEditable = SelectionRef().RangeCount() &&
anchorNode->IsEditable() &&
focusNode->IsEditable();
if (!isSelectionEditable) {
return false;
}
const nsINode* commonAncestor =
SelectionRef().GetAnchorFocusRange()->GetClosestCommonInclusiveAncestor();
while (commonAncestor && !commonAncestor->IsEditable()) {
commonAncestor = commonAncestor->GetParentNode();
}
// If there is no editable common ancestor, return false.
return !!commonAncestor;
}
NS_IMETHODIMP EditorBase::GetIsDocumentEditable(bool* aIsDocumentEditable) {
if (NS_WARN_IF(!aIsDocumentEditable)) {
return NS_ERROR_INVALID_ARG;
}
RefPtr<Document> document = GetDocument();
*aIsDocumentEditable = document && IsModifiable();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetDocument(Document** aDocument) {
if (NS_WARN_IF(!aDocument)) {
return NS_ERROR_INVALID_ARG;
}
*aDocument = do_AddRef(mDocument).take();
return NS_WARN_IF(!*aDocument) ? NS_ERROR_NOT_INITIALIZED : NS_OK;
}
already_AddRefed<nsIWidget> EditorBase::GetWidget() const {
nsPresContext* presContext = GetPresContext();
if (NS_WARN_IF(!presContext)) {
return nullptr;
}
nsCOMPtr<nsIWidget> widget = presContext->GetRootWidget();
return NS_WARN_IF(!widget) ? nullptr : widget.forget();
}
NS_IMETHODIMP EditorBase::GetContentsMIMEType(nsAString& aContentsMIMEType) {
aContentsMIMEType = mContentMIMEType;
return NS_OK;
}
NS_IMETHODIMP EditorBase::SetContentsMIMEType(
const nsAString& aContentsMIMEType) {
mContentMIMEType.Assign(aContentsMIMEType);
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetSelectionController(
nsISelectionController** aSelectionController) {
if (NS_WARN_IF(!aSelectionController)) {
return NS_ERROR_INVALID_ARG;
}
*aSelectionController = do_AddRef(GetSelectionController()).take();
return NS_WARN_IF(!*aSelectionController) ? NS_ERROR_FAILURE : NS_OK;
}
NS_IMETHODIMP EditorBase::DeleteSelection(EDirection aAction,
EStripWrappers aStripWrappers) {
nsresult rv = DeleteSelectionAsAction(aAction, aStripWrappers);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteSelectionAsAction() failed");
return rv;
}
NS_IMETHODIMP EditorBase::GetSelection(Selection** aSelection) {
nsresult rv = GetSelection(SelectionType::eNormal, aSelection);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::GetSelection(SelectionType::eNormal) failed");
return rv;
}
nsresult EditorBase::GetSelection(SelectionType aSelectionType,
Selection** aSelection) const {
if (NS_WARN_IF(!aSelection)) {
return NS_ERROR_INVALID_ARG;
}
if (IsEditActionDataAvailable()) {
*aSelection = do_AddRef(&SelectionRef()).take();
return NS_OK;
}
nsISelectionController* selectionController = GetSelectionController();
if (NS_WARN_IF(!selectionController)) {
*aSelection = nullptr;
return NS_ERROR_NOT_INITIALIZED;
}
*aSelection = do_AddRef(selectionController->GetSelection(
ToRawSelectionType(aSelectionType)))
.take();
return NS_WARN_IF(!*aSelection) ? NS_ERROR_FAILURE : NS_OK;
}
nsresult EditorBase::DoTransactionInternal(nsITransaction* aTransaction) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!ShouldAlreadyHaveHandledBeforeInputEventDispatching(),
"beforeinput event hasn't been dispatched yet");
if (mPlaceholderBatch && !mPlaceholderTransaction) {
MOZ_DIAGNOSTIC_ASSERT(mPlaceholderName);
mPlaceholderTransaction = PlaceholderTransaction::Create(
*this, *mPlaceholderName, std::move(mSelState));
MOZ_ASSERT(mSelState.isNothing());
// We will recurse, but will not hit this case in the nested call
RefPtr<PlaceholderTransaction> placeholderTransaction =
mPlaceholderTransaction;
DebugOnly<nsresult> rvIgnored =
DoTransactionInternal(placeholderTransaction);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::DoTransactionInternal() failed, but ignored");
if (mTransactionManager) {
if (nsCOMPtr<nsITransaction> topTransaction =
mTransactionManager->PeekUndoStack()) {
if (RefPtr<EditTransactionBase> topTransactionBase =
topTransaction->GetAsEditTransactionBase()) {
if (PlaceholderTransaction* topPlaceholderTransaction =
topTransactionBase->GetAsPlaceholderTransaction()) {
// there is a placeholder transaction on top of the undo stack. It
// is either the one we just created, or an earlier one that we are
// now merging into. From here on out remember this placeholder
// instead of the one we just created.
mPlaceholderTransaction = topPlaceholderTransaction;
}
}
}
}
}
if (aTransaction) {
// XXX: Why are we doing selection specific batching stuff here?
// XXX: Most entry points into the editor have auto variables that
// XXX: should trigger Begin/EndUpdateViewBatch() calls that will make
// XXX: these selection batch calls no-ops.
// XXX:
// XXX: I suspect that this was placed here to avoid multiple
// XXX: selection changed notifications from happening until after
// XXX: the transaction was done. I suppose that can still happen
// XXX: if an embedding application called DoTransaction() directly
// XXX: to pump its own transactions through the system, but in that
// XXX: case, wouldn't we want to use Begin/EndUpdateViewBatch() or
// XXX: its auto equivalent AutoUpdateViewBatch to ensure that
// XXX: selection listeners have access to accurate frame data?
// XXX:
// XXX: Note that if we did add Begin/EndUpdateViewBatch() calls
// XXX: we will need to make sure that they are disabled during
// XXX: the init of the editor for text widgets to avoid layout
// XXX: re-entry during initial reflow. - kin
// get the selection and start a batch change
SelectionBatcher selectionBatcher(SelectionRef(), __FUNCTION__);
if (mTransactionManager) {
RefPtr<TransactionManager> transactionManager(mTransactionManager);
nsresult rv = transactionManager->DoTransaction(aTransaction);
if (NS_FAILED(rv)) {
NS_WARNING("TransactionManager::DoTransaction() failed");
return rv;
}
} else {
nsresult rv = aTransaction->DoTransaction();
if (NS_FAILED(rv)) {
NS_WARNING("nsITransaction::DoTransaction() failed");
return rv;
}
}
DoAfterDoTransaction(aTransaction);
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::EnableUndo(bool aEnable) {
// XXX Should we return NS_ERROR_FAILURE if EdnableUndoRedo() or
// DisableUndoRedo() returns false?
if (aEnable) {
DebugOnly<bool> enabledUndoRedo = EnableUndoRedo();
NS_WARNING_ASSERTION(enabledUndoRedo,
"EditorBase::EnableUndoRedo() failed, but ignored");
return NS_OK;
}
DebugOnly<bool> disabledUndoRedo = DisableUndoRedo();
NS_WARNING_ASSERTION(disabledUndoRedo,
"EditorBase::DisableUndoRedo() failed, but ignored");
return NS_OK;
}
NS_IMETHODIMP EditorBase::ClearUndoRedoXPCOM() {
if (MOZ_UNLIKELY(!ClearUndoRedo())) {
return NS_ERROR_FAILURE; // We're handling a transaction
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::Undo() {
nsresult rv = UndoAsAction(1u);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::UndoAsAction() failed");
return rv;
}
NS_IMETHODIMP EditorBase::UndoAll() {
if (!mTransactionManager) {
return NS_OK;
}
size_t numberOfUndoItems = mTransactionManager->NumberOfUndoItems();
if (!numberOfUndoItems) {
return NS_OK; // no transactions
}
nsresult rv = UndoAsAction(numberOfUndoItems);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::UndoAsAction() failed");
return rv;
}
NS_IMETHODIMP EditorBase::GetUndoRedoEnabled(bool* aIsEnabled) {
MOZ_ASSERT(aIsEnabled);
*aIsEnabled = IsUndoRedoEnabled();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetCanUndo(bool* aCanUndo) {
MOZ_ASSERT(aCanUndo);
*aCanUndo = CanUndo();
return NS_OK;
}
NS_IMETHODIMP EditorBase::Redo() {
nsresult rv = RedoAsAction(1u);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::RedoAsAction() failed");
return rv;
}
NS_IMETHODIMP EditorBase::GetCanRedo(bool* aCanRedo) {
MOZ_ASSERT(aCanRedo);
*aCanRedo = CanRedo();
return NS_OK;
}
nsresult EditorBase::UndoAsAction(uint32_t aCount, nsIPrincipal* aPrincipal) {
if (aCount == 0 || IsReadonly()) {
return NS_OK;
}
// If we don't have transaction in the undo stack, we shouldn't notify
// anybody of trying to undo since it's not useful notification but we
// need to pay some runtime cost.
if (!CanUndo()) {
return NS_OK;
}
// If there is composition, we shouldn't allow to undo with committing
// composition since Chrome doesn't allow it and it doesn't make sense
// because committing composition causes one transaction and Undo(1)
// undoes the committing composition.
if (GetComposition()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eUndo, aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoUpdateViewBatch preventSelectionChangeEvent(*this, __FUNCTION__);
NotifyEditorObservers(eNotifyEditorObserversOfBefore);
if (NS_WARN_IF(!CanUndo()) || NS_WARN_IF(Destroyed())) {
return NS_ERROR_FAILURE;
}
rv = NS_OK;
{
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eUndo, nsIEditor::eNone, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return EditorBase::ToGenericNSResult(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() "
"failed, but ignored");
RefPtr<TransactionManager> transactionManager(mTransactionManager);
for (uint32_t i = 0; i < aCount; ++i) {
if (NS_FAILED(transactionManager->Undo())) {
NS_WARNING("TransactionManager::Undo() failed");
break;
}
DoAfterUndoTransaction();
}
if (IsHTMLEditor()) {
rv = AsHTMLEditor()->ReflectPaddingBRElementForEmptyEditor();
}
}
NotifyEditorObservers(eNotifyEditorObserversOfEnd);
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::RedoAsAction(uint32_t aCount, nsIPrincipal* aPrincipal) {
if (aCount == 0 || IsReadonly()) {
return NS_OK;
}
// If we don't have transaction in the redo stack, we shouldn't notify
// anybody of trying to redo since it's not useful notification but we
// need to pay some runtime cost.
if (!CanRedo()) {
return NS_OK;
}
// If there is composition, we shouldn't allow to redo with committing
// composition since Chrome doesn't allow it and it doesn't make sense
// because committing composition causes removing all transactions from
// the redo queue. So, it becomes impossible to redo anything.
if (GetComposition()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eRedo, aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoUpdateViewBatch preventSelectionChangeEvent(*this, __FUNCTION__);
NotifyEditorObservers(eNotifyEditorObserversOfBefore);
if (NS_WARN_IF(!CanRedo()) || NS_WARN_IF(Destroyed())) {
return NS_ERROR_FAILURE;
}
rv = NS_OK;
{
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eRedo, nsIEditor::eNone, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() "
"failed, but ignored");
RefPtr<TransactionManager> transactionManager(mTransactionManager);
for (uint32_t i = 0; i < aCount; ++i) {
if (NS_FAILED(transactionManager->Redo())) {
NS_WARNING("TransactionManager::Redo() failed");
break;
}
DoAfterRedoTransaction();
}
if (IsHTMLEditor()) {
rv = AsHTMLEditor()->ReflectPaddingBRElementForEmptyEditor();
}
}
NotifyEditorObservers(eNotifyEditorObserversOfEnd);
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP EditorBase::BeginTransaction() {
AutoEditActionDataSetter editActionData(*this, EditAction::eUnknown);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
BeginTransactionInternal(__FUNCTION__);
return NS_OK;
}
void EditorBase::BeginTransactionInternal(const char* aRequesterFuncName) {
BeginUpdateViewBatch(aRequesterFuncName);
if (NS_WARN_IF(!mTransactionManager)) {
return;
}
RefPtr<TransactionManager> transactionManager(mTransactionManager);
DebugOnly<nsresult> rvIgnored = transactionManager->BeginBatch(nullptr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TransactionManager::BeginBatch() failed, but ignored");
}
NS_IMETHODIMP EditorBase::EndTransaction() {
AutoEditActionDataSetter editActionData(*this, EditAction::eUnknown);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
EndTransactionInternal(__FUNCTION__);
return NS_OK;
}
void EditorBase::EndTransactionInternal(const char* aRequesterFuncName) {
if (mTransactionManager) {
RefPtr<TransactionManager> transactionManager(mTransactionManager);
DebugOnly<nsresult> rvIgnored = transactionManager->EndBatch(false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TransactionManager::EndBatch() failed, but ignored");
}
EndUpdateViewBatch(aRequesterFuncName);
}
void EditorBase::BeginPlaceholderTransaction(nsStaticAtom& aTransactionName,
const char* aRequesterFuncName) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(mPlaceholderBatch >= 0, "negative placeholder batch count!");
if (!mPlaceholderBatch) {
NotifyEditorObservers(eNotifyEditorObserversOfBefore);
// time to turn on the batch
BeginUpdateViewBatch(aRequesterFuncName);
mPlaceholderTransaction = nullptr;
mPlaceholderName = &aTransactionName;
mSelState.emplace();
mSelState->SaveSelection(SelectionRef());
// Composition transaction can modify multiple nodes and it merges text
// node for ime into single text node.
// So if current selection is into IME text node, it might be failed
// to restore selection by UndoTransaction.
// So we need update selection by range updater.
if (mPlaceholderName == nsGkAtoms::IMETxnName) {
RangeUpdaterRef().RegisterSelectionState(*mSelState);
}
}
mPlaceholderBatch++;
}
void EditorBase::EndPlaceholderTransaction(
ScrollSelectionIntoView aScrollSelectionIntoView,
const char* aRequesterFuncName) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(mPlaceholderBatch > 0,
"zero or negative placeholder batch count when ending batch!");
if (!(--mPlaceholderBatch)) {
// By making the assumption that no reflow happens during the calls
// to EndUpdateViewBatch and ScrollSelectionFocusIntoView, we are able to
// allow the selection to cache a frame offset which is used by the
// caret drawing code. We only enable this cache here; at other times,
// we have no way to know whether reflow invalidates it
// See bugs 35296 and 199412.
SelectionRef().SetCanCacheFrameOffset(true);
// time to turn off the batch
EndUpdateViewBatch(aRequesterFuncName);
// make sure selection is in view
// After ScrollSelectionFocusIntoView(), the pending notifications might be
// flushed and PresShell/PresContext/Frames may be dead. See bug 418470.
// XXX Even if we're destroyed, we need to keep handling below because
// this method changes a lot of status. We should rewrite this safer.
if (aScrollSelectionIntoView == ScrollSelectionIntoView::Yes) {
DebugOnly<nsresult> rvIgnored = ScrollSelectionFocusIntoView();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::ScrollSelectionFocusIntoView() failed, but Ignored");
}
// cached for frame offset are Not available now
SelectionRef().SetCanCacheFrameOffset(false);
if (mSelState) {
// we saved the selection state, but never got to hand it to placeholder
// (else we ould have nulled out this pointer), so destroy it to prevent
// leaks.
if (mPlaceholderName == nsGkAtoms::IMETxnName) {
RangeUpdaterRef().DropSelectionState(*mSelState);
}
mSelState.reset();
}
// We might have never made a placeholder if no action took place.
if (mPlaceholderTransaction) {
// FYI: Disconnect placeholder transaction before dispatching "input"
// event because an input event listener may start other things.
// TODO: We should forget EditActionDataSetter too.
RefPtr<PlaceholderTransaction> placeholderTransaction =
std::move(mPlaceholderTransaction);
DebugOnly<nsresult> rvIgnored =
placeholderTransaction->EndPlaceHolderBatch();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"PlaceholderTransaction::EndPlaceHolderBatch() failed, but ignored");
// notify editor observers of action but if composing, it's done by
// compositionchange event handler.
if (!mComposition) {
NotifyEditorObservers(eNotifyEditorObserversOfEnd);
}
} else {
NotifyEditorObservers(eNotifyEditorObserversOfCancel);
}
}
}
NS_IMETHODIMP EditorBase::GetDocumentIsEmpty(bool* aDocumentIsEmpty) {
MOZ_ASSERT(aDocumentIsEmpty);
*aDocumentIsEmpty = IsEmpty();
return NS_OK;
}
// XXX: The rule system should tell us which node to select all on (ie, the
// root, or the body)
NS_IMETHODIMP EditorBase::SelectAll() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = SelectAllInternal();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "SelectAllInternal() failed");
// This is low level API for XUL applcation. So, we should return raw
// error code here.
return rv;
}
nsresult EditorBase::SelectAllInternal() {
MOZ_ASSERT(IsInitialized());
DebugOnly<nsresult> rvIgnored = CommitComposition();
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
// XXX Do we need to keep handling after committing composition causes moving
// focus to different element? Although TextEditor has independent
// selection, so, we may not see any odd behavior even in such case.
nsresult rv = SelectEntireDocument();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SelectEntireDocument() failed");
return rv;
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP EditorBase::BeginningOfDocument() {
MOZ_ASSERT(IsTextEditor());
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
// get the root element
RefPtr<Element> rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_NULL_POINTER;
}
// find first editable thingy
nsCOMPtr<nsIContent> firstEditableLeaf;
// If we're `TextEditor`, the first editable leaf node is a text node or
// padding `<br>` element. In the first case, we need to collapse selection
// into it.
if (rootElement->GetFirstChild() && rootElement->GetFirstChild()->IsText()) {
firstEditableLeaf = rootElement->GetFirstChild();
}
if (!firstEditableLeaf) {
// just the root node, set selection to inside the root
nsresult rv = CollapseSelectionToStartOf(*rootElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
if (firstEditableLeaf->IsText()) {
// If firstEditableLeaf is text, set selection to beginning of the text
// node.
nsresult rv = CollapseSelectionToStartOf(*firstEditableLeaf);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
// Otherwise, it's a leaf node and we set the selection just in front of it.
nsCOMPtr<nsIContent> parent = firstEditableLeaf->GetParent();
if (NS_WARN_IF(!parent)) {
return NS_ERROR_NULL_POINTER;
}
MOZ_ASSERT(
parent->ComputeIndexOf(firstEditableLeaf).valueOr(UINT32_MAX) == 0,
"How come the first node isn't the left most child in its parent?");
nsresult rv = CollapseSelectionToStartOf(*parent);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
NS_IMETHODIMP EditorBase::EndOfDocument() { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP EditorBase::GetDocumentModified(bool* aOutDocModified) {
if (NS_WARN_IF(!aOutDocModified)) {
return NS_ERROR_INVALID_ARG;
}
int32_t modCount = 0;
DebugOnly<nsresult> rvIgnored = GetModificationCount(&modCount);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::GetModificationCount() failed, but ignored");
*aOutDocModified = (modCount != 0);
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetDocumentCharacterSet(nsACString& aCharacterSet) {
return NS_ERROR_NOT_AVAILABLE;
}
nsresult EditorBase::GetDocumentCharsetInternal(nsACString& aCharset) const {
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_NOT_INITIALIZED;
}
document->GetDocumentCharacterSet()->Name(aCharset);
return NS_OK;
}
NS_IMETHODIMP EditorBase::SetDocumentCharacterSet(
const nsACString& aCharacterSet) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_IMETHODIMP EditorBase::OutputToString(const nsAString& aFormatType,
uint32_t aDocumentEncoderFlags,
nsAString& aOutputString) {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv =
ComputeValueInternal(aFormatType, aDocumentEncoderFlags, aOutputString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::ComputeValueInternal() failed");
// This is low level API for XUL application. So, we should return raw
// error code here.
return rv;
}
nsresult EditorBase::ComputeValueInternal(const nsAString& aFormatType,
uint32_t aDocumentEncoderFlags,
nsAString& aOutputString) const {
MOZ_ASSERT(IsEditActionDataAvailable());
// First, let's try to get the value simply only from text node if the
// caller wants plaintext value.
if (aFormatType.LowerCaseEqualsLiteral("text/plain") &&
!(aDocumentEncoderFlags & (nsIDocumentEncoder::OutputSelectionOnly |
nsIDocumentEncoder::OutputWrap))) {
// Shortcut for empty editor case.
if (IsEmpty()) {
aOutputString.Truncate();
return NS_OK;
}
// NOTE: If it's neither <input type="text"> nor <textarea>, e.g., an HTML
// editor which is in plaintext mode (e.g., plaintext email composer on
// Thunderbird), it should be handled by the expensive path.
if (IsTextEditor()) {
// If it's necessary to check selection range or the editor wraps hard,
// we need some complicated handling. In such case, we need to use the
// expensive path.
// XXX Anything else what we cannot return the text node data simply?
Result<EditActionResult, nsresult> result =
AsTextEditor()->ComputeValueFromTextNodeAndBRElement(aOutputString);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("TextEditor::ComputeValueFromTextNodeAndBRElement() failed");
return result.unwrapErr();
}
if (!result.inspect().Ignored()) {
return NS_OK;
}
}
}
nsAutoCString charset;
nsresult rv = GetDocumentCharsetInternal(charset);
if (NS_FAILED(rv) || charset.IsEmpty()) {
charset.AssignLiteral("windows-1252"); // XXX Why don't we use "UTF-8"?
}
nsCOMPtr<nsIDocumentEncoder> encoder =
GetAndInitDocEncoder(aFormatType, aDocumentEncoderFlags, charset);
if (!encoder) {
NS_WARNING("EditorBase::GetAndInitDocEncoder() failed");
return NS_ERROR_FAILURE;
}
rv = encoder->EncodeToString(aOutputString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsIDocumentEncoder::EncodeToString() failed");
return rv;
}
already_AddRefed<nsIDocumentEncoder> EditorBase::GetAndInitDocEncoder(
const nsAString& aFormatType, uint32_t aDocumentEncoderFlags,
const nsACString& aCharset) const {
MOZ_ASSERT(IsEditActionDataAvailable());
nsCOMPtr<nsIDocumentEncoder> docEncoder;
if (!mCachedDocumentEncoder ||
!mCachedDocumentEncoderType.Equals(aFormatType)) {
nsAutoCString formatType;
LossyAppendUTF16toASCII(aFormatType, formatType);
docEncoder = do_createDocumentEncoder(PromiseFlatCString(formatType).get());
if (NS_WARN_IF(!docEncoder)) {
return nullptr;
}
mCachedDocumentEncoder = docEncoder;
mCachedDocumentEncoderType = aFormatType;
} else {
docEncoder = mCachedDocumentEncoder;
}
RefPtr<Document> doc = GetDocument();
NS_ASSERTION(doc, "Need a document");
nsresult rv = docEncoder->NativeInit(
doc, aFormatType,
aDocumentEncoderFlags | nsIDocumentEncoder::RequiresReinitAfterOutput);
if (NS_FAILED(rv)) {
NS_WARNING("nsIDocumentEncoder::NativeInit() failed");
return nullptr;
}
if (!aCharset.IsEmpty() && !aCharset.EqualsLiteral("null")) {
DebugOnly<nsresult> rvIgnored = docEncoder->SetCharset(aCharset);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIDocumentEncoder::SetCharset() failed, but ignored");
}
const int32_t wrapWidth = std::max(WrapWidth(), 0);
DebugOnly<nsresult> rvIgnored = docEncoder->SetWrapColumn(wrapWidth);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIDocumentEncoder::SetWrapColumn() failed, but ignored");
// Set the selection, if appropriate.
// We do this either if the OutputSelectionOnly flag is set,
// in which case we use our existing selection ...
if (aDocumentEncoderFlags & nsIDocumentEncoder::OutputSelectionOnly) {
if (NS_FAILED(docEncoder->SetSelection(&SelectionRef()))) {
NS_WARNING("nsIDocumentEncoder::SetSelection() failed");
return nullptr;
}
}
// ... or if the root element is not a body,
// in which case we set the selection to encompass the root.
else {
Element* rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return nullptr;
}
if (!rootElement->IsHTMLElement(nsGkAtoms::body)) {
if (NS_FAILED(docEncoder->SetContainerNode(rootElement))) {
NS_WARNING("nsIDocumentEncoder::SetContainerNode() failed");
return nullptr;
}
}
}
return docEncoder.forget();
}
bool EditorBase::AreClipboardCommandsUnconditionallyEnabled() const {
Document* document = GetDocument();
return document && document->AreClipboardCommandsUnconditionallyEnabled();
}
bool EditorBase::CheckForClipboardCommandListener(
nsAtom* aCommand, EventMessage aEventMessage) const {
RefPtr<Document> document = GetDocument();
if (!document) {
return false;
}
// We exclude XUL and chrome docs here to maintain current behavior where
// in these cases the editor element alone is expected to handle clipboard
// command availability.
if (!document->AreClipboardCommandsUnconditionallyEnabled()) {
return false;
}
// So in web content documents, "unconditionally" enabled Cut/Copy are not
// really unconditional; they're enabled if there is a listener that wants
// to handle them. What they're not conditional on here is whether there is
// currently a selection in the editor.
RefPtr<PresShell> presShell = document->GetObservingPresShell();
if (!presShell) {
return false;
}
RefPtr<nsPresContext> presContext = presShell->GetPresContext();
if (!presContext) {
return false;
}
RefPtr<EventTarget> et = IsHTMLEditor()
? AsHTMLEditor()->ComputeEditingHost(
HTMLEditor::LimitInBodyElement::No)
: GetDOMEventTarget();
while (et) {
EventListenerManager* elm = et->GetExistingListenerManager();
if (elm && elm->HasListenersFor(aCommand)) {
return true;
}
InternalClipboardEvent event(true, aEventMessage);
EventChainPreVisitor visitor(presContext, &event, nullptr,
nsEventStatus_eIgnore, false, et);
et->GetEventTargetParent(visitor);
et = visitor.GetParentTarget();
}
return false;
}
Result<EditorBase::ClipboardEventResult, nsresult>
EditorBase::DispatchClipboardEventAndUpdateClipboard(EventMessage aEventMessage,
int32_t aClipboardType) {
MOZ_ASSERT(IsEditActionDataAvailable());
const bool isPasting =
aEventMessage == ePaste || aEventMessage == ePasteNoFormatting;
if (isPasting) {
CommitComposition();
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
}
RefPtr<PresShell> presShell = GetPresShell();
if (NS_WARN_IF(!presShell)) {
return Err(NS_ERROR_NOT_AVAILABLE);
}
const RefPtr<Selection> sel = [&]() {
if (IsHTMLEditor() && aEventMessage == eCopy &&
SelectionRef().IsCollapsed()) {
// If we don't have a usable selection for copy and we're an HTML
// editor (which is global for the document) try to use the last
// focused selection instead.
return nsCopySupport::GetSelectionForCopy(GetDocument());
}
return do_AddRef(&SelectionRef());
}();
bool actionTaken = false;
const bool doDefault = nsCopySupport::FireClipboardEvent(
aEventMessage, aClipboardType, presShell, sel, &actionTaken);
NotifyOfDispatchingClipboardEvent();
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (doDefault) {
MOZ_ASSERT(actionTaken);
return ClipboardEventResult::DoDefault;
}
// If we handle a "paste" and nsCopySupport::FireClipboardEvent sets
// actionTaken to "false" means that it's an error. Otherwise, the "paste"
// event is just canceled.
if (isPasting) {
return actionTaken ? ClipboardEventResult::DefaultPreventedOfPaste
: ClipboardEventResult::IgnoredOrError;
}
// If we handle a "copy", actionTaken is set to true only when
// nsCopySupport::FireClipboardEvent does not meet an error.
// If we handle a "cut", actionTaken is set to true only when
// nsCopySupport::FireClipboardEvent does not meet an error and
// - the selection is collapsed in editable elements when the event is not
// canceled.
// - the event is canceled but update the clipboard with the dataTransfer
// of the event.
return actionTaken ? ClipboardEventResult::CopyOrCutHandled
: ClipboardEventResult::IgnoredOrError;
}
NS_IMETHODIMP EditorBase::Cut() {
nsresult rv = CutAsAction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::CutAsAction() failed");
return rv;
}
nsresult EditorBase::CutAsAction(nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eCut, aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
{
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_UNEXPECTED;
}
const RefPtr<Element> focusedElement = focusManager->GetFocusedElement();
Result<ClipboardEventResult, nsresult> ret =
DispatchClipboardEventAndUpdateClipboard(
eCut, nsIClipboard::kGlobalClipboard);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard(eCut, "
"nsIClipboard::kGlobalClipboard) failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
switch (ret.unwrap()) {
case ClipboardEventResult::DoDefault:
break;
case ClipboardEventResult::CopyOrCutHandled:
return NS_OK;
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::DefaultPreventedOfPaste:
MOZ_ASSERT_UNREACHABLE("Invalid result for eCut");
}
// If focus is changed by a "cut" event listener, we should stop handling
// the cut.
const RefPtr<Element> newFocusedElement = focusManager->GetFocusedElement();
if (MOZ_UNLIKELY(focusedElement != newFocusedElement)) {
if (focusManager->GetFocusedWindow() != GetWindow()) {
return NS_OK;
}
RefPtr<EditorBase> editorBase =
nsContentUtils::GetActiveEditor(GetPresContext());
if (!editorBase || (editorBase->IsHTMLEditor() &&
!editorBase->AsHTMLEditor()->IsActiveInDOMWindow())) {
return NS_OK;
}
if (editorBase != this) {
return NS_OK;
}
}
}
// Dispatch "beforeinput" event after dispatching "cut" event.
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
// XXX This transaction name is referred by PlaceholderTransaction::Merge()
// so that we need to keep using it here.
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::DeleteTxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
rv = DeleteSelectionAsSubAction(
eNone, IsTextEditor() ? nsIEditor::eNoStrip : nsIEditor::eStrip);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::DeleteSelectionAsSubAction(eNone) failed, but ignored");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP EditorBase::CanCut(bool* aCanCut) {
if (NS_WARN_IF(!aCanCut)) {
return NS_ERROR_INVALID_ARG;
}
*aCanCut = IsCutCommandEnabled();
return NS_OK;
}
bool EditorBase::IsCutCommandEnabled() const {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return false;
}
if (IsModifiable() && IsCopyToClipboardAllowedInternal()) {
return true;
}
// If there's an event listener for "cut", we always enable the command
// as we don't really know what the listener may want to do in response.
// We look up the event target chain for a possible listener on a parent
// in addition to checking the immediate target.
return CheckForClipboardCommandListener(nsGkAtoms::oncut, eCut);
}
NS_IMETHODIMP EditorBase::Copy() {
AutoEditActionDataSetter editActionData(*this, EditAction::eCopy);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
Result<ClipboardEventResult, nsresult> ret =
DispatchClipboardEventAndUpdateClipboard(eCopy,
nsIClipboard::kGlobalClipboard);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard(eCopy, "
"nsIClipboard::kGlobalClipboard) failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
switch (ret.unwrap()) {
case ClipboardEventResult::DoDefault:
case ClipboardEventResult::CopyOrCutHandled:
return NS_OK;
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::DefaultPreventedOfPaste:
MOZ_ASSERT_UNREACHABLE("Invalid result for eCopy");
}
return NS_ERROR_UNEXPECTED;
}
NS_IMETHODIMP EditorBase::CanCopy(bool* aCanCopy) {
if (NS_WARN_IF(!aCanCopy)) {
return NS_ERROR_INVALID_ARG;
}
*aCanCopy = IsCopyCommandEnabled();
return NS_OK;
}
bool EditorBase::IsCopyCommandEnabled() const {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return false;
}
if (IsCopyToClipboardAllowedInternal()) {
return true;
}
// Like "cut", always enable "copy" if there's a listener.
return CheckForClipboardCommandListener(nsGkAtoms::oncopy, eCopy);
}
NS_IMETHODIMP EditorBase::Paste(int32_t aClipboardType) {
const nsresult rv = PasteAsAction(aClipboardType, DispatchPasteEvent::Yes);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::PasteAsAction(DispatchPasteEvent::Yes) failed");
return rv;
}
nsresult EditorBase::PasteAsAction(int32_t aClipboardType,
DispatchPasteEvent aDispatchPasteEvent,
nsIPrincipal* aPrincipal /* = nullptr */) {
if (IsHTMLEditor() && IsReadonly()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::ePaste,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (aDispatchPasteEvent == DispatchPasteEvent::Yes) {
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_UNEXPECTED;
}
const RefPtr<Element> focusedElement = focusManager->GetFocusedElement();
Result<ClipboardEventResult, nsresult> ret =
DispatchClipboardEventAndUpdateClipboard(ePaste, aClipboardType);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard(ePaste) "
"failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
switch (ret.inspect()) {
case ClipboardEventResult::DoDefault:
break;
case ClipboardEventResult::DefaultPreventedOfPaste:
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::CopyOrCutHandled:
MOZ_ASSERT_UNREACHABLE("Invalid result for ePaste");
}
// If focus is changed by a "paste" event listener, we should keep handling
// the "pasting" in new focused editor because Chrome works as so.
const RefPtr<Element> newFocusedElement = focusManager->GetFocusedElement();
if (MOZ_UNLIKELY(focusedElement != newFocusedElement)) {
// For the privacy reason, let's top handling it if new focused element is
// in different document.
if (focusManager->GetFocusedWindow() != GetWindow()) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
RefPtr<EditorBase> editorBase =
nsContentUtils::GetActiveEditor(GetPresContext());
if (!editorBase || (editorBase->IsHTMLEditor() &&
!editorBase->AsHTMLEditor()->IsActiveInDOMWindow())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
if (editorBase != this) {
nsresult rv = editorBase->PasteAsAction(
aClipboardType, DispatchPasteEvent::No, aPrincipal);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::PasteAsAction(DispatchPasteEvent::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
}
} else {
// The caller must already have dispatched a "paste" event.
editActionData.NotifyOfDispatchingClipboardEvent();
}
nsresult rv = HandlePaste(editActionData, aClipboardType);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::HandlePaste() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::PasteAsQuotationAsAction(
int32_t aClipboardType, DispatchPasteEvent aDispatchPasteEvent,
nsIPrincipal* aPrincipal /* = nullptr */) {
MOZ_ASSERT(aClipboardType == nsIClipboard::kGlobalClipboard ||
aClipboardType == nsIClipboard::kSelectionClipboard);
if (IsHTMLEditor() && IsReadonly()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::ePasteAsQuotation,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (aDispatchPasteEvent == DispatchPasteEvent::Yes) {
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_UNEXPECTED;
}
const RefPtr<Element> focusedElement = focusManager->GetFocusedElement();
Result<ClipboardEventResult, nsresult> ret =
DispatchClipboardEventAndUpdateClipboard(ePaste, aClipboardType);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard(ePaste) "
"failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
switch (ret.inspect()) {
case ClipboardEventResult::DoDefault:
break;
case ClipboardEventResult::DefaultPreventedOfPaste:
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::CopyOrCutHandled:
MOZ_ASSERT_UNREACHABLE("Invalid result for ePaste");
}
// If focus is changed by a "paste" event listener, we should keep handling
// the "pasting" in new focused editor because Chrome works as so.
const RefPtr<Element> newFocusedElement = focusManager->GetFocusedElement();
if (MOZ_UNLIKELY(focusedElement != newFocusedElement)) {
// For the privacy reason, let's top handling it if new focused element is
// in different document.
if (focusManager->GetFocusedWindow() != GetWindow()) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
RefPtr<EditorBase> editorBase =
nsContentUtils::GetActiveEditor(GetPresContext());
if (!editorBase || (editorBase->IsHTMLEditor() &&
!editorBase->AsHTMLEditor()->IsActiveInDOMWindow())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
if (editorBase != this) {
nsresult rv = editorBase->PasteAsQuotationAsAction(
aClipboardType, DispatchPasteEvent::No, aPrincipal);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::PasteAsQuotationAsAction("
"DispatchPasteEvent::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
}
} else {
// The caller must already have dispatched a "paste" event.
editActionData.NotifyOfDispatchingClipboardEvent();
}
nsresult rv = HandlePasteAsQuotation(editActionData, aClipboardType);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::HandlePasteAsQuotation() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::PasteTransferableAsAction(
nsITransferable* aTransferable, DispatchPasteEvent aDispatchPasteEvent,
nsIPrincipal* aPrincipal /* = nullptr */) {
// FIXME: This may be called as a call of nsIEditor::PasteTransferable.
// In this case, we should keep handling the paste even in the readonly mode.
if (IsHTMLEditor() && IsReadonly()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::ePaste,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (aDispatchPasteEvent == DispatchPasteEvent::Yes) {
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_UNEXPECTED;
}
const RefPtr<Element> focusedElement = focusManager->GetFocusedElement();
// Use an invalid value for the clipboard type as data comes from
// aTransferable and we don't currently implement a way to put that in the
// data transfer in TextEditor yet.
Result<ClipboardEventResult, nsresult> ret =
DispatchClipboardEventAndUpdateClipboard(
ePaste, IsTextEditor() ? -1 : nsIClipboard::kGlobalClipboard);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard(ePaste) "
"failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
switch (ret.inspect()) {
case ClipboardEventResult::DoDefault:
break;
case ClipboardEventResult::DefaultPreventedOfPaste:
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::CopyOrCutHandled:
MOZ_ASSERT_UNREACHABLE("Invalid result for ePaste");
}
// If focus is changed by a "paste" event listener, we should keep handling
// the "pasting" in new focused editor because Chrome works as so.
const RefPtr<Element> newFocusedElement = focusManager->GetFocusedElement();
if (MOZ_UNLIKELY(focusedElement != newFocusedElement)) {
// For the privacy reason, let's top handling it if new focused element is
// in different document.
if (focusManager->GetFocusedWindow() != GetWindow()) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
RefPtr<EditorBase> editorBase =
nsContentUtils::GetActiveEditor(GetPresContext());
if (!editorBase || (editorBase->IsHTMLEditor() &&
!editorBase->AsHTMLEditor()->IsActiveInDOMWindow())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
if (editorBase != this) {
nsresult rv = editorBase->PasteTransferableAsAction(
aTransferable, DispatchPasteEvent::No, aPrincipal);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::PasteTransferableAsAction("
"DispatchPasteEvent::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
}
} else {
// The caller must already have dispatched a "paste" event.
editActionData.NotifyOfDispatchingClipboardEvent();
}
if (NS_WARN_IF(!aTransferable)) {
return NS_ERROR_INVALID_ARG;
}
nsresult rv = HandlePasteTransferable(editActionData, *aTransferable);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::HandlePasteTransferable() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::PrepareToInsertContent(
const EditorDOMPoint& aPointToInsert,
DeleteSelectedContent aDeleteSelectedContent) {
// TODO: Move this method to `EditorBase`.
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSet());
EditorDOMPoint pointToInsert(aPointToInsert);
if (aDeleteSelectedContent == DeleteSelectedContent::Yes) {
AutoTrackDOMPoint tracker(RangeUpdaterRef(), &pointToInsert);
nsresult rv = DeleteSelectionAsSubAction(
nsIEditor::eNone,
IsTextEditor() ? nsIEditor::eNoStrip : nsIEditor::eStrip);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteSelectionAsSubAction(eNone) failed");
return rv;
}
}
nsresult rv = CollapseSelectionTo(pointToInsert);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
nsresult EditorBase::InsertTextAt(
const nsAString& aStringToInsert, const EditorDOMPoint& aPointToInsert,
DeleteSelectedContent aDeleteSelectedContent) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSet());
nsresult rv = PrepareToInsertContent(aPointToInsert, aDeleteSelectedContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::PrepareToInsertContent() failed");
return rv;
}
rv = InsertTextAsSubAction(aStringToInsert, SelectionHandling::Delete);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
return rv;
}
EditorBase::SafeToInsertData EditorBase::IsSafeToInsertData(
nsIPrincipal* aSourcePrincipal) const {
// Try to determine whether we should use a sanitizing fragment sink
RefPtr<Document> destdoc = GetDocument();
NS_ASSERTION(destdoc, "Where is our destination doc?");
nsIDocShell* docShell = nullptr;
if (RefPtr<BrowsingContext> bc = destdoc->GetBrowsingContext()) {
RefPtr<BrowsingContext> root = bc->Top();
MOZ_ASSERT(root, "root should not be null");
docShell = root->GetDocShell();
}
bool isSafe =
docShell && docShell->GetAppType() == nsIDocShell::APP_TYPE_EDITOR;
if (!isSafe && aSourcePrincipal) {
nsIPrincipal* destPrincipal = destdoc->NodePrincipal();
NS_ASSERTION(destPrincipal, "How come we don't have a principal?");
DebugOnly<nsresult> rvIgnored =
aSourcePrincipal->Subsumes(destPrincipal, &isSafe);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsIPrincipal::Subsumes() failed, but ignored");
}
return isSafe ? SafeToInsertData::Yes : SafeToInsertData::No;
}
NS_IMETHODIMP EditorBase::PasteTransferable(nsITransferable* aTransferable) {
nsresult rv =
PasteTransferableAsAction(aTransferable, DispatchPasteEvent::Yes);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::PasteTransferableAsAction(DispatchPasteEvent::Yes) failed");
return rv;
}
NS_IMETHODIMP EditorBase::CanPaste(int32_t aClipboardType, bool* aCanPaste) {
if (NS_WARN_IF(!aCanPaste)) {
return NS_ERROR_INVALID_ARG;
}
*aCanPaste = CanPaste(aClipboardType);
return NS_OK;
}
NS_IMETHODIMP EditorBase::SetAttribute(Element* aElement,
const nsAString& aAttribute,
const nsAString& aValue) {
if (NS_WARN_IF(aAttribute.IsEmpty()) || NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eSetAttribute);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<nsAtom> attribute = NS_Atomize(aAttribute);
rv = SetAttributeWithTransaction(*aElement, *attribute, aValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::SetAttributeWithTransaction(Element& aElement,
nsAtom& aAttribute,
const nsAString& aValue) {
RefPtr<ChangeAttributeTransaction> transaction =
ChangeAttributeTransaction::Create(aElement, aAttribute, aValue);
nsresult rv = DoTransactionInternal(transaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
return rv;
}
NS_IMETHODIMP EditorBase::RemoveAttribute(Element* aElement,
const nsAString& aAttribute) {
if (NS_WARN_IF(aAttribute.IsEmpty()) || NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eRemoveAttribute);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<nsAtom> attribute = NS_Atomize(aAttribute);
rv = RemoveAttributeWithTransaction(*aElement, *attribute);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::RemoveAttributeWithTransaction(Element& aElement,
nsAtom& aAttribute) {
if (!aElement.HasAttr(&aAttribute)) {
return NS_OK;
}
RefPtr<ChangeAttributeTransaction> transaction =
ChangeAttributeTransaction::CreateToRemove(aElement, aAttribute);
nsresult rv = DoTransactionInternal(transaction);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
return rv;
}
nsresult EditorBase::MarkElementDirty(Element& aElement) const {
// Mark the node dirty, but not for webpages (bug 599983)
if (!OutputsMozDirty()) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored =
aElement.SetAttr(kNameSpaceID_None, nsGkAtoms::mozdirty, u""_ns, false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Element::SetAttr(nsGkAtoms::mozdirty) failed, but ignored");
return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : NS_OK;
}
NS_IMETHODIMP EditorBase::GetInlineSpellChecker(
bool aAutoCreate, nsIInlineSpellChecker** aInlineSpellChecker) {
if (NS_WARN_IF(!aInlineSpellChecker)) {
return NS_ERROR_INVALID_ARG;
}
if (mDidPreDestroy) {
// Don't allow people to get or create the spell checker once the editor
// is going away.
*aInlineSpellChecker = nullptr;
return aAutoCreate ? NS_ERROR_NOT_AVAILABLE : NS_OK;
}
// We don't want to show the spell checking UI if there are no spell check
// dictionaries available.
if (!mozInlineSpellChecker::CanEnableInlineSpellChecking()) {
*aInlineSpellChecker = nullptr;
return NS_ERROR_FAILURE;
}
if (!mInlineSpellChecker && aAutoCreate) {
mInlineSpellChecker = new mozInlineSpellChecker();
}
if (mInlineSpellChecker) {
nsresult rv = mInlineSpellChecker->Init(this);
if (NS_FAILED(rv)) {
NS_WARNING("mozInlineSpellChecker::Init() failed");
mInlineSpellChecker = nullptr;
return rv;
}
}
*aInlineSpellChecker = do_AddRef(mInlineSpellChecker).take();
return NS_OK;
}
void EditorBase::SyncRealTimeSpell() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
bool enable = GetDesiredSpellCheckState();
// Initializes mInlineSpellChecker
nsCOMPtr<nsIInlineSpellChecker> spellChecker;
DebugOnly<nsresult> rvIgnored =
GetInlineSpellChecker(enable, getter_AddRefs(spellChecker));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::GetInlineSpellChecker() failed, but ignored");
if (mInlineSpellChecker) {
if (!mSpellCheckerDictionaryUpdated && enable) {
DebugOnly<nsresult> rvIgnored =
mInlineSpellChecker->UpdateCurrentDictionary();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"mozInlineSpellChecker::UpdateCurrentDictionary() "
"failed, but ignored");
mSpellCheckerDictionaryUpdated = true;
}
// We might have a mInlineSpellChecker even if there are no dictionaries
// available since we don't destroy the mInlineSpellChecker when the last
// dictionariy is removed, but in that case spellChecker is null
DebugOnly<nsresult> rvIgnored =
mInlineSpellChecker->SetEnableRealTimeSpell(enable && spellChecker);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"mozInlineSpellChecker::SetEnableRealTimeSpell() failed, but ignored");
}
}
NS_IMETHODIMP EditorBase::SetSpellcheckUserOverride(bool enable) {
mSpellcheckCheckboxState = enable ? eTriTrue : eTriFalse;
SyncRealTimeSpell();
return NS_OK;
}
NS_IMETHODIMP EditorBase::InsertNode(nsINode* aNodeToInsert,
nsINode* aContainer, uint32_t aOffset,
bool aPreserveSelection,
uint8_t aOptionalArgCount) {
MOZ_DIAGNOSTIC_ASSERT(IsHTMLEditor());
nsCOMPtr<nsIContent> contentToInsert =
nsIContent::FromNodeOrNull(aNodeToInsert);
if (NS_WARN_IF(!contentToInsert) || NS_WARN_IF(!aContainer)) {
return NS_ERROR_NULL_POINTER;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertNode);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
// Make dispatch `input` event after stopping preserving selection.
AutoPlaceholderBatch treatAsOneTransaction(
*this,
ScrollSelectionIntoView::No, // not a user interaction
__FUNCTION__);
Maybe<AutoTransactionsConserveSelection> preseveSelection;
if (aOptionalArgCount && aPreserveSelection) {
preseveSelection.emplace(*this);
}
const uint32_t offset = std::min(aOffset, aContainer->Length());
Result<CreateContentResult, nsresult> insertContentResult =
InsertNodeWithTransaction(*contentToInsert,
EditorDOMPoint(aContainer, offset));
if (MOZ_UNLIKELY(insertContentResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return EditorBase::ToGenericNSResult(insertContentResult.unwrapErr());
}
rv = insertContentResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateContentResult::SuggestCaretPointTo() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateContentResult::SuggestCaretPointTo() failed, but ignored");
return NS_OK;
}
template <typename ContentNodeType>
Result<CreateNodeResultBase<ContentNodeType>, nsresult>
EditorBase::InsertNodeWithTransaction(ContentNodeType& aContentToInsert,
const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT_IF(IsTextEditor(), !aContentToInsert.IsText());
if (NS_WARN_IF(!aPointToInsert.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
RefPtr<InsertNodeTransaction> transaction =
InsertNodeTransaction::Create(*this, aContentToInsert, aPointToInsert);
nsresult rv = DoTransactionInternal(transaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
DebugOnly<nsresult> rvIgnored =
RangeUpdaterRef().SelAdjInsertNode(aPointToInsert);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"RangeUpdater::SelAdjInsertNode() failed, but ignored");
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_WARN_IF(aContentToInsert.GetParentNode() !=
aPointToInsert.GetContainer())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (NS_FAILED(rv)) {
return Err(rv);
}
if (IsHTMLEditor()) {
TopLevelEditSubActionDataRef().DidInsertContent(*this, aContentToInsert);
}
return CreateNodeResultBase<ContentNodeType>(
&aContentToInsert, transaction->SuggestPointToPutCaret<EditorDOMPoint>());
}
Result<CreateElementResult, nsresult>
EditorBase::InsertPaddingBRElementForEmptyLastLineWithTransaction(
const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsHTMLEditor() || !aPointToInsert.IsInTextNode());
if (MOZ_UNLIKELY(!aPointToInsert.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
EditorDOMPoint pointToInsert;
if (IsTextEditor()) {
pointToInsert = aPointToInsert;
} else {
Result<EditorDOMPoint, nsresult> maybePointToInsert =
MOZ_KnownLive(AsHTMLEditor())->PrepareToInsertBRElement(aPointToInsert);
if (maybePointToInsert.isErr()) {
return maybePointToInsert.propagateErr();
}
MOZ_ASSERT(maybePointToInsert.inspect().IsSetAndValid());
pointToInsert = maybePointToInsert.unwrap();
}
RefPtr<Element> newBRElement = CreateHTMLContent(nsGkAtoms::br);
if (NS_WARN_IF(!newBRElement)) {
return Err(NS_ERROR_FAILURE);
}
newBRElement->SetFlags(NS_PADDING_FOR_EMPTY_LAST_LINE);
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertNodeWithTransaction<Element>(*newBRElement, pointToInsert);
NS_WARNING_ASSERTION(insertBRElementResult.isOk(),
"EditorBase::InsertNodeWithTransaction() failed");
return insertBRElementResult;
}
NS_IMETHODIMP EditorBase::DeleteNode(nsINode* aNode, bool aPreserveSelection,
uint8_t aOptionalArgCount) {
MOZ_ASSERT_UNREACHABLE("Do not use this API with TextEditor");
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult EditorBase::DeleteNodeWithTransaction(nsIContent& aContent) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT_IF(IsTextEditor(), !aContent.IsText());
// Do nothing if the node is read-only.
if (IsHTMLEditor() && NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(aContent))) {
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eDeleteNode, nsIEditor::ePrevious, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
if (IsHTMLEditor()) {
TopLevelEditSubActionDataRef().WillDeleteContent(*this, aContent);
}
// FYI: DeleteNodeTransaction grabs aContent while it's alive. So, it's safe
// to refer aContent even after calling DoTransaction().
RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
DeleteNodeTransaction::MaybeCreate(*this, aContent);
NS_WARNING_ASSERTION(deleteNodeTransaction,
"DeleteNodeTransaction::MaybeCreate() failed");
nsresult rv;
if (deleteNodeTransaction) {
rv = DoTransactionInternal(deleteNodeTransaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
if (mTextServicesDocument && NS_SUCCEEDED(rv)) {
RefPtr<TextServicesDocument> textServicesDocument = mTextServicesDocument;
textServicesDocument->DidDeleteContent(aContent);
}
} else {
rv = NS_ERROR_FAILURE;
}
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored = listener->DidDeleteNode(&aContent, rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidDeleteNode() failed, but ignored");
}
}
return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : rv;
}
NS_IMETHODIMP EditorBase::NotifySelectionChanged(Document* aDocument,
Selection* aSelection,
int16_t aReason,
int32_t aAmount) {
if (NS_WARN_IF(!aDocument) || NS_WARN_IF(!aSelection)) {
return NS_ERROR_INVALID_ARG;
}
if (mTextInputListener) {
RefPtr<TextInputListener> textInputListener = mTextInputListener;
textInputListener->OnSelectionChange(*aSelection, aReason);
}
if (mIMEContentObserver) {
RefPtr<IMEContentObserver> observer = mIMEContentObserver;
observer->OnSelectionChange(*aSelection);
}
return NS_OK;
}
void EditorBase::NotifyEditorObservers(
NotificationForEditorObservers aNotification) {
MOZ_ASSERT(IsEditActionDataAvailable());
switch (aNotification) {
case eNotifyEditorObserversOfEnd:
mIsInEditSubAction = false;
if (mEditActionData) {
mEditActionData->MarkAsHandled();
}
if (mTextInputListener) {
// TODO: TextInputListener::OnEditActionHandled() may return
// NS_ERROR_OUT_OF_MEMORY. If so and if
// TextControlState::SetValue() setting value with us, we should
// return the result to EditorBase::ReplaceTextAsAction(),
// EditorBase::DeleteSelectionAsAction() and
// TextEditor::InsertTextAsAction(). However, it requires a lot
// of changes in editor classes, but it's not so important since
// editor does not use fallible allocation. Therefore, normally,
// the process must be crashed anyway.
RefPtr<TextInputListener> listener = mTextInputListener;
nsresult rv =
listener->OnEditActionHandled(MOZ_KnownLive(*AsTextEditor()));
MOZ_RELEASE_ASSERT(rv != NS_ERROR_OUT_OF_MEMORY,
"Setting value failed due to out of memory");
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"TextInputListener::OnEditActionHandled() failed, but ignored");
}
if (mIMEContentObserver) {
RefPtr<IMEContentObserver> observer = mIMEContentObserver;
observer->OnEditActionHandled();
}
if (!mDispatchInputEvent || IsEditActionAborted() ||
IsEditActionCanceled()) {
break;
}
DispatchInputEvent();
break;
case eNotifyEditorObserversOfBefore:
if (NS_WARN_IF(mIsInEditSubAction)) {
return;
}
mIsInEditSubAction = true;
if (mIMEContentObserver) {
RefPtr<IMEContentObserver> observer = mIMEContentObserver;
observer->BeforeEditAction();
}
return;
case eNotifyEditorObserversOfCancel:
mIsInEditSubAction = false;
if (mEditActionData) {
mEditActionData->MarkAsHandled();
}
if (mIMEContentObserver) {
RefPtr<IMEContentObserver> observer = mIMEContentObserver;
observer->CancelEditAction();
}
break;
default:
MOZ_CRASH("Handle all notifications here");
break;
}
if (IsHTMLEditor() && !Destroyed()) {
// We may need to show resizing handles or update existing ones after
// all transactions are done. This way of doing is preferred to DOM
// mutation events listeners because all the changes the user can apply
// to a document may result in multiple events, some of them quite hard
// to listen too (in particular when an ancestor of the selection is
// changed but the selection itself is not changed).
DebugOnly<nsresult> rvIgnored =
MOZ_KnownLive(AsHTMLEditor())->RefreshEditingUI();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"HTMLEditor::RefreshEditingUI() failed, but ignored");
}
}
void EditorBase::DispatchInputEvent() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsEditActionCanceled(),
"If preceding beforeinput event is canceled, we shouldn't "
"dispatch input event");
MOZ_ASSERT(
!ShouldAlreadyHaveHandledBeforeInputEventDispatching(),
"We've not handled beforeinput event but trying to dispatch input event");
// We don't need to dispatch multiple input events if there is a pending
// input event. However, it may have different event target. If we resolved
// this issue, we need to manage the pending events in an array. But it's
// overwork. We don't need to do it for the very rare case.
// TODO: However, we start to set InputEvent.inputType. So, each "input"
// event now notifies web app each change. So, perhaps, we should
// not omit input events.
RefPtr<Element> targetElement = GetInputEventTargetElement();
if (NS_WARN_IF(!targetElement)) {
return;
}
RefPtr<DataTransfer> dataTransfer = GetInputEventDataTransfer();
DebugOnly<nsresult> rvIgnored = nsContentUtils::DispatchInputEvent(
targetElement, eEditorInput, ToInputType(GetEditAction()), this,
dataTransfer ? InputEventOptions(dataTransfer,
InputEventOptions::NeverCancelable::No)
: InputEventOptions(GetInputEventData(),
InputEventOptions::NeverCancelable::No));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsContentUtils::DispatchInputEvent() failed, but ignored");
}
NS_IMETHODIMP EditorBase::AddEditActionListener(
nsIEditActionListener* aListener) {
if (NS_WARN_IF(!aListener)) {
return NS_ERROR_INVALID_ARG;
}
// If given edit action listener is text services document for the inline
// spell checker, store it as reference of concrete class for performance
// reason.
if (mInlineSpellChecker) {
EditorSpellCheck* editorSpellCheck =
mInlineSpellChecker->GetEditorSpellCheck();
if (editorSpellCheck) {
mozSpellChecker* spellChecker = editorSpellCheck->GetSpellChecker();
if (spellChecker) {
TextServicesDocument* textServicesDocument =
spellChecker->GetTextServicesDocument();
if (static_cast<nsIEditActionListener*>(textServicesDocument) ==
aListener) {
mTextServicesDocument = textServicesDocument;
return NS_OK;
}
}
}
}
// Make sure the listener isn't already on the list
if (!mActionListeners.Contains(aListener)) {
mActionListeners.AppendElement(*aListener);
NS_WARNING_ASSERTION(
mActionListeners.Length() != 1,
"nsIEditActionListener installed, this editor becomes slower");
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::RemoveEditActionListener(
nsIEditActionListener* aListener) {
if (NS_WARN_IF(!aListener)) {
return NS_ERROR_INVALID_ARG;
}
if (static_cast<nsIEditActionListener*>(mTextServicesDocument) == aListener) {
mTextServicesDocument = nullptr;
return NS_OK;
}
NS_WARNING_ASSERTION(mActionListeners.Length() != 1,
"All nsIEditActionListeners have been removed, this "
"editor becomes faster");
mActionListeners.RemoveElement(aListener);
return NS_OK;
}
NS_IMETHODIMP EditorBase::AddDocumentStateListener(
nsIDocumentStateListener* aListener) {
if (NS_WARN_IF(!aListener)) {
return NS_ERROR_INVALID_ARG;
}
if (!mDocStateListeners.Contains(aListener)) {
mDocStateListeners.AppendElement(*aListener);
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::RemoveDocumentStateListener(
nsIDocumentStateListener* aListener) {
if (NS_WARN_IF(!aListener)) {
return NS_ERROR_INVALID_ARG;
}
mDocStateListeners.RemoveElement(aListener);
return NS_OK;
}
NS_IMETHODIMP EditorBase::ForceCompositionEnd() {
nsresult rv = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CommitComposition() failed");
return rv;
}
nsresult EditorBase::CommitComposition() {
nsPresContext* presContext = GetPresContext();
if (NS_WARN_IF(!presContext)) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!mComposition) {
return NS_OK;
}
nsresult rv =
IMEStateManager::NotifyIME(REQUEST_TO_COMMIT_COMPOSITION, presContext);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "IMEStateManager::NotifyIME() failed");
return rv;
}
nsresult EditorBase::GetPreferredIMEState(IMEState* aState) {
if (NS_WARN_IF(!aState)) {
return NS_ERROR_INVALID_ARG;
}
aState->mEnabled = IMEEnabled::Enabled;
aState->mOpen = IMEState::DONT_CHANGE_OPEN_STATE;
if (IsReadonly()) {
aState->mEnabled = IMEEnabled::Disabled;
return NS_OK;
}
Element* rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_FAILURE;
}
nsIFrame* frameForRootElement = rootElement->GetPrimaryFrame();
if (NS_WARN_IF(!frameForRootElement)) {
return NS_ERROR_FAILURE;
}
switch (frameForRootElement->StyleUIReset()->mIMEMode) {
case StyleImeMode::Auto:
if (IsPasswordEditor()) {
aState->mEnabled = IMEEnabled::Password;
}
break;
case StyleImeMode::Disabled:
// we should use password state for |ime-mode: disabled;|.
aState->mEnabled = IMEEnabled::Password;
break;
case StyleImeMode::Active:
aState->mOpen = IMEState::OPEN;
break;
case StyleImeMode::Inactive:
aState->mOpen = IMEState::CLOSED;
break;
case StyleImeMode::Normal:
break;
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetComposing(bool* aResult) {
if (NS_WARN_IF(!aResult)) {
return NS_ERROR_INVALID_ARG;
}
*aResult = IsIMEComposing();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetRootElement(Element** aRootElement) {
if (NS_WARN_IF(!aRootElement)) {
return NS_ERROR_INVALID_ARG;
}
*aRootElement = do_AddRef(mRootElement).take();
return NS_WARN_IF(!*aRootElement) ? NS_ERROR_NOT_AVAILABLE : NS_OK;
}
void EditorBase::OnStartToHandleTopLevelEditSubAction(
EditSubAction aTopLevelEditSubAction,
nsIEditor::EDirection aDirectionOfTopLevelEditSubAction, ErrorResult& aRv) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aRv.Failed());
mEditActionData->SetTopLevelEditSubAction(aTopLevelEditSubAction,
aDirectionOfTopLevelEditSubAction);
}
nsresult EditorBase::OnEndHandlingTopLevelEditSubAction() {
MOZ_ASSERT(IsEditActionDataAvailable());
mEditActionData->SetTopLevelEditSubAction(EditSubAction::eNone, eNone);
return NS_OK;
}
void EditorBase::DoInsertText(Text& aText, uint32_t aOffset,
const nsAString& aStringToInsert,
ErrorResult& aRv) {
aText.InsertData(aOffset, aStringToInsert, aRv);
if (NS_WARN_IF(Destroyed())) {
aRv = NS_ERROR_EDITOR_DESTROYED;
return;
}
if (aRv.Failed()) {
NS_WARNING("Text::InsertData() failed");
return;
}
if (IsTextEditor() && !aStringToInsert.IsEmpty()) {
aRv = MOZ_KnownLive(AsTextEditor())
->DidInsertText(aText.TextLength(), aOffset,
aStringToInsert.Length());
NS_WARNING_ASSERTION(!aRv.Failed(), "TextEditor::DidInsertText() failed");
}
}
void EditorBase::DoDeleteText(Text& aText, uint32_t aOffset, uint32_t aCount,
ErrorResult& aRv) {
if (IsTextEditor() && aCount > 0) {
AsTextEditor()->WillDeleteText(aText.TextLength(), aOffset, aCount);
}
aText.DeleteData(aOffset, aCount, aRv);
if (NS_WARN_IF(Destroyed())) {
aRv = NS_ERROR_EDITOR_DESTROYED;
return;
}
NS_WARNING_ASSERTION(!aRv.Failed(), "Text::DeleteData() failed");
}
void EditorBase::DoReplaceText(Text& aText, uint32_t aOffset, uint32_t aCount,
const nsAString& aStringToInsert,
ErrorResult& aRv) {
if (IsTextEditor() && aCount > 0) {
AsTextEditor()->WillDeleteText(aText.TextLength(), aOffset, aCount);
}
aText.ReplaceData(aOffset, aCount, aStringToInsert, aRv);
if (NS_WARN_IF(Destroyed())) {
aRv = NS_ERROR_EDITOR_DESTROYED;
return;
}
if (aRv.Failed()) {
NS_WARNING("Text::ReplaceData() failed");
return;
}
if (IsTextEditor() && !aStringToInsert.IsEmpty()) {
aRv = MOZ_KnownLive(AsTextEditor())
->DidInsertText(aText.TextLength(), aOffset,
aStringToInsert.Length());
NS_WARNING_ASSERTION(!aRv.Failed(), "TextEditor::DidInsertText() failed");
}
}
void EditorBase::DoSetText(Text& aText, const nsAString& aStringToSet,
ErrorResult& aRv) {
if (IsTextEditor()) {
uint32_t length = aText.TextLength();
if (length > 0) {
AsTextEditor()->WillDeleteText(length, 0, length);
}
}
aText.SetData(aStringToSet, aRv);
if (NS_WARN_IF(Destroyed())) {
aRv = NS_ERROR_EDITOR_DESTROYED;
return;
}
if (aRv.Failed()) {
NS_WARNING("Text::SetData() failed");
return;
}
if (IsTextEditor() && !aStringToSet.IsEmpty()) {
aRv = MOZ_KnownLive(AsTextEditor())
->DidInsertText(aText.Length(), 0, aStringToSet.Length());
NS_WARNING_ASSERTION(!aRv.Failed(), "TextEditor::DidInsertText() failed");
}
}
nsresult EditorBase::CloneAttributeWithTransaction(nsAtom& aAttribute,
Element& aDestElement,
Element& aSourceElement) {
nsAutoString attrValue;
if (aSourceElement.GetAttr(&aAttribute, attrValue)) {
nsresult rv =
SetAttributeWithTransaction(aDestElement, aAttribute, attrValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction() failed");
return rv;
}
nsresult rv = RemoveAttributeWithTransaction(aDestElement, aAttribute);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction() failed");
return rv;
}
NS_IMETHODIMP EditorBase::CloneAttributes(Element* aDestElement,
Element* aSourceElement) {
if (NS_WARN_IF(!aDestElement) || NS_WARN_IF(!aSourceElement)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eSetAttribute);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
CloneAttributesWithTransaction(*aDestElement, *aSourceElement);
return NS_OK;
}
void EditorBase::CloneAttributesWithTransaction(Element& aDestElement,
Element& aSourceElement) {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
// Use transaction system for undo only if destination is already in the
// document
Element* rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return;
}
OwningNonNull<Element> destElement(aDestElement);
OwningNonNull<Element> sourceElement(aSourceElement);
bool isDestElementInBody = rootElement->Contains(destElement);
// Clear existing attributes
RefPtr<nsDOMAttributeMap> destAttributes = destElement->Attributes();
while (RefPtr<Attr> attr = destAttributes->Item(0)) {
if (isDestElementInBody) {
DebugOnly<nsresult> rvIgnored = RemoveAttributeWithTransaction(
destElement, MOZ_KnownLive(*attr->NodeInfo()->NameAtom()));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::RemoveAttributeWithTransaction() failed, but ignored");
} else {
DebugOnly<nsresult> rvIgnored = destElement->UnsetAttr(
kNameSpaceID_None, attr->NodeInfo()->NameAtom(), true);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Element::UnsetAttr() failed, but ignored");
}
}
// Set just the attributes that the source element has
RefPtr<nsDOMAttributeMap> sourceAttributes = sourceElement->Attributes();
uint32_t sourceCount = sourceAttributes->Length();
for (uint32_t i = 0; i < sourceCount; i++) {
RefPtr<Attr> attr = sourceAttributes->Item(i);
nsAutoString value;
attr->GetValue(value);
if (isDestElementInBody) {
DebugOnly<nsresult> rvIgnored = SetAttributeOrEquivalent(
destElement, MOZ_KnownLive(attr->NodeInfo()->NameAtom()), value,
false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::SetAttributeOrEquivalent() failed, but ignored");
} else {
// The element is not inserted in the document yet, we don't want to put
// a transaction on the UndoStack
DebugOnly<nsresult> rvIgnored = SetAttributeOrEquivalent(
destElement, MOZ_KnownLive(attr->NodeInfo()->NameAtom()), value,
true);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::SetAttributeOrEquivalent() failed, but ignored");
}
}
}
nsresult EditorBase::ScrollSelectionFocusIntoView() const {
nsISelectionController* selectionController = GetSelectionController();
if (!selectionController) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored = selectionController->ScrollSelectionIntoView(
nsISelectionController::SELECTION_NORMAL,
nsISelectionController::SELECTION_FOCUS_REGION,
nsISelectionController::SCROLL_OVERFLOW_HIDDEN);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::ScrollSelectionIntoView() failed, but ignored");
return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : NS_OK;
}
Result<InsertTextResult, nsresult> EditorBase::InsertTextWithTransaction(
Document& aDocument, const nsAString& aStringToInsert,
const EditorDOMPoint& aPointToInsert) {
if (NS_WARN_IF(!aPointToInsert.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
if (!ShouldHandleIMEComposition() && aStringToInsert.IsEmpty()) {
return InsertTextResult();
}
// In some cases, the node may be the anonymous div element or a padding
// <br> element for empty last line. Let's try to look for better insertion
// point in the nearest text node if there is.
EditorDOMPoint pointToInsert = [&]() {
if (IsTextEditor()) {
return AsTextEditor()->FindBetterInsertionPoint(aPointToInsert);
}
return aPointToInsert
.GetPointInTextNodeIfPointingAroundTextNode<EditorDOMPoint>();
}();
if (ShouldHandleIMEComposition()) {
if (!pointToInsert.IsInTextNode()) {
// create a text node
RefPtr<nsTextNode> newTextNode = CreateTextNode(u""_ns);
if (NS_WARN_IF(!newTextNode)) {
return Err(NS_ERROR_FAILURE);
}
// then we insert it into the dom tree
Result<CreateTextResult, nsresult> insertTextNodeResult =
InsertNodeWithTransaction<Text>(*newTextNode, pointToInsert);
if (MOZ_UNLIKELY(insertTextNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertTextNodeResult.propagateErr();
}
insertTextNodeResult.unwrap().IgnoreCaretPointSuggestion();
pointToInsert.Set(newTextNode, 0u);
}
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextIntoTextNodeWithTransaction(aStringToInsert,
pointToInsert.AsInText());
NS_WARNING_ASSERTION(
insertTextResult.isOk(),
"EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
return insertTextResult;
}
if (pointToInsert.IsInTextNode()) {
// we are inserting text into an existing text node.
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextIntoTextNodeWithTransaction(aStringToInsert,
pointToInsert.AsInText());
NS_WARNING_ASSERTION(
insertTextResult.isOk(),
"EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
return insertTextResult;
}
// we are inserting text into a non-text node. first we have to create a
// textnode (this also populates it with the text)
RefPtr<nsTextNode> newTextNode = CreateTextNode(aStringToInsert);
if (NS_WARN_IF(!newTextNode)) {
return Err(NS_ERROR_FAILURE);
}
// then we insert it into the dom tree
Result<CreateTextResult, nsresult> insertTextNodeResult =
InsertNodeWithTransaction<Text>(*newTextNode, pointToInsert);
if (MOZ_UNLIKELY(insertTextNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return Err(insertTextNodeResult.unwrapErr());
}
insertTextNodeResult.unwrap().IgnoreCaretPointSuggestion();
if (NS_WARN_IF(!newTextNode->IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return InsertTextResult(EditorDOMPointInText::AtEndOf(*newTextNode),
EditorDOMPoint::AtEndOf(*newTextNode));
}
static bool TextFragmentBeginsWithStringAtOffset(
const nsTextFragment& aTextFragment, const uint32_t aOffset,
const nsAString& aString) {
const uint32_t stringLength = aString.Length();
if (aOffset + stringLength > aTextFragment.GetLength()) {
return false;
}
if (aTextFragment.Is2b()) {
return aString.Equals(aTextFragment.Get2b() + aOffset);
}
return aString.EqualsLatin1(aTextFragment.Get1b() + aOffset, stringLength);
}
static std::tuple<EditorDOMPointInText, EditorDOMPointInText>
AdjustTextInsertionRange(const EditorDOMPointInText& aInsertedPoint,
const nsAString& aInsertedString) {
if (TextFragmentBeginsWithStringAtOffset(
aInsertedPoint.ContainerAs<Text>()->TextFragment(),
aInsertedPoint.Offset(), aInsertedString)) {
return {aInsertedPoint,
EditorDOMPointInText(
aInsertedPoint.ContainerAs<Text>(),
aInsertedPoint.Offset() + aInsertedString.Length())};
}
return {EditorDOMPointInText(aInsertedPoint.ContainerAs<Text>(), 0),
EditorDOMPointInText::AtEndOf(*aInsertedPoint.ContainerAs<Text>())};
}
std::tuple<EditorDOMPointInText, EditorDOMPointInText>
EditorBase::ComputeInsertedRange(const EditorDOMPointInText& aInsertedPoint,
const nsAString& aInsertedString) const {
MOZ_ASSERT(aInsertedPoint.IsSet());
// The DOM was potentially modified during the transaction. This is possible
// through mutation event listeners. That is, the node could've been removed
// from the doc or otherwise modified.
if (!MayHaveMutationEventListeners(
NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED)) {
EditorDOMPointInText endOfInsertion(
aInsertedPoint.ContainerAs<Text>(),
aInsertedPoint.Offset() + aInsertedString.Length());
return {aInsertedPoint, endOfInsertion};
}
if (aInsertedPoint.ContainerAs<Text>()->IsInComposedDoc()) {
EditorDOMPointInText begin, end;
return AdjustTextInsertionRange(aInsertedPoint, aInsertedString);
}
return {EditorDOMPointInText(), EditorDOMPointInText()};
}
Result<InsertTextResult, nsresult>
EditorBase::InsertTextIntoTextNodeWithTransaction(
const nsAString& aStringToInsert,
const EditorDOMPointInText& aPointToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
RefPtr<EditTransactionBase> transaction;
bool isIMETransaction = false;
if (ShouldHandleIMEComposition()) {
transaction =
CompositionTransaction::Create(*this, aStringToInsert, aPointToInsert);
isIMETransaction = true;
} else {
transaction =
InsertTextTransaction::Create(*this, aStringToInsert, aPointToInsert);
}
// XXX We may not need these view batches anymore. This is handled at a
// higher level now I believe.
BeginUpdateViewBatch(__FUNCTION__);
nsresult rv = DoTransactionInternal(transaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
EndUpdateViewBatch(__FUNCTION__);
// Don't check whether we've been destroyed here because we need to notify
// listeners and observers below even if we've already destroyed.
auto pointToInsert = [&]() -> EditorDOMPointInText {
if (!isIMETransaction) {
return aPointToInsert;
}
if (NS_WARN_IF(!mComposition->GetContainerTextNode())) {
return aPointToInsert;
}
return EditorDOMPointInText(
mComposition->GetContainerTextNode(),
std::min(mComposition->XPOffsetInTextNode(),
mComposition->GetContainerTextNode()->TextDataLength()));
}();
EditorDOMPointInText endOfInsertedText(
pointToInsert.ContainerAs<Text>(),
pointToInsert.Offset() + aStringToInsert.Length());
if (IsHTMLEditor()) {
auto [begin, end] = ComputeInsertedRange(pointToInsert, aStringToInsert);
if (begin.IsSet() && end.IsSet()) {
TopLevelEditSubActionDataRef().DidInsertText(
*this, begin.To<EditorRawDOMPoint>(), end.To<EditorRawDOMPoint>());
}
if (isIMETransaction) {
// Let's mark the text node as "modified frequently" if it interact with
// IME since non-ASCII character may be inserted into it in most cases.
pointToInsert.ContainerAs<Text>()->MarkAsMaybeModifiedFrequently();
}
// XXX Should we update endOfInsertedText here?
}
// let listeners know what happened
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
// TODO: might need adaptation because of mutation event listeners called
// during `DoTransactionInternal`.
DebugOnly<nsresult> rvIgnored = listener->DidInsertText(
pointToInsert.ContainerAs<Text>(),
static_cast<int32_t>(pointToInsert.Offset()), aStringToInsert, rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidInsertText() failed, but ignored");
}
}
// Added some cruft here for bug 43366. Layout was crashing because we left
// an empty text node lying around in the document. So I delete empty text
// nodes caused by IME. I have to mark the IME transaction as "fixed", which
// means that furure IME txns won't merge with it. This is because we don't
// want future IME txns trying to put their text into a node that is no
// longer in the document. This does not break undo/redo, because all these
// txns are wrapped in a parent PlaceHolder txn, and placeholder txns are
// already savvy to having multiple ime txns inside them.
// Delete empty IME text node if there is one
if (IsHTMLEditor() && isIMETransaction && mComposition) {
RefPtr<Text> textNode = mComposition->GetContainerTextNode();
if (textNode && !textNode->Length()) {
rv = DeleteNodeWithTransaction(*textNode);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeTransaction() failed");
if (MOZ_LIKELY(!textNode->IsInComposedDoc())) {
mComposition->OnTextNodeRemoved();
}
static_cast<CompositionTransaction*>(transaction.get())->MarkFixed();
}
}
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
InsertTextTransaction* const insertTextTransaction =
transaction->GetAsInsertTextTransaction();
return insertTextTransaction
? InsertTextResult(std::move(endOfInsertedText),
insertTextTransaction
->SuggestPointToPutCaret<EditorDOMPoint>())
: InsertTextResult(std::move(endOfInsertedText));
}
nsresult EditorBase::NotifyDocumentListeners(
TDocumentListenerNotification aNotificationType) {
switch (aNotificationType) {
case eDocumentCreated:
if (IsTextEditor()) {
return NS_OK;
}
if (RefPtr<ComposerCommandsUpdater> composerCommandsUpdate =
AsHTMLEditor()->mComposerCommandsUpdater) {
composerCommandsUpdate->OnHTMLEditorCreated();
}
return NS_OK;
case eDocumentToBeDestroyed: {
RefPtr<ComposerCommandsUpdater> composerCommandsUpdate =
IsHTMLEditor() ? AsHTMLEditor()->mComposerCommandsUpdater : nullptr;
if (!mDocStateListeners.Length() && !composerCommandsUpdate) {
return NS_OK;
}
// Needs to store all listeners before notifying ComposerCommandsUpdate
// since notifying it might change mDocStateListeners.
const AutoDocumentStateListenerArray listeners(
mDocStateListeners.Clone());
if (composerCommandsUpdate) {
composerCommandsUpdate->OnBeforeHTMLEditorDestroyed();
}
for (auto& listener : listeners) {
// MOZ_KnownLive because 'listeners' is guaranteed to
// keep it alive.
//
// This can go away once
// https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
nsresult rv = MOZ_KnownLive(listener)->NotifyDocumentWillBeDestroyed();
if (NS_FAILED(rv)) {
NS_WARNING(
"nsIDocumentStateListener::NotifyDocumentWillBeDestroyed() "
"failed");
return rv;
}
}
return NS_OK;
}
case eDocumentStateChanged: {
bool docIsDirty;
nsresult rv = GetDocumentModified(&docIsDirty);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::GetDocumentModified() failed");
return rv;
}
if (static_cast<int8_t>(docIsDirty) == mDocDirtyState) {
return NS_OK;
}
mDocDirtyState = docIsDirty;
RefPtr<ComposerCommandsUpdater> composerCommandsUpdate =
IsHTMLEditor() ? AsHTMLEditor()->mComposerCommandsUpdater : nullptr;
if (!mDocStateListeners.Length() && !composerCommandsUpdate) {
return NS_OK;
}
// Needs to store all listeners before notifying ComposerCommandsUpdate
// since notifying it might change mDocStateListeners.
const AutoDocumentStateListenerArray listeners(
mDocStateListeners.Clone());
if (composerCommandsUpdate) {
composerCommandsUpdate->OnHTMLEditorDirtyStateChanged(mDocDirtyState);
}
for (auto& listener : listeners) {
// MOZ_KnownLive because 'listeners' is guaranteed to
// keep it alive.
//
// This can go away once
// https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
nsresult rv =
MOZ_KnownLive(listener)->NotifyDocumentStateChanged(mDocDirtyState);
if (NS_FAILED(rv)) {
NS_WARNING(
"nsIDocumentStateListener::NotifyDocumentStateChanged() failed");
return rv;
}
}
return NS_OK;
}
default:
MOZ_ASSERT_UNREACHABLE("Unknown notification");
return NS_ERROR_FAILURE;
}
}
nsresult EditorBase::SetTextNodeWithoutTransaction(const nsAString& aString,
Text& aTextNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsTextEditor());
MOZ_ASSERT(!IsUndoRedoEnabled());
const uint32_t length = aTextNode.Length();
// Let listeners know what's up
if (!mActionListeners.IsEmpty() && length) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->WillDeleteText(MOZ_KnownLive(&aTextNode), 0, length);
if (NS_WARN_IF(Destroyed())) {
NS_WARNING(
"nsIEditActionListener::WillDeleteText() failed, but ignored");
return NS_ERROR_EDITOR_DESTROYED;
}
}
}
// We don't support undo here, so we don't really need all of the transaction
// machinery, therefore we can run our transaction directly, breaking all of
// the rules!
IgnoredErrorResult error;
DoSetText(aTextNode, aString, error);
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("EditorBase::DoSetText() failed");
return error.StealNSResult();
}
CollapseSelectionTo(EditorRawDOMPoint(&aTextNode, aString.Length()), error);
if (MOZ_UNLIKELY(error.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
NS_WARNING("EditorBase::CollapseSelection() caused destroying the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_ASSERTION(!error.Failed(),
"EditorBase::CollapseSelectionTo() failed, but ignored");
RangeUpdaterRef().SelAdjReplaceText(aTextNode, 0, length, aString.Length());
// Let listeners know what happened
if (!mActionListeners.IsEmpty() && !aString.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->DidInsertText(&aTextNode, 0, aString, NS_OK);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidInsertText() failed, but ignored");
}
}
return NS_OK;
}
Result<CaretPoint, nsresult> EditorBase::DeleteTextWithTransaction(
Text& aTextNode, uint32_t aOffset, uint32_t aLength) {
MOZ_ASSERT(IsEditActionDataAvailable());
RefPtr<DeleteTextTransaction> transaction =
DeleteTextTransaction::MaybeCreate(*this, aTextNode, aOffset, aLength);
if (MOZ_UNLIKELY(!transaction)) {
NS_WARNING("DeleteTextTransaction::MaybeCreate() failed");
return Err(NS_ERROR_FAILURE);
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eDeleteText, nsIEditor::ePrevious, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// Let listeners know what's up
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->WillDeleteText(&aTextNode, aOffset, aLength);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::WillDeleteText() failed, but ignored");
}
}
nsresult rv = DoTransactionInternal(transaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
if (IsHTMLEditor()) {
TopLevelEditSubActionDataRef().DidDeleteText(
*this, EditorRawDOMPoint(&aTextNode, aOffset));
}
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
return Err(rv);
}
return CaretPoint(transaction->SuggestPointToPutCaret());
}
bool EditorBase::IsRoot(const nsINode* inNode) const {
if (NS_WARN_IF(!inNode)) {
return false;
}
nsINode* rootNode = GetRoot();
return inNode == rootNode;
}
bool EditorBase::IsDescendantOfRoot(const nsINode* inNode) const {
if (NS_WARN_IF(!inNode)) {
return false;
}
nsIContent* root = GetRoot();
if (NS_WARN_IF(!root)) {
return false;
}
return inNode->IsInclusiveDescendantOf(root);
}
NS_IMETHODIMP EditorBase::IncrementModificationCount(int32_t inNumMods) {
uint32_t oldModCount = mModCount;
mModCount += inNumMods;
if ((!oldModCount && mModCount) || (oldModCount && !mModCount)) {
DebugOnly<nsresult> rvIgnored =
NotifyDocumentListeners(eDocumentStateChanged);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::NotifyDocumentListeners() failed, but ignored");
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetModificationCount(int32_t* aOutModCount) {
if (NS_WARN_IF(!aOutModCount)) {
return NS_ERROR_INVALID_ARG;
}
*aOutModCount = mModCount;
return NS_OK;
}
NS_IMETHODIMP EditorBase::ResetModificationCount() {
bool doNotify = (mModCount != 0);
mModCount = 0;
if (!doNotify) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored =
NotifyDocumentListeners(eDocumentStateChanged);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::NotifyDocumentListeners() failed, but ignored");
return NS_OK;
}
template <typename EditorDOMPointType>
EditorDOMPointType EditorBase::GetFirstSelectionStartPoint() const {
MOZ_ASSERT(IsEditActionDataAvailable());
if (MOZ_UNLIKELY(!SelectionRef().RangeCount())) {
return EditorDOMPointType();
}
const nsRange* range = SelectionRef().GetRangeAt(0);
if (MOZ_UNLIKELY(NS_WARN_IF(!range) || NS_WARN_IF(!range->IsPositioned()))) {
return EditorDOMPointType();
}
return EditorDOMPointType(range->StartRef());
}
template <typename EditorDOMPointType>
EditorDOMPointType EditorBase::GetFirstSelectionEndPoint() const {
MOZ_ASSERT(IsEditActionDataAvailable());
if (MOZ_UNLIKELY(!SelectionRef().RangeCount())) {
return EditorDOMPointType();
}
const nsRange* range = SelectionRef().GetRangeAt(0);
if (MOZ_UNLIKELY(NS_WARN_IF(!range) || NS_WARN_IF(!range->IsPositioned()))) {
return EditorDOMPointType();
}
return EditorDOMPointType(range->EndRef());
}
// static
nsresult EditorBase::GetEndChildNode(const Selection& aSelection,
nsIContent** aEndNode) {
MOZ_ASSERT(aEndNode);
*aEndNode = nullptr;
if (NS_WARN_IF(!aSelection.RangeCount())) {
return NS_ERROR_FAILURE;
}
const nsRange* range = aSelection.GetRangeAt(0);
if (NS_WARN_IF(!range)) {
return NS_ERROR_FAILURE;
}
if (NS_WARN_IF(!range->IsPositioned())) {
return NS_ERROR_FAILURE;
}
NS_IF_ADDREF(*aEndNode = range->GetChildAtEndOffset());
return NS_OK;
}
nsresult EditorBase::EnsurePaddingBRElementInMultilineEditor() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsTextEditor() || AsHTMLEditor()->IsPlaintextMailComposer());
MOZ_ASSERT(!IsSingleLineEditor());
Element* anonymousDivOrBodyElement = GetRoot();
if (NS_WARN_IF(!anonymousDivOrBodyElement)) {
return NS_ERROR_FAILURE;
}
// Assuming EditorBase::MaybeCreatePaddingBRElementForEmptyEditor() has been
// called first.
// XXX This assumption is wrong. This method may be called alone. Actually,
// we see this warning in mochitest log. So, we should fix this bug
// later.
if (NS_WARN_IF(!anonymousDivOrBodyElement->GetLastChild())) {
return NS_ERROR_FAILURE;
}
RefPtr<HTMLBRElement> brElement =
HTMLBRElement::FromNode(anonymousDivOrBodyElement->GetLastChild());
if (!brElement) {
// TODO: Remove AutoTransactionsConserveSelection here. It's not necessary
// in normal cases. However, it may be required for nested edit
// actions which may be caused by legacy mutation event listeners or
// chrome script.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
EditorDOMPoint endOfAnonymousDiv(
EditorDOMPoint::AtEndOf(*anonymousDivOrBodyElement));
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
endOfAnonymousDiv);
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"EditorBase::InsertPaddingBRElementForEmptyLastLineWithTransaction() "
"failed");
return insertPaddingBRElementResult.unwrapErr();
}
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
}
// Check to see if the trailing BR is a former padding <br> element for empty
// editor - this will have stuck around if we previously morphed a trailing
// node into a padding <br> element.
if (!brElement->IsPaddingForEmptyEditor()) {
return NS_OK;
}
// Morph it back to a padding <br> element for empty last line.
brElement->UnsetFlags(NS_PADDING_FOR_EMPTY_EDITOR);
brElement->SetFlags(NS_PADDING_FOR_EMPTY_LAST_LINE);
return NS_OK;
}
void EditorBase::BeginUpdateViewBatch(const char* aRequesterFuncName) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(mUpdateCount >= 0, "bad state");
if (!mUpdateCount) {
// Turn off selection updates and notifications.
SelectionRef().StartBatchChanges(aRequesterFuncName);
}
mUpdateCount++;
}
void EditorBase::EndUpdateViewBatch(const char* aRequesterFuncName) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(mUpdateCount > 0, "bad state");
if (NS_WARN_IF(mUpdateCount <= 0)) {
mUpdateCount = 0;
return;
}
if (--mUpdateCount) {
return;
}
// Turn selection updating and notifications back on.
SelectionRef().EndBatchChanges(aRequesterFuncName);
}
TextComposition* EditorBase::GetComposition() const { return mComposition; }
template <typename EditorDOMPointType>
EditorDOMPointType EditorBase::GetFirstIMESelectionStartPoint() const {
return mComposition
? EditorDOMPointType(mComposition->FirstIMESelectionStartRef())
: EditorDOMPointType();
}
template <typename EditorDOMPointType>
EditorDOMPointType EditorBase::GetLastIMESelectionEndPoint() const {
return mComposition
? EditorDOMPointType(mComposition->LastIMESelectionEndRef())
: EditorDOMPointType();
}
bool EditorBase::IsIMEComposing() const {
return mComposition && mComposition->IsComposing();
}
bool EditorBase::ShouldHandleIMEComposition() const {
// When the editor is being reframed, the old value may be restored with
// InsertText(). In this time, the text should be inserted as not a part
// of the composition.
return mComposition && mDidPostCreate;
}
bool EditorBase::EnsureComposition(WidgetCompositionEvent& aCompositionEvent) {
if (mComposition) {
return true;
}
// The compositionstart event must cause creating new TextComposition
// instance at being dispatched by IMEStateManager.
mComposition = IMEStateManager::GetTextCompositionFor(&aCompositionEvent);
if (!mComposition) {
// However, TextComposition may be committed before the composition
// event comes here.
return false;
}
mComposition->StartHandlingComposition(this);
return true;
}
nsresult EditorBase::OnCompositionStart(
WidgetCompositionEvent& aCompositionStartEvent) {
if (mComposition) {
NS_WARNING("There was a composition at receiving compositionstart event");
return NS_OK;
}
// "beforeinput" event shouldn't be fired before "compositionstart".
AutoEditActionDataSetter editActionData(*this, EditAction::eStartComposition);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
EnsureComposition(aCompositionStartEvent);
NS_WARNING_ASSERTION(mComposition, "Failed to get TextComposition instance?");
return NS_OK;
}
nsresult EditorBase::OnCompositionChange(
WidgetCompositionEvent& aCompositionChangeEvent) {
MOZ_ASSERT(aCompositionChangeEvent.mMessage == eCompositionChange,
"The event should be eCompositionChange");
if (!mComposition) {
NS_WARNING(
"There is no composition, but receiving compositionchange event");
return NS_ERROR_FAILURE;
}
AutoEditActionDataSetter editActionData(*this,
EditAction::eUpdateComposition);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
// If:
// - new composition string is not empty,
// - there is no composition string in the DOM tree,
// - and there is non-collapsed Selection,
// the selected content will be removed by this composition.
if (aCompositionChangeEvent.mData.IsEmpty() &&
mComposition->String().IsEmpty() && !SelectionRef().IsCollapsed()) {
editActionData.UpdateEditAction(EditAction::eDeleteByComposition);
}
// If Input Events Level 2 is enabled, EditAction::eDeleteByComposition is
// mapped to EditorInputType::eDeleteByComposition and it requires null
// for InputEvent.data. Therefore, only otherwise, we should set data.
if (ToInputType(editActionData.GetEditAction()) !=
EditorInputType::eDeleteByComposition) {
MOZ_ASSERT(ToInputType(editActionData.GetEditAction()) ==
EditorInputType::eInsertCompositionText);
MOZ_ASSERT(!aCompositionChangeEvent.mData.IsVoid());
editActionData.SetData(aCompositionChangeEvent.mData);
}
// If we're an `HTMLEditor` and this is second or later composition change,
// we should set target range to the range of composition string.
// Otherwise, set target ranges to selection ranges (will be done by
// editActionData itself before dispatching `beforeinput` event).
if (IsHTMLEditor() && mComposition->GetContainerTextNode()) {
RefPtr<StaticRange> targetRange = StaticRange::Create(
mComposition->GetContainerTextNode(),
mComposition->XPOffsetInTextNode(),
mComposition->GetContainerTextNode(),
mComposition->XPEndOffsetInTextNode(), IgnoreErrors());
NS_WARNING_ASSERTION(targetRange && targetRange->IsPositioned(),
"StaticRange::Create() failed");
if (targetRange && targetRange->IsPositioned()) {
editActionData.AppendTargetRange(*targetRange);
}
}
// TODO: We need to use different EditAction value for beforeinput event
// if the event is followed by "compositionend" because corresponding
// "input" event will be fired from OnCompositionEnd() later with
// different EditAction value.
// TODO: If Input Events Level 2 is enabled, "beforeinput" event may be
// actually canceled if edit action is eDeleteByComposition. In such
// case, we might need to keep selected text, but insert composition
// string before or after the selection. However, the spec is still
// unstable. We should keep handling the composition since other
// parts including widget may not be ready for such complicated
// behavior.
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (rv != NS_ERROR_EDITOR_ACTION_CANCELED && NS_FAILED(rv)) {
NS_WARNING("MaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
if (!EnsureComposition(aCompositionChangeEvent)) {
NS_WARNING("EditorBase::EnsureComposition() failed");
return NS_OK;
}
if (NS_WARN_IF(!GetPresShell())) {
return NS_ERROR_NOT_INITIALIZED;
}
// NOTE: TextComposition should receive selection change notification before
// CompositionChangeEventHandlingMarker notifies TextComposition of the
// end of handling compositionchange event because TextComposition may
// need to ignore selection changes caused by composition. Therefore,
// CompositionChangeEventHandlingMarker must be destroyed after a call
// of NotifiyEditorObservers(eNotifyEditorObserversOfEnd) or
// NotifiyEditorObservers(eNotifyEditorObserversOfCancel) which notifies
// TextComposition of a selection change.
MOZ_ASSERT(
!mPlaceholderBatch,
"UpdateIMEComposition() must be called without place holder batch");
nsString data(aCompositionChangeEvent.mData);
if (IsHTMLEditor()) {
nsContentUtils::PlatformToDOMLineBreaks(data);
}
{
// This needs to be destroyed before dispatching "input" event from
// the following call of `NotifyEditorObservers`. Therefore, we need to
// put this in this block rather than outside of this.
const bool wasComposing = mComposition->IsComposing();
TextComposition::CompositionChangeEventHandlingMarker
compositionChangeEventHandlingMarker(mComposition,
&aCompositionChangeEvent);
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::IMETxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
// XXX Why don't we get caret after the DOM mutation?
RefPtr<nsCaret> caret = GetCaret();
MOZ_ASSERT(
mIsInEditSubAction,
"AutoPlaceholderBatch should've notified the observes of before-edit");
// If we're updating composition, we need to ignore normal selection
// which may be updated by the web content.
rv = InsertTextAsSubAction(data, wasComposing ? SelectionHandling::Ignore
: SelectionHandling::Delete);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
if (caret) {
caret->SetSelection(&SelectionRef());
}
}
// If still composing, we should fire input event via observer.
// Note that if the composition will be committed by the following
// compositionend event, we don't need to notify editor observes of this
// change.
// NOTE: We must notify after the auto batch will be gone.
if (!aCompositionChangeEvent.IsFollowedByCompositionEnd()) {
// If we're a TextEditor, we'll be initialized with a new anonymous subtree,
// which can be caused by reframing from a "input" event listener. At that
// time, we'll move composition from current text node to the new text node
// with using mComposition's data. Therefore, it's important that
// mComposition already has the latest information here.
MOZ_ASSERT_IF(mComposition, mComposition->String() == data);
NotifyEditorObservers(eNotifyEditorObserversOfEnd);
}
return EditorBase::ToGenericNSResult(rv);
}
void EditorBase::OnCompositionEnd(
WidgetCompositionEvent& aCompositionEndEvent) {
if (!mComposition) {
NS_WARNING("There is no composition, but receiving compositionend event");
return;
}
EditAction editAction = aCompositionEndEvent.mData.IsEmpty()
? EditAction::eCancelComposition
: EditAction::eCommitComposition;
AutoEditActionDataSetter editActionData(*this, editAction);
// If Input Events Level 2 is enabled, EditAction::eCancelComposition is
// mapped to EditorInputType::eDeleteCompositionText and it requires null
// for InputEvent.data. Therefore, only otherwise, we should set data.
if (ToInputType(editAction) != EditorInputType::eDeleteCompositionText) {
MOZ_ASSERT(
ToInputType(editAction) == EditorInputType::eInsertCompositionText ||
ToInputType(editAction) == EditorInputType::eInsertFromComposition);
MOZ_ASSERT(!aCompositionEndEvent.mData.IsVoid());
editActionData.SetData(aCompositionEndEvent.mData);
}
// commit the IME transaction..we can get at it via the transaction mgr.
// Note that this means IME won't work without an undo stack!
if (mTransactionManager) {
if (nsCOMPtr<nsITransaction> transaction =
mTransactionManager->PeekUndoStack()) {
if (RefPtr<EditTransactionBase> transactionBase =
transaction->GetAsEditTransactionBase()) {
if (PlaceholderTransaction* placeholderTransaction =
transactionBase->GetAsPlaceholderTransaction()) {
placeholderTransaction->Commit();
}
}
}
}
// Note that this just marks as that we've already handled "beforeinput" for
// preventing assertions in FireInputEvent(). Note that corresponding
// "beforeinput" event for the following "input" event should've already
// been dispatched from `OnCompositionChange()`.
DebugOnly<nsresult> rvIgnored =
editActionData.MaybeDispatchBeforeInputEvent();
MOZ_ASSERT(rvIgnored != NS_ERROR_EDITOR_ACTION_CANCELED,
"Why beforeinput event was canceled in this case?");
MOZ_ASSERT(NS_SUCCEEDED(rvIgnored),
"MaybeDispatchBeforeInputEvent() should just mark the instance as "
"handled it");
// Composition string may have hidden the caret. Therefore, we need to
// cancel it here.
HideCaret(false);
// FYI: mComposition still keeps storing container text node of committed
// string, its offset and length. However, they will be invalidated
// soon since its Destroy() will be called by IMEStateManager.
mComposition->EndHandlingComposition(this);
mComposition = nullptr;
// notify editor observers of action
// FYI: With current draft, "input" event should be fired from
// OnCompositionChange(), however, it requires a lot of our UI code
// change and does not make sense. See spec issue:
// https://github.com/w3c/uievents/issues/202
NotifyEditorObservers(eNotifyEditorObserversOfEnd);
}
void EditorBase::DoAfterDoTransaction(nsITransaction* aTransaction) {
bool isTransientTransaction;
MOZ_ALWAYS_SUCCEEDS(aTransaction->GetIsTransient(&isTransientTransaction));
if (!isTransientTransaction) {
// we need to deal here with the case where the user saved after some
// edits, then undid one or more times. Then, the undo count is -ve,
// but we can't let a do take it back to zero. So we flip it up to
// a +ve number.
int32_t modCount;
DebugOnly<nsresult> rvIgnored = GetModificationCount(&modCount);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::GetModificationCount() failed, but ignored");
if (modCount < 0) {
modCount = -modCount;
}
// don't count transient transactions
MOZ_ALWAYS_SUCCEEDS(IncrementModificationCount(1));
}
}
void EditorBase::DoAfterUndoTransaction() {
// all undoable transactions are non-transient
MOZ_ALWAYS_SUCCEEDS(IncrementModificationCount(-1));
}
void EditorBase::DoAfterRedoTransaction() {
// all redoable transactions are non-transient
MOZ_ALWAYS_SUCCEEDS(IncrementModificationCount(1));
}
already_AddRefed<DeleteMultipleRangesTransaction>
EditorBase::CreateTransactionForDeleteSelection(
HowToHandleCollapsedRange aHowToHandleCollapsedRange,
const AutoRangeArray& aRangesToDelete) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aRangesToDelete.Ranges().IsEmpty());
// Check whether the selection is collapsed and we should do nothing:
if (NS_WARN_IF(aRangesToDelete.IsCollapsed() &&
aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::Ignore)) {
return nullptr;
}
// allocate the out-param transaction
RefPtr<DeleteMultipleRangesTransaction> transaction =
DeleteMultipleRangesTransaction::Create();
for (const OwningNonNull<nsRange>& range : aRangesToDelete.Ranges()) {
// Same with range as with selection; if it is collapsed and action
// is eNone, do nothing.
if (!range->Collapsed()) {
RefPtr<DeleteRangeTransaction> deleteRangeTransaction =
DeleteRangeTransaction::Create(*this, range);
// XXX Oh, not checking if deleteRangeTransaction can modify the range...
transaction->AppendChild(*deleteRangeTransaction);
continue;
}
if (aHowToHandleCollapsedRange == HowToHandleCollapsedRange::Ignore) {
continue;
}
// Let's extend the collapsed range to delete content around it.
RefPtr<DeleteContentTransactionBase> deleteNodeOrTextTransaction =
CreateTransactionForCollapsedRange(range, aHowToHandleCollapsedRange);
// XXX When there are two or more ranges and at least one of them is
// not editable, deleteNodeOrTextTransaction may be nullptr.
// In such case, should we stop removing other ranges too?
if (!deleteNodeOrTextTransaction) {
NS_WARNING("EditorBase::CreateTransactionForCollapsedRange() failed");
return nullptr;
}
transaction->AppendChild(*deleteNodeOrTextTransaction);
}
return transaction.forget();
}
// XXX: currently, this doesn't handle edge conditions because GetNext/GetPrior
// are not implemented
already_AddRefed<DeleteContentTransactionBase>
EditorBase::CreateTransactionForCollapsedRange(
const nsRange& aCollapsedRange,
HowToHandleCollapsedRange aHowToHandleCollapsedRange) {
MOZ_ASSERT(aCollapsedRange.Collapsed());
MOZ_ASSERT(
aHowToHandleCollapsedRange == HowToHandleCollapsedRange::ExtendBackward ||
aHowToHandleCollapsedRange == HowToHandleCollapsedRange::ExtendForward);
EditorRawDOMPoint point(aCollapsedRange.StartRef());
if (NS_WARN_IF(!point.IsSet())) {
return nullptr;
}
if (IsTextEditor()) {
// There should be only one text node in the anonymous `<div>` (but may
// be followed by a padding `<br>`). We should adjust the point into
// the text node (or return nullptr if there is no text to delete) for
// avoiding finding the text node with complicated API.
if (!point.IsInTextNode()) {
const Element* anonymousDiv = GetRoot();
if (NS_WARN_IF(!anonymousDiv)) {
return nullptr;
}
if (!anonymousDiv->GetFirstChild() ||
!anonymousDiv->GetFirstChild()->IsText()) {
return nullptr; // The value is empty.
}
if (point.GetContainer() == anonymousDiv) {
if (point.IsStartOfContainer()) {
point.Set(anonymousDiv->GetFirstChild(), 0);
} else {
point.SetToEndOf(anonymousDiv->GetFirstChild());
}
} else {
// Must be referring a padding `<br>` element or after the text node.
point.SetToEndOf(anonymousDiv->GetFirstChild());
}
}
MOZ_ASSERT(!point.ContainerAs<Text>()->GetPreviousSibling());
MOZ_ASSERT(!point.ContainerAs<Text>()->GetNextSibling() ||
!point.ContainerAs<Text>()->GetNextSibling()->IsText());
if (aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::ExtendBackward &&
point.IsStartOfContainer()) {
return nullptr;
}
if (aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::ExtendForward &&
point.IsEndOfContainer()) {
return nullptr;
}
}
// XXX: if the container of point is empty, then we'll need to delete the node
// as well as the 1 child
// build a transaction for deleting the appropriate data
// XXX: this has to come from rule section
const Element* const anonymousDivOrEditingHost =
IsTextEditor() ? GetRoot() : AsHTMLEditor()->ComputeEditingHost();
if (aHowToHandleCollapsedRange == HowToHandleCollapsedRange::ExtendBackward &&
point.IsStartOfContainer()) {
MOZ_ASSERT(IsHTMLEditor());
// We're backspacing from the beginning of a node. Delete the last thing
// of previous editable content.
nsIContent* previousEditableContent = HTMLEditUtils::GetPreviousContent(
*point.GetContainer(), {WalkTreeOption::IgnoreNonEditableNode},
IsTextEditor() ? BlockInlineCheck::UseHTMLDefaultStyle
: BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost);
if (!previousEditableContent) {
NS_WARNING("There was no editable content before the collapsed range");
return nullptr;
}
// There is an editable content, so delete its last child (if a text node,
// delete the last char). If it has no children, delete it.
if (previousEditableContent->IsText()) {
uint32_t length = previousEditableContent->Length();
// Bail out for empty text node.
// XXX Do we want to do something else?
// XXX If other browsers delete empty text node, we should follow it.
if (NS_WARN_IF(!length)) {
NS_WARNING("Previous editable content was an empty text node");
return nullptr;
}
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForPreviousCharacter(
*this, *previousEditableContent->AsText(), length);
if (!deleteTextTransaction) {
NS_WARNING(
"DeleteTextTransaction::MaybeCreateForPreviousCharacter() failed");
return nullptr;
}
return deleteTextTransaction.forget();
}
if (IsHTMLEditor() &&
NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*previousEditableContent))) {
return nullptr;
}
RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
DeleteNodeTransaction::MaybeCreate(*this, *previousEditableContent);
if (!deleteNodeTransaction) {
NS_WARNING("DeleteNodeTransaction::MaybeCreate() failed");
return nullptr;
}
return deleteNodeTransaction.forget();
}
if (aHowToHandleCollapsedRange == HowToHandleCollapsedRange::ExtendForward &&
point.IsEndOfContainer()) {
MOZ_ASSERT(IsHTMLEditor());
// We're deleting from the end of a node. Delete the first thing of
// next editable content.
nsIContent* nextEditableContent = HTMLEditUtils::GetNextContent(
*point.GetContainer(), {WalkTreeOption::IgnoreNonEditableNode},
IsTextEditor() ? BlockInlineCheck::UseHTMLDefaultStyle
: BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost);
if (!nextEditableContent) {
NS_WARNING("There was no editable content after the collapsed range");
return nullptr;
}
// There is an editable content, so delete its first child (if a text node,
// delete the first char). If it has no children, delete it.
if (nextEditableContent->IsText()) {
uint32_t length = nextEditableContent->Length();
// Bail out for empty text node.
// XXX Do we want to do something else?
// XXX If other browsers delete empty text node, we should follow it.
if (!length) {
NS_WARNING("Next editable content was an empty text node");
return nullptr;
}
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForNextCharacter(
*this, *nextEditableContent->AsText(), 0);
if (!deleteTextTransaction) {
NS_WARNING(
"DeleteTextTransaction::MaybeCreateForNextCharacter() failed");
return nullptr;
}
return deleteTextTransaction.forget();
}
if (IsHTMLEditor() &&
NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*nextEditableContent))) {
return nullptr;
}
RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
DeleteNodeTransaction::MaybeCreate(*this, *nextEditableContent);
if (!deleteNodeTransaction) {
NS_WARNING("DeleteNodeTransaction::MaybeCreate() failed");
return nullptr;
}
return deleteNodeTransaction.forget();
}
if (point.IsInTextNode()) {
if (aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::ExtendBackward) {
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForPreviousCharacter(
*this, *point.ContainerAs<Text>(), point.Offset());
NS_WARNING_ASSERTION(
deleteTextTransaction,
"DeleteTextTransaction::MaybeCreateForPreviousCharacter() failed");
return deleteTextTransaction.forget();
}
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForNextCharacter(
*this, *point.ContainerAs<Text>(), point.Offset());
NS_WARNING_ASSERTION(
deleteTextTransaction,
"DeleteTextTransaction::MaybeCreateForNextCharacter() failed");
return deleteTextTransaction.forget();
}
nsIContent* editableContent = nullptr;
if (IsHTMLEditor()) {
editableContent =
aHowToHandleCollapsedRange == HowToHandleCollapsedRange::ExtendBackward
? HTMLEditUtils::GetPreviousContent(
point, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost)
: HTMLEditUtils::GetNextContent(
point, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost);
if (!editableContent) {
NS_WARNING("There was no editable content around the collapsed range");
return nullptr;
}
while (editableContent && editableContent->IsCharacterData() &&
!editableContent->Length()) {
// Can't delete an empty text node (bug 762183)
editableContent =
aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::ExtendBackward
? HTMLEditUtils::GetPreviousContent(
*editableContent, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost)
: HTMLEditUtils::GetNextContent(
*editableContent, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::UseComputedDisplayOutsideStyle,
anonymousDivOrEditingHost);
}
if (!editableContent) {
NS_WARNING(
"There was no editable content which is not empty around the "
"collapsed range");
return nullptr;
}
} else {
MOZ_ASSERT(point.IsInTextNode());
editableContent = point.GetContainerAs<nsIContent>();
if (!editableContent) {
NS_WARNING("If there was no text node, should've been handled first");
return nullptr;
}
}
if (editableContent->IsText()) {
if (aHowToHandleCollapsedRange ==
HowToHandleCollapsedRange::ExtendBackward) {
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForPreviousCharacter(
*this, *editableContent->AsText(), editableContent->Length());
NS_WARNING_ASSERTION(
deleteTextTransaction,
"DeleteTextTransaction::MaybeCreateForPreviousCharacter() failed");
return deleteTextTransaction.forget();
}
RefPtr<DeleteTextTransaction> deleteTextTransaction =
DeleteTextTransaction::MaybeCreateForNextCharacter(
*this, *editableContent->AsText(), 0);
NS_WARNING_ASSERTION(
deleteTextTransaction,
"DeleteTextTransaction::MaybeCreateForNextCharacter() failed");
return deleteTextTransaction.forget();
}
MOZ_ASSERT(IsHTMLEditor());
if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*editableContent))) {
return nullptr;
}
RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
DeleteNodeTransaction::MaybeCreate(*this, *editableContent);
NS_WARNING_ASSERTION(deleteNodeTransaction,
"DeleteNodeTransaction::MaybeCreate() failed");
return deleteNodeTransaction.forget();
}
bool EditorBase::FlushPendingNotificationsIfToHandleDeletionWithFrameSelection(
nsIEditor::EDirection aDirectionAndAmount) const {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(Destroyed())) {
return false;
}
if (!EditorUtils::IsFrameSelectionRequiredToExtendSelection(
aDirectionAndAmount, SelectionRef())) {
return true;
}
// Although AutoRangeArray::ExtendAnchorFocusRangeFor() will use
// nsFrameSelection, if it still has dirty frame, nsFrameSelection doesn't
// extend selection since we block script.
if (RefPtr<PresShell> presShell = GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Layout);
if (NS_WARN_IF(Destroyed())) {
return false;
}
}
return true;
}
nsresult EditorBase::DeleteSelectionAsAction(
nsIEditor::EDirection aDirectionAndAmount,
nsIEditor::EStripWrappers aStripWrappers, nsIPrincipal* aPrincipal) {
MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);
// Showing this assertion is fine if this method is called by outside via
// mutation event listener or something. Otherwise, this is called by
// wrong method.
NS_ASSERTION(
!mPlaceholderBatch,
"Should be called only when this is the only edit action of the "
"operation unless mutation event listener nests some operations");
// If we're a TextEditor instance, we don't need to treat parent elements
// so that we can ignore aStripWrappers for skipping unnecessary cost.
if (IsTextEditor()) {
aStripWrappers = nsIEditor::eNoStrip;
}
EditAction editAction = EditAction::eDeleteSelection;
switch (aDirectionAndAmount) {
case nsIEditor::ePrevious:
editAction = EditAction::eDeleteBackward;
break;
case nsIEditor::eNext:
editAction = EditAction::eDeleteForward;
break;
case nsIEditor::ePreviousWord:
editAction = EditAction::eDeleteWordBackward;
break;
case nsIEditor::eNextWord:
editAction = EditAction::eDeleteWordForward;
break;
case nsIEditor::eToBeginningOfLine:
editAction = EditAction::eDeleteToBeginningOfSoftLine;
break;
case nsIEditor::eToEndOfLine:
editAction = EditAction::eDeleteToEndOfSoftLine;
break;
}
AutoEditActionDataSetter editActionData(*this, editAction, aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
// If there is an existing selection when an extended delete is requested,
// platforms that use "caret-style" caret positioning collapse the
// selection to the start and then create a new selection.
// Platforms that use "selection-style" caret positioning just delete the
// existing selection without extending it.
if (!SelectionRef().IsCollapsed()) {
switch (aDirectionAndAmount) {
case eNextWord:
case ePreviousWord:
case eToBeginningOfLine:
case eToEndOfLine: {
if (mCaretStyle != 1) {
aDirectionAndAmount = eNone;
break;
}
ErrorResult error;
SelectionRef().CollapseToStart(error);
if (NS_WARN_IF(Destroyed())) {
error.SuppressException();
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
if (error.Failed()) {
NS_WARNING("Selection::CollapseToStart() failed");
editActionData.Abort();
return EditorBase::ToGenericNSResult(error.StealNSResult());
}
break;
}
default:
break;
}
}
// If Selection is still NOT collapsed, it does not important removing
// range of the operation since we'll remove the selected content. However,
// information of direction (backward or forward) may be important for
// web apps. E.g., web apps may want to mark selected range as "deleted"
// and move caret before or after the range. Therefore, we should forget
// only the range information but keep range information. See discussion
// of the spec issue for the detail:
// https://github.com/w3c/input-events/issues/82
if (!SelectionRef().IsCollapsed()) {
switch (editAction) {
case EditAction::eDeleteWordBackward:
case EditAction::eDeleteToBeginningOfSoftLine:
editActionData.UpdateEditAction(EditAction::eDeleteBackward);
break;
case EditAction::eDeleteWordForward:
case EditAction::eDeleteToEndOfSoftLine:
editActionData.UpdateEditAction(EditAction::eDeleteForward);
break;
default:
break;
}
}
editActionData.SetSelectionCreatedByDoubleclick(
SelectionRef().GetFrameSelection() &&
SelectionRef().GetFrameSelection()->IsDoubleClickSelection());
if (!FlushPendingNotificationsIfToHandleDeletionWithFrameSelection(
aDirectionAndAmount)) {
NS_WARNING("Flusing pending notifications caused destroying the editor");
editActionData.Abort();
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
nsresult rv =
editActionData.MaybeDispatchBeforeInputEvent(aDirectionAndAmount);
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
// delete placeholder txns merge.
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::DeleteTxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
rv = DeleteSelectionAsSubAction(aDirectionAndAmount, aStripWrappers);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteSelectionAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::DeleteSelectionAsSubAction(
nsIEditor::EDirection aDirectionAndAmount,
nsIEditor::EStripWrappers aStripWrappers) {
MOZ_ASSERT(IsEditActionDataAvailable());
// If handling edit action is for table editing, this may be called with
// selecting an any table element by the caller, but it's not usual work of
// this so that `MayEditActionDeleteSelection()` returns false.
MOZ_ASSERT(MayEditActionDeleteSelection(GetEditAction()) ||
IsEditActionTableEditing(GetEditAction()));
MOZ_ASSERT(mPlaceholderBatch);
MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);
NS_ASSERTION(IsHTMLEditor() || aStripWrappers == nsIEditor::eNoStrip,
"TextEditor does not support strip wrappers");
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eDeleteSelectedContent, aDirectionAndAmount,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result =
HandleDeleteSelection(aDirectionAndAmount, aStripWrappers);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("TextEditor::HandleDeleteSelection() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
// XXX This is odd. We just tries to remove empty text node here but we
// refer `Selection`. It may be modified by mutation event listeners
// so that we should remove the empty text node when we make it empty.
const auto atNewStartOfSelection =
GetFirstSelectionStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!atNewStartOfSelection.IsSet())) {
// XXX And also it seems that we don't need to return error here.
// Why don't we just ignore? `Selection::RemoveAllRanges()` may
// have been called by mutation event listeners.
return NS_ERROR_FAILURE;
}
if (IsHTMLEditor() && atNewStartOfSelection.IsInTextNode() &&
!atNewStartOfSelection.GetContainer()->Length()) {
nsresult rv = DeleteNodeWithTransaction(
MOZ_KnownLive(*atNewStartOfSelection.ContainerAs<Text>()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
// XXX I don't think that this is necessary in anonymous `<div>` element of
// TextEditor since there should be at most one text node and at most
// one padding `<br>` element so that `<br>` element won't be before
// caret.
if (!TopLevelEditSubActionDataRef().mDidExplicitlySetInterLine) {
// We prevent the caret from sticking on the left of previous `<br>`
// element (i.e. the end of previous line) after this deletion. Bug 92124.
if (MOZ_UNLIKELY(NS_FAILED(SelectionRef().SetInterlinePosition(
InterlinePosition::StartOfNextLine)))) {
NS_WARNING(
"Selection::SetInterlinePosition(InterlinePosition::StartOfNextLine) "
"failed");
return NS_ERROR_FAILURE; // Don't need to return NS_ERROR_NOT_INITIALIZED
}
}
return NS_OK;
}
nsresult EditorBase::HandleDropEvent(DragEvent* aDropEvent) {
if (NS_WARN_IF(!aDropEvent)) {
return NS_ERROR_INVALID_ARG;
}
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
AutoEditActionDataSetter editActionData(*this, EditAction::eDrop);
// We need to initialize data or dataTransfer later. Therefore, we cannot
// dispatch "beforeinput" event until then.
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
RefPtr<DataTransfer> dataTransfer = aDropEvent->GetDataTransfer();
if (NS_WARN_IF(!dataTransfer)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDragSession> dragSession = nsContentUtils::GetDragSession();
if (NS_WARN_IF(!dragSession)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsINode> sourceNode = dataTransfer->GetMozSourceNode();
// If there is no source document, then the drag was from another application
// or another process (such as an out of process subframe). The latter case is
// not currently handled below when checking for a move/copy and deleting the
// existing text.
RefPtr<Document> srcdoc;
if (sourceNode) {
srcdoc = sourceNode->OwnerDoc();
}
nsCOMPtr<nsIPrincipal> sourcePrincipal;
dragSession->GetTriggeringPrincipal(getter_AddRefs(sourcePrincipal));
if (nsContentUtils::CheckForSubFrameDrop(
dragSession, aDropEvent->WidgetEventPtr()->AsDragEvent())) {
// Don't allow drags from subframe documents with different origins than
// the drop destination.
if (IsSafeToInsertData(sourcePrincipal) == SafeToInsertData::No) {
return NS_OK;
}
}
// Current doc is destination
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_NOT_INITIALIZED;
}
const uint32_t numItems = dataTransfer->MozItemCount();
if (NS_WARN_IF(!numItems)) {
return NS_ERROR_FAILURE; // Nothing to drop?
}
// We have to figure out whether to delete and relocate caret only once
// Parent and offset are under the mouse cursor.
int32_t dropOffset = -1;
nsCOMPtr<nsIContent> dropParentContent =
aDropEvent->GetRangeParentContentAndOffset(&dropOffset);
if (dropOffset < 0) {
NS_WARNING(
"DropEvent::GetRangeParentContentAndOffset() returned negative offset");
return NS_ERROR_FAILURE;
}
EditorDOMPoint droppedAt(dropParentContent,
AssertedCast<uint32_t>(dropOffset));
if (NS_WARN_IF(!droppedAt.IsInContentNode())) {
return NS_ERROR_FAILURE;
}
// Check if dropping into a selected range. If so and the source comes from
// same document, jump through some hoops to determine if mouse is over
// selection (bail) and whether user wants to copy selection or delete it.
if (sourceNode && sourceNode->IsEditable() && srcdoc == document) {
bool isPointInSelection = nsContentUtils::IsPointInSelection(
SelectionRef(), *droppedAt.GetContainer(), droppedAt.Offset());
if (isPointInSelection) {
// If source document and destination document is same and dropping
// into one of selected ranges, we don't need to do nothing.
// XXX If the source comes from outside of this editor, this check
// means that we don't allow to drop the item in the selected
// range. However, the selection is hidden until the <input> or
// <textarea> gets focus, therefore, this looks odd.
return NS_OK;
}
}
// Delete if user doesn't want to copy when user moves selected content
// to different place in same editor.
// XXX Do we need the check whether it's in same document or not?
RefPtr<EditorBase> editorToDeleteSelection;
if (sourceNode && sourceNode->IsEditable() && srcdoc == document) {
if ((dataTransfer->DropEffectInt() &
nsIDragService::DRAGDROP_ACTION_MOVE) &&
!(dataTransfer->DropEffectInt() &
nsIDragService::DRAGDROP_ACTION_COPY)) {
// If the source node is in native anonymous tree, it must be in
// <input> or <textarea> element. If so, its TextEditor can remove it.
if (sourceNode->IsInNativeAnonymousSubtree()) {
if (RefPtr textControlElement = TextControlElement::FromNodeOrNull(
sourceNode
->GetClosestNativeAnonymousSubtreeRootParentOrHost())) {
editorToDeleteSelection = textControlElement->GetTextEditor();
}
}
// Otherwise, must be the content is in HTMLEditor.
else if (IsHTMLEditor()) {
editorToDeleteSelection = this;
} else {
editorToDeleteSelection =
nsContentUtils::GetHTMLEditor(srcdoc->GetPresContext());
}
}
// If the found editor isn't modifiable, we should not try to delete
// selection.
if (editorToDeleteSelection && !editorToDeleteSelection->IsModifiable()) {
editorToDeleteSelection = nullptr;
}
// If the found editor has collapsed selection, we need to delete nothing
// in the editor.
if (editorToDeleteSelection) {
if (Selection* selection = editorToDeleteSelection->GetSelection()) {
if (selection->IsCollapsed()) {
editorToDeleteSelection = nullptr;
}
}
}
}
// Combine any deletion and drop insertion into one transaction.
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
// Don't dispatch "selectionchange" event until inserting all contents.
SelectionBatcher selectionBatcher(SelectionRef(), __FUNCTION__);
// Track dropped point with nsRange because we shouldn't insert the
// dropped content into different position even if some event listeners
// modify selection. Note that Chrome's behavior is really odd. So,
// we don't need to worry about web-compat about this.
IgnoredErrorResult ignoredError;
RefPtr<nsRange> rangeAtDropPoint =
nsRange::Create(droppedAt.ToRawRangeBoundary(),
droppedAt.ToRawRangeBoundary(), ignoredError);
if (NS_WARN_IF(ignoredError.Failed()) ||
NS_WARN_IF(!rangeAtDropPoint->IsPositioned())) {
editActionData.Abort();
return NS_ERROR_FAILURE;
}
// Remove selected contents first here because we need to fire a pair of
// "beforeinput" and "input" for deletion and web apps can cancel only
// this deletion. Note that callee may handle insertion asynchronously.
// Therefore, it is the best to remove selected content here.
if (editorToDeleteSelection) {
nsresult rv = editorToDeleteSelection->DeleteSelectionByDragAsAction(
mDispatchInputEvent);
if (NS_WARN_IF(Destroyed())) {
editActionData.Abort();
return NS_OK;
}
// Ignore the editor instance specific error if it's another editor.
if (this != editorToDeleteSelection &&
(rv == NS_ERROR_NOT_INITIALIZED || rv == NS_ERROR_EDITOR_DESTROYED)) {
rv = NS_OK;
}
// Don't cancel "insertFromDrop" even if "deleteByDrag" is canceled.
if (rv != NS_ERROR_EDITOR_ACTION_CANCELED && NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteSelectionByDragAsAction() failed");
editActionData.Abort();
return EditorBase::ToGenericNSResult(rv);
}
if (NS_WARN_IF(!rangeAtDropPoint->IsPositioned()) ||
NS_WARN_IF(!rangeAtDropPoint->GetStartContainer()->IsContent())) {
editActionData.Abort();
return NS_ERROR_FAILURE;
}
droppedAt = rangeAtDropPoint->StartRef();
MOZ_ASSERT(droppedAt.IsSetAndValid());
MOZ_ASSERT(droppedAt.IsInContentNode());
}
// Before inserting dropping content, we need to move focus for compatibility
// with Chrome and firing "beforeinput" event on new editing host.
RefPtr<Element> focusedElement, newFocusedElement;
if (IsTextEditor()) {
newFocusedElement = GetExposedRoot();
focusedElement = IsActiveInDOMWindow() ? newFocusedElement : nullptr;
}
// TODO: We need to add automated tests when dropping something into an
// editing host for contenteditable which is in a shadow DOM tree
// and its host which is in design mode.
else if (!AsHTMLEditor()->IsInDesignMode()) {
focusedElement = AsHTMLEditor()->ComputeEditingHost();
if (focusedElement &&
droppedAt.ContainerAs<nsIContent>()->IsInclusiveDescendantOf(
focusedElement)) {
newFocusedElement = focusedElement;
} else {
newFocusedElement = droppedAt.ContainerAs<nsIContent>()->GetEditingHost();
}
}
// Move selection right now. Note that this does not move focus because
// `Selection` moves focus with selection change only when the API caller is
// JS. And also this does not notify selection listeners (nor
// "selectionchange") since we created SelectionBatcher above.
ErrorResult error;
SelectionRef().SetStartAndEnd(droppedAt.ToRawRangeBoundary(),
droppedAt.ToRawRangeBoundary(), error);
if (error.Failed()) {
NS_WARNING("Selection::SetStartAndEnd() failed");
editActionData.Abort();
return error.StealNSResult();
}
if (NS_WARN_IF(Destroyed())) {
editActionData.Abort();
return NS_OK;
}
// Then, move focus if necessary. This must cause dispatching "blur" event
// and "focus" event.
if (newFocusedElement && focusedElement != newFocusedElement) {
RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager();
DebugOnly<nsresult> rvIgnored = fm->SetFocus(newFocusedElement, 0);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsFocusManager::SetFocus() failed to set focus "
"to the element, but ignored");
if (NS_WARN_IF(Destroyed())) {
editActionData.Abort();
return NS_OK;
}
// "blur" or "focus" event listener may have changed the value.
// Let's keep using the original point.
if (NS_WARN_IF(!rangeAtDropPoint->IsPositioned()) ||
NS_WARN_IF(!rangeAtDropPoint->GetStartContainer()->IsContent())) {
return NS_ERROR_FAILURE;
}
droppedAt = rangeAtDropPoint->StartRef();
MOZ_ASSERT(droppedAt.IsSetAndValid());
// If focus is changed to different element and we're handling drop in
// contenteditable, we cannot handle it without focus. So, we should give
// it up.
if (IsHTMLEditor() && !AsHTMLEditor()->IsInDesignMode() &&
NS_WARN_IF(newFocusedElement != AsHTMLEditor()->ComputeEditingHost())) {
editActionData.Abort();
return NS_OK;
}
}
nsresult rv = InsertDroppedDataTransferAsAction(editActionData, *dataTransfer,
droppedAt, sourcePrincipal);
if (rv == NS_ERROR_EDITOR_DESTROYED ||
rv == NS_ERROR_EDITOR_ACTION_CANCELED) {
return EditorBase::ToGenericNSResult(rv);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::InsertDroppedDataTransferAsAction() failed, but ignored");
rv = ScrollSelectionFocusIntoView();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::ScrollSelectionFocusIntoView() failed");
return rv;
}
nsresult EditorBase::DeleteSelectionByDragAsAction(bool aDispatchInputEvent) {
// TODO: Move this method to `EditorBase`.
AutoRestore<bool> saveDispatchInputEvent(mDispatchInputEvent);
mDispatchInputEvent = aDispatchInputEvent;
// Even if we're handling "deleteByDrag" in same editor as "insertFromDrop",
// we need to recreate edit action data here because
// `AutoEditActionDataSetter` needs to manage event state separately.
bool requestedByAnotherEditor = GetEditAction() != EditAction::eDrop;
AutoEditActionDataSetter editActionData(*this, EditAction::eDeleteByDrag);
MOZ_ASSERT(!SelectionRef().IsCollapsed());
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return rv;
}
// But keep using placeholder transaction for "insertFromDrop" if there is.
Maybe<AutoPlaceholderBatch> treatAsOneTransaction;
if (requestedByAnotherEditor) {
treatAsOneTransaction.emplace(*this, ScrollSelectionIntoView::Yes,
__FUNCTION__);
}
// We may need to update the source node to dispatch "dragend" below.
// Chrome restricts the new target under the <body> here. Therefore, we
// should follow it here.
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/editing_utilities.cc;l=254;drc=da35f4ed6398ae287d5adc828b9546eec95f668a
const RefPtr<Element> editingHost =
IsHTMLEditor() ? AsHTMLEditor()->ComputeEditingHost(
HTMLEditor::LimitInBodyElement::Yes)
: nullptr;
rv = DeleteSelectionAsSubAction(nsIEditor::eNone, IsTextEditor()
? nsIEditor::eNoStrip
: nsIEditor::eStrip);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteSelectionAsSubAction(eNone) failed");
return rv;
}
if (!mDispatchInputEvent) {
return NS_OK;
}
if (treatAsOneTransaction.isNothing()) {
DispatchInputEvent();
}
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
// If we success everything here, we may need to retarget "dragend" event
// target for compatibility with the other browsers. They do this only when
// their builtin editor delete the source node from the document. Then,
// they retarget the source node to the editing host.
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/page/drag_controller.cc;l=724;drc=d9ba13b8cd8ac0faed7afc3d1f7e4b67ebac2a0b
if (editingHost) {
if (nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1")) {
dragService->MaybeEditorDeletedSourceNode(editingHost);
}
}
return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : NS_OK;
}
nsresult EditorBase::DeleteSelectionWithTransaction(
nsIEditor::EDirection aDirectionAndAmount,
nsIEditor::EStripWrappers aStripWrappers) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
AutoRangeArray rangesToDelete(SelectionRef());
if (NS_WARN_IF(rangesToDelete.Ranges().IsEmpty())) {
NS_ASSERTION(
false,
"For avoiding to throw incompatible exception for `execCommand`, fix "
"the caller");
return NS_ERROR_FAILURE;
}
if (IsTextEditor()) {
if (const Text* theTextNode = AsTextEditor()->GetTextNode()) {
rangesToDelete.EnsureRangesInTextNode(*theTextNode);
}
}
Result<CaretPoint, nsresult> caretPointOrError = DeleteRangesWithTransaction(
aDirectionAndAmount, aStripWrappers, rangesToDelete);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("EditorBase::DeleteRangesWithTransaction() failed");
return caretPointOrError.unwrapErr();
}
nsresult rv = caretPointOrError.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CaretPoint::SuggestCaretPointTo() failed");
}
NS_WARNING_ASSERTION(rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CaretPoint::SuggestCaretPointTo() failed, but ignored");
return NS_OK;
}
Result<CaretPoint, nsresult> EditorBase::DeleteRangesWithTransaction(
nsIEditor::EDirection aDirectionAndAmount,
nsIEditor::EStripWrappers aStripWrappers,
const AutoRangeArray& aRangesToDelete) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!Destroyed());
MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);
MOZ_ASSERT(!aRangesToDelete.Ranges().IsEmpty());
HowToHandleCollapsedRange howToHandleCollapsedRange =
EditorBase::HowToHandleCollapsedRangeFor(aDirectionAndAmount);
if (NS_WARN_IF(aRangesToDelete.IsCollapsed() &&
howToHandleCollapsedRange ==
HowToHandleCollapsedRange::Ignore)) {
NS_ASSERTION(
false,
"For avoiding to throw incompatible exception for `execCommand`, fix "
"the caller");
return Err(NS_ERROR_FAILURE);
}
RefPtr<DeleteMultipleRangesTransaction> deleteSelectionTransaction =
CreateTransactionForDeleteSelection(howToHandleCollapsedRange,
aRangesToDelete);
if (MOZ_UNLIKELY(!deleteSelectionTransaction)) {
NS_WARNING("EditorBase::CreateTransactionForDeleteSelection() failed");
return Err(NS_ERROR_FAILURE);
}
// XXX This is odd, this assumes that there are no multiple collapsed
// ranges in `Selection`, but it's possible scenario.
// XXX This loop looks slow, but it's rarely so because of multiple
// selection is not used so many times.
nsCOMPtr<nsIContent> deleteContent;
uint32_t deleteCharOffset = 0;
for (const OwningNonNull<EditTransactionBase>& transactionBase :
Reversed(deleteSelectionTransaction->ChildTransactions())) {
if (DeleteTextTransaction* deleteTextTransaction =
transactionBase->GetAsDeleteTextTransaction()) {
deleteContent = deleteTextTransaction->GetText();
deleteCharOffset = deleteTextTransaction->Offset();
break;
}
if (DeleteNodeTransaction* deleteNodeTransaction =
transactionBase->GetAsDeleteNodeTransaction()) {
deleteContent = deleteNodeTransaction->GetContent();
break;
}
}
RefPtr<CharacterData> deleteCharData =
CharacterData::FromNodeOrNull(deleteContent);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eDeleteSelectedContent, aDirectionAndAmount,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
if (IsHTMLEditor()) {
if (!deleteContent) {
// XXX We may remove multiple ranges in the following. Therefore,
// this must have a bug since we only add the first range into
// the changed range.
TopLevelEditSubActionDataRef().WillDeleteRange(
*this, aRangesToDelete.GetFirstRangeStartPoint<EditorRawDOMPoint>(),
aRangesToDelete.GetFirstRangeEndPoint<EditorRawDOMPoint>());
} else if (!deleteCharData) {
TopLevelEditSubActionDataRef().WillDeleteContent(*this, *deleteContent);
}
}
// Notify nsIEditActionListener::WillDelete[Selection|Text]
if (!mActionListeners.IsEmpty()) {
if (!deleteContent) {
MOZ_ASSERT(!aRangesToDelete.Ranges().IsEmpty());
AutoTArray<RefPtr<nsRange>, 8> rangesToDelete(
aRangesToDelete.CloneRanges<RefPtr>());
AutoActionListenerArray listeners(mActionListeners.Clone());
for (auto& listener : listeners) {
DebugOnly<nsresult> rvIgnored =
listener->WillDeleteRanges(rangesToDelete);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::WillDeleteRanges() failed, but ignored");
MOZ_DIAGNOSTIC_ASSERT(!Destroyed(),
"nsIEditActionListener::WillDeleteRanges() "
"must not destroy the editor");
}
} else if (deleteCharData) {
AutoActionListenerArray listeners(mActionListeners.Clone());
for (auto& listener : listeners) {
// XXX Why don't we notify listeners of actual length?
DebugOnly<nsresult> rvIgnored =
listener->WillDeleteText(deleteCharData, deleteCharOffset, 1);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::WillDeleteText() failed, but ignored");
MOZ_DIAGNOSTIC_ASSERT(!Destroyed(),
"nsIEditActionListener::WillDeleteText() must "
"not destroy the editor");
}
}
}
// Delete the specified amount
nsresult rv = DoTransactionInternal(deleteSelectionTransaction);
// I'm not sure whether we should keep notifying edit action listeners or
// stop doing it. For now, just keep traditional behavior.
bool destroyedByTransaction = Destroyed();
NS_WARNING_ASSERTION(destroyedByTransaction || NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
if (IsHTMLEditor() && deleteCharData) {
MOZ_ASSERT(deleteContent);
TopLevelEditSubActionDataRef().DidDeleteText(
*this, EditorRawDOMPoint(deleteContent));
}
if (mTextServicesDocument && NS_SUCCEEDED(rv) && deleteContent &&
!deleteCharData) {
RefPtr<TextServicesDocument> textServicesDocument = mTextServicesDocument;
textServicesDocument->DidDeleteContent(*deleteContent);
MOZ_ASSERT(
destroyedByTransaction || !Destroyed(),
"TextServicesDocument::DidDeleteContent() must not destroy the editor");
}
if (!mActionListeners.IsEmpty() && deleteContent && !deleteCharData) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->DidDeleteNode(deleteContent, rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidDeleteNode() failed, but ignored");
MOZ_DIAGNOSTIC_ASSERT(
destroyedByTransaction || !Destroyed(),
"nsIEditActionListener::DidDeleteNode() must not destroy the editor");
}
}
if (NS_WARN_IF(destroyedByTransaction)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
return Err(rv);
}
EditorDOMPoint pointToPutCaret =
deleteSelectionTransaction->SuggestPointToPutCaret();
if (IsHTMLEditor() && aStripWrappers == nsIEditor::eStrip) {
const nsCOMPtr<nsIContent> anchorContent =
pointToPutCaret.GetContainerAs<nsIContent>();
if (MOZ_LIKELY(anchorContent) &&
MOZ_LIKELY(HTMLEditUtils::IsSimplyEditableNode(*anchorContent)) &&
// FIXME: Perhaps, this should use `HTMLEditor::IsEmptyNode` instead.
!anchorContent->Length()) {
AutoTrackDOMPoint trackPoint(RangeUpdaterRef(), &pointToPutCaret);
nsresult rv =
MOZ_KnownLive(AsHTMLEditor())
->RemoveEmptyInclusiveAncestorInlineElements(*anchorContent);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::RemoveEmptyInclusiveAncestorInlineElements() "
"failed");
return Err(rv);
}
}
}
return CaretPoint(std::move(pointToPutCaret));
}
already_AddRefed<Element> EditorBase::CreateHTMLContent(
const nsAtom* aTag) const {
MOZ_ASSERT(aTag);
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return nullptr;
}
// XXX Wallpaper over editor bug (editor tries to create elements with an
// empty nodename).
if (aTag == nsGkAtoms::_empty) {
NS_ERROR(
"Don't pass an empty tag to EditorBase::CreateHTMLContent, "
"check caller.");
return nullptr;
}
return document->CreateElem(nsDependentAtomString(aTag), nullptr,
kNameSpaceID_XHTML);
}
already_AddRefed<nsTextNode> EditorBase::CreateTextNode(
const nsAString& aData) const {
MOZ_ASSERT(IsEditActionDataAvailable());
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return nullptr;
}
RefPtr<nsTextNode> text = document->CreateEmptyTextNode();
text->MarkAsMaybeModifiedFrequently();
if (IsPasswordEditor()) {
text->MarkAsMaybeMasked();
}
// Don't notify; this node is still being created.
DebugOnly<nsresult> rvIgnored = text->SetText(aData, false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Text::SetText() failed, but ignored");
return text.forget();
}
NS_IMETHODIMP EditorBase::SetAttributeOrEquivalent(Element* aElement,
const nsAString& aAttribute,
const nsAString& aValue,
bool aSuppressTransaction) {
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_NULL_POINTER;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eSetAttribute);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<nsAtom> attribute = NS_Atomize(aAttribute);
rv = SetAttributeOrEquivalent(aElement, attribute, aValue,
aSuppressTransaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeOrEquivalent() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP EditorBase::RemoveAttributeOrEquivalent(
Element* aElement, const nsAString& aAttribute, bool aSuppressTransaction) {
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_NULL_POINTER;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eRemoveAttribute);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<nsAtom> attribute = NS_Atomize(aAttribute);
rv = RemoveAttributeOrEquivalent(aElement, attribute, aSuppressTransaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeOrEquivalent() failed");
return EditorBase::ToGenericNSResult(rv);
}
void EditorBase::HandleKeyPressEventInReadOnlyMode(
WidgetKeyboardEvent& aKeyboardEvent) const {
MOZ_ASSERT(IsReadonly());
MOZ_ASSERT(aKeyboardEvent.mMessage == eKeyPress);
switch (aKeyboardEvent.mKeyCode) {
case NS_VK_BACK:
// If it's a `Backspace` key, let's consume it because it may be mapped
// to "Back" of the history navigation. So, it's possible that user
// tries to delete a character with `Backspace` even in the read-only
// editor.
aKeyboardEvent.PreventDefault();
break;
}
// XXX How about space key (page up and page down in browser navigation)?
}
nsresult EditorBase::HandleKeyPressEvent(WidgetKeyboardEvent* aKeyboardEvent) {
MOZ_ASSERT(!IsReadonly());
MOZ_ASSERT(aKeyboardEvent);
MOZ_ASSERT(aKeyboardEvent->mMessage == eKeyPress);
// NOTE: When you change this method, you should also change:
// * editor/libeditor/tests/test_texteditor_keyevent_handling.html
// * editor/libeditor/tests/test_htmleditor_keyevent_handling.html
//
// And also when you add new key handling, you need to change the subclass's
// HandleKeyPressEvent()'s switch statement.
switch (aKeyboardEvent->mKeyCode) {
case NS_VK_META:
case NS_VK_WIN:
case NS_VK_SHIFT:
case NS_VK_CONTROL:
case NS_VK_ALT:
MOZ_ASSERT_UNREACHABLE(
"eKeyPress event shouldn't be fired for modifier keys");
return NS_ERROR_UNEXPECTED;
case NS_VK_BACK: {
if (aKeyboardEvent->IsControl() || aKeyboardEvent->IsAlt() ||
aKeyboardEvent->IsMeta()) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored =
DeleteSelectionAsAction(nsIEditor::ePrevious, nsIEditor::eStrip);
aKeyboardEvent->PreventDefault();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::DeleteSelectionAsAction() failed, but ignored");
return NS_OK;
}
case NS_VK_DELETE: {
// on certain platforms (such as windows) the shift key
// modifies what delete does (cmd_cut in this case).
// bailing here to allow the keybindings to do the cut.
if (aKeyboardEvent->IsShift() || aKeyboardEvent->IsControl() ||
aKeyboardEvent->IsAlt() || aKeyboardEvent->IsMeta()) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored =
DeleteSelectionAsAction(nsIEditor::eNext, nsIEditor::eStrip);
aKeyboardEvent->PreventDefault();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::DeleteSelectionAsAction() failed, but ignored");
return NS_OK;
}
}
return NS_OK;
}
nsresult EditorBase::OnInputText(const nsAString& aStringToInsert) {
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertText);
MOZ_ASSERT(!aStringToInsert.IsVoid());
editActionData.SetData(aStringToInsert);
// FYI: For conforming to current UI Events spec, we should dispatch
// "beforeinput" event before "keypress" event, but here is in a
// "keypress" event listener. However, the other browsers dispatch
// "beforeinput" event after "keypress" event. Therefore, it makes
// sense to follow the other browsers. Spec issue:
// https://github.com/w3c/uievents/issues/220
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::TypingTxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
rv = InsertTextAsSubAction(aStringToInsert, SelectionHandling::Delete);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::ReplaceTextAsAction(
const nsAString& aString, nsRange* aReplaceRange,
AllowBeforeInputEventCancelable aAllowBeforeInputEventCancelable,
nsIPrincipal* aPrincipal) {
MOZ_ASSERT(aString.FindChar(nsCRT::CR) == kNotFound);
MOZ_ASSERT_IF(!aReplaceRange, IsTextEditor());
AutoEditActionDataSetter editActionData(*this, EditAction::eReplaceText,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (aAllowBeforeInputEventCancelable == AllowBeforeInputEventCancelable::No) {
editActionData.MakeBeforeInputEventNonCancelable();
}
if (IsTextEditor()) {
editActionData.SetData(aString);
} else {
editActionData.InitializeDataTransfer(aString);
RefPtr<StaticRange> targetRange;
if (aReplaceRange) {
// Compute offset of the range before dispatching `beforeinput` event
// because it may be referred after the DOM tree is changed and the
// range may have not computed the offset yet.
targetRange = StaticRange::Create(
aReplaceRange->GetStartContainer(), aReplaceRange->StartOffset(),
aReplaceRange->GetEndContainer(), aReplaceRange->EndOffset(),
IgnoreErrors());
NS_WARNING_ASSERTION(targetRange && targetRange->IsPositioned(),
"StaticRange::Create() failed");
} else {
Element* editingHost = AsHTMLEditor()->ComputeEditingHost();
NS_WARNING_ASSERTION(editingHost,
"No active editing host, no target ranges");
if (editingHost) {
targetRange = StaticRange::Create(
editingHost, 0, editingHost, editingHost->Length(), IgnoreErrors());
NS_WARNING_ASSERTION(targetRange && targetRange->IsPositioned(),
"StaticRange::Create() failed");
}
}
if (targetRange && targetRange->IsPositioned()) {
editActionData.AppendTargetRange(*targetRange);
}
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
// This should emulates inserting text for better undo/redo behavior.
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertText, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return EditorBase::ToGenericNSResult(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
if (!aReplaceRange) {
// Use fast path if we're `TextEditor` because it may be in a hot path.
if (IsTextEditor()) {
nsresult rv = MOZ_KnownLive(AsTextEditor())->SetTextAsSubAction(aString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"TextEditor::SetTextAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
MOZ_ASSERT_UNREACHABLE("Setting value of `HTMLEditor` isn't supported");
return EditorBase::ToGenericNSResult(NS_ERROR_FAILURE);
}
if (aString.IsEmpty() && aReplaceRange->Collapsed()) {
NS_WARNING("Setting value was empty and replaced range was empty");
return NS_OK;
}
// Note that do not notify selectionchange caused by selecting all text
// because it's preparation of our delete implementation so web apps
// shouldn't receive such selectionchange before the first mutation.
AutoUpdateViewBatch preventSelectionChangeEvent(*this, __FUNCTION__);
// Select the range but as far as possible, we should not create new range
// even if it's part of special Selection.
ErrorResult error;
SelectionRef().RemoveAllRanges(error);
if (error.Failed()) {
NS_WARNING("Selection::RemoveAllRanges() failed");
return error.StealNSResult();
}
SelectionRef().AddRangeAndSelectFramesAndNotifyListeners(*aReplaceRange,
error);
if (error.Failed()) {
NS_WARNING("Selection::AddRangeAndSelectFramesAndNotifyListeners() failed");
return error.StealNSResult();
}
rv = ReplaceSelectionAsSubAction(aString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::ReplaceSelectionAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::ReplaceSelectionAsSubAction(const nsAString& aString) {
if (aString.IsEmpty()) {
nsresult rv = DeleteSelectionAsSubAction(
nsIEditor::eNone,
IsTextEditor() ? nsIEditor::eNoStrip : nsIEditor::eStrip);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::DeleteSelectionAsSubAction(eNone) failed");
return rv;
}
nsresult rv = InsertTextAsSubAction(aString, SelectionHandling::Delete);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
return rv;
}
nsresult EditorBase::HandleInlineSpellCheck(
const EditorDOMPoint& aPreviouslySelectedStart,
const AbstractRange* aRange) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!mInlineSpellChecker) {
return NS_OK;
}
nsresult rv = mInlineSpellChecker->SpellCheckAfterEditorChange(
GetTopLevelEditSubAction(), SelectionRef(),
aPreviouslySelectedStart.GetContainer(),
aPreviouslySelectedStart.Offset(),
aRange ? aRange->GetStartContainer() : nullptr,
aRange ? aRange->StartOffset() : 0,
aRange ? aRange->GetEndContainer() : nullptr,
aRange ? aRange->EndOffset() : 0);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"mozInlineSpellChecker::SpellCheckAfterEditorChange() failed");
return rv;
}
Element* EditorBase::FindSelectionRoot(const nsINode& aNode) const {
return GetRoot();
}
void EditorBase::InitializeSelectionAncestorLimit(
nsIContent& aAncestorLimit) const {
MOZ_ASSERT(IsEditActionDataAvailable());
SelectionRef().SetAncestorLimiter(&aAncestorLimit);
}
nsresult EditorBase::InitializeSelection(
const nsINode& aOriginalEventTargetNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
nsCOMPtr<nsIContent> selectionRootContent =
FindSelectionRoot(aOriginalEventTargetNode);
if (!selectionRootContent) {
return NS_OK;
}
nsCOMPtr<nsISelectionController> selectionController =
GetSelectionController();
if (NS_WARN_IF(!selectionController)) {
return NS_ERROR_FAILURE;
}
// Init the caret
RefPtr<nsCaret> caret = GetCaret();
if (NS_WARN_IF(!caret)) {
return NS_ERROR_FAILURE;
}
caret->SetSelection(&SelectionRef());
DebugOnly<nsresult> rvIgnored =
selectionController->SetCaretReadOnly(IsReadonly());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetCaretReadOnly() failed, but ignored");
rvIgnored = selectionController->SetCaretEnabled(true);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetCaretEnabled() failed, but ignored");
// NOTE(emilio): It's important for this call to be after
// SetCaretEnabled(true), since that would override mIgnoreUserModify to true.
//
// Also, make sure to always ignore it for designMode, since that effectively
// overrides everything and we allow to edit stuff with
// contenteditable="false" subtrees in such a document.
caret->SetIgnoreUserModify(aOriginalEventTargetNode.IsInDesignMode());
// Init selection
rvIgnored =
selectionController->SetSelectionFlags(nsISelectionDisplay::DISPLAY_ALL);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetSelectionFlags() failed, but ignored");
selectionController->SelectionWillTakeFocus();
// If the computed selection root isn't root content, we should set it
// as selection ancestor limit. However, if that is root element, it means
// there is not limitation of the selection, then, we must set nullptr.
// NOTE: If we set a root element to the ancestor limit, some selection
// methods don't work fine.
if (selectionRootContent->GetParent()) {
InitializeSelectionAncestorLimit(*selectionRootContent);
} else {
SelectionRef().SetAncestorLimiter(nullptr);
}
// If there is composition when this is called, we may need to restore IME
// selection because if the editor is reframed, this already forgot IME
// selection and the transaction.
if (mComposition && mComposition->IsMovingToNewTextNode()) {
MOZ_DIAGNOSTIC_ASSERT(IsTextEditor());
if (NS_WARN_IF(!IsTextEditor())) {
return NS_ERROR_UNEXPECTED;
}
// We need to look for the new text node from current selection.
// XXX If selection is changed during reframe, this doesn't work well!
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
EditorRawDOMPoint atStartOfFirstRange(firstRange->StartRef());
EditorRawDOMPoint betterInsertionPoint =
AsTextEditor()->FindBetterInsertionPoint(atStartOfFirstRange);
RefPtr<Text> textNode = betterInsertionPoint.GetContainerAs<Text>();
MOZ_ASSERT(textNode,
"There must be text node if composition string is not empty");
if (textNode) {
MOZ_ASSERT(textNode->Length() >= mComposition->XPEndOffsetInTextNode(),
"The text node must be different from the old text node");
RefPtr<TextRangeArray> ranges = mComposition->GetRanges();
DebugOnly<nsresult> rvIgnored = CompositionTransaction::SetIMESelection(
*this, textNode, mComposition->XPOffsetInTextNode(),
mComposition->XPLengthInTextNode(), ranges);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"CompositionTransaction::SetIMESelection() failed, but ignored");
mComposition->OnUpdateCompositionInEditor(
mComposition->String(), *textNode,
mComposition->XPOffsetInTextNode());
}
}
return NS_OK;
}
nsresult EditorBase::FinalizeSelection() {
nsCOMPtr<nsISelectionController> selectionController =
GetSelectionController();
if (NS_WARN_IF(!selectionController)) {
return NS_ERROR_FAILURE;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
SelectionRef().SetAncestorLimiter(nullptr);
if (NS_WARN_IF(!GetPresShell())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (RefPtr<nsCaret> caret = GetCaret()) {
caret->SetIgnoreUserModify(true);
DebugOnly<nsresult> rvIgnored = selectionController->SetCaretEnabled(false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISelectionController::SetCaretEnabled(false) failed, but ignored");
}
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_NOT_INITIALIZED;
}
// TODO: Running script from here makes harder to handle blur events. We
// should do this asynchronously.
focusManager->UpdateCaretForCaretBrowsingMode();
if (Element* rootElement = GetExposedRoot()) {
if (rootElement->OwnerDoc()->GetUnretargetedFocusedContent() !=
rootElement) {
selectionController->SelectionWillLoseFocus();
} else {
// We leave this selection as the focused one. When the focus returns, it
// either returns to us (nothing to do), or it returns to something else,
// and nsDocumentViewerFocusListener::HandleEvent fixes it up.
}
}
return NS_OK;
}
Element* EditorBase::GetExposedRoot() const {
Element* rootElement = GetRoot();
if (!rootElement || !rootElement->IsInNativeAnonymousSubtree()) {
return rootElement;
}
return Element::FromNodeOrNull(
rootElement->GetClosestNativeAnonymousSubtreeRootParentOrHost());
}
nsresult EditorBase::DetermineCurrentDirection() {
// Get the current root direction from its frame
Element* rootElement = GetExposedRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_FAILURE;
}
// If we don't have an explicit direction, determine our direction
// from the content's direction
if (!IsRightToLeft() && !IsLeftToRight()) {
nsIFrame* frameForRootElement = rootElement->GetPrimaryFrame();
if (NS_WARN_IF(!frameForRootElement)) {
return NS_ERROR_FAILURE;
}
// Set the flag here, to enable us to use the same code path below.
// It will be flipped before returning from the function.
if (frameForRootElement->StyleVisibility()->mDirection ==
StyleDirection::Rtl) {
mFlags |= nsIEditor::eEditorRightToLeft;
} else {
mFlags |= nsIEditor::eEditorLeftToRight;
}
}
return NS_OK;
}
nsresult EditorBase::ToggleTextDirectionAsAction(nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eSetTextDirection,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = DetermineCurrentDirection();
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DetermineCurrentDirection() failed");
return EditorBase::ToGenericNSResult(rv);
}
MOZ_ASSERT(IsRightToLeft() || IsLeftToRight());
// Note that we need to consider new direction before dispatching
// "beforeinput" event since "beforeinput" event listener may change it
// but not canceled.
TextDirection newDirection =
IsRightToLeft() ? TextDirection::eLTR : TextDirection::eRTL;
editActionData.SetData(IsRightToLeft() ? u"ltr"_ns : u"rtl"_ns);
// FYI: Oddly, Chrome does not dispatch beforeinput event in this case but
// dispatches input event.
rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
rv = SetTextDirectionTo(newDirection);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::SetTextDirectionTo() failed");
return EditorBase::ToGenericNSResult(rv);
}
editActionData.MarkAsHandled();
// XXX When we don't change the text direction, do we really need to
// dispatch input event?
DispatchInputEvent();
return NS_OK;
}
void EditorBase::SwitchTextDirectionTo(TextDirection aTextDirection) {
MOZ_ASSERT(aTextDirection == TextDirection::eLTR ||
aTextDirection == TextDirection::eRTL);
AutoEditActionDataSetter editActionData(*this, EditAction::eSetTextDirection);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
nsresult rv = DetermineCurrentDirection();
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
editActionData.SetData(aTextDirection == TextDirection::eLTR ? u"ltr"_ns
: u"rtl"_ns);
// FYI: Oddly, Chrome does not dispatch beforeinput event in this case but
// dispatches input event.
rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return;
}
if ((aTextDirection == TextDirection::eLTR && IsRightToLeft()) ||
(aTextDirection == TextDirection::eRTL && IsLeftToRight())) {
// Do it only when the direction is still different from the original
// new direction. Note that "beforeinput" event listener may have already
// changed the direction here, but they may not cancel the event.
nsresult rv = SetTextDirectionTo(aTextDirection);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::SetTextDirectionTo() failed");
return;
}
}
editActionData.MarkAsHandled();
// XXX When we don't change the text direction, do we really need to
// dispatch input event?
DispatchInputEvent();
}
nsresult EditorBase::SetTextDirectionTo(TextDirection aTextDirection) {
Element* const editingHostOrTextControlElement =
IsHTMLEditor() ? AsHTMLEditor()->ComputeEditingHost(
HTMLEditor::LimitInBodyElement::No)
: GetExposedRoot();
if (!editingHostOrTextControlElement) { // Don't warn, HTMLEditor may have no
// active editing host
return NS_OK;
}
if (aTextDirection == TextDirection::eLTR) {
NS_ASSERTION(!IsLeftToRight(), "Unexpected mutually exclusive flag");
mFlags &= ~nsIEditor::eEditorRightToLeft;
mFlags |= nsIEditor::eEditorLeftToRight;
nsresult rv = editingHostOrTextControlElement->SetAttr(
kNameSpaceID_None, nsGkAtoms::dir, u"ltr"_ns, true);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Element::SetAttr(nsGkAtoms::dir, ltr) failed");
return rv;
}
if (aTextDirection == TextDirection::eRTL) {
NS_ASSERTION(!IsRightToLeft(), "Unexpected mutually exclusive flag");
mFlags |= nsIEditor::eEditorRightToLeft;
mFlags &= ~nsIEditor::eEditorLeftToRight;
nsresult rv = editingHostOrTextControlElement->SetAttr(
kNameSpaceID_None, nsGkAtoms::dir, u"rtl"_ns, true);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Element::SetAttr(nsGkAtoms::dir, rtl) failed");
return rv;
}
return NS_OK;
}
Element* EditorBase::GetFocusedElement() const {
EventTarget* eventTarget = GetDOMEventTarget();
if (!eventTarget) {
return nullptr;
}
nsFocusManager* focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return nullptr;
}
Element* focusedElement = focusManager->GetFocusedElement();
MOZ_ASSERT((focusedElement == eventTarget) ==
SameCOMIdentity(focusedElement, eventTarget));
return (focusedElement == eventTarget) ? focusedElement : nullptr;
}
bool EditorBase::IsActiveInDOMWindow() const {
EventTarget* piTarget = GetDOMEventTarget();
if (!piTarget) {
return false;
}
nsFocusManager* focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return false; // Do we need to check the singleton instance??
}
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return false;
}
nsPIDOMWindowOuter* ourWindow = document->GetWindow();
nsCOMPtr<nsPIDOMWindowOuter> win;
nsIContent* content = nsFocusManager::GetFocusedDescendant(
ourWindow, nsFocusManager::eOnlyCurrentWindow, getter_AddRefs(win));
return SameCOMIdentity(content, piTarget);
}
bool EditorBase::IsAcceptableInputEvent(WidgetGUIEvent* aGUIEvent) const {
// If the event is trusted, the event should always cause input.
if (NS_WARN_IF(!aGUIEvent)) {
return false;
}
// If this is dispatched by using cordinates but this editor doesn't have
// focus, we shouldn't handle it.
if (aGUIEvent->IsUsingCoordinates() && !GetFocusedElement()) {
return false;
}
// If a composition event isn't dispatched via widget, we need to ignore them
// since they cannot be managed by TextComposition. E.g., the event was
// created by chrome JS.
// Note that if we allow to handle such events, editor may be confused by
// strange event order.
bool needsWidget = false;
switch (aGUIEvent->mMessage) {
case eUnidentifiedEvent:
// If events are not created with proper event interface, their message
// are initialized with eUnidentifiedEvent. Let's ignore such event.
return false;
case eCompositionStart:
case eCompositionEnd:
case eCompositionUpdate:
case eCompositionChange:
case eCompositionCommitAsIs:
// Don't allow composition events whose internal event are not
// WidgetCompositionEvent.
if (!aGUIEvent->AsCompositionEvent()) {
return false;
}
needsWidget = true;
break;
default:
break;
}
if (needsWidget && !aGUIEvent->mWidget) {
return false;
}
// Accept all trusted events.
if (aGUIEvent->IsTrusted()) {
return true;
}
// Ignore untrusted mouse event.
// XXX Why are we handling other untrusted input events?
if (aGUIEvent->AsMouseEventBase()) {
return false;
}
// Otherwise, we shouldn't handle any input events when we're not an active
// element of the DOM window.
return IsActiveInDOMWindow();
}
nsresult EditorBase::FlushPendingSpellCheck() {
// If the spell check skip flag is still enabled from creation time,
// disable it because focused editors are allowed to spell check.
if (!ShouldSkipSpellCheck()) {
return NS_OK;
}
MOZ_ASSERT(!IsHTMLEditor(), "HTMLEditor should not has pending spell checks");
nsresult rv = RemoveFlags(nsIEditor::eEditorSkipSpellCheck);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::RemoveFlags(nsIEditor::eEditorSkipSpellCheck) failed");
return rv;
}
bool EditorBase::CanKeepHandlingFocusEvent(
const nsINode& aOriginalEventTargetNode) const {
if (MOZ_UNLIKELY(!IsListeningToEvents() || Destroyed())) {
return false;
}
nsFocusManager* focusManager = nsFocusManager::GetFocusManager();
if (MOZ_UNLIKELY(!focusManager)) {
return false;
}
// If the event target is document mode, we only need to handle the focus
// event when the document is still in designMode. Otherwise, the
// mode has been disabled by somebody while we're handling the focus event.
if (aOriginalEventTargetNode.IsDocument()) {
return IsHTMLEditor() && aOriginalEventTargetNode.IsInDesignMode();
}
MOZ_ASSERT(aOriginalEventTargetNode.IsContent());
// If nobody has focus, the focus event target has been blurred by somebody
// else. So the editor shouldn't initialize itself to start to handle
// anything.
if (!focusManager->GetFocusedElement()) {
return false;
}
// If there's an HTMLEditor registered in the target document and we
// are not that HTMLEditor (for cases like nested documents), let
// that HTMLEditor to handle the focus event.
if (IsHTMLEditor()) {
const HTMLEditor* precedentHTMLEditor =
aOriginalEventTargetNode.OwnerDoc()->GetHTMLEditor();
if (precedentHTMLEditor && precedentHTMLEditor != this) {
return false;
}
}
const nsIContent* exposedTargetContent =
aOriginalEventTargetNode.AsContent()
->FindFirstNonChromeOnlyAccessContent();
const nsIContent* exposedFocusedContent =
focusManager->GetFocusedElement()->FindFirstNonChromeOnlyAccessContent();
return exposedTargetContent && exposedFocusedContent &&
exposedTargetContent == exposedFocusedContent;
}
nsresult EditorBase::OnFocus(const nsINode& aOriginalEventTargetNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
InitializeSelection(aOriginalEventTargetNode);
mSpellCheckerDictionaryUpdated = false;
if (mInlineSpellChecker && CanEnableSpellCheck()) {
DebugOnly<nsresult> rvIgnored =
mInlineSpellChecker->UpdateCurrentDictionary();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"mozInlineSpellCHecker::UpdateCurrentDictionary() failed, but ignored");
mSpellCheckerDictionaryUpdated = true;
}
// XXX Why don't we stop handling focus with the spell checker immediately
// after calling InitializeSelection?
if (MOZ_UNLIKELY(!CanKeepHandlingFocusEvent(aOriginalEventTargetNode))) {
return NS_ERROR_EDITOR_DESTROYED;
}
const RefPtr<Element> focusedElement = GetFocusedElement();
RefPtr<nsPresContext> presContext =
focusedElement ? focusedElement->GetPresContext(
Element::PresContextFor::eForComposedDoc)
: GetPresContext();
if (NS_WARN_IF(!presContext)) {
return NS_ERROR_FAILURE;
}
IMEStateManager::OnFocusInEditor(*presContext, focusedElement, *this);
return NS_OK;
}
void EditorBase::HideCaret(bool aHide) {
if (mHidingCaret == aHide) {
return;
}
RefPtr<nsCaret> caret = GetCaret();
if (NS_WARN_IF(!caret)) {
return;
}
mHidingCaret = aHide;
if (aHide) {
caret->AddForceHide();
} else {
caret->RemoveForceHide();
}
}
NS_IMETHODIMP EditorBase::Unmask(uint32_t aStart, int64_t aEnd,
uint32_t aTimeout, uint8_t aArgc) {
if (NS_WARN_IF(!IsPasswordEditor())) {
return NS_ERROR_NOT_AVAILABLE;
}
if (NS_WARN_IF(aArgc >= 1 && aStart == UINT32_MAX) ||
NS_WARN_IF(aArgc >= 2 && aEnd == 0) ||
NS_WARN_IF(aArgc >= 2 && aEnd > 0 && aStart >= aEnd)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eHidePassword);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
uint32_t start = aArgc < 1 ? 0 : aStart;
uint32_t length = aArgc < 2 || aEnd < 0 ? UINT32_MAX : aEnd - start;
uint32_t timeout = aArgc < 3 ? 0 : aTimeout;
nsresult rv = MOZ_KnownLive(AsTextEditor())
->SetUnmaskRangeAndNotify(start, length, timeout);
if (NS_FAILED(rv)) {
NS_WARNING("TextEditor::SetUnmaskRangeAndNotify() failed");
return EditorBase::ToGenericNSResult(rv);
}
// Flush pending layout right now since the caller may access us before
// doing it.
if (RefPtr<PresShell> presShell = GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Layout);
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::Mask() {
if (NS_WARN_IF(!IsPasswordEditor())) {
return NS_ERROR_NOT_AVAILABLE;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eHidePassword);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = MOZ_KnownLive(AsTextEditor())->MaskAllCharactersAndNotify();
if (NS_FAILED(rv)) {
NS_WARNING("TextEditor::MaskAllCharactersAndNotify() failed");
return EditorBase::ToGenericNSResult(rv);
}
// Flush pending layout right now since the caller may access us before
// doing it.
if (RefPtr<PresShell> presShell = GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Layout);
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetUnmaskedStart(uint32_t* aResult) {
if (NS_WARN_IF(!IsPasswordEditor())) {
*aResult = 0;
return NS_ERROR_NOT_AVAILABLE;
}
*aResult =
AsTextEditor()->IsAllMasked() ? 0 : AsTextEditor()->UnmaskedStart();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetUnmaskedEnd(uint32_t* aResult) {
if (NS_WARN_IF(!IsPasswordEditor())) {
*aResult = 0;
return NS_ERROR_NOT_AVAILABLE;
}
*aResult = AsTextEditor()->IsAllMasked() ? 0 : AsTextEditor()->UnmaskedEnd();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetAutoMaskingEnabled(bool* aResult) {
if (NS_WARN_IF(!IsPasswordEditor())) {
*aResult = false;
return NS_ERROR_NOT_AVAILABLE;
}
*aResult = AsTextEditor()->IsMaskingPassword();
return NS_OK;
}
NS_IMETHODIMP EditorBase::GetPasswordMask(nsAString& aPasswordMask) {
aPasswordMask.Assign(TextEditor::PasswordMask());
return NS_OK;
}
template <typename PT, typename CT>
EditorBase::AutoCaretBidiLevelManager::AutoCaretBidiLevelManager(
const EditorBase& aEditorBase, nsIEditor::EDirection aDirectionAndAmount,
const EditorDOMPointBase<PT, CT>& aPointAtCaret) {
MOZ_ASSERT(aEditorBase.IsEditActionDataAvailable());
nsPresContext* presContext = aEditorBase.GetPresContext();
if (NS_WARN_IF(!presContext)) {
mFailed = true;
return;
}
if (!presContext->BidiEnabled()) {
return; // Perform the deletion
}
if (!aPointAtCaret.IsInContentNode()) {
mFailed = true;
return;
}
// XXX Not sure whether this requires strong reference here.
RefPtr<nsFrameSelection> frameSelection =
aEditorBase.SelectionRef().GetFrameSelection();
if (NS_WARN_IF(!frameSelection)) {
mFailed = true;
return;
}
nsPrevNextBidiLevels levels = frameSelection->GetPrevNextBidiLevels(
aPointAtCaret.template ContainerAs<nsIContent>(), aPointAtCaret.Offset(),
true);
mozilla::intl::BidiEmbeddingLevel levelBefore = levels.mLevelBefore;
mozilla::intl::BidiEmbeddingLevel levelAfter = levels.mLevelAfter;
mozilla::intl::BidiEmbeddingLevel currentCaretLevel =
frameSelection->GetCaretBidiLevel();
mozilla::intl::BidiEmbeddingLevel levelOfDeletion;
levelOfDeletion = (nsIEditor::eNext == aDirectionAndAmount ||
nsIEditor::eNextWord == aDirectionAndAmount)
? levelAfter
: levelBefore;
if (currentCaretLevel == levelOfDeletion) {
return; // Perform the deletion
}
// Set the bidi level of the caret to that of the
// character that will be (or would have been) deleted
mNewCaretBidiLevel = Some(levelOfDeletion);
mCanceled =
!StaticPrefs::bidi_edit_delete_immediately() && levelBefore != levelAfter;
}
void EditorBase::AutoCaretBidiLevelManager::MaybeUpdateCaretBidiLevel(
const EditorBase& aEditorBase) const {
MOZ_ASSERT(!mFailed);
if (mNewCaretBidiLevel.isNothing()) {
return;
}
RefPtr<nsFrameSelection> frameSelection =
aEditorBase.SelectionRef().GetFrameSelection();
MOZ_ASSERT(frameSelection);
frameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(
mNewCaretBidiLevel.value());
}
void EditorBase::UndefineCaretBidiLevel() const {
MOZ_ASSERT(IsEditActionDataAvailable());
/**
* After inserting text the caret Bidi level must be set to the level of the
* inserted text.This is difficult, because we cannot know what the level is
* until after the Bidi algorithm is applied to the whole paragraph.
*
* So we set the caret Bidi level to UNDEFINED here, and the caret code will
* set it correctly later
*/
nsFrameSelection* frameSelection = SelectionRef().GetFrameSelection();
if (frameSelection) {
frameSelection->UndefineCaretBidiLevel();
}
}
NS_IMETHODIMP EditorBase::GetTextLength(uint32_t* aCount) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP EditorBase::GetNewlineHandling(int32_t* aNewlineHandling) {
if (NS_WARN_IF(!aNewlineHandling)) {
return NS_ERROR_INVALID_ARG;
}
*aNewlineHandling = mNewlineHandling;
return NS_OK;
}
NS_IMETHODIMP EditorBase::SetNewlineHandling(int32_t aNewlineHandling) {
switch (aNewlineHandling) {
case nsIEditor::eNewlinesPasteIntact:
case nsIEditor::eNewlinesPasteToFirst:
case nsIEditor::eNewlinesReplaceWithSpaces:
case nsIEditor::eNewlinesStrip:
case nsIEditor::eNewlinesReplaceWithCommas:
case nsIEditor::eNewlinesStripSurroundingWhitespace:
mNewlineHandling = aNewlineHandling;
return NS_OK;
default:
NS_ERROR("SetNewlineHandling() is called with wrong value");
return NS_ERROR_INVALID_ARG;
}
}
bool EditorBase::IsSelectionRangeContainerNotContent() const {
MOZ_ASSERT(IsEditActionDataAvailable());
// TODO: Make all callers use !AutoRangeArray::IsInContent() instead.
const uint32_t rangeCount = SelectionRef().RangeCount();
for (const uint32_t i : IntegerRange(rangeCount)) {
MOZ_ASSERT(SelectionRef().RangeCount() == rangeCount);
const nsRange* range = SelectionRef().GetRangeAt(i);
MOZ_ASSERT(range);
if (MOZ_UNLIKELY(!range) || MOZ_UNLIKELY(!range->GetStartContainer()) ||
MOZ_UNLIKELY(!range->GetStartContainer()->IsContent()) ||
MOZ_UNLIKELY(!range->GetEndContainer()) ||
MOZ_UNLIKELY(!range->GetEndContainer()->IsContent())) {
return true;
}
}
return false;
}
NS_IMETHODIMP EditorBase::InsertText(const nsAString& aStringToInsert) {
nsresult rv = InsertTextAsAction(aStringToInsert);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsAction() failed");
return rv;
}
nsresult EditorBase::InsertTextAsAction(const nsAString& aStringToInsert,
nsIPrincipal* aPrincipal) {
// Showing this assertion is fine if this method is called by outside via
// mutation event listener or something. Otherwise, this is called by
// wrong method.
NS_ASSERTION(!mPlaceholderBatch,
"Should be called only when this is the only edit action of the "
"operation "
"unless mutation event listener nests some operations");
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertText,
aPrincipal);
// Note that we don't need to replace native line breaks with XP line breaks
// here because Chrome does not do it.
MOZ_ASSERT(!aStringToInsert.IsVoid());
editActionData.SetData(aStringToInsert);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsString stringToInsert(aStringToInsert);
if (IsTextEditor()) {
nsContentUtils::PlatformToDOMLineBreaks(stringToInsert);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertTextAsSubAction(stringToInsert, SelectionHandling::Delete);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult EditorBase::InsertTextAsSubAction(
const nsAString& aStringToInsert, SelectionHandling aSelectionHandling) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(mPlaceholderBatch);
MOZ_ASSERT(IsHTMLEditor() ||
aStringToInsert.FindChar(nsCRT::CR) == kNotFound);
MOZ_ASSERT_IF(aSelectionHandling == SelectionHandling::Ignore, mComposition);
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
EditSubAction editSubAction = ShouldHandleIMEComposition()
? EditSubAction::eInsertTextComingFromIME
: EditSubAction::eInsertText;
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, editSubAction, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
Result<EditActionResult, nsresult> result =
HandleInsertText(editSubAction, aStringToInsert, aSelectionHandling);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("EditorBase::HandleInsertText() failed");
return result.unwrapErr();
}
return NS_OK;
}
NS_IMETHODIMP EditorBase::InsertLineBreak() { return NS_ERROR_NOT_IMPLEMENTED; }
/*****************************************************************************
* mozilla::EditorBase::AutoEditActionDataSetter
*****************************************************************************/
EditorBase::AutoEditActionDataSetter::AutoEditActionDataSetter(
const EditorBase& aEditorBase, EditAction aEditAction,
nsIPrincipal* aPrincipal /* = nullptr */)
: mEditorBase(const_cast<EditorBase&>(aEditorBase)),
mPrincipal(aPrincipal),
mParentData(aEditorBase.mEditActionData),
mData(VoidString()),
mRawEditAction(aEditAction),
mTopLevelEditSubAction(EditSubAction::eNone),
mAborted(false),
mHasTriedToDispatchBeforeInputEvent(false),
mBeforeInputEventCanceled(false),
mMakeBeforeInputEventNonCancelable(false),
mHasTriedToDispatchClipboardEvent(false),
mEditorWasDestroyedDuringHandlingEditAction(
mParentData &&
mParentData->mEditorWasDestroyedDuringHandlingEditAction),
mHandled(false) {
// If we're nested edit action, copies necessary data from the parent.
if (mParentData) {
mSelection = mParentData->mSelection;
MOZ_ASSERT(!mSelection ||
(mSelection->GetType() == SelectionType::eNormal));
// If we're not editing something, we should inherit the parent's edit
// action. This may occur if creator or its callee use public methods which
// just returns something.
if (IsEditActionInOrderToEditSomething(aEditAction)) {
mEditAction = aEditAction;
} else {
mEditAction = mParentData->mEditAction;
// If we inherit an edit action whose handler needs to dispatch a
// clipboard event, we should inherit the clipboard dispatching state
// too because this nest occurs by a clipboard event listener or
// a beforeinput/mutation event listener is important for checking
// whether we've already called `MaybeDispatchBeforeInputEvent()`
// property in some points. If the former case, not yet dispatching
// beforeinput event is okay (not fine).
mHasTriedToDispatchClipboardEvent =
mParentData->mHasTriedToDispatchClipboardEvent;
}
mTopLevelEditSubAction = mParentData->mTopLevelEditSubAction;
// Parent's mTopLevelEditSubActionData should be referred instead so that
// we don't need to set mTopLevelEditSubActionData.mSelectedRange nor
// mTopLevelEditActionData.mChangedRange here.
mDirectionOfTopLevelEditSubAction =
mParentData->mDirectionOfTopLevelEditSubAction;
} else {
mSelection = mEditorBase.GetSelection();
if (NS_WARN_IF(!mSelection)) {
return;
}
MOZ_ASSERT(mSelection->GetType() == SelectionType::eNormal);
mEditAction = aEditAction;
mDirectionOfTopLevelEditSubAction = eNone;
if (mEditorBase.IsHTMLEditor()) {
mTopLevelEditSubActionData.mSelectedRange =
mEditorBase.AsHTMLEditor()
->GetSelectedRangeItemForTopLevelEditSubAction();
mTopLevelEditSubActionData.mChangedRange =
mEditorBase.AsHTMLEditor()->GetChangedRangeForTopLevelEditSubAction();
mTopLevelEditSubActionData.mCachedPendingStyles.emplace();
}
}
mEditorBase.mEditActionData = this;
}
EditorBase::AutoEditActionDataSetter::~AutoEditActionDataSetter() {
MOZ_ASSERT(mHasCanHandleChecked);
if (!mSelection || NS_WARN_IF(mEditorBase.mEditActionData != this)) {
return;
}
mEditorBase.mEditActionData = mParentData;
MOZ_ASSERT(
!mTopLevelEditSubActionData.mSelectedRange ||
(!mTopLevelEditSubActionData.mSelectedRange->mStartContainer &&
!mTopLevelEditSubActionData.mSelectedRange->mEndContainer),
"mTopLevelEditSubActionData.mSelectedRange should've been cleared");
}
void EditorBase::AutoEditActionDataSetter::UpdateSelectionCache(
Selection& aSelection) {
MOZ_ASSERT(aSelection.GetType() == SelectionType::eNormal);
if (mSelection == &aSelection) {
return;
}
AutoEditActionDataSetter& topLevelEditActionData =
[&]() -> AutoEditActionDataSetter& {
for (AutoEditActionDataSetter* editActionData = this;;
editActionData = editActionData->mParentData) {
if (!editActionData->mParentData) {
return *editActionData;
}
}
MOZ_ASSERT_UNREACHABLE("You do something wrong");
}();
// Keep grabbing the old selection in the top level edit action data until the
// all owners end handling it.
if (mSelection) {
topLevelEditActionData.mRetiredSelections.AppendElement(*mSelection);
}
// If the old selection is in batch, we should end the batch which
// `EditorBase::BeginUpdateViewBatch` started.
if (mEditorBase.mUpdateCount && mSelection) {
mSelection->EndBatchChanges(__FUNCTION__);
}
Selection* previousSelection = mSelection;
mSelection = &aSelection;
for (AutoEditActionDataSetter* parentActionData = mParentData;
parentActionData; parentActionData = parentActionData->mParentData) {
if (!parentActionData->mSelection) {
continue;
}
// Skip scanning mRetiredSelections if we've already handled the selection
// previous time.
if (parentActionData->mSelection != previousSelection) {
if (!topLevelEditActionData.mRetiredSelections.Contains(
OwningNonNull<Selection>(*parentActionData->mSelection))) {
topLevelEditActionData.mRetiredSelections.AppendElement(
*parentActionData->mSelection);
}
previousSelection = parentActionData->mSelection;
}
parentActionData->mSelection = &aSelection;
}
// Restart the batching in the new selection.
if (mEditorBase.mUpdateCount) {
aSelection.StartBatchChanges(__FUNCTION__);
}
}
void EditorBase::AutoEditActionDataSetter::SetColorData(
const nsAString& aData) {
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"It's too late to set data since this may have already dispatched "
"a beforeinput event");
if (aData.IsEmpty()) {
// When removing color/background-color, let's use empty string.
mData.Truncate();
MOZ_ASSERT(!mData.IsVoid());
return;
}
DebugOnly<bool> validColorValue = HTMLEditUtils::GetNormalizedCSSColorValue(
aData, HTMLEditUtils::ZeroAlphaColor::RGBAValue, mData);
MOZ_ASSERT_IF(validColorValue, !mData.IsVoid());
}
void EditorBase::AutoEditActionDataSetter::InitializeDataTransfer(
DataTransfer* aDataTransfer) {
MOZ_ASSERT(aDataTransfer);
MOZ_ASSERT(aDataTransfer->IsReadOnly());
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"It's too late to set dataTransfer since this may have already "
"dispatched a beforeinput event");
mDataTransfer = aDataTransfer;
}
void EditorBase::AutoEditActionDataSetter::InitializeDataTransfer(
nsITransferable* aTransferable) {
MOZ_ASSERT(aTransferable);
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"It's too late to set dataTransfer since this may have already "
"dispatched a beforeinput event");
Document* document = mEditorBase.GetDocument();
nsIGlobalObject* scopeObject =
document ? document->GetScopeObject() : nullptr;
mDataTransfer = new DataTransfer(scopeObject, eEditorInput, aTransferable);
}
void EditorBase::AutoEditActionDataSetter::InitializeDataTransfer(
const nsAString& aString) {
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"It's too late to set dataTransfer since this may have already "
"dispatched a beforeinput event");
Document* document = mEditorBase.GetDocument();
nsIGlobalObject* scopeObject =
document ? document->GetScopeObject() : nullptr;
mDataTransfer = new DataTransfer(scopeObject, eEditorInput, aString);
}
void EditorBase::AutoEditActionDataSetter::InitializeDataTransferWithClipboard(
SettingDataTransfer aSettingDataTransfer, int32_t aClipboardType) {
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"It's too late to set dataTransfer since this may have already "
"dispatched a beforeinput event");
Document* document = mEditorBase.GetDocument();
nsIGlobalObject* scopeObject =
document ? document->GetScopeObject() : nullptr;
// mDataTransfer will be used for eEditorInput event, but we can keep
// using ePaste and ePasteNoFormatting here. If we need to use eEditorInput,
// we need to create eEditorInputNoFormatting or something...
mDataTransfer =
new DataTransfer(scopeObject,
aSettingDataTransfer == SettingDataTransfer::eWithFormat
? ePaste
: ePasteNoFormatting,
true /* is external */, aClipboardType);
}
void EditorBase::AutoEditActionDataSetter::AppendTargetRange(
StaticRange& aTargetRange) {
mTargetRanges.AppendElement(aTargetRange);
}
bool EditorBase::AutoEditActionDataSetter::IsBeforeInputEventEnabled() const {
// Don't dispatch "beforeinput" event when the editor user makes us stop
// dispatching input event.
if (mEditorBase.IsSuppressingDispatchingInputEvent()) {
return false;
}
return EditorBase::TreatAsUserInput(mPrincipal);
}
// static
bool EditorBase::TreatAsUserInput(nsIPrincipal* aPrincipal) {
// If aPrincipal it not nullptr, it means that the caller is handling an edit
// action which is requested by JS. If it's not chrome script, we shouldn't
// dispatch "beforeinput" event.
if (aPrincipal && !aPrincipal->IsSystemPrincipal()) {
// But if it's content script of an addon, `execCommand` calls are a
// part of browser's default action from point of view of web apps.
// Therefore, we should dispatch `beforeinput` event.
// https://github.com/w3c/input-events/issues/91
if (!aPrincipal->GetIsAddonOrExpandedAddonPrincipal()) {
return false;
}
}
return true;
}
nsresult EditorBase::AutoEditActionDataSetter::MaybeFlushPendingNotifications()
const {
MOZ_ASSERT(CanHandle());
if (!MayEditActionRequireLayout(mRawEditAction)) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
OwningNonNull<EditorBase> editorBase = mEditorBase;
RefPtr<PresShell> presShell = editorBase->GetPresShell();
if (MOZ_UNLIKELY(NS_WARN_IF(!presShell))) {
return NS_ERROR_NOT_AVAILABLE;
}
presShell->FlushPendingNotifications(FlushType::Layout);
if (MOZ_UNLIKELY(NS_WARN_IF(editorBase->Destroyed()))) {
return NS_ERROR_EDITOR_DESTROYED;
}
return NS_OK;
}
nsresult EditorBase::AutoEditActionDataSetter::MaybeDispatchBeforeInputEvent(
nsIEditor::EDirection aDeleteDirectionAndAmount /* = nsIEditor::eNone */) {
MOZ_ASSERT(!HasTriedToDispatchBeforeInputEvent(),
"We've already handled beforeinput event");
MOZ_ASSERT(CanHandle());
MOZ_ASSERT_IF(IsBeforeInputEventEnabled(),
ShouldAlreadyHaveHandledBeforeInputEventDispatching());
MOZ_ASSERT_IF(!MayEditActionDeleteAroundCollapsedSelection(mEditAction),
aDeleteDirectionAndAmount == nsIEditor::eNone);
mHasTriedToDispatchBeforeInputEvent = true;
if (!IsBeforeInputEventEnabled()) {
return NS_OK;
}
// If we're called from OnCompositionEnd(), we shouldn't dispatch
// "beforeinput" event since the preceding OnCompositionChange() call has
// already dispatched "beforeinput" event for this.
if (mEditAction == EditAction::eCommitComposition ||
mEditAction == EditAction::eCancelComposition) {
return NS_OK;
}
RefPtr<Element> targetElement = mEditorBase.GetInputEventTargetElement();
if (!targetElement) {
// If selection is not in editable element and it is outside of any
// editing hosts, there may be no target element to dispatch `beforeinput`
// event. In this case, the caller shouldn't keep handling the edit
// action since web apps cannot override it with `beforeinput` event
// listener, but for backward compatibility, we should return a special
// success code instead of error.
return NS_OK;
}
OwningNonNull<EditorBase> editorBase = mEditorBase;
EditorInputType inputType = ToInputType(mEditAction);
if (editorBase->IsHTMLEditor() && mTargetRanges.IsEmpty()) {
// If the edit action will delete selected ranges, compute the range
// strictly.
if (MayEditActionDeleteAroundCollapsedSelection(mEditAction) ||
(!editorBase->SelectionRef().IsCollapsed() &&
MayEditActionDeleteSelection(mEditAction))) {
if (!editorBase
->FlushPendingNotificationsIfToHandleDeletionWithFrameSelection(
aDeleteDirectionAndAmount)) {
NS_WARNING(
"Flusing pending notifications caused destroying the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
AutoRangeArray rangesToDelete(editorBase->SelectionRef());
if (!rangesToDelete.Ranges().IsEmpty()) {
nsresult rv = MOZ_KnownLive(editorBase->AsHTMLEditor())
->ComputeTargetRanges(aDeleteDirectionAndAmount,
rangesToDelete);
if (rv == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING("HTMLEditor::ComputeTargetRanges() destroyed the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
if (rv == NS_ERROR_EDITOR_NO_EDITABLE_RANGE) {
// For now, keep dispatching `beforeinput` event even if no selection
// range can be editable.
rv = NS_OK;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::ComputeTargetRanges() failed, but ignored");
for (auto& range : rangesToDelete.Ranges()) {
RefPtr<StaticRange> staticRange =
StaticRange::Create(range, IgnoreErrors());
if (NS_WARN_IF(!staticRange)) {
continue;
}
AppendTargetRange(*staticRange);
}
}
}
// Otherwise, just set target ranges to selection ranges.
else if (MayHaveTargetRangesOnHTMLEditor(inputType)) {
if (uint32_t rangeCount = editorBase->SelectionRef().RangeCount()) {
mTargetRanges.SetCapacity(rangeCount);
for (const uint32_t i : IntegerRange(rangeCount)) {
MOZ_ASSERT(editorBase->SelectionRef().RangeCount() == rangeCount);
const nsRange* range = editorBase->SelectionRef().GetRangeAt(i);
MOZ_ASSERT(range);
MOZ_ASSERT(range->IsPositioned());
if (MOZ_UNLIKELY(NS_WARN_IF(!range)) ||
MOZ_UNLIKELY(NS_WARN_IF(!range->IsPositioned()))) {
continue;
}
// Now, we need to fix the offset of target range because it may
// be referred after modifying the DOM tree and range boundaries
// of `range` may have not computed offset yet.
RefPtr<StaticRange> targetRange = StaticRange::Create(
range->GetStartContainer(), range->StartOffset(),
range->GetEndContainer(), range->EndOffset(), IgnoreErrors());
if (NS_WARN_IF(!targetRange) ||
NS_WARN_IF(!targetRange->IsPositioned())) {
continue;
}
mTargetRanges.AppendElement(std::move(targetRange));
}
}
}
}
nsEventStatus status = nsEventStatus_eIgnore;
InputEventOptions::NeverCancelable neverCancelable =
mMakeBeforeInputEventNonCancelable
? InputEventOptions::NeverCancelable::Yes
: InputEventOptions::NeverCancelable::No;
nsresult rv = nsContentUtils::DispatchInputEvent(
targetElement, eEditorBeforeInput, inputType, editorBase,
mDataTransfer
? InputEventOptions(mDataTransfer, std::move(mTargetRanges),
neverCancelable)
: InputEventOptions(mData, std::move(mTargetRanges), neverCancelable),
&status);
if (NS_WARN_IF(mEditorBase.Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING("nsContentUtils::DispatchInputEvent() failed");
return rv;
}
mBeforeInputEventCanceled = status == nsEventStatus_eConsumeNoDefault;
if (mBeforeInputEventCanceled && mEditorBase.IsHTMLEditor()) {
mEditorBase.AsHTMLEditor()->mHasBeforeInputBeenCanceled = true;
}
return mBeforeInputEventCanceled ? NS_ERROR_EDITOR_ACTION_CANCELED : NS_OK;
}
/*****************************************************************************
* mozilla::EditorBase::TopLevelEditSubActionData
*****************************************************************************/
nsresult EditorBase::TopLevelEditSubActionData::AddNodeToChangedRange(
const HTMLEditor& aHTMLEditor, nsINode& aNode) {
EditorRawDOMPoint startPoint(&aNode);
EditorRawDOMPoint endPoint(&aNode);
DebugOnly<bool> advanced = endPoint.AdvanceOffset();
NS_WARNING_ASSERTION(advanced, "Failed to set endPoint to next to aNode");
nsresult rv = AddRangeToChangedRange(aHTMLEditor, startPoint, endPoint);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"TopLevelEditSubActionData::AddRangeToChangedRange() failed");
return rv;
}
nsresult EditorBase::TopLevelEditSubActionData::AddPointToChangedRange(
const HTMLEditor& aHTMLEditor, const EditorRawDOMPoint& aPoint) {
nsresult rv = AddRangeToChangedRange(aHTMLEditor, aPoint, aPoint);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"TopLevelEditSubActionData::AddRangeToChangedRange() failed");
return rv;
}
nsresult EditorBase::TopLevelEditSubActionData::AddRangeToChangedRange(
const HTMLEditor& aHTMLEditor, const EditorRawDOMPoint& aStart,
const EditorRawDOMPoint& aEnd) {
if (NS_WARN_IF(!aStart.IsSet()) || NS_WARN_IF(!aEnd.IsSet())) {
return NS_ERROR_INVALID_ARG;
}
if (!aHTMLEditor.IsDescendantOfRoot(aStart.GetContainer()) ||
(aStart.GetContainer() != aEnd.GetContainer() &&
!aHTMLEditor.IsDescendantOfRoot(aEnd.GetContainer()))) {
return NS_OK;
}
// If mChangedRange hasn't been set, we can just set it to `aStart` and
// `aEnd`.
if (!mChangedRange->IsPositioned()) {
nsresult rv = mChangedRange->SetStartAndEnd(aStart.ToRawRangeBoundary(),
aEnd.ToRawRangeBoundary());
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "nsRange::SetStartAndEnd() failed");
return rv;
}
Maybe<int32_t> relation =
mChangedRange->StartRef().IsSet()
? nsContentUtils::ComparePoints(mChangedRange->StartRef(),
aStart.ToRawRangeBoundary())
: Some(1);
if (NS_WARN_IF(!relation)) {
return NS_ERROR_FAILURE;
}
// If aStart is before start of mChangedRange, reset the start.
if (*relation > 0) {
ErrorResult error;
mChangedRange->SetStart(aStart.ToRawRangeBoundary(), error);
if (error.Failed()) {
NS_WARNING("nsRange::SetStart() failed");
return error.StealNSResult();
}
}
relation = mChangedRange->EndRef().IsSet()
? nsContentUtils::ComparePoints(mChangedRange->EndRef(),
aEnd.ToRawRangeBoundary())
: Some(1);
if (NS_WARN_IF(!relation)) {
return NS_ERROR_FAILURE;
}
// If aEnd is after end of mChangedRange, reset the end.
if (*relation < 0) {
ErrorResult error;
mChangedRange->SetEnd(aEnd.ToRawRangeBoundary(), error);
if (error.Failed()) {
NS_WARNING("nsRange::SetEnd() failed");
return error.StealNSResult();
}
}
return NS_OK;
}
void EditorBase::TopLevelEditSubActionData::DidCreateElement(
EditorBase& aEditorBase, Element& aNewElement) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored =
AddNodeToChangedRange(*aEditorBase.AsHTMLEditor(), aNewElement);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddNodeToChangedRange() failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::DidInsertContent(
EditorBase& aEditorBase, nsIContent& aNewContent) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored =
AddNodeToChangedRange(*aEditorBase.AsHTMLEditor(), aNewContent);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddNodeToChangedRange() failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::WillDeleteContent(
EditorBase& aEditorBase, nsIContent& aRemovingContent) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored =
AddNodeToChangedRange(*aEditorBase.AsHTMLEditor(), aRemovingContent);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddNodeToChangedRange() failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::DidSplitContent(
EditorBase& aEditorBase, nsIContent& aSplitContent,
nsIContent& aNewContent) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored = AddRangeToChangedRange(
*aEditorBase.AsHTMLEditor(), EditorRawDOMPoint::AtEndOf(aSplitContent),
EditorRawDOMPoint::AtEndOf(aNewContent));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddRangeToChangedRange() "
"failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::DidJoinContents(
EditorBase& aEditorBase, const EditorRawDOMPoint& aJoinedPoint) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored =
AddPointToChangedRange(*aEditorBase.AsHTMLEditor(), aJoinedPoint);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddPointToChangedRange() "
"failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::DidInsertText(
EditorBase& aEditorBase, const EditorRawDOMPoint& aInsertionBegin,
const EditorRawDOMPoint& aInsertionEnd) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored = AddRangeToChangedRange(
*aEditorBase.AsHTMLEditor(), aInsertionBegin, aInsertionEnd);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddRangeToChangedRange() "
"failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::DidDeleteText(
EditorBase& aEditorBase, const EditorRawDOMPoint& aStartInTextNode) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
DebugOnly<nsresult> rvIgnored =
AddPointToChangedRange(*aEditorBase.AsHTMLEditor(), aStartInTextNode);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddPointToChangedRange() "
"failed, but ignored");
}
void EditorBase::TopLevelEditSubActionData::WillDeleteRange(
EditorBase& aEditorBase, const EditorRawDOMPoint& aStart,
const EditorRawDOMPoint& aEnd) {
MOZ_ASSERT(aEditorBase.AsHTMLEditor());
MOZ_ASSERT(aStart.IsSet());
MOZ_ASSERT(aEnd.IsSet());
if (!aEditorBase.mInitSucceeded || aEditorBase.Destroyed()) {
return; // We have not been initialized yet or already been destroyed.
}
if (!aEditorBase.EditSubActionDataRef().mAdjustChangedRangeFromListener) {
return; // Temporarily disabled by edit sub-action handler.
}
// XXX Looks like that this is wrong. We delete multiple selection ranges
// once, but this adds only first range into the changed range.
// Anyway, we should take the range as an argument.
DebugOnly<nsresult> rvIgnored =
AddRangeToChangedRange(*aEditorBase.AsHTMLEditor(), aStart, aEnd);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"TopLevelEditSubActionData::AddRangeToChangedRange() "
"failed, but ignored");
}
nsPIDOMWindowOuter* EditorBase::GetWindow() const {
return mDocument ? mDocument->GetWindow() : nullptr;
}
nsPIDOMWindowInner* EditorBase::GetInnerWindow() const {
return mDocument ? mDocument->GetInnerWindow() : nullptr;
}
PresShell* EditorBase::GetPresShell() const {
return mDocument ? mDocument->GetPresShell() : nullptr;
}
nsPresContext* EditorBase::GetPresContext() const {
PresShell* presShell = GetPresShell();
return presShell ? presShell->GetPresContext() : nullptr;
}
already_AddRefed<nsCaret> EditorBase::GetCaret() const {
PresShell* presShell = GetPresShell();
if (NS_WARN_IF(!presShell)) {
return nullptr;
}
return presShell->GetCaret();
}
nsISelectionController* EditorBase::GetSelectionController() const {
if (mSelectionController) {
return mSelectionController;
}
if (!mDocument) {
return nullptr;
}
return mDocument->GetPresShell();
}
} // namespace mozilla
|