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
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "HTMLEditor.h"
#include "HTMLEditorInlines.h"
#include "HTMLEditorNestedClasses.h"
#include <algorithm>
#include <utility>
#include "AutoRangeArray.h"
#include "CSSEditUtils.h"
#include "EditAction.h"
#include "EditorDOMPoint.h"
#include "EditorUtils.h"
#include "HTMLEditHelpers.h"
#include "HTMLEditUtils.h"
#include "PendingStyles.h" // for SpecifiedStyle
#include "WSRunObject.h"
#include "ErrorList.h"
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/InternalMutationEvent.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Maybe.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/RangeUtils.h"
#include "mozilla/StaticPrefs_editor.h" // for StaticPrefs::editor_*
#include "mozilla/TextComposition.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLBRElement.h"
#include "mozilla/dom/RangeBinding.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/StaticRange.h"
#include "mozilla/mozalloc.h"
#include "nsAString.h"
#include "nsAlgorithm.h"
#include "nsAtom.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsFrameSelection.h"
#include "nsGkAtoms.h"
#include "nsHTMLDocument.h"
#include "nsIContent.h"
#include "nsID.h"
#include "nsIFrame.h"
#include "nsINode.h"
#include "nsLiteralString.h"
#include "nsPrintfCString.h"
#include "nsRange.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsStyledElement.h"
#include "nsTArray.h"
#include "nsTextNode.h"
#include "nsThreadUtils.h"
#include "nsUnicharUtils.h"
class nsISupports;
namespace mozilla {
using namespace dom;
using EmptyCheckOption = HTMLEditUtils::EmptyCheckOption;
using EmptyCheckOptions = HTMLEditUtils::EmptyCheckOptions;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
using LeafNodeTypes = HTMLEditUtils::LeafNodeTypes;
using WalkTextOption = HTMLEditUtils::WalkTextOption;
using WalkTreeDirection = HTMLEditUtils::WalkTreeDirection;
using WalkTreeOption = HTMLEditUtils::WalkTreeOption;
/********************************************************
* first some helpful functors we will use
********************************************************/
static bool IsPendingStyleCachePreservingSubAction(
EditSubAction aEditSubAction) {
switch (aEditSubAction) {
case EditSubAction::eDeleteSelectedContent:
case EditSubAction::eInsertLineBreak:
case EditSubAction::eInsertParagraphSeparator:
case EditSubAction::eCreateOrChangeList:
case EditSubAction::eIndent:
case EditSubAction::eOutdent:
case EditSubAction::eSetOrClearAlignment:
case EditSubAction::eCreateOrRemoveBlock:
case EditSubAction::eMergeBlockContents:
case EditSubAction::eRemoveList:
case EditSubAction::eCreateOrChangeDefinitionListItem:
case EditSubAction::eInsertElement:
case EditSubAction::eInsertQuotation:
case EditSubAction::eInsertQuotedText:
return true;
default:
return false;
}
}
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorDOMRange& aRange);
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorRawDOMRange& aRange);
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorDOMPoint& aStartPoint, const EditorDOMPoint& aEndPoint);
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorRawDOMPoint& aStartPoint, const EditorDOMPoint& aEndPoint);
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorDOMPoint& aStartPoint, const EditorRawDOMPoint& aEndPoint);
template already_AddRefed<nsRange>
HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorRawDOMPoint& aStartPoint, const EditorRawDOMPoint& aEndPoint);
nsresult HTMLEditor::InitEditorContentAndSelection() {
MOZ_ASSERT(IsEditActionDataAvailable());
// We should do nothing with the result of GetRoot() if only a part of the
// document is editable.
if (!EntireDocumentIsEditable()) {
return NS_OK;
}
nsresult rv = MaybeCreatePaddingBRElementForEmptyEditor();
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::MaybeCreatePaddingBRElementForEmptyEditor() failed");
return rv;
}
// If the selection hasn't been set up yet, set it up collapsed to the end of
// our editable content.
// XXX I think that this shouldn't do it in `HTMLEditor` because it maybe
// removed by the web app and if they call `Selection::AddRange()` without
// checking the range count, it may cause multiple selection ranges.
if (!SelectionRef().RangeCount()) {
nsresult rv = CollapseSelectionToEndOfLastLeafNodeOfDocument();
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::CollapseSelectionToEndOfLastLeafNodeOfDocument() "
"failed");
return rv;
}
}
if (IsInPlaintextMode()) {
// XXX Should we do this in HTMLEditor? It's odd to guarantee that last
// empty line is visible only when it's in the plain text mode.
nsresult rv = EnsurePaddingBRElementInMultilineEditor();
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::EnsurePaddingBRElementInMultilineEditor() failed");
return rv;
}
}
Element* bodyOrDocumentElement = GetRoot();
if (NS_WARN_IF(!bodyOrDocumentElement && !GetDocument())) {
return NS_ERROR_FAILURE;
}
if (!bodyOrDocumentElement) {
return NS_OK;
}
rv = InsertBRElementToEmptyListItemsAndTableCellsInRange(
RawRangeBoundary(bodyOrDocumentElement, 0u),
RawRangeBoundary(bodyOrDocumentElement,
bodyOrDocumentElement->GetChildCount()));
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertBRElementToEmptyListItemsAndTableCellsInRange() "
"failed, but ignored");
return NS_OK;
}
void HTMLEditor::OnStartToHandleTopLevelEditSubAction(
EditSubAction aTopLevelEditSubAction,
nsIEditor::EDirection aDirectionOfTopLevelEditSubAction, ErrorResult& aRv) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aRv.Failed());
EditorBase::OnStartToHandleTopLevelEditSubAction(
aTopLevelEditSubAction, aDirectionOfTopLevelEditSubAction, aRv);
MOZ_ASSERT(GetTopLevelEditSubAction() == aTopLevelEditSubAction);
MOZ_ASSERT(GetDirectionOfTopLevelEditSubAction() ==
aDirectionOfTopLevelEditSubAction);
if (NS_WARN_IF(Destroyed())) {
aRv.Throw(NS_ERROR_EDITOR_DESTROYED);
return;
}
if (!mInitSucceeded) {
return; // We should do nothing if we're being initialized.
}
NS_WARNING_ASSERTION(
!aRv.Failed(),
"EditorBase::OnStartToHandleTopLevelEditSubAction() failed");
// Let's work with the latest layout information after (maybe) dispatching
// `beforeinput` event.
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
document->FlushPendingNotifications(FlushType::Frames);
if (NS_WARN_IF(Destroyed())) {
aRv.Throw(NS_ERROR_EDITOR_DESTROYED);
return;
}
// Remember where our selection was before edit action took place:
const auto atCompositionStart =
GetFirstIMESelectionStartPoint<EditorRawDOMPoint>();
if (atCompositionStart.IsSet()) {
// If there is composition string, let's remember current composition
// range.
TopLevelEditSubActionDataRef().mSelectedRange->StoreRange(
atCompositionStart, GetLastIMESelectionEndPoint<EditorRawDOMPoint>());
} else {
// Get the selection location
// XXX This may occur so that I think that we shouldn't throw exception
// in this case.
if (NS_WARN_IF(!SelectionRef().RangeCount())) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
if (const nsRange* range = SelectionRef().GetRangeAt(0)) {
TopLevelEditSubActionDataRef().mSelectedRange->StoreRange(*range);
}
}
// Register with range updater to track this as we perturb the doc
RangeUpdaterRef().RegisterRangeItem(
*TopLevelEditSubActionDataRef().mSelectedRange);
// Remember current inline styles for deletion and normal insertion ops
const bool cacheInlineStyles = [&]() {
switch (aTopLevelEditSubAction) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eDeleteSelectedContent:
return true;
default:
return IsPendingStyleCachePreservingSubAction(aTopLevelEditSubAction);
}
}();
if (cacheInlineStyles) {
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
nsIContent* const startContainer =
HTMLEditUtils::GetContentToPreserveInlineStyles(
TopLevelEditSubActionDataRef()
.mSelectedRange->StartPoint<EditorRawDOMPoint>(),
*editingHost);
if (NS_WARN_IF(!startContainer)) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
if (const RefPtr<Element> startContainerElement =
startContainer->GetAsElementOrParentElement()) {
nsresult rv = CacheInlineStyles(*startContainerElement);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::CacheInlineStyles() failed");
aRv.Throw(rv);
return;
}
}
}
// Stabilize the document against contenteditable count changes
if (document->GetEditingState() == Document::EditingState::eContentEditable) {
document->ChangeContentEditableCount(nullptr, +1);
TopLevelEditSubActionDataRef().mRestoreContentEditableCount = true;
}
// Check that selection is in subtree defined by body node
nsresult rv = EnsureSelectionInBodyOrDocumentElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
aRv.Throw(NS_ERROR_EDITOR_DESTROYED);
return;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureSelectionInBodyOrDocumentElement() "
"failed, but ignored");
}
nsresult HTMLEditor::OnEndHandlingTopLevelEditSubAction() {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
nsresult rv;
while (true) {
if (NS_WARN_IF(Destroyed())) {
rv = NS_ERROR_EDITOR_DESTROYED;
break;
}
if (!mInitSucceeded) {
rv = NS_OK; // We should do nothing if we're being initialized.
break;
}
// Do all the tricky stuff
rv = OnEndHandlingTopLevelEditSubActionInternal();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::OnEndHandlingTopLevelEditSubActionInternal() failied");
// Perhaps, we need to do the following jobs even if the editor has been
// destroyed since they adjust some states of HTML document but don't
// modify the DOM tree nor Selection.
// Free up selectionState range item
if (TopLevelEditSubActionDataRef().mSelectedRange) {
RangeUpdaterRef().DropRangeItem(
*TopLevelEditSubActionDataRef().mSelectedRange);
}
// Reset the contenteditable count to its previous value
if (TopLevelEditSubActionDataRef().mRestoreContentEditableCount) {
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
rv = NS_ERROR_FAILURE;
break;
}
if (document->GetEditingState() ==
Document::EditingState::eContentEditable) {
document->ChangeContentEditableCount(nullptr, -1);
}
}
break;
}
DebugOnly<nsresult> rvIgnored =
EditorBase::OnEndHandlingTopLevelEditSubAction();
NS_WARNING_ASSERTION(
NS_FAILED(rv) || NS_SUCCEEDED(rvIgnored),
"EditorBase::OnEndHandlingTopLevelEditSubAction() failed, but ignored");
MOZ_ASSERT(!GetTopLevelEditSubAction());
MOZ_ASSERT(GetDirectionOfTopLevelEditSubAction() == eNone);
return rv;
}
nsresult HTMLEditor::OnEndHandlingTopLevelEditSubActionInternal() {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
nsresult rv = EnsureSelectionInBodyOrDocumentElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureSelectionInBodyOrDocumentElement() "
"failed, but ignored");
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eReplaceHeadWithHTMLSource:
case EditSubAction::eCreatePaddingBRElementForEmptyEditor:
return NS_OK;
default:
break;
}
if (TopLevelEditSubActionDataRef().mChangedRange->IsPositioned() &&
GetTopLevelEditSubAction() != EditSubAction::eUndo &&
GetTopLevelEditSubAction() != EditSubAction::eRedo) {
// don't let any txns in here move the selection around behind our back.
// Note that this won't prevent explicit selection setting from working.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
{
EditorDOMRange changedRange(
*TopLevelEditSubActionDataRef().mChangedRange);
if (changedRange.IsPositioned() &&
changedRange.EnsureNotInNativeAnonymousSubtree()) {
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eInsertLineBreak:
case EditSubAction::eInsertParagraphSeparator:
case EditSubAction::eDeleteText: {
// XXX We should investigate whether this is really needed because
// it seems that the following code does not handle the
// white-spaces.
RefPtr<nsRange> extendedChangedRange =
CreateRangeIncludingAdjuscentWhiteSpaces(changedRange);
if (extendedChangedRange) {
MOZ_ASSERT(extendedChangedRange->IsPositioned());
// Use extended range temporarily.
TopLevelEditSubActionDataRef().mChangedRange =
std::move(extendedChangedRange);
}
break;
}
default: {
if (Element* editingHost = ComputeEditingHost()) {
if (RefPtr<nsRange> extendedChangedRange = AutoRangeArray::
CreateRangeWrappingStartAndEndLinesContainingBoundaries(
changedRange, GetTopLevelEditSubAction(),
*editingHost)) {
MOZ_ASSERT(extendedChangedRange->IsPositioned());
// Use extended range temporarily.
TopLevelEditSubActionDataRef().mChangedRange =
std::move(extendedChangedRange);
}
break;
}
}
}
}
}
// if we did a ranged deletion or handling backspace key, make sure we have
// a place to put caret.
// Note we only want to do this if the overall operation was deletion,
// not if deletion was done along the way for
// EditSubAction::eInsertHTMLSource, EditSubAction::eInsertText, etc.
// That's why this is here rather than DeleteSelectionAsSubAction().
// However, we shouldn't insert <br> elements if we've already removed
// empty block parents because users may want to disappear the line by
// the deletion.
// XXX We should make HandleDeleteSelection() store expected container
// for handling this here since we cannot trust current selection is
// collapsed at deleted point.
if (GetTopLevelEditSubAction() == EditSubAction::eDeleteSelectedContent &&
TopLevelEditSubActionDataRef().mDidDeleteNonCollapsedRange &&
!TopLevelEditSubActionDataRef().mDidDeleteEmptyParentBlocks) {
const auto newCaretPosition =
GetFirstSelectionStartPoint<EditorDOMPoint>();
if (!newCaretPosition.IsSet()) {
NS_WARNING("There was no selection range");
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
Result<CaretPoint, nsresult> caretPointOrError =
InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary(
newCaretPosition);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary() "
"failed");
return caretPointOrError.unwrapErr();
}
nsresult rv = caretPointOrError.unwrap().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion});
if (NS_FAILED(rv)) {
NS_WARNING("CaretPoint::SuggestCaretPointTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CaretPoint::SuggestCaretPointTo() failed, but ignored");
}
// add in any needed <br>s, and remove any unneeded ones.
nsresult rv = InsertBRElementToEmptyListItemsAndTableCellsInRange(
TopLevelEditSubActionDataRef().mChangedRange->StartRef().AsRaw(),
TopLevelEditSubActionDataRef().mChangedRange->EndRef().AsRaw());
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertBRElementToEmptyListItemsAndTableCellsInRange()"
" failed, but ignored");
// merge any adjacent text nodes
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
break;
default: {
nsresult rv = CollapseAdjacentTextNodes(
MOZ_KnownLive(*TopLevelEditSubActionDataRef().mChangedRange));
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::CollapseAdjacentTextNodes() failed");
return rv;
}
break;
}
}
// Clean up any empty nodes in the changed range unless they are inserted
// intentionally.
if (TopLevelEditSubActionDataRef().mNeedsToCleanUpEmptyElements) {
nsresult rv = RemoveEmptyNodesIn(
EditorDOMRange(*TopLevelEditSubActionDataRef().mChangedRange));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::RemoveEmptyNodesIn() failed");
return rv;
}
}
// attempt to transform any unneeded nbsp's into spaces after doing various
// operations
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eDeleteSelectedContent:
if (TopLevelEditSubActionDataRef().mDidNormalizeWhitespaces) {
break;
}
[[fallthrough]];
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eInsertLineBreak:
case EditSubAction::eInsertParagraphSeparator:
case EditSubAction::ePasteHTMLContent:
case EditSubAction::eInsertHTMLSource: {
// Due to the replacement of white-spaces in
// WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt(),
// selection ranges may be changed since DOM ranges track the DOM
// mutation by themselves. However, we want to keep selection as-is.
// Therefore, we should restore `Selection` after replacing
// white-spaces.
AutoSelectionRestorer restoreSelection(*this);
// TODO: Temporarily, WhiteSpaceVisibilityKeeper replaces ASCII
// white-spaces with NPSPs and then, we'll replace them with ASCII
// white-spaces here. We should avoid this overwriting things as
// far as possible because replacing characters in text nodes
// causes running mutation event listeners which are really
// expensive.
// Adjust end of composition string if there is composition string.
auto pointToAdjust = GetLastIMESelectionEndPoint<EditorDOMPoint>();
if (!pointToAdjust.IsInContentNode()) {
// Otherwise, adjust current selection start point.
pointToAdjust = GetFirstSelectionStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToAdjust.IsInContentNode())) {
return NS_ERROR_FAILURE;
}
}
if (EditorUtils::IsEditableContent(
*pointToAdjust.ContainerAs<nsIContent>(), EditorType::HTML)) {
AutoTrackDOMPoint trackPointToAdjust(RangeUpdaterRef(),
&pointToAdjust);
nsresult rv =
WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt(
*this, pointToAdjust);
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt() "
"failed");
return rv;
}
}
// also do this for original selection endpoints.
// XXX Hmm, if `NormalizeVisibleWhiteSpacesAt()` runs mutation event
// listener and that causes changing `mSelectedRange`, what we
// should do?
if (NS_WARN_IF(!TopLevelEditSubActionDataRef()
.mSelectedRange->IsPositioned())) {
return NS_ERROR_FAILURE;
}
EditorDOMPoint atStart =
TopLevelEditSubActionDataRef().mSelectedRange->StartPoint();
if (atStart != pointToAdjust && atStart.IsInContentNode() &&
EditorUtils::IsEditableContent(*atStart.ContainerAs<nsIContent>(),
EditorType::HTML)) {
AutoTrackDOMPoint trackPointToAdjust(RangeUpdaterRef(),
&pointToAdjust);
AutoTrackDOMPoint trackStartPoint(RangeUpdaterRef(), &atStart);
nsresult rv =
WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt(
*this, atStart);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt() "
"failed, but ignored");
}
// we only need to handle old selection endpoint if it was different
// from start
EditorDOMPoint atEnd =
TopLevelEditSubActionDataRef().mSelectedRange->EndPoint();
if (!TopLevelEditSubActionDataRef().mSelectedRange->Collapsed() &&
atEnd != pointToAdjust && atEnd != atStart &&
atEnd.IsInContentNode() &&
EditorUtils::IsEditableContent(*atEnd.ContainerAs<nsIContent>(),
EditorType::HTML)) {
nsresult rv =
WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt(*this,
atEnd);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"WhiteSpaceVisibilityKeeper::NormalizeVisibleWhiteSpacesAt() "
"failed, but ignored");
}
break;
}
default:
break;
}
// Adjust selection for insert text, html paste, and delete actions if
// we haven't removed new empty blocks. Note that if empty block parents
// are removed, Selection should've been adjusted by the method which
// did it.
if (!TopLevelEditSubActionDataRef().mDidDeleteEmptyParentBlocks &&
SelectionRef().IsCollapsed()) {
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eDeleteSelectedContent:
case EditSubAction::eInsertLineBreak:
case EditSubAction::eInsertParagraphSeparator:
case EditSubAction::ePasteHTMLContent:
case EditSubAction::eInsertHTMLSource:
// XXX AdjustCaretPositionAndEnsurePaddingBRElement() intentionally
// does not create padding `<br>` element for empty editor.
// Investigate which is better that whether this should does it
// or wait MaybeCreatePaddingBRElementForEmptyEditor().
rv = AdjustCaretPositionAndEnsurePaddingBRElement(
GetDirectionOfTopLevelEditSubAction());
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::AdjustCaretPositionAndEnsurePaddingBRElement() "
"failed");
return rv;
}
break;
default:
break;
}
}
// check for any styles which were removed inappropriately
bool reapplyCachedStyle;
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eDeleteSelectedContent:
reapplyCachedStyle = true;
break;
default:
reapplyCachedStyle =
IsPendingStyleCachePreservingSubAction(GetTopLevelEditSubAction());
break;
}
// If the selection is in empty inline HTML elements, we should delete
// them unless it's inserted intentionally.
if (mPlaceholderBatch &&
TopLevelEditSubActionDataRef().mNeedsToCleanUpEmptyElements &&
SelectionRef().IsCollapsed() && SelectionRef().GetFocusNode()) {
RefPtr<Element> mostDistantEmptyInlineAncestor = nullptr;
for (Element* ancestor :
SelectionRef().GetFocusNode()->InclusiveAncestorsOfType<Element>()) {
if (!ancestor->IsHTMLElement() ||
!HTMLEditUtils::IsRemovableFromParentNode(*ancestor) ||
!HTMLEditUtils::IsEmptyInlineContainer(
*ancestor, {EmptyCheckOption::TreatSingleBRElementAsVisible})) {
break;
}
mostDistantEmptyInlineAncestor = ancestor;
}
if (mostDistantEmptyInlineAncestor) {
nsresult rv =
DeleteNodeWithTransaction(*mostDistantEmptyInlineAncestor);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteNodeWithTransaction() failed at deleting "
"empty inline ancestors");
return rv;
}
}
}
// But the cached inline styles should be restored from type-in-state later.
if (reapplyCachedStyle) {
DebugOnly<nsresult> rvIgnored =
mPendingStylesToApplyToNewContent->UpdateSelState(*this);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"PendingStyles::UpdateSelState() failed, but ignored");
rvIgnored = ReapplyCachedStyles();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::ReapplyCachedStyles() failed, but ignored");
TopLevelEditSubActionDataRef().mCachedPendingStyles->Clear();
}
}
rv = HandleInlineSpellCheck(
TopLevelEditSubActionDataRef().mSelectedRange->StartPoint(),
TopLevelEditSubActionDataRef().mChangedRange);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::HandleInlineSpellCheck() failed");
return rv;
}
// detect empty doc
// XXX Need to investigate when the padding <br> element is removed because
// I don't see the <br> element with testing manually. If it won't be
// used, we can get rid of this cost.
rv = MaybeCreatePaddingBRElementForEmptyEditor();
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::MaybeCreatePaddingBRElementForEmptyEditor() failed");
return rv;
}
// adjust selection HINT if needed
if (!TopLevelEditSubActionDataRef().mDidExplicitlySetInterLine &&
SelectionRef().IsCollapsed()) {
SetSelectionInterlinePosition();
}
return NS_OK;
}
Result<EditActionResult, nsresult> HTMLEditor::CanHandleHTMLEditSubAction(
CheckSelectionInReplacedElement aCheckSelectionInReplacedElement
/* = CheckSelectionInReplacedElement::Yes */) const {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
// If there is not selection ranges, we should ignore the result.
if (!SelectionRef().RangeCount()) {
return EditActionResult::CanceledResult();
}
const nsRange* range = SelectionRef().GetRangeAt(0);
nsINode* selStartNode = range->GetStartContainer();
if (NS_WARN_IF(!selStartNode) || NS_WARN_IF(!selStartNode->IsContent())) {
return Err(NS_ERROR_FAILURE);
}
if (!HTMLEditUtils::IsSimplyEditableNode(*selStartNode)) {
return EditActionResult::CanceledResult();
}
nsINode* selEndNode = range->GetEndContainer();
if (NS_WARN_IF(!selEndNode) || NS_WARN_IF(!selEndNode->IsContent())) {
return Err(NS_ERROR_FAILURE);
}
if (selStartNode == selEndNode) {
if (aCheckSelectionInReplacedElement ==
CheckSelectionInReplacedElement::Yes &&
HTMLEditUtils::IsNonEditableReplacedContent(
*selStartNode->AsContent())) {
return EditActionResult::CanceledResult();
}
return EditActionResult::IgnoredResult();
}
if (HTMLEditUtils::IsNonEditableReplacedContent(*selStartNode->AsContent()) ||
HTMLEditUtils::IsNonEditableReplacedContent(*selEndNode->AsContent())) {
return EditActionResult::CanceledResult();
}
if (!HTMLEditUtils::IsSimplyEditableNode(*selEndNode)) {
return EditActionResult::CanceledResult();
}
// If anchor node is in an HTML element which has inert attribute, we should
// do nothing.
// XXX HTMLEditor typically uses first range instead of anchor/focus range.
// Therefore, referring first range here is more reasonable than
// anchor/focus range of Selection.
nsIContent* const selAnchorContent = SelectionRef().GetDirection() == eDirNext
? nsIContent::FromNode(selStartNode)
: nsIContent::FromNode(selEndNode);
if (selAnchorContent &&
HTMLEditUtils::ContentIsInert(*selAnchorContent->AsContent())) {
return EditActionResult::CanceledResult();
}
// XXX What does it mean the common ancestor is editable? I have no idea.
// It should be in same (active) editing host, and even if it's editable,
// there may be non-editable contents in the range.
nsINode* commonAncestor = range->GetClosestCommonInclusiveAncestor();
if (MOZ_UNLIKELY(!commonAncestor)) {
NS_WARNING(
"AbstractRange::GetClosestCommonInclusiveAncestor() returned nullptr");
return Err(NS_ERROR_FAILURE);
}
return HTMLEditUtils::IsSimplyEditableNode(*commonAncestor)
? EditActionResult::IgnoredResult()
: EditActionResult::CanceledResult();
}
MOZ_CAN_RUN_SCRIPT static nsStaticAtom& MarginPropertyAtomForIndent(
nsIContent& aContent) {
nsAutoString direction;
DebugOnly<nsresult> rvIgnored = CSSEditUtils::GetComputedProperty(
aContent, *nsGkAtoms::direction, direction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetComputedProperty(nsGkAtoms::direction)"
" failed, but ignored");
return direction.EqualsLiteral("rtl") ? *nsGkAtoms::marginRight
: *nsGkAtoms::marginLeft;
}
nsresult HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(SelectionRef().IsCollapsed());
// If we are after a padding `<br>` element for empty last line in the same
// block, then move selection to be before it
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
EditorRawDOMPoint atSelectionStart(firstRange->StartRef());
if (NS_WARN_IF(!atSelectionStart.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atSelectionStart.IsSetAndValid());
if (!atSelectionStart.IsInContentNode()) {
return NS_OK;
}
Element* editingHost = ComputeEditingHost();
if (!editingHost) {
NS_WARNING(
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() did nothing "
"because of no editing host");
return NS_OK;
}
nsIContent* previousBRElement =
HTMLEditUtils::GetPreviousContent(atSelectionStart, {}, editingHost);
if (!previousBRElement || !previousBRElement->IsHTMLElement(nsGkAtoms::br) ||
!previousBRElement->GetParent() ||
!EditorUtils::IsEditableContent(*previousBRElement->GetParent(),
EditorType::HTML) ||
!HTMLEditUtils::IsInvisibleBRElement(*previousBRElement)) {
return NS_OK;
}
const RefPtr<const Element> blockElementAtSelectionStart =
HTMLEditUtils::GetInclusiveAncestorElement(
*atSelectionStart.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestBlockElement);
const RefPtr<const Element> parentBlockElementOfBRElement =
HTMLEditUtils::GetAncestorElement(*previousBRElement,
HTMLEditUtils::ClosestBlockElement);
if (!blockElementAtSelectionStart ||
blockElementAtSelectionStart != parentBlockElementOfBRElement) {
return NS_OK;
}
// If we are here then the selection is right after a padding <br>
// element for empty last line that is in the same block as the
// selection. We need to move the selection start to be before the
// padding <br> element.
EditorRawDOMPoint atInvisibleBRElement(previousBRElement);
nsresult rv = CollapseSelectionTo(atInvisibleBRElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
nsresult HTMLEditor::MaybeCreatePaddingBRElementForEmptyEditor() {
MOZ_ASSERT(IsEditActionDataAvailable());
if (mPaddingBRElementForEmptyEditor) {
return NS_OK;
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eCreatePaddingBRElementForEmptyEditor,
nsIEditor::eNone, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
ignoredError.SuppressException();
RefPtr<Element> rootElement = GetRoot();
if (!rootElement) {
return NS_OK;
}
// Now we've got the body element. Iterate over the body element's children,
// looking for editable content. If no editable content is found, insert the
// padding <br> element.
EditorType editorType = GetEditorType();
bool isRootEditable =
EditorUtils::IsEditableContent(*rootElement, editorType);
for (nsIContent* rootChild = rootElement->GetFirstChild(); rootChild;
rootChild = rootChild->GetNextSibling()) {
if (EditorUtils::IsPaddingBRElementForEmptyEditor(*rootChild) ||
!isRootEditable ||
EditorUtils::IsEditableContent(*rootChild, editorType) ||
HTMLEditUtils::IsBlockElement(*rootChild)) {
return NS_OK;
}
}
// Skip adding the padding <br> element for empty editor if body
// is read-only.
if (IsHTMLEditor() && !HTMLEditUtils::IsSimplyEditableNode(*rootElement)) {
return NS_OK;
}
// Create a br.
RefPtr<Element> newBRElement = CreateHTMLContent(nsGkAtoms::br);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_WARN_IF(!newBRElement)) {
return NS_ERROR_FAILURE;
}
mPaddingBRElementForEmptyEditor =
static_cast<HTMLBRElement*>(newBRElement.get());
// Give it a special attribute.
newBRElement->SetFlags(NS_PADDING_FOR_EMPTY_EDITOR);
// Put the node in the document.
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertNodeWithTransaction<Element>(*newBRElement,
EditorDOMPoint(rootElement, 0u));
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertBRElementResult.unwrapErr();
}
// Set selection.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
nsresult rv = CollapseSelectionToStartOf(*rootElement);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionToStartOf() caused destroying the "
"editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed, but ignored");
return NS_OK;
}
nsresult HTMLEditor::EnsureNoPaddingBRElementForEmptyEditor() {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!mPaddingBRElementForEmptyEditor) {
return NS_OK;
}
// If we're an HTML editor, a mutation event listener may recreate padding
// <br> element for empty editor again during the call of
// DeleteNodeWithTransaction(). So, move it first.
RefPtr<HTMLBRElement> paddingBRElement(
std::move(mPaddingBRElementForEmptyEditor));
nsresult rv = DeleteNodeWithTransaction(*paddingBRElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
nsresult HTMLEditor::ReflectPaddingBRElementForEmptyEditor() {
if (NS_WARN_IF(!mRootElement)) {
NS_WARNING("Failed to handle padding BR element due to no root element");
return NS_ERROR_FAILURE;
}
// The idea here is to see if the magic empty node has suddenly reappeared. If
// it has, set our state so we remember it. There is a tradeoff between doing
// here and at redo, or doing it everywhere else that might care. Since undo
// and redo are relatively rare, it makes sense to take the (small)
// performance hit here.
nsIContent* firstLeafChild = HTMLEditUtils::GetFirstLeafContent(
*mRootElement, {LeafNodeType::OnlyLeafNode});
if (firstLeafChild &&
EditorUtils::IsPaddingBRElementForEmptyEditor(*firstLeafChild)) {
mPaddingBRElementForEmptyEditor =
static_cast<HTMLBRElement*>(firstLeafChild);
} else {
mPaddingBRElementForEmptyEditor = nullptr;
}
return NS_OK;
}
nsresult HTMLEditor::PrepareInlineStylesForCaret() {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(SelectionRef().IsCollapsed());
// XXX This method works with the top level edit sub-action, but this
// must be wrong if we are handling nested edit action.
if (TopLevelEditSubActionDataRef().mDidDeleteSelection) {
switch (GetTopLevelEditSubAction()) {
case EditSubAction::eInsertText:
case EditSubAction::eInsertTextComingFromIME:
case EditSubAction::eDeleteSelectedContent: {
nsresult rv = ReapplyCachedStyles();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::ReapplyCachedStyles() failed");
return rv;
}
break;
}
default:
break;
}
}
// For most actions we want to clear the cached styles, but there are
// exceptions
if (!IsPendingStyleCachePreservingSubAction(GetTopLevelEditSubAction())) {
TopLevelEditSubActionDataRef().mCachedPendingStyles->Clear();
}
return NS_OK;
}
Result<EditActionResult, nsresult> HTMLEditor::HandleInsertText(
EditSubAction aEditSubAction, const nsAString& aInsertionString,
SelectionHandling aSelectionHandling) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(aEditSubAction == EditSubAction::eInsertText ||
aEditSubAction == EditSubAction::eInsertTextComingFromIME);
MOZ_ASSERT_IF(aSelectionHandling == SelectionHandling::Ignore,
aEditSubAction == EditSubAction::eInsertTextComingFromIME);
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
UndefineCaretBidiLevel();
// If the selection isn't collapsed, delete it. Don't delete existing inline
// tags, because we're hopefully going to insert text (bug 787432).
if (!SelectionRef().IsCollapsed() &&
aSelectionHandling == SelectionHandling::Delete) {
nsresult rv =
DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eNoStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(nsIEditor::eNone, "
"nsIEditor::eNoStrip) failed");
return Err(rv);
}
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return Err(NS_ERROR_FAILURE);
}
const RefPtr<Element> editingHost = ComputeEditingHost(
GetDocument()->IsXMLDocument() ? LimitInBodyElement::No
: LimitInBodyElement::Yes);
if (NS_WARN_IF(!editingHost)) {
return Err(NS_ERROR_FAILURE);
}
auto pointToInsert = GetFirstSelectionStartPoint<EditorDOMPoint>();
if (MOZ_UNLIKELY(!pointToInsert.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
// for every property that is set, insert a new inline style node
Result<EditorDOMPoint, nsresult> setStyleResult =
CreateStyleForInsertText(pointToInsert, *editingHost);
if (MOZ_UNLIKELY(setStyleResult.isErr())) {
NS_WARNING("HTMLEditor::CreateStyleForInsertText() failed");
return setStyleResult.propagateErr();
}
if (setStyleResult.inspect().IsSet()) {
pointToInsert = setStyleResult.unwrap();
}
if (NS_WARN_IF(!pointToInsert.IsSetAndValid()) ||
NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
MOZ_ASSERT(pointToInsert.IsSetAndValid());
// If the point is not in an element which can contain text nodes, climb up
// the DOM tree.
if (!pointToInsert.IsInTextNode()) {
while (!HTMLEditUtils::CanNodeContain(*pointToInsert.GetContainer(),
*nsGkAtoms::textTagName)) {
if (NS_WARN_IF(pointToInsert.GetContainer() == editingHost) ||
NS_WARN_IF(!pointToInsert.GetContainerParentAs<nsIContent>())) {
NS_WARNING("Selection start point couldn't have text nodes");
return Err(NS_ERROR_FAILURE);
}
pointToInsert.Set(pointToInsert.ContainerAs<nsIContent>());
}
}
if (aEditSubAction == EditSubAction::eInsertTextComingFromIME) {
auto compositionStartPoint =
GetFirstIMESelectionStartPoint<EditorDOMPoint>();
if (!compositionStartPoint.IsSet()) {
compositionStartPoint = pointToInsert;
}
if (aInsertionString.IsEmpty()) {
// Right now the WhiteSpaceVisibilityKeeper code bails on empty strings,
// but IME needs the InsertTextWithTransaction() call to still happen
// since empty strings are meaningful there.
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextWithTransaction(*document, aInsertionString,
compositionStartPoint);
if (MOZ_UNLIKELY(insertTextResult.isErr())) {
NS_WARNING("HTMLEditor::InsertTextWithTransaction() failed");
return insertTextResult.propagateErr();
}
nsresult rv = insertTextResult.unwrap().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CaretPoint::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CaretPoint::SuggestCaretPointTo() failed, but ignored");
return EditActionResult::HandledResult();
}
auto compositionEndPoint = GetLastIMESelectionEndPoint<EditorDOMPoint>();
if (!compositionEndPoint.IsSet()) {
compositionEndPoint = compositionStartPoint;
}
Result<InsertTextResult, nsresult> replaceTextResult =
WhiteSpaceVisibilityKeeper::ReplaceText(
*this, aInsertionString,
EditorDOMRange(compositionStartPoint, compositionEndPoint),
*editingHost);
if (MOZ_UNLIKELY(replaceTextResult.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::ReplaceText() failed");
return replaceTextResult.propagateErr();
}
// CompositionTransaction should've set selection so that we should ignore
// caret suggestion.
replaceTextResult.unwrap().IgnoreCaretPointSuggestion();
compositionStartPoint = GetFirstIMESelectionStartPoint<EditorDOMPoint>();
compositionEndPoint = GetLastIMESelectionEndPoint<EditorDOMPoint>();
if (NS_WARN_IF(!compositionStartPoint.IsSet()) ||
NS_WARN_IF(!compositionEndPoint.IsSet())) {
// Mutation event listener has changed the DOM tree...
return EditActionResult::HandledResult();
}
nsresult rv = TopLevelEditSubActionDataRef().mChangedRange->SetStartAndEnd(
compositionStartPoint.ToRawRangeBoundary(),
compositionEndPoint.ToRawRangeBoundary());
if (NS_FAILED(rv)) {
NS_WARNING("nsRange::SetStartAndEnd() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
MOZ_ASSERT(aEditSubAction == EditSubAction::eInsertText);
// find where we are
EditorDOMPoint currentPoint(pointToInsert);
// is our text going to be PREformatted?
// We remember this so that we know how to handle tabs.
const bool isWhiteSpaceCollapsible = !EditorUtils::IsWhiteSpacePreformatted(
*pointToInsert.ContainerAs<nsIContent>());
// turn off the edit listener: we know how to
// build the "doc changed range" ourselves, and it's
// must faster to do it once here than to track all
// the changes one at a time.
AutoRestore<bool> disableListener(
EditSubActionDataRef().mAdjustChangedRangeFromListener);
EditSubActionDataRef().mAdjustChangedRangeFromListener = false;
// don't change my selection in subtransactions
AutoTransactionsConserveSelection dontChangeMySelection(*this);
int32_t pos = 0;
constexpr auto newlineStr = NS_LITERAL_STRING_FROM_CSTRING(LFSTR);
{
AutoTrackDOMPoint tracker(RangeUpdaterRef(), &pointToInsert);
// for efficiency, break out the pre case separately. This is because
// its a lot cheaper to search the input string for only newlines than
// it is to search for both tabs and newlines.
if (!isWhiteSpaceCollapsible || IsInPlaintextMode()) {
while (pos != -1 &&
pos < AssertedCast<int32_t>(aInsertionString.Length())) {
int32_t oldPos = pos;
int32_t subStrLen;
pos = aInsertionString.FindChar(nsCRT::LF, oldPos);
if (pos != -1) {
subStrLen = pos - oldPos;
// if first char is newline, then use just it
if (!subStrLen) {
subStrLen = 1;
}
} else {
subStrLen = aInsertionString.Length() - oldPos;
pos = aInsertionString.Length();
}
nsDependentSubstring subStr(aInsertionString, oldPos, subStrLen);
// is it a return?
if (subStr.Equals(newlineStr)) {
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, currentPoint);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// We don't want to update selection here because we've blocked
// InsertNodeTransaction updating selection with
// dontChangeMySelection.
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(!AllowsTransactionsToChangeSelection());
pos++;
RefPtr<Element> brElement =
unwrappedInsertBRElementResult.UnwrapNewNode();
if (brElement->GetNextSibling()) {
pointToInsert.Set(brElement->GetNextSibling());
} else {
pointToInsert.SetToEndOf(currentPoint.GetContainer());
}
// XXX In most cases, pointToInsert and currentPoint are same here.
// But if the <br> element has been moved to different point by
// mutation observer, those points become different.
currentPoint.SetAfter(brElement);
NS_WARNING_ASSERTION(currentPoint.IsSet(),
"Failed to set after the <br> element");
NS_WARNING_ASSERTION(currentPoint == pointToInsert,
"Perhaps, <br> element position has been moved "
"to different point "
"by mutation observer");
} else {
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextWithTransaction(*document, subStr, currentPoint);
if (MOZ_UNLIKELY(insertTextResult.isErr())) {
NS_WARNING("HTMLEditor::InsertTextWithTransaction() failed");
return insertTextResult.propagateErr();
}
// Ignore the caret suggestion because of `dontChangeMySelection`
// above.
insertTextResult.inspect().IgnoreCaretPointSuggestion();
if (insertTextResult.inspect().Handled()) {
pointToInsert = currentPoint = insertTextResult.unwrap()
.EndOfInsertedTextRef()
.To<EditorDOMPoint>();
} else {
pointToInsert = currentPoint;
}
}
}
} else {
constexpr auto tabStr = u"\t"_ns;
constexpr auto spacesStr = u" "_ns;
nsAutoString insertionString(aInsertionString); // For FindCharInSet().
while (pos != -1 &&
pos < AssertedCast<int32_t>(insertionString.Length())) {
int32_t oldPos = pos;
int32_t subStrLen;
pos = insertionString.FindCharInSet(u"\t\n", oldPos);
if (pos != -1) {
subStrLen = pos - oldPos;
// if first char is newline, then use just it
if (!subStrLen) {
subStrLen = 1;
}
} else {
subStrLen = insertionString.Length() - oldPos;
pos = insertionString.Length();
}
nsDependentSubstring subStr(insertionString, oldPos, subStrLen);
// is it a tab?
if (subStr.Equals(tabStr)) {
Result<InsertTextResult, nsresult> insertTextResult =
WhiteSpaceVisibilityKeeper::InsertText(
*this, spacesStr, currentPoint, *editingHost);
if (MOZ_UNLIKELY(insertTextResult.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::InsertText() failed");
return insertTextResult.propagateErr();
}
// Ignore the caret suggestion because of `dontChangeMySelection`
// above.
insertTextResult.inspect().IgnoreCaretPointSuggestion();
pos++;
if (insertTextResult.inspect().Handled()) {
pointToInsert = currentPoint = insertTextResult.unwrap()
.EndOfInsertedTextRef()
.To<EditorDOMPoint>();
MOZ_ASSERT(pointToInsert.IsSet());
} else {
pointToInsert = currentPoint;
MOZ_ASSERT(pointToInsert.IsSet());
}
}
// is it a return?
else if (subStr.Equals(newlineStr)) {
Result<CreateElementResult, nsresult> insertBRElementResult =
WhiteSpaceVisibilityKeeper::InsertBRElement(*this, currentPoint,
*editingHost);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::InsertBRElement() failed");
return insertBRElementResult.propagateErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// TODO: Some methods called for handling non-preformatted text use
// ComputeEditingHost(). Therefore, they depend on the latest
// selection. So we cannot skip updating selection here.
nsresult rv = unwrappedInsertBRElementResult.SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateElementResult::SuggestCaretPointTo() failed, but ignored");
pos++;
RefPtr<Element> newBRElement =
unwrappedInsertBRElementResult.UnwrapNewNode();
MOZ_DIAGNOSTIC_ASSERT(newBRElement);
if (newBRElement->GetNextSibling()) {
pointToInsert.Set(newBRElement->GetNextSibling());
} else {
pointToInsert.SetToEndOf(currentPoint.GetContainer());
}
currentPoint.SetAfter(newBRElement);
NS_WARNING_ASSERTION(currentPoint.IsSet(),
"Failed to set after the new <br> element");
// XXX If the newBRElement has been moved or removed by mutation
// observer, we hit this assert. We need to check if
// newBRElement is in expected point, though, we must have
// a lot of same bugs...
NS_WARNING_ASSERTION(
currentPoint == pointToInsert,
"Perhaps, newBRElement has been moved or removed unexpectedly");
} else {
Result<InsertTextResult, nsresult> insertTextResult =
WhiteSpaceVisibilityKeeper::InsertText(
*this, subStr, currentPoint, *editingHost);
if (MOZ_UNLIKELY(insertTextResult.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::InsertText() failed");
return insertTextResult.propagateErr();
}
// Ignore the caret suggestion because of `dontChangeMySelection`
// above.
insertTextResult.inspect().IgnoreCaretPointSuggestion();
if (insertTextResult.inspect().Handled()) {
pointToInsert = currentPoint = insertTextResult.unwrap()
.EndOfInsertedTextRef()
.To<EditorDOMPoint>();
MOZ_ASSERT(pointToInsert.IsSet());
} else {
pointToInsert = currentPoint;
MOZ_ASSERT(pointToInsert.IsSet());
}
}
}
}
// After this block, pointToInsert is updated by AutoTrackDOMPoint.
}
if (currentPoint.IsSet()) {
currentPoint.SetInterlinePosition(InterlinePosition::EndOfLine);
nsresult rv = CollapseSelectionTo(currentPoint);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Selection::Collapse() failed, but ignored");
// manually update the doc changed range so that AfterEdit will clean up
// the correct portion of the document.
rv = TopLevelEditSubActionDataRef().mChangedRange->SetStartAndEnd(
pointToInsert.ToRawRangeBoundary(), currentPoint.ToRawRangeBoundary());
if (NS_FAILED(rv)) {
NS_WARNING("nsRange::SetStartAndEnd() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
DebugOnly<nsresult> rvIgnored =
SelectionRef().SetInterlinePosition(InterlinePosition::EndOfLine);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"EndOfLine) failed, but ignored");
rv = TopLevelEditSubActionDataRef().mChangedRange->CollapseTo(pointToInsert);
if (NS_FAILED(rv)) {
NS_WARNING("nsRange::CollapseTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::InsertLineBreakAsSubAction() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsSelectionRangeContainerNotContent());
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
// XXX This may be called by execCommand() with "insertLineBreak".
// In such case, naming the transaction "TypingTxnName" is odd.
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::TypingTxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
// calling it text insertion to trigger moz br treatment by rules
// XXX Why do we use EditSubAction::eInsertText here? Looks like
// EditSubAction::eInsertLineBreak or EditSubAction::eInsertNode
// is better.
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertText, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
UndefineCaretBidiLevel();
// If the selection isn't collapsed, delete it.
if (!SelectionRef().IsCollapsed()) {
nsresult rv =
DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return rv;
}
}
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
EditorDOMPoint atStartOfSelection(firstRange->StartRef());
if (NS_WARN_IF(!atStartOfSelection.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atStartOfSelection.IsSetAndValid());
RefPtr<Element> editingHost = ComputeEditingHost();
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
// For backward compatibility, we should not insert a linefeed if
// paragraph separator is set to "br" which is Gecko-specific mode.
if (GetDefaultParagraphSeparator() == ParagraphSeparator::br ||
!HTMLEditUtils::ShouldInsertLinefeedCharacter(atStartOfSelection,
*editingHost)) {
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, atStartOfSelection,
nsIEditor::eNext);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.unwrapErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
MOZ_ASSERT(unwrappedInsertBRElementResult.GetNewNode());
// Next inserting text should be inserted into styled inline elements if
// they have first visible thing in the new line.
auto pointToPutCaret = [&]() -> EditorDOMPoint {
WSScanResult forwardScanResult =
WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(
editingHost, EditorRawDOMPoint::After(
*unwrappedInsertBRElementResult.GetNewNode()));
if (forwardScanResult.InVisibleOrCollapsibleCharacters()) {
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
return forwardScanResult.Point<EditorDOMPoint>();
}
if (forwardScanResult.ReachedSpecialContent()) {
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
return forwardScanResult.PointAtContent<EditorDOMPoint>();
}
return unwrappedInsertBRElementResult.UnwrapCaretPoint();
}();
nsresult rv = CollapseSelectionTo(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"CreateElementResult::SuggestCaretPointTo() failed");
return rv;
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
atStartOfSelection = EditorDOMPoint(firstRange->StartRef());
if (NS_WARN_IF(!atStartOfSelection.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atStartOfSelection.IsSetAndValid());
// Do nothing if the node is read-only
if (!HTMLEditUtils::IsSimplyEditableNode(
*atStartOfSelection.GetContainer())) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
Result<EditorDOMPoint, nsresult> insertLineFeedResult =
HandleInsertLinefeed(atStartOfSelection, *editingHost);
if (MOZ_UNLIKELY(insertLineFeedResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertLinefeed() failed");
return insertLineFeedResult.unwrapErr();
}
rv = CollapseSelectionTo(insertLineFeedResult.inspect());
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
Result<EditActionResult, nsresult>
HTMLEditor::InsertParagraphSeparatorAsSubAction(const Element& aEditingHost) {
if (NS_WARN_IF(!mInitSucceeded)) {
return Err(NS_ERROR_NOT_INITIALIZED);
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction(
CheckSelectionInReplacedElement::OnlyWhenNotInSameNode);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
// XXX This may be called by execCommand() with "insertParagraph".
// In such case, naming the transaction "TypingTxnName" is odd.
AutoPlaceholderBatch treatAsOneTransaction(*this, *nsGkAtoms::TypingTxnName,
ScrollSelectionIntoView::Yes,
__FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertParagraphSeparator, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
UndefineCaretBidiLevel();
// If the selection isn't collapsed, delete it.
if (!SelectionRef().IsCollapsed()) {
nsresult rv =
DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return Err(rv);
}
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
AutoRangeArray selectionRanges(SelectionRef());
{
// If the editing host is the body element, the selection may be outside
// aEditingHost. In the case, we should use the editing host outside the
// <body> only here for keeping our traditional behavior for now.
// This should be fixed in bug 1634351.
const Element* editingHostMaybeOutsideBody = &aEditingHost;
if (aEditingHost.IsHTMLElement(nsGkAtoms::body)) {
editingHostMaybeOutsideBody = ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHostMaybeOutsideBody)) {
return Err(NS_ERROR_FAILURE);
}
}
selectionRanges.EnsureOnlyEditableRanges(*editingHostMaybeOutsideBody);
if (NS_WARN_IF(selectionRanges.Ranges().IsEmpty())) {
return Err(NS_ERROR_FAILURE);
}
}
auto pointToInsert =
selectionRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
while (true) {
Element* element = pointToInsert.GetContainerOrContainerParentElement();
if (MOZ_UNLIKELY(!element)) {
return Err(NS_ERROR_FAILURE);
}
// If the element can have a <br> element (it means that the element or its
// container must be able to have <div> or <p> too), we can handle
// insertParagraph at the point.
if (HTMLEditUtils::CanNodeContain(*element, *nsGkAtoms::br)) {
break;
}
// Otherwise, try to insert paragraph at the parent.
pointToInsert = pointToInsert.ParentPoint();
}
if (IsMailEditor()) {
if (RefPtr<Element> mailCiteElement = GetMostDistantAncestorMailCiteElement(
*pointToInsert.ContainerAs<nsIContent>())) {
// Split any mailcites in the way. Should we abort this if we encounter
// table cell boundaries?
Result<EditorDOMPoint, nsresult> atNewBRElementOrError =
HandleInsertParagraphInMailCiteElement(*mailCiteElement,
pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(atNewBRElementOrError.isErr())) {
NS_WARNING(
"HTMLEditor::HandleInsertParagraphInMailCiteElement() failed");
return atNewBRElementOrError.propagateErr();
}
EditorDOMPoint pointToPutCaret = atNewBRElementOrError.unwrap();
MOZ_ASSERT(pointToPutCaret.IsSet());
pointToPutCaret.SetInterlinePosition(InterlinePosition::StartOfNextLine);
MOZ_ASSERT(pointToPutCaret.GetChild());
MOZ_ASSERT(pointToPutCaret.GetChild()->IsHTMLElement(nsGkAtoms::br));
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
}
// If the active editing host is an inline element, or if the active editing
// host is the block parent itself and we're configured to use <br> as a
// paragraph separator, just append a <br>.
// If the editing host parent element is editable, it means that the editing
// host must be a <body> element and the selection may be outside the body
// element. If the selection is outside the editing host, we should not
// insert new paragraph nor <br> element.
// XXX Currently, we don't support editing outside <body> element, but Blink
// does it.
if (aEditingHost.GetParentElement() &&
HTMLEditUtils::IsSimplyEditableNode(*aEditingHost.GetParentElement()) &&
!nsContentUtils::ContentIsFlattenedTreeDescendantOf(
pointToInsert.ContainerAs<nsIContent>(), &aEditingHost)) {
return Err(NS_ERROR_EDITOR_NO_EDITABLE_RANGE);
}
auto InsertLineBreakInstead =
[](const Element* aEditableBlockElement,
const EditorDOMPoint& aCandidatePointToSplit,
ParagraphSeparator aDefaultParagraphSeparator,
const Element& aEditingHost) {
// If there is no block parent in the editing host, i.e., the editing
// host itself is also a non-block element, we should insert a line
// break.
if (!aEditableBlockElement) {
// XXX Chromium checks if the CSS box of the editing host is a block.
return true;
}
// If the editable block element is not splittable, e.g., it's an
// editing host, and the default paragraph separator is <br> or the
// element cannot contain a <p> element, we should insert a <br>
// element.
if (!HTMLEditUtils::IsSplittableNode(*aEditableBlockElement)) {
return aDefaultParagraphSeparator == ParagraphSeparator::br ||
!HTMLEditUtils::CanElementContainParagraph(aEditingHost) ||
HTMLEditUtils::ShouldInsertLinefeedCharacter(
aCandidatePointToSplit, aEditingHost);
}
// If the nearest block parent is a single-line container declared in
// the execCommand spec and not the editing host, we should separate the
// block even if the default paragraph separator is <br> element.
if (HTMLEditUtils::IsSingleLineContainer(*aEditableBlockElement)) {
return false;
}
// Otherwise, unless there is no block ancestor which can contain <p>
// element, we shouldn't insert a line break here.
for (const Element* editableBlockAncestor = aEditableBlockElement;
editableBlockAncestor;
editableBlockAncestor = HTMLEditUtils::GetAncestorElement(
*editableBlockAncestor,
HTMLEditUtils::ClosestEditableBlockElementOrButtonElement)) {
if (HTMLEditUtils::CanElementContainParagraph(
*editableBlockAncestor)) {
return false;
}
}
return true;
};
// Look for the nearest parent block. However, don't return error even if
// there is no block parent here because in such case, i.e., editing host
// is an inline element, we should insert <br> simply.
RefPtr<Element> editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*pointToInsert.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElementOrButtonElement);
// If we cannot insert a <p>/<div> element at the selection, we should insert
// a <br> element or a linefeed instead.
const ParagraphSeparator separator = GetDefaultParagraphSeparator();
if (InsertLineBreakInstead(editableBlockElement, pointToInsert, separator,
aEditingHost)) {
// For backward compatibility, we should not insert a linefeed if
// paragraph separator is set to "br" which is Gecko-specific mode.
if (separator != ParagraphSeparator::br &&
HTMLEditUtils::ShouldInsertLinefeedCharacter(pointToInsert,
aEditingHost)) {
Result<EditorDOMPoint, nsresult> insertLineFeedResult =
HandleInsertLinefeed(pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(insertLineFeedResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertLinefeed() failed");
return insertLineFeedResult.propagateErr();
}
nsresult rv = CollapseSelectionTo(insertLineFeedResult.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
Result<CreateElementResult, nsresult> insertBRElementResult =
HandleInsertBRElement(pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertBRElement() failed");
return insertBRElementResult.propagateErr();
}
nsresult rv =
insertBRElementResult.inspect().SuggestCaretPointTo(*this, {});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
// If somebody wants to restrict caret position in a block element below,
// we should guarantee it. Otherwise, we can put caret to the candidate
// point.
auto CollapseSelection =
[this](const EditorDOMPoint& aCandidatePointToPutCaret,
const Element* aBlockElementShouldHaveCaret,
const SuggestCaretOptions& aOptions)
MOZ_CAN_RUN_SCRIPT -> nsresult {
if (!aCandidatePointToPutCaret.IsSet()) {
if (aOptions.contains(SuggestCaret::OnlyIfHasSuggestion)) {
return NS_OK;
}
return aOptions.contains(SuggestCaret::AndIgnoreTrivialError)
? NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR
: NS_ERROR_FAILURE;
}
EditorDOMPoint pointToPutCaret(aCandidatePointToPutCaret);
if (aBlockElementShouldHaveCaret) {
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorDOMPoint>(*aBlockElementShouldHaveCaret,
aCandidatePointToPutCaret);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() "
"failed, but ignored");
} else if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv) && MOZ_LIKELY(rv != NS_ERROR_EDITOR_DESTROYED) &&
aOptions.contains(SuggestCaret::AndIgnoreTrivialError)) {
rv = NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR;
}
return rv;
};
RefPtr<Element> blockElementToPutCaret;
// If the default paragraph separator is not <br> and selection is not in
// a splittable block element, we should wrap selected contents in a new
// paragraph, then, split it.
if (!HTMLEditUtils::IsSplittableNode(*editableBlockElement) &&
separator != ParagraphSeparator::br) {
MOZ_ASSERT(separator == ParagraphSeparator::div ||
separator == ParagraphSeparator::p);
Result<RefPtr<Element>, nsresult> suggestBlockElementToPutCaretOrError =
FormatBlockContainerWithTransaction(
selectionRanges,
MOZ_KnownLive(HTMLEditor::ToParagraphSeparatorTagName(separator)),
aEditingHost);
if (MOZ_UNLIKELY(suggestBlockElementToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::FormatBlockContainerWithTransaction() failed");
return suggestBlockElementToPutCaretOrError.propagateErr();
}
if (selectionRanges.HasSavedRanges()) {
selectionRanges.RestoreFromSavedRanges();
}
pointToInsert = selectionRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
MOZ_ASSERT(pointToInsert.IsSetAndValid());
blockElementToPutCaret = suggestBlockElementToPutCaretOrError.unwrap();
editableBlockElement = HTMLEditUtils::GetInclusiveAncestorElement(
*pointToInsert.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElementOrButtonElement);
if (NS_WARN_IF(!editableBlockElement)) {
return Err(NS_ERROR_UNEXPECTED);
}
if (NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(*editableBlockElement))) {
// Didn't create a new block for some reason, fall back to <br>
Result<CreateElementResult, nsresult> insertBRElementResult =
HandleInsertBRElement(pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertBRElement() failed");
return insertBRElementResult.propagateErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
EditorDOMPoint pointToPutCaret =
unwrappedInsertBRElementResult.UnwrapCaretPoint();
if (MOZ_UNLIKELY(!pointToPutCaret.IsSet())) {
NS_WARNING(
"HTMLEditor::HandleInsertBRElement() didn't suggest a point to put "
"caret");
return Err(NS_ERROR_FAILURE);
}
nsresult rv =
CollapseSelection(pointToPutCaret, blockElementToPutCaret, {});
if (NS_FAILED(rv)) {
NS_WARNING("CollapseSelection() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
// We want to collapse selection in the editable block element.
blockElementToPutCaret = editableBlockElement;
}
// If block is empty, populate with br. (For example, imagine a div that
// contains the word "text". The user selects "text" and types return.
// "Text" is deleted leaving an empty block. We want to put in one br to
// make block have a line. Then code further below will put in a second br.)
RefPtr<Element> insertedPaddingBRElement;
if (HTMLEditUtils::IsEmptyBlockElement(
*editableBlockElement,
{EmptyCheckOption::TreatSingleBRElementAsVisible})) {
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes,
EditorDOMPoint::AtEndOf(*editableBlockElement));
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedInsertBRElementResult.GetNewNode());
insertedPaddingBRElement = unwrappedInsertBRElementResult.UnwrapNewNode();
pointToInsert = selectionRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
RefPtr<Element> maybeNonEditableListItem =
HTMLEditUtils::GetClosestAncestorListItemElement(*editableBlockElement,
&aEditingHost);
if (maybeNonEditableListItem &&
HTMLEditUtils::IsSplittableNode(*maybeNonEditableListItem)) {
Result<InsertParagraphResult, nsresult> insertParagraphInListItemResult =
HandleInsertParagraphInListItemElement(*maybeNonEditableListItem,
pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(insertParagraphInListItemResult.isErr())) {
if (NS_WARN_IF(insertParagraphInListItemResult.unwrapErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::HandleInsertParagraphInListItemElement() failed, but "
"ignored");
return EditActionResult::HandledResult();
}
InsertParagraphResult unwrappedInsertParagraphInListItemResult =
insertParagraphInListItemResult.unwrap();
MOZ_ASSERT(unwrappedInsertParagraphInListItemResult.Handled());
MOZ_ASSERT(unwrappedInsertParagraphInListItemResult.GetNewNode());
const RefPtr<Element> listItemOrParagraphElement =
unwrappedInsertParagraphInListItemResult.UnwrapNewNode();
const EditorDOMPoint pointToPutCaret =
unwrappedInsertParagraphInListItemResult.UnwrapCaretPoint();
nsresult rv = CollapseSelection(pointToPutCaret, listItemOrParagraphElement,
{SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CollapseSelection() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CollapseSelection() failed, but ignored");
return EditActionResult::HandledResult();
}
if (HTMLEditUtils::IsHeader(*editableBlockElement)) {
Result<InsertParagraphResult, nsresult>
insertParagraphInHeadingElementResult =
HandleInsertParagraphInHeadingElement(*editableBlockElement,
pointToInsert);
if (MOZ_UNLIKELY(insertParagraphInHeadingElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::HandleInsertParagraphInHeadingElement() failed, but "
"ignored");
return EditActionResult::HandledResult();
}
InsertParagraphResult unwrappedInsertParagraphInHeadingElementResult =
insertParagraphInHeadingElementResult.unwrap();
if (unwrappedInsertParagraphInHeadingElementResult.Handled()) {
MOZ_ASSERT(unwrappedInsertParagraphInHeadingElementResult.GetNewNode());
blockElementToPutCaret =
unwrappedInsertParagraphInHeadingElementResult.UnwrapNewNode();
}
const EditorDOMPoint pointToPutCaret =
unwrappedInsertParagraphInHeadingElementResult.UnwrapCaretPoint();
nsresult rv = CollapseSelection(pointToPutCaret, blockElementToPutCaret,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CollapseSelection() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CollapseSelection() failed, but ignored");
return EditActionResult::HandledResult();
}
// XXX Ideally, we should take same behavior with both <p> container and
// <div> container. However, we are still using <br> as default
// paragraph separator (non-standard) and we've split only <p> container
// long time. Therefore, some web apps may depend on this behavior like
// Gmail. So, let's use traditional odd behavior only when the default
// paragraph separator is <br>. Otherwise, take consistent behavior
// between <p> container and <div> container.
if ((separator == ParagraphSeparator::br &&
editableBlockElement->IsHTMLElement(nsGkAtoms::p)) ||
(separator != ParagraphSeparator::br &&
editableBlockElement->IsAnyOfHTMLElements(nsGkAtoms::p,
nsGkAtoms::div))) {
// Paragraphs: special rules to look for <br>s
Result<SplitNodeResult, nsresult> splitNodeResult =
HandleInsertParagraphInParagraph(
*editableBlockElement,
insertedPaddingBRElement ? EditorDOMPoint(insertedPaddingBRElement)
: pointToInsert,
aEditingHost);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertParagraphInParagraph() failed");
return splitNodeResult.propagateErr();
}
if (splitNodeResult.inspect().Handled()) {
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
const RefPtr<Element> rightParagraphElement =
unwrappedSplitNodeResult.DidSplit()
? unwrappedSplitNodeResult.GetNextContentAs<Element>()
: blockElementToPutCaret.get();
const EditorDOMPoint pointToPutCaret =
unwrappedSplitNodeResult.UnwrapCaretPoint();
nsresult rv = CollapseSelection(pointToPutCaret, rightParagraphElement,
{SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CollapseSelection() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CollapseSelection() failed, but ignored");
return EditActionResult::HandledResult();
}
MOZ_ASSERT(!splitNodeResult.inspect().HasCaretPointSuggestion());
// Fall through, if HandleInsertParagraphInParagraph() didn't handle it.
MOZ_ASSERT(pointToInsert.IsSetAndValid(),
"HTMLEditor::HandleInsertParagraphInParagraph() shouldn't touch "
"the DOM tree if it returns not-handled state");
}
// If nobody handles this edit action, let's insert new <br> at the selection.
Result<CreateElementResult, nsresult> insertBRElementResult =
HandleInsertBRElement(pointToInsert, aEditingHost);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::HandleInsertBRElement() failed");
return insertBRElementResult.propagateErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
EditorDOMPoint pointToPutCaret =
unwrappedInsertBRElementResult.UnwrapCaretPoint();
rv = CollapseSelection(pointToPutCaret, blockElementToPutCaret, {});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
Result<CreateElementResult, nsresult> HTMLEditor::HandleInsertBRElement(
const EditorDOMPoint& aPointToBreak, const Element& aEditingHost) {
MOZ_ASSERT(aPointToBreak.IsSet());
MOZ_ASSERT(IsEditActionDataAvailable());
bool brElementIsAfterBlock = false, brElementIsBeforeBlock = false;
// First, insert a <br> element.
RefPtr<Element> brElement;
if (IsInPlaintextMode()) {
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, aPointToBreak);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult;
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// We'll return with suggesting new caret position and nobody refers
// selection after here. So we don't need to update selection here.
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedInsertBRElementResult.GetNewNode());
brElement = unwrappedInsertBRElementResult.UnwrapNewNode();
} else {
EditorDOMPoint pointToBreak(aPointToBreak);
WSRunScanner wsRunScanner(&aEditingHost, pointToBreak);
WSScanResult backwardScanResult =
wsRunScanner.ScanPreviousVisibleNodeOrBlockBoundaryFrom(pointToBreak);
if (MOZ_UNLIKELY(backwardScanResult.Failed())) {
NS_WARNING(
"WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundaryFrom() failed");
return Err(NS_ERROR_FAILURE);
}
brElementIsAfterBlock = backwardScanResult.ReachedBlockBoundary();
WSScanResult forwardScanResult =
wsRunScanner.ScanNextVisibleNodeOrBlockBoundaryFrom(pointToBreak);
if (MOZ_UNLIKELY(forwardScanResult.Failed())) {
NS_WARNING(
"WSRunScanner::ScanNextVisibleNodeOrBlockBoundaryFrom() failed");
return Err(NS_ERROR_FAILURE);
}
brElementIsBeforeBlock = forwardScanResult.ReachedBlockBoundary();
// If the container of the break is a link, we need to split it and
// insert new <br> between the split links.
RefPtr<Element> linkNode =
HTMLEditor::GetLinkElement(pointToBreak.GetContainer());
if (linkNode) {
Result<SplitNodeResult, nsresult> splitLinkNodeResult =
SplitNodeDeepWithTransaction(
*linkNode, pointToBreak,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitLinkNodeResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) failed");
return splitLinkNodeResult.propagateErr();
}
// TODO: Some methods called by
// WhiteSpaceVisibilityKeeper::InsertBRElement() use
// ComputeEditingHost() which depends on selection. Therefore,
// we cannot skip updating selection here.
nsresult rv = splitLinkNodeResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
pointToBreak =
splitLinkNodeResult.inspect().AtSplitPoint<EditorDOMPoint>();
}
Result<CreateElementResult, nsresult> insertBRElementResult =
WhiteSpaceVisibilityKeeper::InsertBRElement(*this, pointToBreak,
aEditingHost);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::InsertBRElement() failed");
return insertBRElementResult;
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// We'll return with suggesting new caret position and nobody refers
// selection after here. So we don't need to update selection here.
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
brElement = unwrappedInsertBRElementResult.UnwrapNewNode();
MOZ_ASSERT(brElement);
}
if (MOZ_UNLIKELY(!brElement->GetParentNode())) {
NS_WARNING("Inserted <br> element was removed by the web app");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (brElementIsAfterBlock && brElementIsBeforeBlock) {
// We just placed a <br> between block boundaries. This is the one case
// where we want the selection to be before the br we just placed, as the
// br will be on a new line, rather than at end of prior line.
// XXX brElementIsAfterBlock and brElementIsBeforeBlock were set before
// modifying the DOM tree. So, now, the <br> element may not be
// between blocks.
EditorDOMPoint pointToPutCaret(brElement,
InterlinePosition::StartOfNextLine);
return CreateElementResult(std::move(brElement),
std::move(pointToPutCaret));
}
auto afterBRElement = EditorDOMPoint::After(brElement);
WSScanResult forwardScanFromAfterBRElementResult =
WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(&aEditingHost,
afterBRElement);
if (MOZ_UNLIKELY(forwardScanFromAfterBRElementResult.Failed())) {
NS_WARNING("WSRunScanner::ScanNextVisibleNodeOrBlockBoundary() failed");
return Err(NS_ERROR_FAILURE);
}
if (forwardScanFromAfterBRElementResult.ReachedBRElement()) {
// The next thing after the break we inserted is another break. Move the
// second break to be the first break's sibling. This will prevent them
// from being in different inline nodes, which would break
// SetInterlinePosition(). It will also assure that if the user clicks
// away and then clicks back on their new blank line, they will still get
// the style from the line above.
if (brElement->GetNextSibling() !=
forwardScanFromAfterBRElementResult.BRElementPtr()) {
MOZ_ASSERT(forwardScanFromAfterBRElementResult.BRElementPtr());
Result<MoveNodeResult, nsresult> moveBRElementResult =
MoveNodeWithTransaction(
MOZ_KnownLive(
*forwardScanFromAfterBRElementResult.BRElementPtr()),
afterBRElement);
if (MOZ_UNLIKELY(moveBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveBRElementResult.propagateErr();
}
nsresult rv = moveBRElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
}
}
// We want the caret to stick to whatever is past the break. This is because
// the break is on the same line we were on, but the next content will be on
// the following line.
// An exception to this is if the break has a next sibling that is a block
// node. Then we stick to the left to avoid an uber caret.
nsIContent* nextSiblingOfBRElement = brElement->GetNextSibling();
afterBRElement.SetInterlinePosition(
nextSiblingOfBRElement &&
HTMLEditUtils::IsBlockElement(*nextSiblingOfBRElement)
? InterlinePosition::EndOfLine
: InterlinePosition::StartOfNextLine);
return CreateElementResult(std::move(brElement), afterBRElement);
}
Result<EditorDOMPoint, nsresult> HTMLEditor::HandleInsertLinefeed(
const EditorDOMPoint& aPointToBreak, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aPointToBreak.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
const RefPtr<Document> document = GetDocument();
MOZ_DIAGNOSTIC_ASSERT(document);
if (NS_WARN_IF(!document)) {
return Err(NS_ERROR_FAILURE);
}
// TODO: The following code is duplicated from `HandleInsertText`. They
// should be merged when we fix bug 92921.
Result<EditorDOMPoint, nsresult> setStyleResult =
CreateStyleForInsertText(aPointToBreak, aEditingHost);
if (MOZ_UNLIKELY(setStyleResult.isErr())) {
NS_WARNING("HTMLEditor::CreateStyleForInsertText() failed");
return setStyleResult.propagateErr();
}
EditorDOMPoint pointToInsert = setStyleResult.inspect().IsSet()
? setStyleResult.inspect()
: aPointToBreak;
if (NS_WARN_IF(!pointToInsert.IsSetAndValid()) ||
NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
MOZ_ASSERT(pointToInsert.IsSetAndValid());
// The node may not be able to have a text node so that we need to check it
// here.
if (!pointToInsert.IsInTextNode() &&
!HTMLEditUtils::CanNodeContain(*pointToInsert.ContainerAs<nsIContent>(),
*nsGkAtoms::textTagName)) {
NS_WARNING(
"HTMLEditor::HandleInsertLinefeed() couldn't insert a linefeed because "
"the insertion position couldn't have text nodes");
return Err(NS_ERROR_EDITOR_NO_EDITABLE_RANGE);
}
AutoRestore<bool> disableListener(
EditSubActionDataRef().mAdjustChangedRangeFromListener);
EditSubActionDataRef().mAdjustChangedRangeFromListener = false;
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
EditorDOMPoint pointToPutCaret;
{
AutoTrackDOMPoint trackingInsertingPosition(RangeUpdaterRef(),
&pointToInsert);
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextWithTransaction(*document, u"\n"_ns, pointToInsert);
if (MOZ_UNLIKELY(insertTextResult.isErr())) {
NS_WARNING("HTMLEditor::InsertTextWithTransaction() failed");
return insertTextResult.propagateErr();
}
// Ignore the caret suggestion because of `dontChangeMySelection` above.
insertTextResult.inspect().IgnoreCaretPointSuggestion();
pointToPutCaret = insertTextResult.inspect().Handled()
? insertTextResult.unwrap()
.EndOfInsertedTextRef()
.To<EditorDOMPoint>()
: pointToInsert;
}
// Insert a padding <br> element at the end of the block element if there is
// no content between the inserted linefeed and the following block boundary
// to make sure that the last line is visible.
// XXX Blink/WebKit inserts another linefeed character in this case. However,
// for doing it, we need more work, e.g., updating serializer, deleting
// unnecessary padding <br> element at modifying the last line.
if (pointToPutCaret.IsInContentNode() && pointToPutCaret.IsEndOfContainer()) {
WSRunScanner wsScannerAtCaret(&aEditingHost, pointToPutCaret);
if (wsScannerAtCaret.StartsFromPreformattedLineBreak() &&
wsScannerAtCaret.EndsByBlockBoundary() &&
HTMLEditUtils::CanNodeContain(*wsScannerAtCaret.GetEndReasonContent(),
*nsGkAtoms::br)) {
AutoTrackDOMPoint trackingInsertedPosition(RangeUpdaterRef(),
&pointToInsert);
AutoTrackDOMPoint trackingNewCaretPosition(RangeUpdaterRef(),
&pointToPutCaret);
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToPutCaret);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
// We're tracking next caret position with newCaretPosition. Therefore,
// we don't need to update selection here.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(insertBRElementResult.inspect().GetNewNode());
}
}
// manually update the doc changed range so that
// OnEndHandlingTopLevelEditSubActionInternal will clean up the correct
// portion of the document.
MOZ_ASSERT(pointToPutCaret.IsSet());
if (NS_WARN_IF(!pointToPutCaret.IsSet())) {
// XXX Here is odd. We did mChangedRange->SetStartAndEnd(pointToInsert,
// pointToPutCaret), but it always fails because of the latter is unset.
// Therefore, always returning NS_ERROR_FAILURE from here is the
// traditional behavior...
// TODO: Stop updating the interline position of Selection with fixing here
// and returning expected point.
DebugOnly<nsresult> rvIgnored =
SelectionRef().SetInterlinePosition(InterlinePosition::EndOfLine);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"EndOfLine) failed, but ignored");
if (NS_FAILED(TopLevelEditSubActionDataRef().mChangedRange->CollapseTo(
pointToInsert))) {
NS_WARNING("nsRange::CollapseTo() failed");
return Err(NS_ERROR_FAILURE);
}
NS_WARNING(
"We always return NS_ERROR_FAILURE here because of a failure of "
"updating mChangedRange");
return Err(NS_ERROR_FAILURE);
}
if (NS_FAILED(TopLevelEditSubActionDataRef().mChangedRange->SetStartAndEnd(
pointToInsert.ToRawRangeBoundary(),
pointToPutCaret.ToRawRangeBoundary()))) {
NS_WARNING("nsRange::SetStartAndEnd() failed");
return Err(NS_ERROR_FAILURE);
}
pointToPutCaret.SetInterlinePosition(InterlinePosition::EndOfLine);
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::HandleInsertParagraphInMailCiteElement(
Element& aMailCiteElement, const EditorDOMPoint& aPointToSplit,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToSplit.IsSet());
NS_ASSERTION(!HTMLEditUtils::IsEmptyNode(aMailCiteElement),
"The mail-cite element will be deleted, does it expected result "
"for you?");
auto splitCiteElementResult =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
EditorDOMPoint pointToSplit(aPointToSplit);
// If our selection is just before a break, nudge it to be just after
// it. This does two things for us. It saves us the trouble of having
// to add a break here ourselves to preserve the "blockness" of the
// inline span mailquote (in the inline case), and : it means the break
// won't end up making an empty line that happens to be inside a
// mailquote (in either inline or block case). The latter can confuse a
// user if they click there and start typing, because being in the
// mailquote may affect wrapping behavior, or font color, etc.
WSScanResult forwardScanFromPointToSplitResult =
WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(&aEditingHost,
pointToSplit);
if (forwardScanFromPointToSplitResult.Failed()) {
return Err(NS_ERROR_FAILURE);
}
// If selection start point is before a break and it's inside the
// mailquote, let's split it after the visible node.
if (forwardScanFromPointToSplitResult.ReachedBRElement() &&
forwardScanFromPointToSplitResult.BRElementPtr() != &aMailCiteElement &&
aMailCiteElement.Contains(
forwardScanFromPointToSplitResult.BRElementPtr())) {
pointToSplit =
forwardScanFromPointToSplitResult.PointAfterContent<EditorDOMPoint>();
}
if (NS_WARN_IF(!pointToSplit.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
Result<SplitNodeResult, nsresult> splitResult =
SplitNodeDeepWithTransaction(aMailCiteElement, pointToSplit,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(aMailCiteElement, "
"SplitAtEdges::eDoNotCreateEmptyContainer) failed");
return splitResult;
}
nsresult rv = splitResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
return splitResult;
}();
if (MOZ_UNLIKELY(splitCiteElementResult.isErr())) {
NS_WARNING("Failed to split a mail-cite element");
return splitCiteElementResult.propagateErr();
}
SplitNodeResult unwrappedSplitCiteElementResult =
splitCiteElementResult.unwrap();
// When adding caret suggestion to SplitNodeResult, here didn't change
// selection so that just ignore it.
unwrappedSplitCiteElementResult.IgnoreCaretPointSuggestion();
// Add an invisible <br> to the end of left cite node if it was a <span> of
// style="display: block". This is important, since when serializing the cite
// to plain text, the span which caused the visual break is discarded. So the
// added <br> will guarantee that the serializer will insert a break where the
// user saw one.
// FYI: unwrappedSplitCiteElementResult grabs the previous node and the next
// node with nsCOMPtr or EditorDOMPoint. So, it's safe to access
// leftCiteElement and rightCiteElement even after changing the DOM tree
// and/or selection even though it's raw pointer.
auto* const leftCiteElement =
unwrappedSplitCiteElementResult.GetPreviousContentAs<Element>();
auto* const rightCiteElement =
unwrappedSplitCiteElementResult.GetNextContentAs<Element>();
if (leftCiteElement && leftCiteElement->IsHTMLElement(nsGkAtoms::span) &&
// XXX Oh, this depends on layout information of new element, and it's
// created by the hacky flush in DoSplitNode(). So we need to
// redesign around this for bug 1710784.
leftCiteElement->GetPrimaryFrame() &&
leftCiteElement->GetPrimaryFrame()->IsBlockFrameOrSubclass()) {
nsIContent* lastChild = leftCiteElement->GetLastChild();
if (lastChild && !lastChild->IsHTMLElement(nsGkAtoms::br)) {
Result<CreateElementResult, nsresult> insertInvisibleBRElementResult =
InsertBRElement(WithTransaction::Yes,
EditorDOMPoint::AtEndOf(*leftCiteElement));
if (MOZ_UNLIKELY(insertInvisibleBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertInvisibleBRElementResult.propagateErr();
}
// We don't need to update selection here because we'll do another
// InsertBRElement call soon.
insertInvisibleBRElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(insertInvisibleBRElementResult.inspect().GetNewNode());
}
}
// In most cases, <br> should be inserted after current cite. However, if
// left cite hasn't been created because the split point was start of the
// cite node, <br> should be inserted before the current cite.
Result<CreateElementResult, nsresult> insertBRElementResult = InsertBRElement(
WithTransaction::Yes,
unwrappedSplitCiteElementResult.AtSplitPoint<EditorDOMPoint>());
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return Err(insertBRElementResult.unwrapErr());
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// We'll return with suggesting caret position. Therefore, we don't need
// to update selection here.
unwrappedInsertBRElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedInsertBRElementResult.GetNewNode());
// if aMailCiteElement wasn't a block, we might also want another break before
// it. We need to examine the content both before the br we just added and
// also just after it. If we don't have another br or block boundary
// adjacent, then we will need a 2nd br added to achieve blank line that user
// expects.
if (HTMLEditUtils::IsInlineElement(aMailCiteElement)) {
nsresult rvOfInsertingBRElement = [&]() MOZ_CAN_RUN_SCRIPT {
EditorDOMPoint pointToCreateNewBRElement(
unwrappedInsertBRElementResult.GetNewNode());
// XXX Cannot we replace this complicated check with just a call of
// HTMLEditUtils::IsVisibleBRElement with
// resultOfInsertingBRElement.inspect()?
WSScanResult backwardScanFromPointToCreateNewBRElementResult =
WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary(
&aEditingHost, pointToCreateNewBRElement);
if (MOZ_UNLIKELY(
backwardScanFromPointToCreateNewBRElementResult.Failed())) {
NS_WARNING(
"WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary() "
"failed");
return NS_ERROR_FAILURE;
}
if (!backwardScanFromPointToCreateNewBRElementResult
.InVisibleOrCollapsibleCharacters() &&
!backwardScanFromPointToCreateNewBRElementResult
.ReachedSpecialContent()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
WSScanResult forwardScanFromPointAfterNewBRElementResult =
WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(
&aEditingHost,
EditorRawDOMPoint::After(pointToCreateNewBRElement));
if (MOZ_UNLIKELY(forwardScanFromPointAfterNewBRElementResult.Failed())) {
NS_WARNING("WSRunScanner::ScanNextVisibleNodeOrBlockBoundary() failed");
return NS_ERROR_FAILURE;
}
if (!forwardScanFromPointAfterNewBRElementResult
.InVisibleOrCollapsibleCharacters() &&
!forwardScanFromPointAfterNewBRElementResult
.ReachedSpecialContent() &&
// In case we're at the very end.
!forwardScanFromPointAfterNewBRElementResult
.ReachedCurrentBlockBoundary()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToCreateNewBRElement);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.unwrapErr();
}
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(insertBRElementResult.inspect().GetNewNode());
return NS_OK;
}();
if (NS_FAILED(rvOfInsertingBRElement)) {
NS_WARNING(
"Failed to insert additional <br> element before the inline right "
"mail-cite element");
return Err(rvOfInsertingBRElement);
}
}
if (leftCiteElement && HTMLEditUtils::IsEmptyNode(*leftCiteElement)) {
// MOZ_KnownLive(leftCiteElement) because it's grabbed by
// unwrappedSplitCiteElementResult.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*leftCiteElement));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
if (rightCiteElement && HTMLEditUtils::IsEmptyNode(*rightCiteElement)) {
// MOZ_KnownLive(rightCiteElement) because it's grabbed by
// unwrappedSplitCiteElementResult.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*rightCiteElement));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
if (MOZ_UNLIKELY(!unwrappedInsertBRElementResult.GetNewNode()->GetParent())) {
NS_WARNING("Inserted <br> shouldn't become an orphan node");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return EditorDOMPoint(unwrappedInsertBRElementResult.GetNewNode());
}
HTMLEditor::CharPointData
HTMLEditor::GetPreviousCharPointDataForNormalizingWhiteSpaces(
const EditorDOMPointInText& aPoint) const {
MOZ_ASSERT(aPoint.IsSetAndValid());
if (!aPoint.IsStartOfContainer()) {
return CharPointData::InSameTextNode(
HTMLEditor::GetPreviousCharPointType(aPoint));
}
const auto previousCharPoint =
WSRunScanner::GetPreviousEditableCharPoint<EditorRawDOMPointInText>(
ComputeEditingHost(), aPoint);
if (!previousCharPoint.IsSet()) {
return CharPointData::InDifferentTextNode(CharPointType::TextEnd);
}
return CharPointData::InDifferentTextNode(
HTMLEditor::GetCharPointType(previousCharPoint));
}
HTMLEditor::CharPointData
HTMLEditor::GetInclusiveNextCharPointDataForNormalizingWhiteSpaces(
const EditorDOMPointInText& aPoint) const {
MOZ_ASSERT(aPoint.IsSetAndValid());
if (!aPoint.IsEndOfContainer()) {
return CharPointData::InSameTextNode(HTMLEditor::GetCharPointType(aPoint));
}
const auto nextCharPoint =
WSRunScanner::GetInclusiveNextEditableCharPoint<EditorRawDOMPointInText>(
ComputeEditingHost(), aPoint);
if (!nextCharPoint.IsSet()) {
return CharPointData::InDifferentTextNode(CharPointType::TextEnd);
}
return CharPointData::InDifferentTextNode(
HTMLEditor::GetCharPointType(nextCharPoint));
}
// static
void HTMLEditor::GenerateWhiteSpaceSequence(
nsAString& aResult, uint32_t aLength,
const CharPointData& aPreviousCharPointData,
const CharPointData& aNextCharPointData) {
MOZ_ASSERT(aResult.IsEmpty());
MOZ_ASSERT(aLength);
// For now, this method does not assume that result will be append to
// white-space sequence in the text node.
MOZ_ASSERT(aPreviousCharPointData.AcrossTextNodeBoundary() ||
!aPreviousCharPointData.IsCollapsibleWhiteSpace());
// For now, this method does not assume that the result will be inserted
// into white-space sequence nor start of white-space sequence.
MOZ_ASSERT(aNextCharPointData.AcrossTextNodeBoundary() ||
!aNextCharPointData.IsCollapsibleWhiteSpace());
if (aLength == 1) {
// Even if previous/next char is in different text node, we should put
// an ASCII white-space between visible characters.
// XXX This means that this does not allow to put an NBSP in HTML editor
// without preformatted style. However, Chrome has same issue too.
if (aPreviousCharPointData.Type() == CharPointType::VisibleChar &&
aNextCharPointData.Type() == CharPointType::VisibleChar) {
aResult.Assign(HTMLEditUtils::kSpace);
return;
}
// If it's start or end of text, put an NBSP.
if (aPreviousCharPointData.Type() == CharPointType::TextEnd ||
aNextCharPointData.Type() == CharPointType::TextEnd) {
aResult.Assign(HTMLEditUtils::kNBSP);
return;
}
// If the character is next to a preformatted linefeed, we need to put
// an NBSP for avoiding collapsed into the linefeed.
if (aPreviousCharPointData.Type() == CharPointType::PreformattedLineBreak ||
aNextCharPointData.Type() == CharPointType::PreformattedLineBreak) {
aResult.Assign(HTMLEditUtils::kNBSP);
return;
}
// Now, the white-space will be inserted to a white-space sequence, but not
// end of text. We can put an ASCII white-space only when both sides are
// not ASCII white-spaces.
aResult.Assign(
aPreviousCharPointData.Type() == CharPointType::ASCIIWhiteSpace ||
aNextCharPointData.Type() == CharPointType::ASCIIWhiteSpace
? HTMLEditUtils::kNBSP
: HTMLEditUtils::kSpace);
return;
}
// Generate pairs of NBSP and ASCII white-space.
aResult.SetLength(aLength);
bool appendNBSP = true; // Basically, starts with an NBSP.
char16_t* lastChar = aResult.EndWriting() - 1;
for (char16_t* iter = aResult.BeginWriting(); iter != lastChar; iter++) {
*iter = appendNBSP ? HTMLEditUtils::kNBSP : HTMLEditUtils::kSpace;
appendNBSP = !appendNBSP;
}
// If the final one is expected to an NBSP, we can put an NBSP simply.
if (appendNBSP) {
*lastChar = HTMLEditUtils::kNBSP;
return;
}
// If next char point is end of text node, an ASCII white-space or
// preformatted linefeed, we need to put an NBSP.
*lastChar =
aNextCharPointData.AcrossTextNodeBoundary() ||
aNextCharPointData.Type() == CharPointType::ASCIIWhiteSpace ||
aNextCharPointData.Type() == CharPointType::PreformattedLineBreak
? HTMLEditUtils::kNBSP
: HTMLEditUtils::kSpace;
}
void HTMLEditor::ExtendRangeToDeleteWithNormalizingWhiteSpaces(
EditorDOMPointInText& aStartToDelete, EditorDOMPointInText& aEndToDelete,
nsAString& aNormalizedWhiteSpacesInStartNode,
nsAString& aNormalizedWhiteSpacesInEndNode) const {
MOZ_ASSERT(aStartToDelete.IsSetAndValid());
MOZ_ASSERT(aEndToDelete.IsSetAndValid());
MOZ_ASSERT(aStartToDelete.EqualsOrIsBefore(aEndToDelete));
MOZ_ASSERT(aNormalizedWhiteSpacesInStartNode.IsEmpty());
MOZ_ASSERT(aNormalizedWhiteSpacesInEndNode.IsEmpty());
// First, check whether there is surrounding white-spaces or not, and if there
// are, check whether they are collapsible or not. Note that we shouldn't
// touch white-spaces in different text nodes for performance, but we need
// adjacent text node's first or last character information in some cases.
Element* editingHost = ComputeEditingHost();
const EditorDOMPointInText precedingCharPoint =
WSRunScanner::GetPreviousEditableCharPoint(editingHost, aStartToDelete);
const EditorDOMPointInText followingCharPoint =
WSRunScanner::GetInclusiveNextEditableCharPoint(editingHost,
aEndToDelete);
// Blink-compat: Normalize white-spaces in first node only when not removing
// its last character or no text nodes follow the first node.
// If removing last character of first node and there are
// following text nodes, white-spaces in following text node are
// normalized instead.
const bool removingLastCharOfStartNode =
aStartToDelete.ContainerAs<Text>() != aEndToDelete.ContainerAs<Text>() ||
(aEndToDelete.IsEndOfContainer() && followingCharPoint.IsSet());
const bool maybeNormalizePrecedingWhiteSpaces =
!removingLastCharOfStartNode && precedingCharPoint.IsSet() &&
!precedingCharPoint.IsEndOfContainer() &&
precedingCharPoint.ContainerAs<Text>() ==
aStartToDelete.ContainerAs<Text>() &&
precedingCharPoint.IsCharCollapsibleASCIISpaceOrNBSP();
const bool maybeNormalizeFollowingWhiteSpaces =
followingCharPoint.IsSet() && !followingCharPoint.IsEndOfContainer() &&
(followingCharPoint.ContainerAs<Text>() ==
aEndToDelete.ContainerAs<Text>() ||
removingLastCharOfStartNode) &&
followingCharPoint.IsCharCollapsibleASCIISpaceOrNBSP();
if (!maybeNormalizePrecedingWhiteSpaces &&
!maybeNormalizeFollowingWhiteSpaces) {
return; // There are no white-spaces.
}
// Next, consider the range to normalize.
EditorDOMPointInText startToNormalize, endToNormalize;
if (maybeNormalizePrecedingWhiteSpaces) {
Maybe<uint32_t> previousCharOffsetOfWhiteSpaces =
HTMLEditUtils::GetPreviousNonCollapsibleCharOffset(
precedingCharPoint, {WalkTextOption::TreatNBSPsCollapsible});
startToNormalize.Set(precedingCharPoint.ContainerAs<Text>(),
previousCharOffsetOfWhiteSpaces.isSome()
? previousCharOffsetOfWhiteSpaces.value() + 1
: 0);
MOZ_ASSERT(!startToNormalize.IsEndOfContainer());
}
if (maybeNormalizeFollowingWhiteSpaces) {
Maybe<uint32_t> nextCharOffsetOfWhiteSpaces =
HTMLEditUtils::GetInclusiveNextNonCollapsibleCharOffset(
followingCharPoint, {WalkTextOption::TreatNBSPsCollapsible});
if (nextCharOffsetOfWhiteSpaces.isSome()) {
endToNormalize.Set(followingCharPoint.ContainerAs<Text>(),
nextCharOffsetOfWhiteSpaces.value());
} else {
endToNormalize.SetToEndOf(followingCharPoint.ContainerAs<Text>());
}
MOZ_ASSERT(!endToNormalize.IsStartOfContainer());
}
// Next, retrieve surrounding information of white-space sequence.
// If we're removing first text node's last character, we need to
// normalize white-spaces starts from another text node. In this case,
// we need to lie for avoiding assertion in GenerateWhiteSpaceSequence().
CharPointData previousCharPointData =
removingLastCharOfStartNode
? CharPointData::InDifferentTextNode(CharPointType::TextEnd)
: GetPreviousCharPointDataForNormalizingWhiteSpaces(
startToNormalize.IsSet() ? startToNormalize : aStartToDelete);
CharPointData nextCharPointData =
GetInclusiveNextCharPointDataForNormalizingWhiteSpaces(
endToNormalize.IsSet() ? endToNormalize : aEndToDelete);
// Next, compute number of white-spaces in start/end node.
uint32_t lengthInStartNode = 0, lengthInEndNode = 0;
if (startToNormalize.IsSet()) {
MOZ_ASSERT(startToNormalize.ContainerAs<Text>() ==
aStartToDelete.ContainerAs<Text>());
lengthInStartNode = aStartToDelete.Offset() - startToNormalize.Offset();
MOZ_ASSERT(lengthInStartNode);
}
if (endToNormalize.IsSet()) {
lengthInEndNode =
endToNormalize.ContainerAs<Text>() == aEndToDelete.ContainerAs<Text>()
? endToNormalize.Offset() - aEndToDelete.Offset()
: endToNormalize.Offset();
MOZ_ASSERT(lengthInEndNode);
// If we normalize white-spaces in a text node, we can replace all of them
// with one ReplaceTextTransaction.
if (endToNormalize.ContainerAs<Text>() ==
aStartToDelete.ContainerAs<Text>()) {
lengthInStartNode += lengthInEndNode;
lengthInEndNode = 0;
}
}
MOZ_ASSERT(lengthInStartNode + lengthInEndNode);
// Next, generate normalized white-spaces.
if (!lengthInEndNode) {
HTMLEditor::GenerateWhiteSpaceSequence(
aNormalizedWhiteSpacesInStartNode, lengthInStartNode,
previousCharPointData, nextCharPointData);
} else if (!lengthInStartNode) {
HTMLEditor::GenerateWhiteSpaceSequence(
aNormalizedWhiteSpacesInEndNode, lengthInEndNode, previousCharPointData,
nextCharPointData);
} else {
// For making `GenerateWhiteSpaceSequence()` simpler, we should create
// whole white-space sequence first, then, copy to the out params.
nsAutoString whiteSpaces;
HTMLEditor::GenerateWhiteSpaceSequence(
whiteSpaces, lengthInStartNode + lengthInEndNode, previousCharPointData,
nextCharPointData);
aNormalizedWhiteSpacesInStartNode =
Substring(whiteSpaces, 0, lengthInStartNode);
aNormalizedWhiteSpacesInEndNode = Substring(whiteSpaces, lengthInStartNode);
MOZ_ASSERT(aNormalizedWhiteSpacesInEndNode.Length() == lengthInEndNode);
}
// TODO: Shrink the replacing range and string as far as possible because
// this may run a lot, i.e., HTMLEditor creates ReplaceTextTransaction
// a lot for normalizing white-spaces. Then, each transaction shouldn't
// have all white-spaces every time because once it's normalized, we
// don't need to normalize all of the sequence again, but currently
// we do.
// Finally, extend the range.
if (startToNormalize.IsSet()) {
aStartToDelete = startToNormalize;
}
if (endToNormalize.IsSet()) {
aEndToDelete = endToNormalize;
}
}
Result<CaretPoint, nsresult>
HTMLEditor::DeleteTextAndNormalizeSurroundingWhiteSpaces(
const EditorDOMPointInText& aStartToDelete,
const EditorDOMPointInText& aEndToDelete,
TreatEmptyTextNodes aTreatEmptyTextNodes,
DeleteDirection aDeleteDirection) {
MOZ_ASSERT(aStartToDelete.IsSetAndValid());
MOZ_ASSERT(aEndToDelete.IsSetAndValid());
MOZ_ASSERT(aStartToDelete.EqualsOrIsBefore(aEndToDelete));
// Use nsString for these replacing string because we should avoid to copy
// the buffer from auto storange to ReplaceTextTransaction.
nsString normalizedWhiteSpacesInFirstNode, normalizedWhiteSpacesInLastNode;
// First, check whether we need to normalize white-spaces after deleting
// the given range.
EditorDOMPointInText startToDelete(aStartToDelete);
EditorDOMPointInText endToDelete(aEndToDelete);
ExtendRangeToDeleteWithNormalizingWhiteSpaces(
startToDelete, endToDelete, normalizedWhiteSpacesInFirstNode,
normalizedWhiteSpacesInLastNode);
// If extended range is still collapsed, i.e., the caller just wants to
// normalize white-space sequence, but there is no white-spaces which need to
// be replaced, we need to do nothing here.
if (startToDelete == endToDelete) {
return CaretPoint(aStartToDelete.To<EditorDOMPoint>());
}
// Note that the container text node of startToDelete may be removed from
// the tree if it becomes empty. Therefore, we need to track the point.
EditorDOMPoint newCaretPosition;
if (aStartToDelete.ContainerAs<Text>() == aEndToDelete.ContainerAs<Text>()) {
newCaretPosition = aEndToDelete.To<EditorDOMPoint>();
} else if (aDeleteDirection == DeleteDirection::Forward) {
newCaretPosition.SetToEndOf(aStartToDelete.ContainerAs<Text>());
} else {
newCaretPosition.Set(aEndToDelete.ContainerAs<Text>(), 0u);
}
// Then, modify the text nodes in the range.
while (true) {
AutoTrackDOMPoint trackingNewCaretPosition(RangeUpdaterRef(),
&newCaretPosition);
// Use ReplaceTextTransaction if we need to normalize white-spaces in
// the first text node.
if (!normalizedWhiteSpacesInFirstNode.IsEmpty()) {
EditorDOMPoint trackingEndToDelete(endToDelete.ContainerAs<Text>(),
endToDelete.Offset());
{
AutoTrackDOMPoint trackEndToDelete(RangeUpdaterRef(),
&trackingEndToDelete);
uint32_t lengthToReplaceInFirstTextNode =
startToDelete.ContainerAs<Text>() ==
trackingEndToDelete.ContainerAs<Text>()
? trackingEndToDelete.Offset() - startToDelete.Offset()
: startToDelete.ContainerAs<Text>()->TextLength() -
startToDelete.Offset();
Result<InsertTextResult, nsresult> replaceTextResult =
ReplaceTextWithTransaction(
MOZ_KnownLive(*startToDelete.ContainerAs<Text>()),
startToDelete.Offset(), lengthToReplaceInFirstTextNode,
normalizedWhiteSpacesInFirstNode);
if (MOZ_UNLIKELY(replaceTextResult.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceTextResult.propagateErr();
}
// We'll return computed caret point, newCaretPosition, below.
replaceTextResult.unwrap().IgnoreCaretPointSuggestion();
if (startToDelete.ContainerAs<Text>() ==
trackingEndToDelete.ContainerAs<Text>()) {
MOZ_ASSERT(normalizedWhiteSpacesInLastNode.IsEmpty());
break; // There is no more text which we need to delete.
}
}
if (MayHaveMutationEventListeners(
NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED) &&
(NS_WARN_IF(!trackingEndToDelete.IsSetAndValid()) ||
NS_WARN_IF(!trackingEndToDelete.IsInTextNode()))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
MOZ_ASSERT(trackingEndToDelete.IsInTextNode());
endToDelete.Set(trackingEndToDelete.ContainerAs<Text>(),
trackingEndToDelete.Offset());
// If the remaining range was modified by mutation event listener,
// we should stop handling the deletion.
startToDelete =
EditorDOMPointInText::AtEndOf(*startToDelete.ContainerAs<Text>());
if (MayHaveMutationEventListeners(
NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED) &&
NS_WARN_IF(!startToDelete.IsBefore(endToDelete))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Delete ASCII whiteSpaces in the range simpley if there are some text
// nodes which we don't need to replace their text.
if (normalizedWhiteSpacesInLastNode.IsEmpty() ||
startToDelete.ContainerAs<Text>() != endToDelete.ContainerAs<Text>()) {
// If we need to replace text in the last text node, we should
// delete text before its previous text node.
EditorDOMPointInText endToDeleteExceptReplaceRange =
normalizedWhiteSpacesInLastNode.IsEmpty()
? endToDelete
: EditorDOMPointInText(endToDelete.ContainerAs<Text>(), 0);
if (startToDelete != endToDeleteExceptReplaceRange) {
Result<CaretPoint, nsresult> caretPointOrError =
DeleteTextAndTextNodesWithTransaction(startToDelete,
endToDeleteExceptReplaceRange,
aTreatEmptyTextNodes);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::DeleteTextAndTextNodesWithTransaction() failed");
return caretPointOrError.propagateErr();
}
nsresult rv = caretPointOrError.unwrap().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CaretPoint::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CaretPoint::SuggestCaretPointTo() failed, but ignored");
if (normalizedWhiteSpacesInLastNode.IsEmpty()) {
break; // There is no more text which we need to delete.
}
if (MayHaveMutationEventListeners(
NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED |
NS_EVENT_BITS_MUTATION_NODEREMOVED |
NS_EVENT_BITS_MUTATION_NODEREMOVEDFROMDOCUMENT |
NS_EVENT_BITS_MUTATION_SUBTREEMODIFIED) &&
(NS_WARN_IF(!endToDeleteExceptReplaceRange.IsSetAndValid()) ||
NS_WARN_IF(!endToDelete.IsSetAndValid()) ||
NS_WARN_IF(endToDelete.IsStartOfContainer()))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// Then, replace the text in the last text node.
startToDelete = endToDeleteExceptReplaceRange;
}
}
// Replace ASCII whiteSpaces in the range and following character in the
// last text node.
MOZ_ASSERT(!normalizedWhiteSpacesInLastNode.IsEmpty());
MOZ_ASSERT(startToDelete.ContainerAs<Text>() ==
endToDelete.ContainerAs<Text>());
Result<InsertTextResult, nsresult> replaceTextResult =
ReplaceTextWithTransaction(
MOZ_KnownLive(*startToDelete.ContainerAs<Text>()),
startToDelete.Offset(),
endToDelete.Offset() - startToDelete.Offset(),
normalizedWhiteSpacesInLastNode);
if (MOZ_UNLIKELY(replaceTextResult.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceTextResult.propagateErr();
}
// We'll return computed caret point, newCaretPosition, below.
replaceTextResult.unwrap().IgnoreCaretPointSuggestion();
break;
}
if (NS_WARN_IF(!newCaretPosition.IsSetAndValid()) ||
NS_WARN_IF(!newCaretPosition.GetContainer()->IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// Look for leaf node to put caret if we remove some empty inline ancestors
// at new caret position.
if (!newCaretPosition.IsInTextNode()) {
if (const Element* editableBlockElementOrInlineEditingHost =
HTMLEditUtils::GetInclusiveAncestorElement(
*newCaretPosition.ContainerAs<nsIContent>(),
HTMLEditUtils::
ClosestEditableBlockElementOrInlineEditingHost)) {
Element* editingHost = ComputeEditingHost();
// Try to put caret next to immediately after previous editable leaf.
nsIContent* previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
newCaretPosition, *editableBlockElementOrInlineEditingHost,
{LeafNodeType::LeafNodeOrNonEditableNode}, editingHost);
if (previousContent && !HTMLEditUtils::IsBlockElement(*previousContent)) {
newCaretPosition =
previousContent->IsText() ||
HTMLEditUtils::IsContainerNode(*previousContent)
? EditorDOMPoint::AtEndOf(*previousContent)
: EditorDOMPoint::After(*previousContent);
}
// But if the point is very first of a block element or immediately after
// a child block, look for next editable leaf instead.
else if (nsIContent* nextContent =
HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
newCaretPosition,
*editableBlockElementOrInlineEditingHost,
{LeafNodeType::LeafNodeOrNonEditableNode},
editingHost)) {
newCaretPosition = nextContent->IsText() ||
HTMLEditUtils::IsContainerNode(*nextContent)
? EditorDOMPoint(nextContent, 0)
: EditorDOMPoint(nextContent);
}
}
}
// For compatibility with Blink, we should move caret to end of previous
// text node if it's direct previous sibling of the first text node in the
// range.
if (newCaretPosition.IsStartOfContainer() &&
newCaretPosition.IsInTextNode() &&
newCaretPosition.GetContainer()->GetPreviousSibling() &&
newCaretPosition.GetContainer()->GetPreviousSibling()->IsText()) {
newCaretPosition.SetToEndOf(
newCaretPosition.GetContainer()->GetPreviousSibling()->AsText());
}
{
AutoTrackDOMPoint trackingNewCaretPosition(RangeUpdaterRef(),
&newCaretPosition);
Result<CaretPoint, nsresult> caretPointOrError =
InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary(
newCaretPosition);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary() failed");
return caretPointOrError;
}
}
if (!newCaretPosition.IsSetAndValid()) {
NS_WARNING("Inserting <br> element caused unexpected DOM tree");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return CaretPoint(std::move(newCaretPosition));
}
Result<CaretPoint, nsresult>
HTMLEditor::InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary(
const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSet());
if (!aPointToInsert.IsInContentNode()) {
return CaretPoint(EditorDOMPoint());
}
// If container of the point is not in a block, we don't need to put a
// `<br>` element here.
if (!HTMLEditUtils::IsBlockElement(
*aPointToInsert.ContainerAs<nsIContent>())) {
return CaretPoint(EditorDOMPoint());
}
WSRunScanner wsRunScanner(ComputeEditingHost(), aPointToInsert);
// If the point is not start of a hard line, we don't need to put a `<br>`
// element here.
if (!wsRunScanner.StartsFromHardLineBreak()) {
return CaretPoint(EditorDOMPoint());
}
// If the point is not end of a hard line or the hard line does not end with
// block boundary, we don't need to put a `<br>` element here.
if (!wsRunScanner.EndsByBlockBoundary()) {
return CaretPoint(EditorDOMPoint());
}
// If we cannot insert a `<br>` element here, do nothing.
if (!HTMLEditUtils::CanNodeContain(*aPointToInsert.GetContainer(),
*nsGkAtoms::br)) {
return CaretPoint(EditorDOMPoint());
}
Result<CreateElementResult, nsresult> insertBRElementResult = InsertBRElement(
WithTransaction::Yes, aPointToInsert, nsIEditor::ePrevious);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes, ePrevious) failed");
return insertBRElementResult.propagateErr();
}
return CaretPoint(insertBRElementResult.unwrap().UnwrapCaretPoint());
}
Result<EditActionResult, nsresult>
HTMLEditor::MakeOrChangeListAndListItemAsSubAction(
const nsStaticAtom& aListElementOrListItemElementTagName,
const nsAString& aBulletType,
SelectAllOfCurrentList aSelectAllOfCurrentList) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(&aListElementOrListItemElementTagName == nsGkAtoms::ul ||
&aListElementOrListItemElementTagName == nsGkAtoms::ol ||
&aListElementOrListItemElementTagName == nsGkAtoms::dl ||
&aListElementOrListItemElementTagName == nsGkAtoms::dd ||
&aListElementOrListItemElementTagName == nsGkAtoms::dt);
if (NS_WARN_IF(!mInitSucceeded)) {
return Err(NS_ERROR_NOT_INITIALIZED);
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Some selection containers are not content node, but ignored");
return EditActionResult::IgnoredResult();
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
// XXX EditSubAction::eCreateOrChangeDefinitionListItem and
// EditSubAction::eCreateOrChangeList are treated differently in
// HTMLEditor::MaybeSplitElementsAtEveryBRElement(). Only when
// EditSubAction::eCreateOrChangeList, it splits inline nodes.
// Currently, it shouldn't be done when we called for formatting
// `<dd>` or `<dt>` by
// HTMLEditor::MakeDefinitionListItemWithTransaction(). But this
// difference may be a bug. We should investigate this later.
IgnoredErrorResult error;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this,
&aListElementOrListItemElementTagName == nsGkAtoms::dd ||
&aListElementOrListItemElementTagName == nsGkAtoms::dt
? EditSubAction::eCreateOrChangeDefinitionListItem
: EditSubAction::eCreateOrChangeList,
nsIEditor::eNext, error);
if (NS_WARN_IF(error.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(error.StealNSResult());
}
NS_WARNING_ASSERTION(
!error.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
const nsStaticAtom* listTagName = nullptr;
const nsStaticAtom* listItemTagName = nullptr;
if (&aListElementOrListItemElementTagName == nsGkAtoms::ul ||
&aListElementOrListItemElementTagName == nsGkAtoms::ol) {
listTagName = &aListElementOrListItemElementTagName;
listItemTagName = nsGkAtoms::li;
} else if (&aListElementOrListItemElementTagName == nsGkAtoms::dl) {
listTagName = &aListElementOrListItemElementTagName;
listItemTagName = nsGkAtoms::dd;
} else if (&aListElementOrListItemElementTagName == nsGkAtoms::dd ||
&aListElementOrListItemElementTagName == nsGkAtoms::dt) {
listTagName = nsGkAtoms::dl;
listItemTagName = &aListElementOrListItemElementTagName;
} else {
NS_WARNING(
"aListElementOrListItemElementTagName was neither list element name "
"nor "
"definition listitem element name");
return Err(NS_ERROR_INVALID_ARG);
}
const RefPtr<Element> editingHost = ComputeEditingHost();
if (MOZ_UNLIKELY(!editingHost)) {
return EditActionResult::CanceledResult();
}
// Expands selection range to include the immediate block parent, and then
// further expands to include any ancestors whose children are all in the
// range.
// XXX Why do we do this only when there is only one selection range?
if (!SelectionRef().IsCollapsed() && SelectionRef().RangeCount() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
SelectionRef().GetRangeAt(0u), *editingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.propagateErr();
}
// Note that end point may be prior to start point. So, we
// cannot use Selection::SetStartAndEndInLimit() here.
error.SuppressException();
SelectionRef().SetBaseAndExtentInLimiter(
extendedRange.inspect().StartRef().ToRawRangeBoundary(),
extendedRange.inspect().EndRef().ToRawRangeBoundary(), error);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("Selection::SetBaseAndExtentInLimiter() failed");
return Err(error.StealNSResult());
}
}
AutoListElementCreator listCreator(*listTagName, *listItemTagName,
aBulletType);
AutoRangeArray selectionRanges(SelectionRef());
Result<EditActionResult, nsresult> result = listCreator.Run(
*this, selectionRanges, aSelectAllOfCurrentList, *editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::ConvertContentAroundRangesToList() failed");
// XXX Should we try to restore selection ranges in this case?
return result;
}
rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::ApplyTo() failed");
return Err(rv);
}
return result.inspect().Ignored() ? EditActionResult::CanceledResult()
: EditActionResult::HandledResult();
}
Result<EditActionResult, nsresult> HTMLEditor::AutoListElementCreator::Run(
HTMLEditor& aHTMLEditor, AutoRangeArray& aRanges,
SelectAllOfCurrentList aSelectAllOfCurrentList,
const Element& aEditingHost) const {
MOZ_ASSERT(aHTMLEditor.IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(!aHTMLEditor.IsSelectionRangeContainerNotContent());
if (NS_WARN_IF(!aRanges.SaveAndTrackRanges(aHTMLEditor))) {
return Err(NS_ERROR_FAILURE);
}
AutoContentNodeArray arrayOfContents;
nsresult rv = SplitAtRangeEdgesAndCollectContentNodesToMoveIntoList(
aHTMLEditor, aRanges, aSelectAllOfCurrentList, aEditingHost,
arrayOfContents);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoListElementCreator::"
"SplitAtRangeEdgesAndCollectContentNodesToMoveIntoList() failed");
return Err(rv);
}
// check if all our nodes are <br>s, or empty inlines
// if no nodes, we make empty list. Ditto if the user tried to make a list
// of some # of breaks.
if (AutoListElementCreator::
IsEmptyOrContainsOnlyBRElementsOrEmptyInlineElements(
arrayOfContents)) {
Result<RefPtr<Element>, nsresult> newListItemElementOrError =
ReplaceContentNodesWithEmptyNewList(aHTMLEditor, aRanges,
arrayOfContents, aEditingHost);
if (MOZ_UNLIKELY(newListItemElementOrError.isErr())) {
NS_WARNING(
"AutoListElementCreator::ReplaceContentNodesWithEmptyNewList() "
"failed");
return newListItemElementOrError.propagateErr();
}
if (MOZ_UNLIKELY(!newListItemElementOrError.inspect())) {
aRanges.RestoreFromSavedRanges();
return EditActionResult::CanceledResult();
}
aRanges.ClearSavedRanges();
nsresult rv = aRanges.Collapse(
EditorRawDOMPoint(newListItemElementOrError.inspect(), 0u));
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::Collapse() failed");
return Err(rv);
}
return EditActionResult::IgnoredResult();
}
Result<RefPtr<Element>, nsresult> listItemOrListToPutCaretOrError =
WrapContentNodesIntoNewListElements(aHTMLEditor, aRanges, arrayOfContents,
aEditingHost);
if (MOZ_UNLIKELY(listItemOrListToPutCaretOrError.isErr())) {
NS_WARNING(
"AutoListElementCreator::WrapContentNodesIntoNewListElements() failed");
return listItemOrListToPutCaretOrError.propagateErr();
}
MOZ_ASSERT(aRanges.HasSavedRanges());
aRanges.RestoreFromSavedRanges();
// If selection will be collapsed but not in listItemOrListToPutCaret, we need
// to adjust the caret position into it.
if (listItemOrListToPutCaretOrError.inspect()) {
DebugOnly<nsresult> rvIgnored =
EnsureCollapsedRangeIsInListItemOrListElement(
*listItemOrListToPutCaretOrError.inspect(), aRanges);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"AutoListElementCreator::"
"EnsureCollapsedRangeIsInListItemOrListElement() failed, but ignored");
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::AutoListElementCreator::
SplitAtRangeEdgesAndCollectContentNodesToMoveIntoList(
HTMLEditor& aHTMLEditor, AutoRangeArray& aRanges,
SelectAllOfCurrentList aSelectAllOfCurrentList,
const Element& aEditingHost,
ContentNodeArray& aOutArrayOfContents) const {
MOZ_ASSERT(aOutArrayOfContents.IsEmpty());
if (aSelectAllOfCurrentList == SelectAllOfCurrentList::Yes) {
if (Element* parentListElementOfRanges =
aRanges.GetClosestAncestorAnyListElementOfRange()) {
aOutArrayOfContents.AppendElement(
OwningNonNull<nsIContent>(*parentListElementOfRanges));
return NS_OK;
}
}
AutoRangeArray extendedRanges(aRanges);
// TODO: We don't need AutoTransactionsConserveSelection here in the
// normal cases, but removing this may cause the behavior with the
// legacy mutation event listeners. We should try to delete this in
// a bug.
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
extendedRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eCreateOrChangeList, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedRanges.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
aHTMLEditor, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() failed");
return splitResult.unwrapErr();
}
nsresult rv = extendedRanges.CollectEditTargetNodes(
aHTMLEditor, aOutArrayOfContents, EditSubAction::eCreateOrChangeList,
AutoRangeArray::CollectNonEditableNodes::No);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::"
"eCreateOrChangeList, CollectNonEditableNodes::No) failed");
return rv;
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
aHTMLEditor.MaybeSplitElementsAtEveryBRElement(
aOutArrayOfContents, EditSubAction::eCreateOrChangeList);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eCreateOrChangeList) failed");
return splitAtBRElementsResult.unwrapErr();
}
return NS_OK;
}
// static
bool HTMLEditor::AutoListElementCreator::
IsEmptyOrContainsOnlyBRElementsOrEmptyInlineElements(
const ContentNodeArray& aArrayOfContents) {
for (const OwningNonNull<nsIContent>& content : aArrayOfContents) {
// if content is not a <br> or empty inline, we're done
// XXX Should we handle line breaks in preformatted text node?
if (!content->IsHTMLElement(nsGkAtoms::br) &&
!HTMLEditUtils::IsEmptyInlineContainer(
content, {EmptyCheckOption::TreatSingleBRElementAsVisible})) {
return false;
}
}
return true;
}
Result<RefPtr<Element>, nsresult>
HTMLEditor::AutoListElementCreator::ReplaceContentNodesWithEmptyNewList(
HTMLEditor& aHTMLEditor, const AutoRangeArray& aRanges,
const AutoContentNodeArray& aArrayOfContents,
const Element& aEditingHost) const {
// if only breaks, delete them
for (const OwningNonNull<nsIContent>& content : aArrayOfContents) {
// MOZ_KnownLive because of bug 1620312
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(*content));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
const auto firstRangeStartPoint =
aRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!firstRangeStartPoint.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
// Make sure we can put a list here.
if (!HTMLEditUtils::CanNodeContain(*firstRangeStartPoint.GetContainer(),
mListTagName)) {
return RefPtr<Element>();
}
RefPtr<Element> newListItemElement;
Result<CreateElementResult, nsresult> createNewListElementResult =
aHTMLEditor.InsertElementWithSplittingAncestorsWithTransaction(
mListTagName, firstRangeStartPoint, BRElementNextToSplitPoint::Keep,
aEditingHost,
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[&](HTMLEditor& aHTMLEditor, Element& aListElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
AutoHandlingState dummyState;
Result<CreateElementResult, nsresult> createListItemElementResult =
AppendListItemElement(aHTMLEditor, aListElement, dummyState);
if (MOZ_UNLIKELY(createListItemElementResult.isErr())) {
NS_WARNING(
"AutoListElementCreator::AppendListItemElement() failed");
return createListItemElementResult.unwrapErr();
}
CreateElementResult unwrappedResult =
createListItemElementResult.unwrap();
// There is AutoSelectionRestorer in this method so that it'll
// be restored or updated with making it abort. Therefore,
// we don't need to update selection here.
// XXX I'd like to check aRanges.HasSavedRanges() here, but it
// requires ifdefs to avoid bustage of opt builds caused
// by unused warning...
unwrappedResult.IgnoreCaretPointSuggestion();
newListItemElement = unwrappedResult.UnwrapNewNode();
MOZ_ASSERT(newListItemElement);
return NS_OK;
});
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"%s) failed",
nsAtomCString(&mListTagName).get())
.get());
return createNewListElementResult.propagateErr();
}
MOZ_ASSERT(createNewListElementResult.inspect().GetNewNode());
// Put selection in new list item and don't restore the Selection.
createNewListElementResult.inspect().IgnoreCaretPointSuggestion();
return newListItemElement;
}
Result<RefPtr<Element>, nsresult>
HTMLEditor::AutoListElementCreator::WrapContentNodesIntoNewListElements(
HTMLEditor& aHTMLEditor, AutoRangeArray& aRanges,
AutoContentNodeArray& aArrayOfContents, const Element& aEditingHost) const {
// if there is only one node in the array, and it is a list, div, or
// blockquote, then look inside of it until we find inner list or content.
if (aArrayOfContents.Length() == 1) {
if (Element* deepestDivBlockquoteOrListElement =
HTMLEditUtils::GetInclusiveDeepestFirstChildWhichHasOneChild(
aArrayOfContents[0], {WalkTreeOption::IgnoreNonEditableNode},
nsGkAtoms::div, nsGkAtoms::blockquote, nsGkAtoms::ul,
nsGkAtoms::ol, nsGkAtoms::dl)) {
if (deepestDivBlockquoteOrListElement->IsAnyOfHTMLElements(
nsGkAtoms::div, nsGkAtoms::blockquote)) {
aArrayOfContents.Clear();
HTMLEditUtils::CollectChildren(*deepestDivBlockquoteOrListElement,
aArrayOfContents, 0, {});
} else {
aArrayOfContents.ReplaceElementAt(
0, OwningNonNull<nsIContent>(*deepestDivBlockquoteOrListElement));
}
}
}
// Ok, now go through all the nodes and put then in the list,
// or whatever is appropriate. Wohoo!
AutoHandlingState handlingState;
for (const OwningNonNull<nsIContent>& content : aArrayOfContents) {
// MOZ_KnownLive because of bug 1620312
nsresult rv = HandleChildContent(aHTMLEditor, MOZ_KnownLive(content),
handlingState, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoListElementCreator::HandleChildContent() failed");
return Err(rv);
}
}
return std::move(handlingState.mListOrListItemElementToPutCaret);
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildContent(
HTMLEditor& aHTMLEditor, nsIContent& aHandlingContent,
AutoHandlingState& aState, const Element& aEditingHost) const {
// make sure we don't assemble content that is in different table cells
// into the same list. respect table cell boundaries when listifying.
if (aState.mCurrentListElement &&
HTMLEditUtils::GetInclusiveAncestorAnyTableElement(
*aState.mCurrentListElement) !=
HTMLEditUtils::GetInclusiveAncestorAnyTableElement(
aHandlingContent)) {
aState.mCurrentListElement = nullptr;
}
// If current node is a `<br>` element, delete it and forget previous
// list item element.
// If current node is an empty inline node, just delete it.
if (EditorUtils::IsEditableContent(aHandlingContent, EditorType::HTML) &&
(aHandlingContent.IsHTMLElement(nsGkAtoms::br) ||
HTMLEditUtils::IsEmptyInlineContainer(
aHandlingContent,
{EmptyCheckOption::TreatSingleBRElementAsVisible}))) {
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(aHandlingContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
if (aHandlingContent.IsHTMLElement(nsGkAtoms::br)) {
aState.mPreviousListItemElement = nullptr;
}
return NS_OK;
}
// If we meet a list, we can reuse it or convert it to the expected type list.
if (HTMLEditUtils::IsAnyListElement(&aHandlingContent)) {
nsresult rv = HandleChildListElement(
aHTMLEditor, MOZ_KnownLive(*aHandlingContent.AsElement()), aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::HandleChildListElement() failed");
return rv;
}
// We cannot handle nodes if not in element node.
if (NS_WARN_IF(!aHandlingContent.GetParentElement())) {
return NS_ERROR_FAILURE;
}
// If we meet a list item, we can just move it to current list element or new
// list element.
if (HTMLEditUtils::IsListItem(&aHandlingContent)) {
nsresult rv = HandleChildListItemElement(
aHTMLEditor, MOZ_KnownLive(*aHandlingContent.AsElement()), aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::HandleChildListItemElement() failed");
return rv;
}
// If we meet a <div> or a <p>, we want only its children to wrapping into
// list element. Therefore, this call will call this recursively.
if (aHandlingContent.IsAnyOfHTMLElements(nsGkAtoms::div, nsGkAtoms::p)) {
nsresult rv = HandleChildDivOrParagraphElement(
aHTMLEditor, MOZ_KnownLive(*aHandlingContent.AsElement()), aState,
aEditingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::HandleChildDivOrParagraphElement() failed");
return rv;
}
// If we've not met a list element, create a list element and make it
// current list element.
if (!aState.mCurrentListElement) {
nsresult rv = CreateAndUpdateCurrentListElement(
aHTMLEditor, EditorDOMPoint(&aHandlingContent),
EmptyListItem::NotCreate, aState, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoListElementCreator::HandleChildInlineElement() failed");
return rv;
}
}
// If we meet an inline content, we want to move it to previously used list
// item element or new list item element.
// XXX Despite the name, HTMLEditUtils::IsInlineElement() returns true for
// non-element content nodes too.
if (HTMLEditUtils::IsInlineElement(aHandlingContent)) {
nsresult rv =
HandleChildInlineContent(aHTMLEditor, aHandlingContent, aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::HandleChildInlineElement() failed");
return rv;
}
// Otherwise, we should wrap it into new list item element.
nsresult rv =
WrapContentIntoNewListItemElement(aHTMLEditor, aHandlingContent, aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::WrapContentIntoNewListItemElement() failed");
return rv;
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildListElement(
HTMLEditor& aHTMLEditor, Element& aHandlingListElement,
AutoHandlingState& aState) const {
MOZ_ASSERT(HTMLEditUtils::IsAnyListElement(&aHandlingListElement));
// If we met a list element and current list element is not a descendant
// of the list, append current node to end of the current list element.
// Then, wrap it with list item element and delete the old container.
if (aState.mCurrentListElement &&
!EditorUtils::IsDescendantOf(aHandlingListElement,
*aState.mCurrentListElement)) {
Result<MoveNodeResult, nsresult> moveNodeResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
aHandlingListElement, MOZ_KnownLive(*aState.mCurrentListElement));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
moveNodeResult.inspect().IgnoreCaretPointSuggestion();
Result<CreateElementResult, nsresult> convertListTypeResult =
aHTMLEditor.ChangeListElementType(aHandlingListElement, mListTagName,
mListItemTagName);
if (MOZ_UNLIKELY(convertListTypeResult.isErr())) {
NS_WARNING("HTMLEditor::ChangeListElementType() failed");
return convertListTypeResult.propagateErr();
}
convertListTypeResult.inspect().IgnoreCaretPointSuggestion();
Result<EditorDOMPoint, nsresult> unwrapNewListElementResult =
aHTMLEditor.RemoveBlockContainerWithTransaction(
MOZ_KnownLive(*convertListTypeResult.inspect().GetNewNode()));
if (MOZ_UNLIKELY(unwrapNewListElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapNewListElementResult.propagateErr();
}
aState.mPreviousListItemElement = nullptr;
return NS_OK;
}
// If current list element is in found list element or we've not met a
// list element, convert current list element to proper type.
Result<CreateElementResult, nsresult> convertListTypeResult =
aHTMLEditor.ChangeListElementType(aHandlingListElement, mListTagName,
mListItemTagName);
if (MOZ_UNLIKELY(convertListTypeResult.isErr())) {
NS_WARNING("HTMLEditor::ChangeListElementType() failed");
return convertListTypeResult.propagateErr();
}
CreateElementResult unwrappedConvertListTypeResult =
convertListTypeResult.unwrap();
unwrappedConvertListTypeResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedConvertListTypeResult.GetNewNode());
aState.mCurrentListElement = unwrappedConvertListTypeResult.UnwrapNewNode();
aState.mPreviousListItemElement = nullptr;
return NS_OK;
}
nsresult
HTMLEditor::AutoListElementCreator::HandleChildListItemInDifferentTypeList(
HTMLEditor& aHTMLEditor, Element& aHandlingListItemElement,
AutoHandlingState& aState) const {
MOZ_ASSERT(HTMLEditUtils::IsListItem(&aHandlingListItemElement));
MOZ_ASSERT(
!aHandlingListItemElement.GetParent()->IsHTMLElement(&mListTagName));
// If we've not met a list element or current node is not in current list
// element, insert a list element at current node and set current list element
// to the new one.
if (!aState.mCurrentListElement ||
aHandlingListItemElement.IsInclusiveDescendantOf(
aState.mCurrentListElement)) {
EditorDOMPoint atListItem(&aHandlingListItemElement);
MOZ_ASSERT(atListItem.IsInContentNode());
Result<SplitNodeResult, nsresult> splitListItemParentResult =
aHTMLEditor.SplitNodeWithTransaction(atListItem);
if (MOZ_UNLIKELY(splitListItemParentResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitListItemParentResult.propagateErr();
}
SplitNodeResult unwrappedSplitListItemParentResult =
splitListItemParentResult.unwrap();
MOZ_ASSERT(unwrappedSplitListItemParentResult.DidSplit());
unwrappedSplitListItemParentResult.IgnoreCaretPointSuggestion();
Result<CreateElementResult, nsresult> createNewListElementResult =
aHTMLEditor.CreateAndInsertElement(
WithTransaction::Yes, mListTagName,
unwrappedSplitListItemParentResult.AtNextContent<EditorDOMPoint>());
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) "
"failed");
return createNewListElementResult.propagateErr();
}
CreateElementResult unwrapCreateNewListElementResult =
createNewListElementResult.unwrap();
unwrapCreateNewListElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrapCreateNewListElementResult.GetNewNode());
aState.mCurrentListElement =
unwrapCreateNewListElementResult.UnwrapNewNode();
}
// Then, move current node into current list element.
Result<MoveNodeResult, nsresult> moveNodeResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
aHandlingListItemElement, MOZ_KnownLive(*aState.mCurrentListElement));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
moveNodeResult.inspect().IgnoreCaretPointSuggestion();
// Convert list item type if current node is different list item type.
if (aHandlingListItemElement.IsHTMLElement(&mListItemTagName)) {
return NS_OK;
}
Result<CreateElementResult, nsresult> newListItemElementOrError =
aHTMLEditor.ReplaceContainerAndCloneAttributesWithTransaction(
aHandlingListItemElement, mListItemTagName);
if (MOZ_UNLIKELY(newListItemElementOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceContainerWithTransaction() failed");
return newListItemElementOrError.propagateErr();
}
newListItemElementOrError.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildListItemElement(
HTMLEditor& aHTMLEditor, Element& aHandlingListItemElement,
AutoHandlingState& aState) const {
MOZ_ASSERT(aHandlingListItemElement.GetParentNode());
MOZ_ASSERT(HTMLEditUtils::IsListItem(&aHandlingListItemElement));
// If current list item element is not in proper list element, we need
// to convert the list element.
// XXX This check is not enough,
if (!aHandlingListItemElement.GetParentNode()->IsHTMLElement(&mListTagName)) {
nsresult rv = HandleChildListItemInDifferentTypeList(
aHTMLEditor, aHandlingListItemElement, aState);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoListElementCreator::HandleChildListItemInDifferentTypeList() "
"failed");
return rv;
}
} else {
nsresult rv = HandleChildListItemInSameTypeList(
aHTMLEditor, aHandlingListItemElement, aState);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoListElementCreator::HandleChildListItemInSameTypeList() failed");
return rv;
}
}
// If bullet type is specified, set list type attribute.
// XXX Cannot we set type attribute before inserting the list item
// element into the DOM tree?
if (!mBulletType.IsEmpty()) {
nsresult rv = aHTMLEditor.SetAttributeWithTransaction(
aHandlingListItemElement, *nsGkAtoms::type, mBulletType);
if (NS_WARN_IF(aHTMLEditor.Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction(nsGkAtoms::type) failed");
return rv;
}
// Otherwise, remove list type attribute if there is.
if (!aHandlingListItemElement.HasAttr(nsGkAtoms::type)) {
return NS_OK;
}
nsresult rv = aHTMLEditor.RemoveAttributeWithTransaction(
aHandlingListItemElement, *nsGkAtoms::type);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::type) failed");
return rv;
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildListItemInSameTypeList(
HTMLEditor& aHTMLEditor, Element& aHandlingListItemElement,
AutoHandlingState& aState) const {
MOZ_ASSERT(HTMLEditUtils::IsListItem(&aHandlingListItemElement));
MOZ_ASSERT(
aHandlingListItemElement.GetParent()->IsHTMLElement(&mListTagName));
EditorDOMPoint atListItem(&aHandlingListItemElement);
MOZ_ASSERT(atListItem.IsInContentNode());
// If we've not met a list element, set current list element to the
// parent of current list item element.
if (!aState.mCurrentListElement) {
aState.mCurrentListElement = atListItem.GetContainerAs<Element>();
NS_WARNING_ASSERTION(
HTMLEditUtils::IsAnyListElement(aState.mCurrentListElement),
"Current list item parent is not a list element");
}
// If current list item element is not a child of current list element,
// move it into current list item.
else if (atListItem.GetContainer() != aState.mCurrentListElement) {
Result<MoveNodeResult, nsresult> moveNodeResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
aHandlingListItemElement,
MOZ_KnownLive(*aState.mCurrentListElement));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
moveNodeResult.inspect().IgnoreCaretPointSuggestion();
}
// Then, if current list item element is not proper type for current
// list element, convert list item element to proper element.
if (aHandlingListItemElement.IsHTMLElement(&mListItemTagName)) {
return NS_OK;
}
// FIXME: Manage attribute cloning
Result<CreateElementResult, nsresult> newListItemElementOrError =
aHTMLEditor.ReplaceContainerAndCloneAttributesWithTransaction(
aHandlingListItemElement, mListItemTagName);
if (MOZ_UNLIKELY(newListItemElementOrError.isErr())) {
NS_WARNING(
"HTMLEditor::ReplaceContainerAndCloneAttributesWithTransaction() "
"failed");
return newListItemElementOrError.propagateErr();
}
newListItemElementOrError.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildDivOrParagraphElement(
HTMLEditor& aHTMLEditor, Element& aHandlingDivOrParagraphElement,
AutoHandlingState& aState, const Element& aEditingHost) const {
MOZ_ASSERT(aHandlingDivOrParagraphElement.IsAnyOfHTMLElements(nsGkAtoms::div,
nsGkAtoms::p));
AutoRestore<RefPtr<Element>> previouslyReplacingBlockElement(
aState.mReplacingBlockElement);
aState.mReplacingBlockElement = &aHandlingDivOrParagraphElement;
AutoRestore<bool> previouslyReplacingBlockElementIdCopied(
aState.mMaybeCopiedReplacingBlockElementId);
aState.mMaybeCopiedReplacingBlockElementId = false;
// If the <div> or <p> is empty, we should replace it with a list element
// and/or a list item element.
if (HTMLEditUtils::IsEmptyNode(aHandlingDivOrParagraphElement,
{EmptyCheckOption::IgnoreEditableState,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible})) {
if (!aState.mCurrentListElement) {
nsresult rv = CreateAndUpdateCurrentListElement(
aHTMLEditor, EditorDOMPoint(&aHandlingDivOrParagraphElement),
EmptyListItem::Create, aState, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoListElementCreator::CreateAndUpdateCurrentListElement("
"EmptyListItem::Create) failed");
return rv;
}
} else {
Result<CreateElementResult, nsresult> createListItemElementResult =
AppendListItemElement(
aHTMLEditor, MOZ_KnownLive(*aState.mCurrentListElement), aState);
if (MOZ_UNLIKELY(createListItemElementResult.isErr())) {
NS_WARNING("AutoListElementCreator::AppendListItemElement() failed");
return createListItemElementResult.unwrapErr();
}
CreateElementResult unwrappedResult =
createListItemElementResult.unwrap();
unwrappedResult.IgnoreCaretPointSuggestion();
aState.mListOrListItemElementToPutCaret = unwrappedResult.UnwrapNewNode();
}
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(aHandlingDivOrParagraphElement);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteNodeWithTransaction() failed");
return rv;
}
// We don't want new inline contents inserted into the new list item element
// because we want to keep the line break at end of
// aHandlingDivOrParagraphElement.
aState.mPreviousListItemElement = nullptr;
return NS_OK;
}
// If current node is a <div> element, replace it with its children and handle
// them as same as topmost children in the range.
AutoContentNodeArray arrayOfContentsInDiv;
HTMLEditUtils::CollectChildren(aHandlingDivOrParagraphElement,
arrayOfContentsInDiv, 0,
{CollectChildrenOption::CollectListChildren,
CollectChildrenOption::CollectTableChildren});
Result<EditorDOMPoint, nsresult> unwrapDivElementResult =
aHTMLEditor.RemoveContainerWithTransaction(
aHandlingDivOrParagraphElement);
if (MOZ_UNLIKELY(unwrapDivElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapDivElementResult.unwrapErr();
}
for (const OwningNonNull<nsIContent>& content : arrayOfContentsInDiv) {
// MOZ_KnownLive because of bug 1620312
nsresult rv = HandleChildContent(aHTMLEditor, MOZ_KnownLive(content),
aState, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoListElementCreator::HandleChildContent() failed");
return rv;
}
}
// We don't want new inline contents inserted into the new list item element
// because we want to keep the line break at end of
// aHandlingDivOrParagraphElement.
aState.mPreviousListItemElement = nullptr;
return NS_OK;
}
nsresult HTMLEditor::AutoListElementCreator::CreateAndUpdateCurrentListElement(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPointToInsert,
EmptyListItem aEmptyListItem, AutoHandlingState& aState,
const Element& aEditingHost) const {
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
aState.mPreviousListItemElement = nullptr;
RefPtr<Element> newListItemElement;
auto initializer =
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[&](HTMLEditor&, Element& aListElement, const EditorDOMPoint&)
MOZ_CAN_RUN_SCRIPT_BOUNDARY {
// If the replacing element has `dir` attribute, the new list
// element should take it to correct its list marker position.
if (aState.mReplacingBlockElement) {
nsString dirValue;
if (aState.mReplacingBlockElement->GetAttr(nsGkAtoms::dir,
dirValue) &&
!dirValue.IsEmpty()) {
// We don't need to use transaction to set `dir` attribute here
// because the element will be stored with the `dir` attribute
// in InsertNodeTransaction. Therefore, undo should work.
IgnoredErrorResult ignoredError;
aListElement.SetAttr(nsGkAtoms::dir, dirValue, ignoredError);
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"Element::SetAttr(nsGkAtoms::dir) failed, but ignored");
}
}
if (aEmptyListItem == EmptyListItem::Create) {
Result<CreateElementResult, nsresult> createNewListItemResult =
AppendListItemElement(aHTMLEditor, aListElement, aState);
if (MOZ_UNLIKELY(createNewListItemResult.isErr())) {
NS_WARNING(
"HTMLEditor::AppendNewElementToInsertingElement()"
" failed");
return createNewListItemResult.unwrapErr();
}
CreateElementResult unwrappedResult =
createNewListItemResult.unwrap();
unwrappedResult.IgnoreCaretPointSuggestion();
newListItemElement = unwrappedResult.UnwrapNewNode();
}
return NS_OK;
};
Result<CreateElementResult, nsresult> createNewListElementResult =
aHTMLEditor.InsertElementWithSplittingAncestorsWithTransaction(
mListTagName, aPointToInsert, BRElementNextToSplitPoint::Keep,
aEditingHost, initializer);
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTransaction(%s) failed",
nsAtomCString(&mListTagName).get())
.get());
return createNewListElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewListElementResult =
createNewListElementResult.unwrap();
unwrappedCreateNewListElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedCreateNewListElementResult.GetNewNode());
aState.mListOrListItemElementToPutCaret =
newListItemElement ? newListItemElement.get()
: unwrappedCreateNewListElementResult.GetNewNode();
aState.mCurrentListElement =
unwrappedCreateNewListElementResult.UnwrapNewNode();
aState.mPreviousListItemElement = std::move(newListItemElement);
return NS_OK;
}
// static
nsresult HTMLEditor::AutoListElementCreator::MaybeCloneAttributesToNewListItem(
HTMLEditor& aHTMLEditor, Element& aListItemElement,
AutoHandlingState& aState) {
if (!aState.mReplacingBlockElement) {
return NS_OK;
}
// If we're replacing a block element, the list items should have attributes
// of the replacing element. However, we don't want to copy `dir` attribute
// because it does not affect content in list item element and setting
// opposite direction from the parent list causes the marker invisible.
// Therefore, we don't want to take it. Finally, we don't need to use
// transaction to copy the attributes here because the element will be stored
// with the attributes in InsertNodeTransaction. Therefore, undo should work.
nsresult rv = aHTMLEditor.CopyAttributes(
WithTransaction::No, aListItemElement,
MOZ_KnownLive(*aState.mReplacingBlockElement),
aState.mMaybeCopiedReplacingBlockElementId
? HTMLEditor::CopyAllAttributesExceptIdAndDir
: HTMLEditor::CopyAllAttributesExceptDir);
aState.mMaybeCopiedReplacingBlockElementId = true;
if (NS_WARN_IF(aHTMLEditor.Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::CopyAttributes(WithTransaction::No) failed");
return rv;
}
Result<CreateElementResult, nsresult>
HTMLEditor::AutoListElementCreator::AppendListItemElement(
HTMLEditor& aHTMLEditor, const Element& aListElement,
AutoHandlingState& aState) const {
const WithTransaction withTransaction = aListElement.IsInComposedDoc()
? WithTransaction::Yes
: WithTransaction::No;
Result<CreateElementResult, nsresult> createNewListItemResult =
aHTMLEditor.CreateAndInsertElement(
withTransaction, mListItemTagName,
EditorDOMPoint::AtEndOf(aListElement),
!aState.mReplacingBlockElement
? HTMLEditor::DoNothingForNewElement
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
: [&aState](HTMLEditor& aHTMLEditor, Element& aListItemElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
nsresult rv =
AutoListElementCreator::MaybeCloneAttributesToNewListItem(
aHTMLEditor, aListItemElement, aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::"
"MaybeCloneAttributesToNewListItem() failed");
return rv;
});
NS_WARNING_ASSERTION(createNewListItemResult.isOk(),
"HTMLEditor::CreateAndInsertElement() failed");
return createNewListItemResult;
}
nsresult HTMLEditor::AutoListElementCreator::HandleChildInlineContent(
HTMLEditor& aHTMLEditor, nsIContent& aHandlingInlineContent,
AutoHandlingState& aState) const {
MOZ_ASSERT(HTMLEditUtils::IsInlineElement(aHandlingInlineContent));
// If we're currently handling contents of a list item and current node
// is not a block element, move current node into the list item.
if (!aState.mPreviousListItemElement) {
nsresult rv = WrapContentIntoNewListItemElement(
aHTMLEditor, aHandlingInlineContent, aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::WrapContentIntoNewListItemElement() failed");
return rv;
}
Result<MoveNodeResult, nsresult> moveInlineElementResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
aHandlingInlineContent,
MOZ_KnownLive(*aState.mPreviousListItemElement));
if (MOZ_UNLIKELY(moveInlineElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveInlineElementResult.propagateErr();
}
moveInlineElementResult.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
}
nsresult HTMLEditor::AutoListElementCreator::WrapContentIntoNewListItemElement(
HTMLEditor& aHTMLEditor, nsIContent& aHandlingContent,
AutoHandlingState& aState) const {
// If current node is not a paragraph, wrap current node with new list
// item element and move it into current list element.
Result<CreateElementResult, nsresult> wrapContentInListItemElementResult =
aHTMLEditor.InsertContainerWithTransaction(
aHandlingContent, mListItemTagName,
!aState.mReplacingBlockElement
? HTMLEditor::DoNothingForNewElement
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
: [&aState](HTMLEditor& aHTMLEditor, Element& aListItemElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
nsresult rv =
AutoListElementCreator::MaybeCloneAttributesToNewListItem(
aHTMLEditor, aListItemElement, aState);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoListElementCreator::"
"MaybeCloneAttributesToNewListItem() failed");
return rv;
});
if (MOZ_UNLIKELY(wrapContentInListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertContainerWithTransaction() failed");
return wrapContentInListItemElementResult.unwrapErr();
}
CreateElementResult unwrappedWrapContentInListItemElementResult =
wrapContentInListItemElementResult.unwrap();
unwrappedWrapContentInListItemElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedWrapContentInListItemElementResult.GetNewNode());
// MOZ_KnownLive(unwrappedWrapContentInListItemElementResult.GetNewNode()):
// The result is grabbed by unwrappedWrapContentInListItemElementResult.
Result<MoveNodeResult, nsresult> moveListItemElementResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
MOZ_KnownLive(
*unwrappedWrapContentInListItemElementResult.GetNewNode()),
MOZ_KnownLive(*aState.mCurrentListElement));
if (MOZ_UNLIKELY(moveListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveListItemElementResult.unwrapErr();
}
moveListItemElementResult.inspect().IgnoreCaretPointSuggestion();
// If current node is not a block element, new list item should have
// following inline nodes too.
if (HTMLEditUtils::IsInlineElement(aHandlingContent)) {
aState.mPreviousListItemElement =
unwrappedWrapContentInListItemElementResult.UnwrapNewNode();
} else {
aState.mPreviousListItemElement = nullptr;
}
// XXX Why don't we set `type` attribute here??
return NS_OK;
}
nsresult HTMLEditor::AutoListElementCreator::
EnsureCollapsedRangeIsInListItemOrListElement(
Element& aListItemOrListToPutCaret, AutoRangeArray& aRanges) const {
if (!aRanges.IsCollapsed() || aRanges.Ranges().IsEmpty()) {
return NS_OK;
}
const auto firstRangeStartPoint =
aRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!firstRangeStartPoint.IsSet())) {
return NS_OK;
}
Result<EditorRawDOMPoint, nsresult> pointToPutCaretOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(aListItemOrListToPutCaret, firstRangeStartPoint);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditUtils::ComputePointToPutCaretInElementIfOutside()");
return pointToPutCaretOrError.unwrapErr();
}
if (pointToPutCaretOrError.inspect().IsSet()) {
nsresult rv = aRanges.Collapse(pointToPutCaretOrError.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::Collapse() failed");
return rv;
}
}
return NS_OK;
}
nsresult HTMLEditor::RemoveListAtSelectionAsSubAction(
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult error;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eRemoveList, nsIEditor::eNext, error);
if (NS_WARN_IF(error.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return error.StealNSResult();
}
NS_WARNING_ASSERTION(
!error.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// XXX Why do we do this only when there is only one selection range?
if (!SelectionRef().IsCollapsed() && SelectionRef().RangeCount() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
SelectionRef().GetRangeAt(0u), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.unwrapErr();
}
// Note that end point may be prior to start point. So, we
// cannot use Selection::SetStartAndEndInLimit() here.
error.SuppressException();
SelectionRef().SetBaseAndExtentInLimiter(
extendedRange.inspect().StartRef().ToRawRangeBoundary(),
extendedRange.inspect().EndRef().ToRawRangeBoundary(), error);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (error.Failed()) {
NS_WARNING("Selection::SetBaseAndExtentInLimiter() failed");
return error.StealNSResult();
}
}
AutoSelectionRestorer restoreSelectionLater(*this);
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
{
AutoRangeArray extendedSelectionRanges(SelectionRef());
extendedSelectionRanges
.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eCreateOrChangeList, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedSelectionRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() "
"failed");
return splitResult.unwrapErr();
}
nsresult rv = extendedSelectionRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eCreateOrChangeList,
AutoRangeArray::CollectNonEditableNodes::No);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::"
"eCreateOrChangeList, CollectNonEditableNodes::No) failed");
return rv;
}
}
const Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eCreateOrChangeList);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eCreateOrChangeList) failed");
return splitAtBRElementsResult.inspectErr();
}
}
// Remove all non-editable nodes. Leave them be.
// XXX CollectEditTargetNodes() should return only editable contents when it's
// called with CollectNonEditableNodes::No, but checking it here, looks
// like just wasting the runtime cost.
for (int32_t i = arrayOfContents.Length() - 1; i >= 0; i--) {
OwningNonNull<nsIContent>& content = arrayOfContents[i];
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
arrayOfContents.RemoveElementAt(i);
}
}
// Only act on lists or list items in the array
for (auto& content : arrayOfContents) {
// here's where we actually figure out what to do
if (HTMLEditUtils::IsListItem(content)) {
// unlist this listitem
nsresult rv = LiftUpListItemElement(MOZ_KnownLive(*content->AsElement()),
LiftUpFromAllParentListElements::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::LiftUpListItemElement(LiftUpFromAllParentListElements:"
":Yes) failed");
return rv;
}
continue;
}
if (HTMLEditUtils::IsAnyListElement(content)) {
// node is a list, move list items out
nsresult rv =
DestroyListStructureRecursively(MOZ_KnownLive(*content->AsElement()));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DestroyListStructureRecursively() failed");
return rv;
}
continue;
}
}
return NS_OK;
}
Result<RefPtr<Element>, nsresult>
HTMLEditor::FormatBlockContainerWithTransaction(
AutoRangeArray& aSelectionRanges, nsAtom& blockType,
const Element& aEditingHost) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
// XXX Why do we do this only when there is only one selection range?
if (!aSelectionRanges.IsCollapsed() &&
aSelectionRanges.Ranges().Length() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
aSelectionRanges.FirstRangeRef(), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.propagateErr();
}
// Note that end point may be prior to start point. So, we
// cannot use AutoRangeArray::SetStartAndEnd() here.
if (NS_FAILED(aSelectionRanges.SetBaseAndExtent(
extendedRange.inspect().StartRef(),
extendedRange.inspect().EndRef()))) {
NS_WARNING("AutoRangeArray::SetBaseAndExtent() failed");
return Err(NS_ERROR_FAILURE);
}
}
MOZ_ALWAYS_TRUE(aSelectionRanges.SaveAndTrackRanges(*this));
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
aSelectionRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eCreateOrRemoveBlock, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
aSelectionRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() failed");
return splitResult.propagateErr();
}
nsresult rv = aSelectionRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eCreateOrRemoveBlock,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::"
"eCreateOrRemoveBlock, CollectNonEditableNodes::No) failed");
return Err(rv);
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eCreateOrRemoveBlock);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eCreateOrRemoveBlock) failed");
return splitAtBRElementsResult.propagateErr();
}
// If there is no visible and editable nodes in the edit targets, make an
// empty block.
// XXX Isn't this odd if there are only non-editable visible nodes?
if (HTMLEditUtils::IsEmptyOneHardLine(arrayOfContents)) {
if (NS_WARN_IF(aSelectionRanges.Ranges().IsEmpty())) {
return Err(NS_ERROR_FAILURE);
}
auto pointToInsertBlock =
aSelectionRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (&blockType == nsGkAtoms::normal || &blockType == nsGkAtoms::_empty) {
if (!pointToInsertBlock.IsInContentNode()) {
NS_WARNING(
"HTMLEditor::FormatBlockContainerWithTransaction() couldn't find "
"block parent because container of the point is not content");
return Err(NS_ERROR_FAILURE);
}
// We are removing blocks (going to "body text")
const RefPtr<Element> editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*pointToInsertBlock.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement);
if (!editableBlockElement) {
NS_WARNING(
"HTMLEditor::FormatBlockContainerWithTransaction() couldn't find "
"block parent");
return Err(NS_ERROR_FAILURE);
}
if (!HTMLEditUtils::IsFormatNode(editableBlockElement)) {
return RefPtr<Element>();
}
// If the first editable node after selection is a br, consume it.
// Otherwise it gets pushed into a following block after the split,
// which is visually bad.
if (nsCOMPtr<nsIContent> brContent = HTMLEditUtils::GetNextContent(
pointToInsertBlock, {WalkTreeOption::IgnoreNonEditableNode},
&aEditingHost)) {
if (brContent && brContent->IsHTMLElement(nsGkAtoms::br)) {
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsertBlock);
nsresult rv = DeleteNodeWithTransaction(*brContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
}
// Do the splits!
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeDeepWithTransaction(
*editableBlockElement, pointToInsertBlock,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
unwrappedSplitNodeResult.IgnoreCaretPointSuggestion();
// Put a <br> element at the split point
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(
WithTransaction::Yes,
unwrappedSplitNodeResult.AtSplitPoint<EditorDOMPoint>());
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
MOZ_ASSERT(insertBRElementResult.inspect().GetNewNode());
aSelectionRanges.ClearSavedRanges();
nsresult rv = aSelectionRanges.Collapse(
EditorRawDOMPoint(insertBRElementResult.inspect().GetNewNode()));
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::Collapse() failed");
return Err(rv);
}
return RefPtr<Element>();
}
// We are making a block. Consume a br, if needed.
if (nsCOMPtr<nsIContent> maybeBRContent = HTMLEditUtils::GetNextContent(
pointToInsertBlock,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
&aEditingHost)) {
if (maybeBRContent->IsHTMLElement(nsGkAtoms::br)) {
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsertBlock);
nsresult rv = DeleteNodeWithTransaction(*maybeBRContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
// We don't need to act on this node any more
arrayOfContents.RemoveElement(maybeBRContent);
}
}
// Make sure we can put a block here.
Result<CreateElementResult, nsresult> createNewBlockElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
blockType, pointToInsertBlock, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewBlockElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"%s) failed",
nsAtomCString(&blockType).get())
.get());
return createNewBlockElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewBlockElementResult =
createNewBlockElementResult.unwrap();
unwrappedCreateNewBlockElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedCreateNewBlockElementResult.GetNewNode());
// Delete anything that was in the list of nodes
while (!arrayOfContents.IsEmpty()) {
OwningNonNull<nsIContent>& content = arrayOfContents[0];
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*content));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
arrayOfContents.RemoveElementAt(0);
}
// Put selection in new block
aSelectionRanges.ClearSavedRanges();
nsresult rv = aSelectionRanges.Collapse(EditorRawDOMPoint(
unwrappedCreateNewBlockElementResult.GetNewNode(), 0u));
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::Collapse() failed");
return Err(rv);
}
return unwrappedCreateNewBlockElementResult.UnwrapNewNode();
}
// Okay, now go through all the nodes and make the right kind of blocks, or
// whatever is appropriate.
// Note: blockquote is handled a little differently.
if (&blockType == nsGkAtoms::blockquote) {
Result<CreateElementResult, nsresult>
wrapContentsInBlockquoteElementsResult =
WrapContentsInBlockquoteElementsWithTransaction(arrayOfContents,
aEditingHost);
if (MOZ_UNLIKELY(wrapContentsInBlockquoteElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::WrapContentsInBlockquoteElementsWithTransaction() "
"failed");
return wrapContentsInBlockquoteElementsResult.propagateErr();
}
wrapContentsInBlockquoteElementsResult.inspect()
.IgnoreCaretPointSuggestion();
return wrapContentsInBlockquoteElementsResult.unwrap().UnwrapNewNode();
}
if (&blockType == nsGkAtoms::normal || &blockType == nsGkAtoms::_empty) {
Result<EditorDOMPoint, nsresult> removeBlockContainerElementsResult =
RemoveBlockContainerElementsWithTransaction(arrayOfContents);
if (MOZ_UNLIKELY(removeBlockContainerElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementsWithTransaction() failed");
return removeBlockContainerElementsResult.propagateErr();
}
return RefPtr<Element>();
}
Result<CreateElementResult, nsresult> wrapContentsInBlockElementResult =
CreateOrChangeBlockContainerElement(arrayOfContents, blockType,
aEditingHost);
if (MOZ_UNLIKELY(wrapContentsInBlockElementResult.isErr())) {
NS_WARNING("HTMLEditor::CreateOrChangeBlockContainerElement() failed");
return wrapContentsInBlockElementResult.propagateErr();
}
wrapContentsInBlockElementResult.inspect().IgnoreCaretPointSuggestion();
return wrapContentsInBlockElementResult.unwrap().UnwrapNewNode();
}
nsresult HTMLEditor::MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsSelectionRangeContainerNotContent());
if (!SelectionRef().IsCollapsed()) {
return NS_OK;
}
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
const RangeBoundary& atStartOfSelection = firstRange->StartRef();
if (NS_WARN_IF(!atStartOfSelection.IsSet())) {
return NS_ERROR_FAILURE;
}
if (!atStartOfSelection.Container()->IsElement()) {
return NS_OK;
}
OwningNonNull<Element> startContainerElement =
*atStartOfSelection.Container()->AsElement();
nsresult rv =
InsertPaddingBRElementForEmptyLastLineIfNeeded(startContainerElement);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineIfNeeded() failed");
return rv;
}
Result<EditActionResult, nsresult> HTMLEditor::IndentAsSubAction(
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eIndent, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Some selection containers are not content node, but ignored");
return EditActionResult::IgnoredResult();
}
Result<EditActionResult, nsresult> result =
HandleIndentAtSelection(aEditingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::HandleIndentAtSelection() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Mutation event listener might have changed selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// TODO: Investigate when we need to put a `<br>` element after indenting
// ranges. Then, we could stop calling this here, or maybe we need to
// do it while moving content nodes.
nsresult rv = MaybeInsertPaddingBRElementForEmptyLastLineAtSelection();
if (NS_FAILED(rv)) {
NS_WARNING(
"MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() failed");
return Err(rv);
}
return result;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::IndentListChildWithTransaction(
RefPtr<Element>* aSubListElement, const EditorDOMPoint& aPointInListElement,
nsIContent& aContentMovingToSubList, const Element& aEditingHost) {
MOZ_ASSERT(
HTMLEditUtils::IsAnyListElement(aPointInListElement.GetContainer()),
"unexpected container");
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
// some logic for putting list items into nested lists...
// If aContentMovingToSubList is followed by a sub-list element whose tag is
// same as the parent list element's tag, we can move it to start of the
// sub-list.
if (nsIContent* nextEditableSibling = HTMLEditUtils::GetNextSibling(
aContentMovingToSubList, {WalkTreeOption::IgnoreWhiteSpaceOnlyText,
WalkTreeOption::IgnoreNonEditableNode})) {
if (HTMLEditUtils::IsAnyListElement(nextEditableSibling) &&
aPointInListElement.GetContainer()->NodeInfo()->NameAtom() ==
nextEditableSibling->NodeInfo()->NameAtom() &&
aPointInListElement.GetContainer()->NodeInfo()->NamespaceID() ==
nextEditableSibling->NodeInfo()->NamespaceID()) {
Result<MoveNodeResult, nsresult> moveListElementResult =
MoveNodeWithTransaction(aContentMovingToSubList,
EditorDOMPoint(nextEditableSibling, 0u));
if (MOZ_UNLIKELY(moveListElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveListElementResult.propagateErr();
}
return moveListElementResult.unwrap().UnwrapCaretPoint();
}
}
// If aContentMovingToSubList follows a sub-list element whose tag is same
// as the parent list element's tag, we can move it to end of the sub-list.
if (nsCOMPtr<nsIContent> previousEditableSibling =
HTMLEditUtils::GetPreviousSibling(
aContentMovingToSubList,
{WalkTreeOption::IgnoreWhiteSpaceOnlyText,
WalkTreeOption::IgnoreNonEditableNode})) {
if (HTMLEditUtils::IsAnyListElement(previousEditableSibling) &&
aPointInListElement.GetContainer()->NodeInfo()->NameAtom() ==
previousEditableSibling->NodeInfo()->NameAtom() &&
aPointInListElement.GetContainer()->NodeInfo()->NamespaceID() ==
previousEditableSibling->NodeInfo()->NamespaceID()) {
Result<MoveNodeResult, nsresult> moveListElementResult =
MoveNodeToEndWithTransaction(aContentMovingToSubList,
*previousEditableSibling);
if (MOZ_UNLIKELY(moveListElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveListElementResult.propagateErr();
}
return moveListElementResult.unwrap().UnwrapCaretPoint();
}
}
// If aContentMovingToSubList does not follow aSubListElement, we need
// to create new sub-list element.
EditorDOMPoint pointToPutCaret;
nsIContent* previousEditableSibling =
*aSubListElement ? HTMLEditUtils::GetPreviousSibling(
aContentMovingToSubList,
{WalkTreeOption::IgnoreWhiteSpaceOnlyText,
WalkTreeOption::IgnoreNonEditableNode})
: nullptr;
if (!*aSubListElement || (previousEditableSibling &&
previousEditableSibling != *aSubListElement)) {
nsAtom* containerName =
aPointInListElement.GetContainer()->NodeInfo()->NameAtom();
// Create a new nested list of correct type.
Result<CreateElementResult, nsresult> createNewListElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
MOZ_KnownLive(*containerName), aPointInListElement,
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"%s) failed",
nsAtomCString(containerName).get())
.get());
return createNewListElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewListElementResult =
createNewListElementResult.unwrap();
MOZ_ASSERT(unwrappedCreateNewListElementResult.GetNewNode());
pointToPutCaret = unwrappedCreateNewListElementResult.UnwrapCaretPoint();
*aSubListElement = unwrappedCreateNewListElementResult.UnwrapNewNode();
}
// Finally, we should move aContentMovingToSubList into aSubListElement.
const RefPtr<Element> subListElement = *aSubListElement;
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(aContentMovingToSubList, *subListElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
if (unwrappedMoveNodeResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveNodeResult.UnwrapCaretPoint();
}
return pointToPutCaret;
}
Result<EditActionResult, nsresult> HTMLEditor::HandleIndentAtSelection(
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsSelectionRangeContainerNotContent());
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
AutoRangeArray selectionRanges(SelectionRef());
if (MOZ_UNLIKELY(!selectionRanges.IsInContent())) {
NS_WARNING("Mutation event listener might have changed the selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (IsCSSEnabled()) {
nsresult rv = HandleCSSIndentAroundRanges(selectionRanges, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::HandleCSSIndentAroundRanges() failed");
return Err(rv);
}
} else {
nsresult rv = HandleHTMLIndentAroundRanges(selectionRanges, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::HandleHTMLIndentAroundRanges() failed");
return Err(rv);
}
}
rv = selectionRanges.ApplyTo(SelectionRef());
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING("AutoRangeArray::ApplyTo() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::ApplyTo() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::HandleCSSIndentAroundRanges(AutoRangeArray& aRanges,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(!aRanges.Ranges().IsEmpty());
MOZ_ASSERT(aRanges.IsInContent());
if (aRanges.Ranges().IsEmpty()) {
NS_WARNING("There is no selection range");
return NS_ERROR_FAILURE;
}
// XXX Why do we do this only when there is only one selection range?
if (!aRanges.IsCollapsed() && aRanges.Ranges().Length() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
aRanges.FirstRangeRef(), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.unwrapErr();
}
// Note that end point may be prior to start point. So, we
// cannot use SetStartAndEnd() here.
nsresult rv = aRanges.SetBaseAndExtent(extendedRange.inspect().StartRef(),
extendedRange.inspect().EndRef());
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::SetBaseAndExtent() failed");
return rv;
}
}
if (NS_WARN_IF(!aRanges.SaveAndTrackRanges(*this))) {
return NS_ERROR_FAILURE;
}
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
// short circuit: detect case of collapsed selection inside an <li>.
// just sublist that <li>. This prevents bug 97797.
if (aRanges.IsCollapsed()) {
const auto atCaret = aRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!atCaret.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atCaret.IsInContentNode());
Element* const editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*atCaret.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement);
if (editableBlockElement &&
HTMLEditUtils::IsListItem(editableBlockElement)) {
arrayOfContents.AppendElement(*editableBlockElement);
}
}
EditorDOMPoint pointToPutCaret;
if (arrayOfContents.IsEmpty()) {
{
AutoRangeArray extendedRanges(aRanges);
extendedRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eIndent, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() "
"failed");
return splitResult.unwrapErr();
}
if (splitResult.inspect().IsSet()) {
pointToPutCaret = splitResult.unwrap();
}
nsresult rv = extendedRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eIndent,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::eIndent, "
"CollectNonEditableNodes::Yes) failed");
return rv;
}
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eIndent);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eIndent) failed");
return splitAtBRElementsResult.inspectErr();
}
if (splitAtBRElementsResult.inspect().IsSet()) {
pointToPutCaret = splitAtBRElementsResult.unwrap();
}
}
// If there is no visible and editable nodes in the edit targets, make an
// empty block.
// XXX Isn't this odd if there are only non-editable visible nodes?
if (HTMLEditUtils::IsEmptyOneHardLine(arrayOfContents)) {
const EditorDOMPoint pointToInsertDivElement =
pointToPutCaret.IsSet()
? std::move(pointToPutCaret)
: aRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToInsertDivElement.IsSet())) {
return NS_ERROR_FAILURE;
}
// make sure we can put a block here
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, pointToInsertDivElement,
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
// We'll collapse ranges below, so we don't need to touch the ranges here.
unwrappedCreateNewDivElementResult.IgnoreCaretPointSuggestion();
const RefPtr<Element> newDivElement =
unwrappedCreateNewDivElementResult.UnwrapNewNode();
MOZ_ASSERT(newDivElement);
const Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ChangeMarginStart(*newDivElement, ChangeMargin::Increase, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (NS_WARN_IF(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Increase) failed, but "
"ignored");
}
// delete anything that was in the list of nodes
// XXX We don't need to remove the nodes from the array for performance.
for (const OwningNonNull<nsIContent>& content : arrayOfContents) {
// MOZ_KnownLive(content) due to bug 1622253
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(content));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
aRanges.ClearSavedRanges();
nsresult rv = aRanges.Collapse(EditorDOMPoint(newDivElement, 0u));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "AutoRangeArray::Collapse() failed");
return rv;
}
RefPtr<Element> latestNewBlockElement;
auto RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside =
[&]() -> nsresult {
MOZ_ASSERT(aRanges.HasSavedRanges());
aRanges.RestoreFromSavedRanges();
if (!latestNewBlockElement || !aRanges.IsCollapsed() ||
aRanges.Ranges().IsEmpty()) {
return NS_OK;
}
const auto firstRangeStartRawPoint =
aRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!firstRangeStartRawPoint.IsSet())) {
return NS_OK;
}
Result<EditorRawDOMPoint, nsresult> pointInNewBlockElementOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(*latestNewBlockElement, firstRangeStartRawPoint);
if (MOZ_UNLIKELY(pointInNewBlockElementOrError.isErr())) {
NS_WARNING(
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() failed, "
"but ignored");
return NS_OK;
}
if (!pointInNewBlockElementOrError.inspect().IsSet()) {
return NS_OK;
}
return aRanges.Collapse(pointInNewBlockElementOrError.unwrap());
};
// Ok, now go through all the nodes and put them into sub-list element
// elements and new <div> elements which have start margin.
RefPtr<Element> subListElement, divElement;
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
// Here's where we actually figure out what to do.
EditorDOMPoint atContent(content);
if (NS_WARN_IF(!atContent.IsSet())) {
continue;
}
// Ignore all non-editable nodes. Leave them be.
// XXX We ignore non-editable nodes here, but not so in the above block.
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
continue;
}
if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
const RefPtr<Element> oldSubListElement = subListElement;
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
IndentListChildWithTransaction(&subListElement, atContent,
MOZ_KnownLive(content), aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::IndentListChildWithTransaction() failed");
return pointToPutCaretOrError.unwrapErr();
}
if (subListElement != oldSubListElement) {
// New list element is created, so we should put caret into the new list
// element.
latestNewBlockElement = subListElement;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
continue;
}
// Not a list item.
if (HTMLEditUtils::IsBlockElement(content)) {
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ChangeMarginStart(MOZ_KnownLive(*content->AsElement()),
ChangeMargin::Increase, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (MOZ_UNLIKELY(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Increase) failed");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Increase) failed, but "
"ignored");
} else if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
divElement = nullptr;
continue;
}
if (!divElement) {
// First, check that our element can contain a div.
if (!HTMLEditUtils::CanNodeContain(*atContent.GetContainer(),
*nsGkAtoms::div)) {
// XXX This is odd, why do we stop indenting remaining content nodes?
// Perhaps, `continue` is better.
nsresult rv =
RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"RestoreSavedRangesAndCollapseInLatestBlockElement"
"IfOutside() failed");
return rv;
}
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
pointToPutCaret = unwrappedCreateNewDivElementResult.UnwrapCaretPoint();
MOZ_ASSERT(unwrappedCreateNewDivElementResult.GetNewNode());
divElement = unwrappedCreateNewDivElementResult.UnwrapNewNode();
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ChangeMarginStart(*divElement, ChangeMargin::Increase, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (MOZ_UNLIKELY(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Increase) failed");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Increase) failed, but "
"ignored");
} else if (AllowsTransactionsToChangeSelection() &&
pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
latestNewBlockElement = divElement;
}
// Move the content into the <div> which has start margin.
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content), *divElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.unwrapErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
if (unwrappedMoveNodeResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveNodeResult.UnwrapCaretPoint();
}
}
nsresult rv = RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside() failed");
return rv;
}
nsresult HTMLEditor::HandleHTMLIndentAroundRanges(AutoRangeArray& aRanges,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(!aRanges.Ranges().IsEmpty());
MOZ_ASSERT(aRanges.IsInContent());
// XXX Why do we do this only when there is only one range?
if (!aRanges.IsCollapsed() && aRanges.Ranges().Length() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
aRanges.FirstRangeRef(), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.unwrapErr();
}
// Note that end point may be prior to start point. So, we cannot use
// SetStartAndEnd() here.
nsresult rv = aRanges.SetBaseAndExtent(extendedRange.inspect().StartRef(),
extendedRange.inspect().EndRef());
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::SetBaseAndExtent() failed");
return rv;
}
}
if (NS_WARN_IF(!aRanges.SaveAndTrackRanges(*this))) {
return NS_ERROR_FAILURE;
}
EditorDOMPoint pointToPutCaret;
// convert the selection ranges into "promoted" selection ranges:
// this basically just expands the range to include the immediate
// block parent, and then further expands to include any ancestors
// whose children are all in the range
// use these ranges to construct a list of nodes to act on.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
AutoRangeArray extendedRanges(aRanges);
extendedRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eIndent, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() "
"failed");
return splitResult.unwrapErr();
}
if (splitResult.inspect().IsSet()) {
pointToPutCaret = splitResult.unwrap();
}
nsresult rv = extendedRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eIndent,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::eIndent, "
"CollectNonEditableNodes::Yes) failed");
return rv;
}
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eIndent);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::eIndent)"
" failed");
return splitAtBRElementsResult.inspectErr();
}
if (splitAtBRElementsResult.inspect().IsSet()) {
pointToPutCaret = splitAtBRElementsResult.unwrap();
}
// If there is no visible and editable nodes in the edit targets, make an
// empty block.
// XXX Isn't this odd if there are only non-editable visible nodes?
if (HTMLEditUtils::IsEmptyOneHardLine(arrayOfContents)) {
const EditorDOMPoint pointToInsertBlockquoteElement =
pointToPutCaret.IsSet()
? std::move(pointToPutCaret)
: EditorBase::GetFirstSelectionStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToInsertBlockquoteElement.IsSet())) {
return NS_ERROR_FAILURE;
}
// Make sure we can put a block here.
Result<CreateElementResult, nsresult> createNewBlockquoteElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::blockquote, pointToInsertBlockquoteElement,
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewBlockquoteElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::blockquote) failed");
return createNewBlockquoteElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewBlockquoteElementResult =
createNewBlockquoteElementResult.unwrap();
unwrappedCreateNewBlockquoteElementResult.IgnoreCaretPointSuggestion();
RefPtr<Element> newBlockquoteElement =
unwrappedCreateNewBlockquoteElementResult.UnwrapNewNode();
MOZ_ASSERT(newBlockquoteElement);
// delete anything that was in the list of nodes
// XXX We don't need to remove the nodes from the array for performance.
for (const OwningNonNull<nsIContent>& content : arrayOfContents) {
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*content));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
aRanges.ClearSavedRanges();
nsresult rv = aRanges.Collapse(EditorRawDOMPoint(newBlockquoteElement, 0u));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
RefPtr<Element> latestNewBlockElement;
auto RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside =
[&]() -> nsresult {
MOZ_ASSERT(aRanges.HasSavedRanges());
aRanges.RestoreFromSavedRanges();
if (!latestNewBlockElement || !aRanges.IsCollapsed() ||
aRanges.Ranges().IsEmpty()) {
return NS_OK;
}
const auto firstRangeStartRawPoint =
aRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!firstRangeStartRawPoint.IsSet())) {
return NS_OK;
}
Result<EditorRawDOMPoint, nsresult> pointInNewBlockElementOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(*latestNewBlockElement, firstRangeStartRawPoint);
if (MOZ_UNLIKELY(pointInNewBlockElementOrError.isErr())) {
NS_WARNING(
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() failed, "
"but ignored");
return NS_OK;
}
if (!pointInNewBlockElementOrError.inspect().IsSet()) {
return NS_OK;
}
return aRanges.Collapse(pointInNewBlockElementOrError.unwrap());
};
// Ok, now go through all the nodes and put them in a blockquote,
// or whatever is appropriate. Wohoo!
RefPtr<Element> subListElement, blockquoteElement, indentedListItemElement;
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
// Here's where we actually figure out what to do.
EditorDOMPoint atContent(content);
if (NS_WARN_IF(!atContent.IsSet())) {
continue;
}
// Ignore all non-editable nodes. Leave them be.
// XXX We ignore non-editable nodes here, but not so in the above block.
if (!EditorUtils::IsEditableContent(content, EditorType::HTML) ||
!HTMLEditUtils::IsRemovableNode(content)) {
continue;
}
if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
const RefPtr<Element> oldSubListElement = subListElement;
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
IndentListChildWithTransaction(&subListElement, atContent,
MOZ_KnownLive(content), aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::IndentListChildWithTransaction() failed");
return pointToPutCaretOrError.unwrapErr();
}
if (oldSubListElement != subListElement) {
// New list element is created, so we should put caret into the new list
// element.
latestNewBlockElement = subListElement;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
blockquoteElement = nullptr;
continue;
}
// Not a list item, use blockquote?
// if we are inside a list item, we don't want to blockquote, we want
// to sublist the list item. We may have several nodes listed in the
// array of nodes to act on, that are in the same list item. Since
// we only want to indent that li once, we must keep track of the most
// recent indented list item, and not indent it if we find another node
// to act on that is still inside the same li.
if (RefPtr<Element> listItem =
HTMLEditUtils::GetClosestAncestorListItemElement(content,
&aEditingHost)) {
if (indentedListItemElement == listItem) {
// already indented this list item
continue;
}
// check to see if subListElement is still appropriate. Which it is if
// content is still right after it in the same list.
nsIContent* previousEditableSibling =
subListElement
? HTMLEditUtils::GetPreviousSibling(
*listItem, {WalkTreeOption::IgnoreNonEditableNode})
: nullptr;
if (!subListElement || (previousEditableSibling &&
previousEditableSibling != subListElement)) {
EditorDOMPoint atListItem(listItem);
if (NS_WARN_IF(!listItem)) {
return NS_ERROR_FAILURE;
}
nsAtom* containerName =
atListItem.GetContainer()->NodeInfo()->NameAtom();
// Create a new nested list of correct type.
Result<CreateElementResult, nsresult> createNewListElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
MOZ_KnownLive(*containerName), atListItem,
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(nsPrintfCString("HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTr"
"ansaction(%s) failed",
nsAtomCString(containerName).get())
.get());
return createNewListElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewListElementResult =
createNewListElementResult.unwrap();
if (unwrappedCreateNewListElementResult.HasCaretPointSuggestion()) {
pointToPutCaret =
unwrappedCreateNewListElementResult.UnwrapCaretPoint();
}
MOZ_ASSERT(unwrappedCreateNewListElementResult.GetNewNode());
subListElement = unwrappedCreateNewListElementResult.UnwrapNewNode();
}
Result<MoveNodeResult, nsresult> moveListItemElementResult =
MoveNodeToEndWithTransaction(*listItem, *subListElement);
if (MOZ_UNLIKELY(moveListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveListItemElementResult.unwrapErr();
}
MoveNodeResult unwrappedMoveListItemElementResult =
moveListItemElementResult.unwrap();
if (unwrappedMoveListItemElementResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveListItemElementResult.UnwrapCaretPoint();
}
// Remember the list item element which we indented now for ignoring its
// children to avoid using <blockquote> in it.
indentedListItemElement = std::move(listItem);
continue;
}
// need to make a blockquote to put things in if we haven't already,
// or if this node doesn't go in blockquote we used earlier.
// One reason it might not go in prio blockquote is if we are now
// in a different table cell.
if (blockquoteElement &&
HTMLEditUtils::GetInclusiveAncestorAnyTableElement(
*blockquoteElement) !=
HTMLEditUtils::GetInclusiveAncestorAnyTableElement(content)) {
blockquoteElement = nullptr;
}
if (!blockquoteElement) {
// First, check that our element can contain a blockquote.
if (!HTMLEditUtils::CanNodeContain(*atContent.GetContainer(),
*nsGkAtoms::blockquote)) {
// XXX This is odd, why do we stop indenting remaining content nodes?
// Perhaps, `continue` is better.
nsresult rv =
RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"RestoreSavedRangesAndCollapseInLatestBlockElement"
"IfOutside() failed");
return rv;
}
Result<CreateElementResult, nsresult> createNewBlockquoteElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::blockquote, atContent,
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewBlockquoteElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::blockquote) failed");
return createNewBlockquoteElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewBlockquoteElementResult =
createNewBlockquoteElementResult.unwrap();
if (unwrappedCreateNewBlockquoteElementResult.HasCaretPointSuggestion()) {
pointToPutCaret =
unwrappedCreateNewBlockquoteElementResult.UnwrapCaretPoint();
}
MOZ_ASSERT(unwrappedCreateNewBlockquoteElementResult.GetNewNode());
blockquoteElement =
unwrappedCreateNewBlockquoteElementResult.UnwrapNewNode();
latestNewBlockElement = blockquoteElement;
}
// tuck the node into the end of the active blockquote
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content),
*blockquoteElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.unwrapErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
if (unwrappedMoveNodeResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveNodeResult.UnwrapCaretPoint();
}
subListElement = nullptr;
}
nsresult rv = RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"RestoreSavedRangesAndCollapseInLatestBlockElementIfOutside() failed");
return rv;
}
Result<EditActionResult, nsresult> HTMLEditor::OutdentAsSubAction(
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eOutdent, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Some selection containers are not content node, but ignored");
return EditActionResult::IgnoredResult();
}
Result<EditActionResult, nsresult> result =
HandleOutdentAtSelection(aEditingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::HandleOutdentAtSelection() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Mutation event listener might have changed the selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
nsresult rv = MaybeInsertPaddingBRElementForEmptyLastLineAtSelection();
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() "
"failed");
return Err(rv);
}
return result;
}
Result<EditActionResult, nsresult> HTMLEditor::HandleOutdentAtSelection(
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsSelectionRangeContainerNotContent());
// XXX Why do we do this only when there is only one selection range?
if (!SelectionRef().IsCollapsed() && SelectionRef().RangeCount() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
SelectionRef().GetRangeAt(0u), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.propagateErr();
}
// Note that end point may be prior to start point. So, we
// cannot use Selection::SetStartAndEndInLimit() here.
IgnoredErrorResult error;
SelectionRef().SetBaseAndExtentInLimiter(
extendedRange.inspect().StartRef().ToRawRangeBoundary(),
extendedRange.inspect().EndRef().ToRawRangeBoundary(), error);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("Selection::SetBaseAndExtentInLimiter() failed");
return Err(error.StealNSResult());
}
}
// HandleOutdentAtSelectionInternal() creates AutoSelectionRestorer.
// Therefore, even if it returns NS_OK, the editor might have been destroyed
// at restoring Selection.
Result<SplitRangeOffFromNodeResult, nsresult> outdentResult =
HandleOutdentAtSelectionInternal(aEditingHost);
MOZ_ASSERT_IF(outdentResult.isOk(),
!outdentResult.inspect().HasCaretPointSuggestion());
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (MOZ_UNLIKELY(outdentResult.isErr())) {
NS_WARNING("HTMLEditor::HandleOutdentAtSelectionInternal() failed");
return outdentResult.propagateErr();
}
SplitRangeOffFromNodeResult unwrappedOutdentResult = outdentResult.unwrap();
// Make sure selection didn't stick to last piece of content in old bq (only
// a problem for collapsed selections)
if (!unwrappedOutdentResult.GetLeftContent() &&
!unwrappedOutdentResult.GetRightContent()) {
return EditActionResult::HandledResult();
}
if (!SelectionRef().IsCollapsed()) {
return EditActionResult::HandledResult();
}
// Push selection past end of left element of last split indented element.
if (unwrappedOutdentResult.GetLeftContent()) {
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return EditActionResult::HandledResult();
}
const RangeBoundary& atStartOfSelection = firstRange->StartRef();
if (NS_WARN_IF(!atStartOfSelection.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
if (atStartOfSelection.Container() ==
unwrappedOutdentResult.GetLeftContent() ||
EditorUtils::IsDescendantOf(*atStartOfSelection.Container(),
*unwrappedOutdentResult.GetLeftContent())) {
// Selection is inside the left node - push it past it.
EditorRawDOMPoint afterRememberedLeftBQ(
EditorRawDOMPoint::After(*unwrappedOutdentResult.GetLeftContent()));
NS_WARNING_ASSERTION(
afterRememberedLeftBQ.IsSet(),
"Failed to set after remembered left blockquote element");
nsresult rv = CollapseSelectionTo(afterRememberedLeftBQ);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
}
// And pull selection before beginning of right element of last split
// indented element.
if (unwrappedOutdentResult.GetRightContent()) {
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return EditActionResult::HandledResult();
}
const RangeBoundary& atStartOfSelection = firstRange->StartRef();
if (NS_WARN_IF(!atStartOfSelection.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
if (atStartOfSelection.Container() ==
unwrappedOutdentResult.GetRightContent() ||
EditorUtils::IsDescendantOf(
*atStartOfSelection.Container(),
*unwrappedOutdentResult.GetRightContent())) {
// Selection is inside the right element - push it before it.
EditorRawDOMPoint atRememberedRightBQ(
unwrappedOutdentResult.GetRightContent());
nsresult rv = CollapseSelectionTo(atRememberedRightBQ);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
}
return EditActionResult::HandledResult();
}
Result<SplitRangeOffFromNodeResult, nsresult>
HTMLEditor::HandleOutdentAtSelectionInternal(const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoSelectionRestorer restoreSelectionLater(*this);
bool useCSS = IsCSSEnabled();
// Convert the selection ranges into "promoted" selection ranges: this
// basically just expands the range to include the immediate block parent,
// and then further expands to include any ancestors whose children are all
// in the range
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
AutoRangeArray extendedSelectionRanges(SelectionRef());
extendedSelectionRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eOutdent, aEditingHost);
nsresult rv = extendedSelectionRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eOutdent,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::eOutdent, "
"CollectNonEditableNodes::Yes) failed");
return Err(rv);
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eOutdent);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eOutdent) failed");
return splitAtBRElementsResult.propagateErr();
}
if (AllowsTransactionsToChangeSelection() &&
splitAtBRElementsResult.inspect().IsSet()) {
nsresult rv = CollapseSelectionTo(splitAtBRElementsResult.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
}
nsCOMPtr<nsIContent> leftContentOfLastOutdented;
nsCOMPtr<nsIContent> middleContentOfLastOutdented;
nsCOMPtr<nsIContent> rightContentOfLastOutdented;
RefPtr<Element> indentedParentElement;
nsCOMPtr<nsIContent> firstContentToBeOutdented, lastContentToBeOutdented;
BlockIndentedWith indentedParentIndentedWith = BlockIndentedWith::HTML;
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
// Here's where we actually figure out what to do
EditorDOMPoint atContent(content);
if (!atContent.IsSet()) {
continue;
}
// If it's a `<blockquote>`, remove it to outdent its children.
if (content->IsHTMLElement(nsGkAtoms::blockquote)) {
// If we've already found an ancestor block element indented, we need to
// split it and remove the block element first.
if (indentedParentElement) {
NS_WARNING_ASSERTION(indentedParentElement == content,
"Indented parent element is not the <blockquote>");
Result<SplitRangeOffFromNodeResult, nsresult> outdentResult =
OutdentPartOfBlock(*indentedParentElement,
*firstContentToBeOutdented,
*lastContentToBeOutdented,
indentedParentIndentedWith, aEditingHost);
if (MOZ_UNLIKELY(outdentResult.isErr())) {
NS_WARNING("HTMLEditor::OutdentPartOfBlock() failed");
return outdentResult;
}
SplitRangeOffFromNodeResult unwrappedOutdentResult =
outdentResult.unwrap();
unwrappedOutdentResult.IgnoreCaretPointSuggestion();
leftContentOfLastOutdented = unwrappedOutdentResult.UnwrapLeftContent();
middleContentOfLastOutdented =
unwrappedOutdentResult.UnwrapMiddleContent();
rightContentOfLastOutdented =
unwrappedOutdentResult.UnwrapRightContent();
indentedParentElement = nullptr;
firstContentToBeOutdented = nullptr;
lastContentToBeOutdented = nullptr;
indentedParentIndentedWith = BlockIndentedWith::HTML;
}
Result<EditorDOMPoint, nsresult> unwrapBlockquoteElementResult =
RemoveBlockContainerWithTransaction(
MOZ_KnownLive(*content->AsElement()));
if (MOZ_UNLIKELY(unwrapBlockquoteElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapBlockquoteElementResult.propagateErr();
}
const EditorDOMPoint& pointToPutCaret =
unwrapBlockquoteElementResult.inspect();
if (AllowsTransactionsToChangeSelection() && pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
continue;
}
// If we're using CSS and the node is a block element, check its start
// margin whether it's indented with CSS.
if (useCSS && HTMLEditUtils::IsBlockElement(content)) {
nsStaticAtom& marginProperty =
MarginPropertyAtomForIndent(MOZ_KnownLive(content));
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
nsAutoString value;
DebugOnly<nsresult> rvIgnored =
CSSEditUtils::GetSpecifiedProperty(content, marginProperty, value);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetSpecifiedProperty() failed, but ignored");
float startMargin = 0;
RefPtr<nsAtom> unit;
CSSEditUtils::ParseLength(value, &startMargin, getter_AddRefs(unit));
// If indented with CSS, we should decrease the start margin.
if (startMargin > 0) {
const Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ChangeMarginStart(MOZ_KnownLive(*content->AsElement()),
ChangeMargin::Decrease, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (NS_WARN_IF(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Decrease) failed, "
"but ignored");
} else if (AllowsTransactionsToChangeSelection() &&
pointToPutCaretOrError.inspect().IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaretOrError.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
continue;
}
}
// If it's a list item, we should treat as that it "indents" its children.
if (HTMLEditUtils::IsListItem(content)) {
// If it is a list item, that means we are not outdenting whole list.
// XXX I don't understand this sentence... We may meet parent list
// element, no?
if (indentedParentElement) {
Result<SplitRangeOffFromNodeResult, nsresult> outdentResult =
OutdentPartOfBlock(*indentedParentElement,
*firstContentToBeOutdented,
*lastContentToBeOutdented,
indentedParentIndentedWith, aEditingHost);
if (MOZ_UNLIKELY(outdentResult.isErr())) {
NS_WARNING("HTMLEditor::OutdentPartOfBlock() failed");
return outdentResult;
}
SplitRangeOffFromNodeResult unwrappedOutdentResult =
outdentResult.unwrap();
unwrappedOutdentResult.IgnoreCaretPointSuggestion();
leftContentOfLastOutdented = unwrappedOutdentResult.UnwrapLeftContent();
middleContentOfLastOutdented =
unwrappedOutdentResult.UnwrapMiddleContent();
rightContentOfLastOutdented =
unwrappedOutdentResult.UnwrapRightContent();
indentedParentElement = nullptr;
firstContentToBeOutdented = nullptr;
lastContentToBeOutdented = nullptr;
indentedParentIndentedWith = BlockIndentedWith::HTML;
}
// XXX `content` could become different element since
// `OutdentPartOfBlock()` may run mutation event listeners.
nsresult rv = LiftUpListItemElement(MOZ_KnownLive(*content->AsElement()),
LiftUpFromAllParentListElements::No);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::LiftUpListItemElement(LiftUpFromAllParentListElements:"
":No) failed");
return Err(rv);
}
continue;
}
// If we've found an ancestor block element which indents its children
// and the current node is NOT a descendant of it, we should remove it to
// outdent its children. Otherwise, i.e., current node is a descendant of
// it, we meet new node which should be outdented when the indented parent
// is removed.
if (indentedParentElement) {
if (EditorUtils::IsDescendantOf(*content, *indentedParentElement)) {
// Extend the range to be outdented at removing the
// indentedParentElement.
lastContentToBeOutdented = content;
continue;
}
Result<SplitRangeOffFromNodeResult, nsresult> outdentResult =
OutdentPartOfBlock(*indentedParentElement, *firstContentToBeOutdented,
*lastContentToBeOutdented,
indentedParentIndentedWith, aEditingHost);
if (MOZ_UNLIKELY(outdentResult.isErr())) {
NS_WARNING("HTMLEditor::OutdentPartOfBlock() failed");
return outdentResult;
}
SplitRangeOffFromNodeResult unwrappedOutdentResult =
outdentResult.unwrap();
unwrappedOutdentResult.IgnoreCaretPointSuggestion();
leftContentOfLastOutdented = unwrappedOutdentResult.UnwrapLeftContent();
middleContentOfLastOutdented =
unwrappedOutdentResult.UnwrapMiddleContent();
rightContentOfLastOutdented = unwrappedOutdentResult.UnwrapRightContent();
indentedParentElement = nullptr;
firstContentToBeOutdented = nullptr;
lastContentToBeOutdented = nullptr;
// curBlockIndentedWith = HTMLEditor::BlockIndentedWith::HTML;
// Then, we need to look for next indentedParentElement.
}
indentedParentIndentedWith = BlockIndentedWith::HTML;
for (nsCOMPtr<nsIContent> parentContent = content->GetParent();
parentContent && !parentContent->IsHTMLElement(nsGkAtoms::body) &&
parentContent != &aEditingHost &&
(parentContent->IsHTMLElement(nsGkAtoms::table) ||
!HTMLEditUtils::IsAnyTableElement(parentContent));
parentContent = parentContent->GetParent()) {
if (MOZ_UNLIKELY(!HTMLEditUtils::IsRemovableNode(*parentContent))) {
continue;
}
// If we reach a `<blockquote>` ancestor, it should be split at next
// time at least for outdenting current node.
if (parentContent->IsHTMLElement(nsGkAtoms::blockquote)) {
indentedParentElement = parentContent->AsElement();
firstContentToBeOutdented = content;
lastContentToBeOutdented = content;
break;
}
if (!useCSS) {
continue;
}
nsCOMPtr<nsINode> grandParentNode = parentContent->GetParentNode();
nsStaticAtom& marginProperty =
MarginPropertyAtomForIndent(MOZ_KnownLive(content));
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_WARN_IF(grandParentNode != parentContent->GetParentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
nsAutoString value;
DebugOnly<nsresult> rvIgnored = CSSEditUtils::GetSpecifiedProperty(
*parentContent, marginProperty, value);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetSpecifiedProperty() failed, but ignored");
// XXX Now, editing host may become different element. If so, shouldn't
// we stop this handling?
float startMargin;
RefPtr<nsAtom> unit;
CSSEditUtils::ParseLength(value, &startMargin, getter_AddRefs(unit));
// If we reach a block element which indents its children with start
// margin, we should remove it at next time.
if (startMargin > 0 &&
!(HTMLEditUtils::IsAnyListElement(atContent.GetContainer()) &&
HTMLEditUtils::IsAnyListElement(content))) {
indentedParentElement = parentContent->AsElement();
firstContentToBeOutdented = content;
lastContentToBeOutdented = content;
indentedParentIndentedWith = BlockIndentedWith::CSS;
break;
}
}
if (indentedParentElement) {
continue;
}
// If we don't have any block elements which indents current node and
// both current node and its parent are list element, remove current
// node to move all its children to the parent list.
// XXX This is buggy. When both lists' item types are different,
// we create invalid tree. E.g., `<ul>` may have `<dd>` as its
// list item element.
if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
if (!HTMLEditUtils::IsAnyListElement(content)) {
continue;
}
// Just unwrap this sublist
Result<EditorDOMPoint, nsresult> unwrapSubListElementResult =
RemoveBlockContainerWithTransaction(
MOZ_KnownLive(*content->AsElement()));
if (MOZ_UNLIKELY(unwrapSubListElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapSubListElementResult.propagateErr();
}
const EditorDOMPoint& pointToPutCaret =
unwrapSubListElementResult.inspect();
if (!AllowsTransactionsToChangeSelection() || !pointToPutCaret.IsSet()) {
continue;
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
continue;
}
// If current content is a list element but its parent is not a list
// element, move children to where it is and remove it from the tree.
if (HTMLEditUtils::IsAnyListElement(content)) {
// XXX If mutation event listener appends new children forever, this
// becomes an infinite loop so that we should set limitation from
// first child count.
for (nsCOMPtr<nsIContent> lastChildContent = content->GetLastChild();
lastChildContent; lastChildContent = content->GetLastChild()) {
if (HTMLEditUtils::IsListItem(lastChildContent)) {
nsresult rv = LiftUpListItemElement(
MOZ_KnownLive(*lastChildContent->AsElement()),
LiftUpFromAllParentListElements::No);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::LiftUpListItemElement("
"LiftUpFromAllParentListElements::No) failed");
return Err(rv);
}
continue;
}
if (HTMLEditUtils::IsAnyListElement(lastChildContent)) {
// We have an embedded list, so move it out from under the parent
// list. Be sure to put it after the parent list because this
// loop iterates backwards through the parent's list of children.
EditorDOMPoint afterCurrentList(EditorDOMPoint::After(atContent));
NS_WARNING_ASSERTION(
afterCurrentList.IsSet(),
"Failed to set it to after current list element");
Result<MoveNodeResult, nsresult> moveListElementResult =
MoveNodeWithTransaction(*lastChildContent, afterCurrentList);
if (MOZ_UNLIKELY(moveListElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveListElementResult.propagateErr();
}
nsresult rv = moveListElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
continue;
}
// Delete any non-list items for now
// XXX Chrome moves it from the list element. We should follow it.
nsresult rv = DeleteNodeWithTransaction(*lastChildContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
// Delete the now-empty list
Result<EditorDOMPoint, nsresult> unwrapListElementResult =
RemoveBlockContainerWithTransaction(
MOZ_KnownLive(*content->AsElement()));
if (MOZ_UNLIKELY(unwrapListElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapListElementResult.propagateErr();
}
const EditorDOMPoint& pointToPutCaret = unwrapListElementResult.inspect();
if (!AllowsTransactionsToChangeSelection() || !pointToPutCaret.IsSet()) {
continue;
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
continue;
}
if (useCSS) {
if (RefPtr<Element> element = content->GetAsElementOrParentElement()) {
const Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ChangeMarginStart(*element, ChangeMargin::Decrease, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (NS_WARN_IF(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::ChangeMarginStart(ChangeMargin::Decrease) failed, "
"but ignored");
} else if (AllowsTransactionsToChangeSelection() &&
pointToPutCaretOrError.inspect().IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaretOrError.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
}
continue;
}
}
if (!indentedParentElement) {
return SplitRangeOffFromNodeResult(leftContentOfLastOutdented,
middleContentOfLastOutdented,
rightContentOfLastOutdented);
}
// We have a <blockquote> we haven't finished handling.
Result<SplitRangeOffFromNodeResult, nsresult> outdentResult =
OutdentPartOfBlock(*indentedParentElement, *firstContentToBeOutdented,
*lastContentToBeOutdented, indentedParentIndentedWith,
aEditingHost);
if (MOZ_UNLIKELY(outdentResult.isErr())) {
NS_WARNING("HTMLEditor::OutdentPartOfBlock() failed");
return outdentResult;
}
// We will restore selection soon. Therefore, callers do not need to restore
// the selection.
SplitRangeOffFromNodeResult unwrappedOutdentResult = outdentResult.unwrap();
unwrappedOutdentResult.ForgetCaretPointSuggestion();
return unwrappedOutdentResult;
}
Result<SplitRangeOffFromNodeResult, nsresult>
HTMLEditor::RemoveBlockContainerElementWithTransactionBetween(
Element& aBlockContainerElement, nsIContent& aStartOfRange,
nsIContent& aEndOfRange) {
MOZ_ASSERT(IsEditActionDataAvailable());
EditorDOMPoint pointToPutCaret;
Result<SplitRangeOffFromNodeResult, nsresult> splitResult =
SplitRangeOffFromBlock(aBlockContainerElement, aStartOfRange,
aEndOfRange);
if (MOZ_UNLIKELY(splitResult.isErr())) {
if (splitResult.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING("HTMLEditor::SplitRangeOffFromBlock() failed");
return splitResult;
}
NS_WARNING(
"HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored");
return SplitRangeOffFromNodeResult(nullptr, nullptr, nullptr);
}
SplitRangeOffFromNodeResult unwrappedSplitResult = splitResult.unwrap();
unwrappedSplitResult.MoveCaretPointTo(pointToPutCaret,
{SuggestCaret::OnlyIfHasSuggestion});
// Even if either split aBlockContainerElement or did not split it, we should
// unwrap the right most element which is split from aBlockContainerElement
// (or aBlockContainerElement itself if it was not split without errors).
Element* rightmostElement =
unwrappedSplitResult.GetRightmostContentAs<Element>();
MOZ_ASSERT(rightmostElement);
if (NS_WARN_IF(!rightmostElement)) {
return Err(NS_ERROR_FAILURE);
}
MOZ_ASSERT_IF(GetSplitNodeDirection() == SplitNodeDirection::LeftNodeIsNewOne,
rightmostElement == &aBlockContainerElement);
{
// MOZ_KnownLive(rightmostElement) because it's grabbed by
// unwrappedSplitResult.
Result<EditorDOMPoint, nsresult> unwrapBlockElementResult =
RemoveBlockContainerWithTransaction(MOZ_KnownLive(*rightmostElement));
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapBlockElementResult.propagateErr();
}
if (unwrapBlockElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapBlockElementResult.unwrap();
}
}
return SplitRangeOffFromNodeResult(
unwrappedSplitResult.GetLeftContent(), nullptr,
unwrappedSplitResult.GetRightContent(), std::move(pointToPutCaret));
}
Result<SplitRangeOffFromNodeResult, nsresult>
HTMLEditor::SplitRangeOffFromBlock(Element& aBlockElement,
nsIContent& aStartOfMiddleElement,
nsIContent& aEndOfMiddleElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
// aStartOfMiddleElement and aEndOfMiddleElement must be exclusive
// descendants of aBlockElement.
MOZ_ASSERT(EditorUtils::IsDescendantOf(aStartOfMiddleElement, aBlockElement));
MOZ_ASSERT(EditorUtils::IsDescendantOf(aEndOfMiddleElement, aBlockElement));
EditorDOMPoint pointToPutCaret;
// Split at the start.
Result<SplitNodeResult, nsresult> splitAtStartResult =
SplitNodeDeepWithTransaction(aBlockElement,
EditorDOMPoint(&aStartOfMiddleElement),
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitAtStartResult.isErr())) {
if (splitAtStartResult.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed (at left)");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) at start of middle element failed");
} else {
splitAtStartResult.inspect().CopyCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
// Split at after the end
auto atAfterEnd = EditorDOMPoint::After(aEndOfMiddleElement);
Element* rightElement =
splitAtStartResult.isOk() && splitAtStartResult.inspect().DidSplit()
? splitAtStartResult.inspect().GetNextContentAs<Element>()
: &aBlockElement;
// MOZ_KnownLive(rightElement) because it's grabbed by splitAtStartResult or
// aBlockElement whose lifetime is guaranteed by the caller.
Result<SplitNodeResult, nsresult> splitAtEndResult =
SplitNodeDeepWithTransaction(MOZ_KnownLive(*rightElement), atAfterEnd,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitAtEndResult.isErr())) {
if (splitAtEndResult.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction() failed (at right)");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) after end of middle element failed");
} else {
splitAtEndResult.inspect().CopyCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
if (splitAtStartResult.isOk() && splitAtStartResult.inspect().DidSplit() &&
splitAtEndResult.isOk() && splitAtEndResult.inspect().DidSplit()) {
// Note that the middle node can be computed only with the latter split
// result.
return SplitRangeOffFromNodeResult(
splitAtStartResult.inspect().GetPreviousContent(),
splitAtEndResult.inspect().GetPreviousContent(),
splitAtEndResult.inspect().GetNextContent(),
std::move(pointToPutCaret));
}
if (splitAtStartResult.isOk() && splitAtStartResult.inspect().DidSplit()) {
return SplitRangeOffFromNodeResult(
splitAtStartResult.inspect().GetPreviousContent(),
splitAtStartResult.inspect().GetNextContent(), nullptr,
std::move(pointToPutCaret));
}
if (splitAtEndResult.isOk() && splitAtEndResult.inspect().DidSplit()) {
return SplitRangeOffFromNodeResult(
nullptr, splitAtEndResult.inspect().GetPreviousContent(),
splitAtEndResult.inspect().GetNextContent(),
std::move(pointToPutCaret));
}
return SplitRangeOffFromNodeResult(nullptr, &aBlockElement, nullptr,
std::move(pointToPutCaret));
}
Result<SplitRangeOffFromNodeResult, nsresult> HTMLEditor::OutdentPartOfBlock(
Element& aBlockElement, nsIContent& aStartOfOutdent,
nsIContent& aEndOfOutdent, BlockIndentedWith aBlockIndentedWith,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
Result<SplitRangeOffFromNodeResult, nsresult> splitResult =
SplitRangeOffFromBlock(aBlockElement, aStartOfOutdent, aEndOfOutdent);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING("HTMLEditor::SplitRangeOffFromBlock() failed");
return splitResult;
}
SplitRangeOffFromNodeResult unwrappedSplitResult = splitResult.unwrap();
Element* middleElement = unwrappedSplitResult.GetMiddleContentAs<Element>();
if (MOZ_UNLIKELY(!middleElement)) {
NS_WARNING(
"HTMLEditor::SplitRangeOffFromBlock() didn't return middle content");
unwrappedSplitResult.IgnoreCaretPointSuggestion();
return Err(NS_ERROR_FAILURE);
}
if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*middleElement))) {
unwrappedSplitResult.IgnoreCaretPointSuggestion();
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
nsresult rv = unwrappedSplitResult.SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"SplitRangeOffFromNodeResult::SuggestCaretPointTo() "
"failed, but ignored");
if (aBlockIndentedWith == BlockIndentedWith::HTML) {
// MOZ_KnownLive(middleElement) because of grabbed by unwrappedSplitResult.
Result<EditorDOMPoint, nsresult> unwrapBlockElementResult =
RemoveBlockContainerWithTransaction(MOZ_KnownLive(*middleElement));
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapBlockElementResult.propagateErr();
}
const EditorDOMPoint& pointToPutCaret = unwrapBlockElementResult.inspect();
if (AllowsTransactionsToChangeSelection() && pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
return SplitRangeOffFromNodeResult(unwrappedSplitResult.GetLeftContent(),
nullptr,
unwrappedSplitResult.GetRightContent());
}
// MOZ_KnownLive(middleElement) because of grabbed by unwrappedSplitResult.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError = ChangeMarginStart(
MOZ_KnownLive(*middleElement), ChangeMargin::Decrease, aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::ChangeMarginStart(ChangeMargin::Decrease) failed");
return pointToPutCaretOrError.propagateErr();
}
if (AllowsTransactionsToChangeSelection() &&
pointToPutCaretOrError.inspect().IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaretOrError.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
return unwrappedSplitResult;
}
Result<CreateElementResult, nsresult> HTMLEditor::ChangeListElementType(
Element& aListElement, nsAtom& aNewListTag, nsAtom& aNewListItemTag) {
MOZ_ASSERT(IsEditActionDataAvailable());
EditorDOMPoint pointToPutCaret;
AutoTArray<OwningNonNull<nsIContent>, 32> listElementChildren;
HTMLEditUtils::CollectAllChildren(aListElement, listElementChildren);
for (const OwningNonNull<nsIContent>& childContent : listElementChildren) {
if (!childContent->IsElement()) {
continue;
}
Element* childElement = childContent->AsElement();
if (HTMLEditUtils::IsListItem(childElement) &&
!childContent->IsHTMLElement(&aNewListItemTag)) {
// MOZ_KnownLive(childElement) because its lifetime is guaranteed by
// listElementChildren.
Result<CreateElementResult, nsresult>
replaceWithNewListItemElementResult =
ReplaceContainerAndCloneAttributesWithTransaction(
MOZ_KnownLive(*childElement), aNewListItemTag);
if (MOZ_UNLIKELY(replaceWithNewListItemElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::ReplaceContainerAndCloneAttributesWithTransaction() "
"failed");
return replaceWithNewListItemElementResult;
}
CreateElementResult unwrappedReplaceWithNewListItemElementResult =
replaceWithNewListItemElementResult.unwrap();
unwrappedReplaceWithNewListItemElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
continue;
}
if (HTMLEditUtils::IsAnyListElement(childElement) &&
!childElement->IsHTMLElement(&aNewListTag)) {
// XXX List elements shouldn't have other list elements as their
// child. Why do we handle such invalid tree?
// -> Maybe, for bug 525888.
// MOZ_KnownLive(childElement) because its lifetime is guaranteed by
// listElementChildren.
Result<CreateElementResult, nsresult> convertListTypeResult =
ChangeListElementType(MOZ_KnownLive(*childElement), aNewListTag,
aNewListItemTag);
if (MOZ_UNLIKELY(convertListTypeResult.isErr())) {
NS_WARNING("HTMLEditor::ChangeListElementType() failed");
return convertListTypeResult;
}
CreateElementResult unwrappedConvertListTypeResult =
convertListTypeResult.unwrap();
unwrappedConvertListTypeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
continue;
}
}
if (aListElement.IsHTMLElement(&aNewListTag)) {
return CreateElementResult(&aListElement, std::move(pointToPutCaret));
}
// XXX If we replace the list element, shouldn't we create it first and then,
// move children into it before inserting the new list element into the
// DOM tree? Then, we could reduce the cost of dispatching DOM mutation
// events.
Result<CreateElementResult, nsresult> replaceWithNewListElementResult =
ReplaceContainerWithTransaction(aListElement, aNewListTag);
if (MOZ_UNLIKELY(replaceWithNewListElementResult.isErr())) {
NS_WARNING("HTMLEditor::ReplaceContainerWithTransaction() failed");
return replaceWithNewListElementResult;
}
CreateElementResult unwrappedReplaceWithNewListElementResult =
replaceWithNewListElementResult.unwrap();
unwrappedReplaceWithNewListElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
return CreateElementResult(
unwrappedReplaceWithNewListElementResult.UnwrapNewNode(),
std::move(pointToPutCaret));
}
Result<EditorDOMPoint, nsresult> HTMLEditor::CreateStyleForInsertText(
const EditorDOMPoint& aPointToInsertText, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsertText.IsSetAndValid());
MOZ_ASSERT(mPendingStylesToApplyToNewContent);
const RefPtr<Element> documentRootElement = GetDocument()->GetRootElement();
if (NS_WARN_IF(!documentRootElement)) {
return Err(NS_ERROR_FAILURE);
}
// process clearing any styles first
UniquePtr<PendingStyle> pendingStyle =
mPendingStylesToApplyToNewContent->TakeClearingStyle();
EditorDOMPoint pointToPutCaret(aPointToInsertText);
{
// Transactions may set selection, but we will set selection if necessary.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
while (pendingStyle &&
pointToPutCaret.GetContainer() != documentRootElement) {
// MOZ_KnownLive because we own pendingStyle which guarantees the lifetime
// of its members.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
ClearStyleAt(pointToPutCaret, pendingStyle->ToInlineStyle(),
pendingStyle->GetSpecifiedStyle());
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::ClearStyleAt() failed");
return pointToPutCaretOrError;
}
pointToPutCaret = pointToPutCaretOrError.unwrap();
if (NS_WARN_IF(!pointToPutCaret.IsSetAndValid())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
pendingStyle = mPendingStylesToApplyToNewContent->TakeClearingStyle();
}
}
// then process setting any styles
const int32_t relFontSize =
mPendingStylesToApplyToNewContent->TakeRelativeFontSize();
AutoTArray<EditorInlineStyleAndValue, 32> stylesToSet;
mPendingStylesToApplyToNewContent->TakeAllPreservedStyles(stylesToSet);
if (stylesToSet.IsEmpty() && !relFontSize) {
return pointToPutCaret;
}
// We're in chrome, e.g., the email composer of Thunderbird, and there is
// relative font size changes, we need to keep using legacy path until we port
// IncrementOrDecrementFontSizeAsSubAction() to work with
// AutoInlineStyleSetter.
if (relFontSize) {
// we have at least one style to add; make a new text node to insert style
// nodes above.
EditorDOMPoint pointToInsertTextNode(pointToPutCaret);
if (pointToInsertTextNode.IsInTextNode()) {
// if we are in a text node, split it
Result<SplitNodeResult, nsresult> splitTextNodeResult =
SplitNodeDeepWithTransaction(
MOZ_KnownLive(*pointToInsertTextNode.ContainerAs<Text>()),
pointToInsertTextNode,
SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitTextNodeResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eAllowToCreateEmptyContainer) failed");
return splitTextNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitTextNodeResult =
splitTextNodeResult.unwrap();
unwrappedSplitTextNodeResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
pointToInsertTextNode =
unwrappedSplitTextNodeResult.AtSplitPoint<EditorDOMPoint>();
}
if (!pointToInsertTextNode.IsInContentNode() ||
!HTMLEditUtils::IsContainerNode(
*pointToInsertTextNode.ContainerAs<nsIContent>())) {
return pointToPutCaret;
}
RefPtr<Text> newEmptyTextNode = CreateTextNode(u""_ns);
if (!newEmptyTextNode) {
NS_WARNING("EditorBase::CreateTextNode() failed");
return Err(NS_ERROR_FAILURE);
}
Result<CreateTextResult, nsresult> insertNewTextNodeResult =
InsertNodeWithTransaction<Text>(*newEmptyTextNode,
pointToInsertTextNode);
if (MOZ_UNLIKELY(insertNewTextNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertNewTextNodeResult.propagateErr();
}
insertNewTextNodeResult.inspect().IgnoreCaretPointSuggestion();
pointToPutCaret.Set(newEmptyTextNode, 0u);
// FIXME: If the stylesToSet have background-color style, it may
// be applied shorter because outer <span> element height is not
// computed with inner element's height.
HTMLEditor::FontSize incrementOrDecrement =
relFontSize > 0 ? HTMLEditor::FontSize::incr
: HTMLEditor::FontSize::decr;
for ([[maybe_unused]] uint32_t j : IntegerRange(Abs(relFontSize))) {
Result<CreateElementResult, nsresult> wrapTextInBigOrSmallElementResult =
SetFontSizeOnTextNode(*newEmptyTextNode, 0, UINT32_MAX,
incrementOrDecrement);
if (MOZ_UNLIKELY(wrapTextInBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOnTextNode() failed");
return wrapTextInBigOrSmallElementResult.propagateErr();
}
// We don't need to update here because we'll suggest caret position
// which is computed above.
MOZ_ASSERT(pointToPutCaret.IsSet());
wrapTextInBigOrSmallElementResult.inspect().IgnoreCaretPointSuggestion();
}
for (const EditorInlineStyleAndValue& styleToSet : stylesToSet) {
AutoInlineStyleSetter inlineStyleSetter(styleToSet);
// MOZ_KnownLive(...ContainerAs<nsIContent>()) because pointToPutCaret
// grabs the result.
Result<CaretPoint, nsresult> setStyleResult =
inlineStyleSetter.ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(
*this, MOZ_KnownLive(*pointToPutCaret.ContainerAs<nsIContent>()));
if (MOZ_UNLIKELY(setStyleResult.isErr())) {
NS_WARNING("HTMLEditor::SetInlinePropertyOnNode() failed");
return setStyleResult.propagateErr();
}
// We don't need to update here because we'll suggest caret position which
// is computed above.
MOZ_ASSERT(pointToPutCaret.IsSet());
setStyleResult.unwrap().IgnoreCaretPointSuggestion();
}
return pointToPutCaret;
}
// If we have preserved commands except relative font style changes, we can
// use inline style setting code which reuse ancestors better.
AutoRangeArray ranges(pointToPutCaret);
if (MOZ_UNLIKELY(ranges.Ranges().IsEmpty())) {
NS_WARNING("AutoRangeArray::AutoRangeArray() failed");
return Err(NS_ERROR_FAILURE);
}
nsresult rv =
SetInlinePropertiesAroundRanges(ranges, stylesToSet, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::SetInlinePropertiesAroundRanges() failed");
return Err(rv);
}
if (NS_WARN_IF(ranges.Ranges().IsEmpty())) {
return Err(NS_ERROR_FAILURE);
}
// Now `ranges` selects new styled contents and the range may not be
// collapsed. We should use the deepest editable start point of the range
// to insert text.
nsINode* container = ranges.FirstRangeRef()->GetStartContainer();
if (MOZ_UNLIKELY(!container->IsContent())) {
container = ranges.FirstRangeRef()->GetChildAtStartOffset();
if (MOZ_UNLIKELY(!container)) {
NS_WARNING("How did we get lost insertion point?");
return Err(NS_ERROR_FAILURE);
}
}
pointToPutCaret =
HTMLEditUtils::GetDeepestEditableStartPointOf<EditorDOMPoint>(
*container->AsContent());
if (NS_WARN_IF(!pointToPutCaret.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
return pointToPutCaret;
}
Result<EditActionResult, nsresult> HTMLEditor::AlignAsSubAction(
const nsAString& aAlignType, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eSetOrClearAlignment, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Some selection containers are not content node, but ignored");
return EditActionResult::IgnoredResult();
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Mutation event listener might have changed the selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
AutoRangeArray selectionRanges(SelectionRef());
// XXX Why do we do this only when there is only one selection range?
if (!selectionRanges.IsCollapsed() &&
selectionRanges.Ranges().Length() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
selectionRanges.FirstRangeRef(), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.propagateErr();
}
// Note that end point may be prior to start point. So, we
// cannot use etStartAndEnd() here.
nsresult rv = selectionRanges.SetBaseAndExtent(
extendedRange.inspect().StartRef(), extendedRange.inspect().EndRef());
if (NS_FAILED(rv)) {
NS_WARNING("Selection::SetBaseAndExtentInLimiter() failed");
return Err(rv);
}
}
rv = AlignContentsAtRanges(selectionRanges, aAlignType, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::AlignContentsAtSelection() failed");
return Err(rv);
}
rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::ApplyTo() failed");
return Err(rv);
}
if (MOZ_UNLIKELY(IsSelectionRangeContainerNotContent())) {
NS_WARNING("Mutation event listener might have changed the selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
rv = MaybeInsertPaddingBRElementForEmptyLastLineAtSelection();
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() "
"failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::AlignContentsAtRanges(AutoRangeArray& aRanges,
const nsAString& aAlignType,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(aRanges.IsInContent());
if (NS_WARN_IF(!aRanges.SaveAndTrackRanges(*this))) {
return NS_ERROR_FAILURE;
}
EditorDOMPoint pointToPutCaret;
// Convert the selection ranges into "promoted" selection ranges: This
// basically just expands the range to include the immediate block parent,
// and then further expands to include any ancestors whose children are all
// in the range
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
AutoRangeArray extendedRanges(aRanges);
extendedRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eSetOrClearAlignment, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() "
"failed");
return splitResult.unwrapErr();
}
if (splitResult.inspect().IsSet()) {
pointToPutCaret = splitResult.unwrap();
}
nsresult rv = extendedRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eSetOrClearAlignment,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::"
"eSetOrClearAlignment, CollectNonEditableNodes::Yes) failed");
return rv;
}
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eSetOrClearAlignment);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eSetOrClearAlignment) failed");
return splitAtBRElementsResult.inspectErr();
}
if (splitAtBRElementsResult.inspect().IsSet()) {
pointToPutCaret = splitAtBRElementsResult.unwrap();
}
// If we don't have any nodes, or we have only a single br, then we are
// creating an empty alignment div. We have to do some different things for
// these.
bool createEmptyDivElement = arrayOfContents.IsEmpty();
if (arrayOfContents.Length() == 1) {
OwningNonNull<nsIContent>& content = arrayOfContents[0];
if (HTMLEditUtils::SupportsAlignAttr(content)) {
// The node is a table element, an hr, a paragraph, a div or a section
// header; in HTML 4, it can directly carry the ALIGN attribute and we
// don't need to make a div! If we are in CSS mode, all the work is done
// in SetBlockElementAlign().
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
SetBlockElementAlign(MOZ_KnownLive(*content->AsElement()), aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::SetBlockElementAlign() failed");
return pointToPutCaretOrError.unwrapErr();
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
if (content->IsHTMLElement(nsGkAtoms::br)) {
// The special case createEmptyDivElement code (below) that consumes
// `<br>` elements can cause tables to split if the start node of the
// selection is not in a table cell or caption, for example parent is a
// `<tr>`. Avoid this unnecessary splitting if possible by leaving
// createEmptyDivElement false so that we fall through to the normal case
// alignment code.
//
// XXX: It seems a little error prone for the createEmptyDivElement
// special case code to assume that the start node of the selection
// is the parent of the single node in the arrayOfContents, as the
// paragraph above points out. Do we rely on the selection start
// node because of the fact that arrayOfContents can be empty? We
// should probably revisit this issue. - kin
const EditorDOMPoint firstRangeStartPoint =
pointToPutCaret.IsSet()
? pointToPutCaret
: aRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!firstRangeStartPoint.IsSet())) {
return NS_ERROR_FAILURE;
}
nsINode* parent = firstRangeStartPoint.GetContainer();
createEmptyDivElement = !HTMLEditUtils::IsAnyTableElement(parent) ||
HTMLEditUtils::IsTableCellOrCaption(*parent);
}
}
if (createEmptyDivElement) {
if (MOZ_UNLIKELY(!pointToPutCaret.IsSet() && !aRanges.IsInContent())) {
NS_WARNING("Mutation event listener might have changed the selection");
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
const EditorDOMPoint pointToInsertDivElement =
pointToPutCaret.IsSet()
? pointToPutCaret
: aRanges.GetFirstRangeStartPoint<EditorDOMPoint>();
Result<CreateElementResult, nsresult> insertNewDivElementResult =
InsertDivElementToAlignContents(pointToInsertDivElement, aAlignType,
aEditingHost);
if (insertNewDivElementResult.isErr()) {
NS_WARNING("HTMLEditor::InsertDivElementToAlignContents() failed");
return insertNewDivElementResult.unwrapErr();
}
CreateElementResult unwrappedInsertNewDivElementResult =
insertNewDivElementResult.unwrap();
aRanges.ClearSavedRanges();
EditorDOMPoint pointToPutCaret =
unwrappedInsertNewDivElementResult.UnwrapCaretPoint();
nsresult rv = aRanges.Collapse(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "AutoRangeArray::Collapse() failed");
return rv;
}
Result<CreateElementResult, nsresult> maybeCreateDivElementResult =
AlignNodesAndDescendants(arrayOfContents, aAlignType, aEditingHost);
if (MOZ_UNLIKELY(maybeCreateDivElementResult.isErr())) {
NS_WARNING("HTMLEditor::AlignNodesAndDescendants() failed");
return maybeCreateDivElementResult.unwrapErr();
}
maybeCreateDivElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(aRanges.HasSavedRanges());
aRanges.RestoreFromSavedRanges();
// If restored range is collapsed outside the latest cased <div> element,
// we should move caret into the <div>.
if (maybeCreateDivElementResult.inspect().GetNewNode() &&
aRanges.IsCollapsed() && !aRanges.Ranges().IsEmpty()) {
const auto firstRangeStartRawPoint =
aRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (MOZ_LIKELY(firstRangeStartRawPoint.IsSet())) {
Result<EditorRawDOMPoint, nsresult> pointInNewDivOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(
*maybeCreateDivElementResult.inspect().GetNewNode(),
firstRangeStartRawPoint);
if (MOZ_UNLIKELY(pointInNewDivOrError.isErr())) {
NS_WARNING(
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() failed, "
"but ignored");
} else if (pointInNewDivOrError.inspect().IsSet()) {
nsresult rv = aRanges.Collapse(pointInNewDivOrError.unwrap());
if (NS_FAILED(rv)) {
NS_WARNING("AutoRangeArray::Collapse() failed");
return rv;
}
}
}
}
return NS_OK;
}
Result<CreateElementResult, nsresult>
HTMLEditor::InsertDivElementToAlignContents(
const EditorDOMPoint& aPointToInsert, const nsAString& aAlignType,
const Element& aEditingHost) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
MOZ_ASSERT(!IsSelectionRangeContainerNotContent());
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
if (NS_WARN_IF(!aPointToInsert.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, aPointToInsert, BRElementNextToSplitPoint::Delete,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div, BRElementNextToSplitPoint::Delete) failed");
return createNewDivElementResult;
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
// We'll suggest start of the new <div>, so we don't need the suggested
// position.
unwrappedCreateNewDivElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedCreateNewDivElementResult.GetNewNode());
RefPtr<Element> newDivElement =
unwrappedCreateNewDivElementResult.UnwrapNewNode();
// Set up the alignment on the div, using HTML or CSS
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
SetBlockElementAlign(*newDivElement, aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::SetBlockElementAlign(EditTarget::"
"OnlyDescendantsExceptTable) failed");
return pointToPutCaretOrError.propagateErr();
}
// We don't need the new suggested position too.
// Put in a padding <br> element for empty last line so that it won't get
// deleted.
{
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
EditorDOMPoint(newDivElement, 0u));
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction() "
"failed");
return insertPaddingBRElementResult;
}
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
}
return CreateElementResult(std::move(newDivElement),
EditorDOMPoint(newDivElement, 0u));
}
Result<CreateElementResult, nsresult> HTMLEditor::AlignNodesAndDescendants(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents,
const nsAString& aAlignType, const Element& aEditingHost) {
// Detect all the transitions in the array, where a transition means that
// adjacent nodes in the array don't have the same parent.
AutoTArray<bool, 64> transitionList;
HTMLEditor::MakeTransitionList(aArrayOfContents, transitionList);
RefPtr<Element> latestCreatedDivElement;
EditorDOMPoint pointToPutCaret;
// Okay, now go through all the nodes and give them an align attrib or put
// them in a div, or whatever is appropriate. Woohoo!
RefPtr<Element> createdDivElement;
const bool useCSS = IsCSSEnabled();
int32_t indexOfTransitionList = -1;
for (OwningNonNull<nsIContent>& content : aArrayOfContents) {
++indexOfTransitionList;
// Ignore all non-editable nodes. Leave them be.
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
continue;
}
// The node is a table element, an hr, a paragraph, a div or a section
// header; in HTML 4, it can directly carry the ALIGN attribute and we
// don't need to nest it, just set the alignment. In CSS, assign the
// corresponding CSS styles in SetBlockElementAlign().
if (HTMLEditUtils::SupportsAlignAttr(content)) {
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
SetBlockElementAlign(MOZ_KnownLive(*content->AsElement()), aAlignType,
EditTarget::NodeAndDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::SetBlockElementAlign(EditTarget::"
"NodeAndDescendantsExceptTable) failed");
return pointToPutCaretOrError.propagateErr();
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
// Clear out createdDivElement so that we don't put nodes after this one
// into it
createdDivElement = nullptr;
continue;
}
EditorDOMPoint atContent(content);
if (NS_WARN_IF(!atContent.IsSet())) {
continue;
}
// Skip insignificant formatting text nodes to prevent unnecessary
// structure splitting!
if (content->IsText() &&
((HTMLEditUtils::IsAnyTableElement(atContent.GetContainer()) &&
!HTMLEditUtils::IsTableCellOrCaption(*atContent.GetContainer())) ||
HTMLEditUtils::IsAnyListElement(atContent.GetContainer()) ||
HTMLEditUtils::IsEmptyNode(
*content, {EmptyCheckOption::TreatSingleBRElementAsVisible}))) {
continue;
}
// If it's a list item, or a list inside a list, forget any "current" div,
// and instead put divs inside the appropriate block (td, li, etc.)
if (HTMLEditUtils::IsListItem(content) ||
HTMLEditUtils::IsAnyListElement(content)) {
Element* listOrListItemElement = content->AsElement();
{
AutoEditorDOMPointOffsetInvalidator lockChild(atContent);
// MOZ_KnownLive(*listOrListItemElement): An element of aArrayOfContents
// which is array of OwningNonNull.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
RemoveAlignFromDescendants(MOZ_KnownLive(*listOrListItemElement),
aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveAlignFromDescendants(EditTarget::"
"OnlyDescendantsExceptTable) failed");
return pointToPutCaretOrError.propagateErr();
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
if (NS_WARN_IF(!atContent.IsSetAndValid())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (useCSS) {
nsStyledElement* styledListOrListItemElement =
nsStyledElement::FromNode(listOrListItemElement);
if (styledListOrListItemElement &&
EditorElementStyle::Align().IsCSSSettable(
*styledListOrListItemElement)) {
// MOZ_KnownLive(*styledListOrListItemElement): An element of
// aArrayOfContents which is array of OwningNonNull.
Result<size_t, nsresult> result =
CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this,
MOZ_KnownLive(*styledListOrListItemElement),
EditorElementStyle::Align(), &aAlignType);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return result.propagateErr();
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"Align()) failed, but ignored");
}
}
createdDivElement = nullptr;
continue;
}
if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
// If we don't use CSS, add a content to list element: they have to
// be inside another list, i.e., >= second level of nesting.
// XXX AlignContentsInAllTableCellsAndListItems() handles only list
// item elements and table cells. Is it intentional? Why don't
// we need to align contents in other type blocks?
// MOZ_KnownLive(*listOrListItemElement): An element of aArrayOfContents
// which is array of OwningNonNull.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
AlignContentsInAllTableCellsAndListItems(
MOZ_KnownLive(*listOrListItemElement), aAlignType);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::AlignContentsInAllTableCellsAndListItems() failed");
return pointToPutCaretOrError.propagateErr();
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
createdDivElement = nullptr;
continue;
}
// Clear out createdDivElement so that we don't put nodes after this one
// into it
}
// Need to make a div to put things in if we haven't already, or if this
// node doesn't go in div we used earlier.
if (!createdDivElement || transitionList[indexOfTransitionList]) {
// First, check that our element can contain a div.
if (!HTMLEditUtils::CanNodeContain(*atContent.GetContainer(),
*nsGkAtoms::div)) {
// XXX Why do we return "OK" here rather than returning error or
// doing continue?
return latestCreatedDivElement
? CreateElementResult(std::move(latestCreatedDivElement),
std::move(pointToPutCaret))
: CreateElementResult::NotHandled(
std::move(pointToPutCaret));
}
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult;
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
if (unwrappedCreateNewDivElementResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedCreateNewDivElementResult.UnwrapCaretPoint();
}
MOZ_ASSERT(unwrappedCreateNewDivElementResult.GetNewNode());
createdDivElement = unwrappedCreateNewDivElementResult.UnwrapNewNode();
// Set up the alignment on the div
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
SetBlockElementAlign(*createdDivElement, aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
if (NS_WARN_IF(pointToPutCaretOrError.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return pointToPutCaretOrError.propagateErr();
}
NS_WARNING(
"HTMLEditor::SetBlockElementAlign(EditTarget::"
"OnlyDescendantsExceptTable) failed, but ignored");
} else if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
latestCreatedDivElement = createdDivElement;
}
// Tuck the node into the end of the active div
//
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content),
*createdDivElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
if (unwrappedMoveNodeResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveNodeResult.UnwrapCaretPoint();
}
}
return latestCreatedDivElement
? CreateElementResult(std::move(latestCreatedDivElement),
std::move(pointToPutCaret))
: CreateElementResult::NotHandled(std::move(pointToPutCaret));
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::AlignContentsInAllTableCellsAndListItems(
Element& aElement, const nsAString& aAlignType) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Gather list of table cells or list items
AutoTArray<OwningNonNull<Element>, 64> arrayOfTableCellsAndListItems;
DOMIterator iter(aElement);
iter.AppendNodesToArray(
+[](nsINode& aNode, void*) -> bool {
MOZ_ASSERT(Element::FromNode(&aNode));
return HTMLEditUtils::IsTableCell(&aNode) ||
HTMLEditUtils::IsListItem(&aNode);
},
arrayOfTableCellsAndListItems);
// Now that we have the list, align their contents as requested
EditorDOMPoint pointToPutCaret;
for (auto& tableCellOrListItemElement : arrayOfTableCellsAndListItems) {
// MOZ_KnownLive because 'arrayOfTableCellsAndListItems' is guaranteed to
// keep it alive.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
AlignBlockContentsWithDivElement(
MOZ_KnownLive(tableCellOrListItemElement), aAlignType);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::AlignBlockContentsWithDivElement() failed");
return pointToPutCaretOrError;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::AlignBlockContentsWithDivElement(
Element& aBlockElement, const nsAString& aAlignType) {
MOZ_ASSERT(IsEditActionDataAvailable());
// XXX I don't understand why we should NOT align non-editable children
// with modifying EDITABLE `<div>` element.
nsCOMPtr<nsIContent> firstEditableContent = HTMLEditUtils::GetFirstChild(
aBlockElement, {WalkTreeOption::IgnoreNonEditableNode});
if (!firstEditableContent) {
// This block has no editable content, nothing to align.
return EditorDOMPoint();
}
// If there is only one editable content and it's a `<div>` element,
// just set `align` attribute of it.
nsCOMPtr<nsIContent> lastEditableContent = HTMLEditUtils::GetLastChild(
aBlockElement, {WalkTreeOption::IgnoreNonEditableNode});
if (firstEditableContent == lastEditableContent &&
firstEditableContent->IsHTMLElement(nsGkAtoms::div)) {
nsresult rv = SetAttributeOrEquivalent(
MOZ_KnownLive(firstEditableContent->AsElement()), nsGkAtoms::align,
aAlignType, false);
if (NS_WARN_IF(Destroyed())) {
NS_WARNING(
"EditorBase::SetAttributeOrEquivalent(nsGkAtoms::align) caused "
"destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::SetAttributeOrEquivalent(nsGkAtoms::align) failed");
return Err(rv);
}
return EditorDOMPoint();
}
// Otherwise, we need to insert a `<div>` element to set `align` attribute.
// XXX Don't insert the new `<div>` element until we set `align` attribute
// for avoiding running mutation event listeners.
Result<CreateElementResult, nsresult> createNewDivElementResult =
CreateAndInsertElement(
WithTransaction::Yes, *nsGkAtoms::div,
EditorDOMPoint(&aBlockElement, 0u),
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[&aAlignType](HTMLEditor& aHTMLEditor, Element& aDivElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
MOZ_ASSERT(!aDivElement.IsInComposedDoc());
// If aDivElement has not been connected yet, we do not need
// transaction of setting align attribute here.
nsresult rv = aHTMLEditor.SetAttributeOrEquivalent(
&aDivElement, nsGkAtoms::align, aAlignType, false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeOrEquivalent("
"nsGkAtoms::align, \"...\", false) failed");
return rv;
});
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes, "
"nsGkAtoms::div) failed");
return createNewDivElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
EditorDOMPoint pointToPutCaret =
unwrappedCreateNewDivElementResult.UnwrapCaretPoint();
RefPtr<Element> newDivElement =
unwrappedCreateNewDivElementResult.UnwrapNewNode();
MOZ_ASSERT(newDivElement);
// XXX This is tricky and does not work with mutation event listeners.
// But I'm not sure what we should do if new content is inserted.
// Anyway, I don't think that we should move editable contents
// over non-editable contents. Chrome does no do that.
while (lastEditableContent && (lastEditableContent != newDivElement)) {
Result<MoveNodeResult, nsresult> moveNodeResult = MoveNodeWithTransaction(
*lastEditableContent, EditorDOMPoint(newDivElement, 0u));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
if (unwrappedMoveNodeResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedMoveNodeResult.UnwrapCaretPoint();
}
lastEditableContent = HTMLEditUtils::GetLastChild(
aBlockElement, {WalkTreeOption::IgnoreNonEditableNode});
}
return pointToPutCaret;
}
Result<EditorRawDOMRange, nsresult>
HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction(
const nsRange* aRange, const Element& aEditingHost) const {
MOZ_ASSERT(IsEditActionDataAvailable());
// This tweaks selections to be more "natural".
// Idea here is to adjust edges of selection ranges so that they do not cross
// breaks or block boundaries unless something editable beyond that boundary
// is also selected. This adjustment makes it much easier for the various
// block operations to determine what nodes to act on.
if (NS_WARN_IF(!aRange) || NS_WARN_IF(!aRange->IsPositioned())) {
return Err(NS_ERROR_FAILURE);
}
const EditorRawDOMPoint startPoint(aRange->StartRef());
if (NS_WARN_IF(!startPoint.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
const EditorRawDOMPoint endPoint(aRange->EndRef());
if (NS_WARN_IF(!endPoint.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
// adjusted values default to original values
EditorRawDOMRange newRange(startPoint, endPoint);
// Is there any intervening visible white-space? If so we can't push
// selection past that, it would visibly change meaning of users selection.
WSRunScanner wsScannerAtEnd(&aEditingHost, endPoint);
WSScanResult scanResultAtEnd =
wsScannerAtEnd.ScanPreviousVisibleNodeOrBlockBoundaryFrom(endPoint);
if (scanResultAtEnd.Failed()) {
NS_WARNING(
"WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundaryFrom() failed");
return Err(NS_ERROR_FAILURE);
}
if (scanResultAtEnd.ReachedSomethingNonTextContent()) {
// eThisBlock and eOtherBlock conveniently distinguish cases
// of going "down" into a block and "up" out of a block.
if (wsScannerAtEnd.StartsFromOtherBlockElement()) {
// endpoint is just after the close of a block.
if (nsIContent* child = HTMLEditUtils::GetLastLeafContent(
*wsScannerAtEnd.StartReasonOtherBlockElementPtr(),
{LeafNodeType::LeafNodeOrChildBlock})) {
newRange.SetEnd(EditorRawDOMPoint::After(*child));
}
// else block is empty - we can leave selection alone here, i think.
} else if (wsScannerAtEnd.StartsFromCurrentBlockBoundary()) {
// endpoint is just after start of this block
if (nsIContent* child = HTMLEditUtils::GetPreviousContent(
endPoint, {WalkTreeOption::IgnoreNonEditableNode},
&aEditingHost)) {
newRange.SetEnd(EditorRawDOMPoint::After(*child));
}
// else block is empty - we can leave selection alone here, i think.
} else if (wsScannerAtEnd.StartsFromBRElement()) {
// endpoint is just after break. lets adjust it to before it.
newRange.SetEnd(
EditorRawDOMPoint(wsScannerAtEnd.StartReasonBRElementPtr()));
}
}
// Is there any intervening visible white-space? If so we can't push
// selection past that, it would visibly change meaning of users selection.
WSRunScanner wsScannerAtStart(&aEditingHost, startPoint);
WSScanResult scanResultAtStart =
wsScannerAtStart.ScanNextVisibleNodeOrBlockBoundaryFrom(startPoint);
if (scanResultAtStart.Failed()) {
NS_WARNING("WSRunScanner::ScanNextVisibleNodeOrBlockBoundaryFrom() failed");
return Err(NS_ERROR_FAILURE);
}
if (scanResultAtStart.ReachedSomethingNonTextContent()) {
// eThisBlock and eOtherBlock conveniently distinguish cases
// of going "down" into a block and "up" out of a block.
if (wsScannerAtStart.EndsByOtherBlockElement()) {
// startpoint is just before the start of a block.
if (nsIContent* child = HTMLEditUtils::GetFirstLeafContent(
*wsScannerAtStart.EndReasonOtherBlockElementPtr(),
{LeafNodeType::LeafNodeOrChildBlock})) {
newRange.SetStart(EditorRawDOMPoint(child));
}
// else block is empty - we can leave selection alone here, i think.
} else if (wsScannerAtStart.EndsByCurrentBlockBoundary()) {
// startpoint is just before end of this block
if (nsIContent* child = HTMLEditUtils::GetNextContent(
startPoint, {WalkTreeOption::IgnoreNonEditableNode},
&aEditingHost)) {
newRange.SetStart(EditorRawDOMPoint(child));
}
// else block is empty - we can leave selection alone here, i think.
} else if (wsScannerAtStart.EndsByBRElement()) {
// startpoint is just before a break. lets adjust it to after it.
newRange.SetStart(
EditorRawDOMPoint::After(*wsScannerAtStart.EndReasonBRElementPtr()));
}
}
// There is a demented possibility we have to check for. We might have a very
// strange selection that is not collapsed and yet does not contain any
// editable content, and satisfies some of the above conditions that cause
// tweaking. In this case we don't want to tweak the selection into a block
// it was never in, etc. There are a variety of strategies one might use to
// try to detect these cases, but I think the most straightforward is to see
// if the adjusted locations "cross" the old values: i.e., new end before old
// start, or new start after old end. If so then just leave things alone.
Maybe<int32_t> comp = nsContentUtils::ComparePoints(
startPoint.ToRawRangeBoundary(), newRange.EndRef().ToRawRangeBoundary());
if (NS_WARN_IF(!comp)) {
return Err(NS_ERROR_FAILURE);
}
if (*comp == 1) {
return EditorRawDOMRange(); // New end before old start.
}
comp = nsContentUtils::ComparePoints(newRange.StartRef().ToRawRangeBoundary(),
endPoint.ToRawRangeBoundary());
if (NS_WARN_IF(!comp)) {
return Err(NS_ERROR_FAILURE);
}
if (*comp == 1) {
return EditorRawDOMRange(); // New start after old end.
}
return newRange;
}
template <typename EditorDOMRangeType>
already_AddRefed<nsRange> HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorDOMRangeType& aRange) {
MOZ_DIAGNOSTIC_ASSERT(aRange.IsPositioned());
return CreateRangeIncludingAdjuscentWhiteSpaces(aRange.StartRef(),
aRange.EndRef());
}
template <typename EditorDOMPointType1, typename EditorDOMPointType2>
already_AddRefed<nsRange> HTMLEditor::CreateRangeIncludingAdjuscentWhiteSpaces(
const EditorDOMPointType1& aStartPoint,
const EditorDOMPointType2& aEndPoint) {
MOZ_DIAGNOSTIC_ASSERT(!aStartPoint.IsInNativeAnonymousSubtree());
MOZ_DIAGNOSTIC_ASSERT(!aEndPoint.IsInNativeAnonymousSubtree());
if (!aStartPoint.IsInContentNode() || !aEndPoint.IsInContentNode()) {
NS_WARNING_ASSERTION(aStartPoint.IsSet(), "aStartPoint was not set");
NS_WARNING_ASSERTION(aEndPoint.IsSet(), "aEndPoint was not set");
return nullptr;
}
const Element* const editingHost = ComputeEditingHost();
if (NS_WARN_IF(!editingHost)) {
return nullptr;
}
EditorDOMPoint startPoint = aStartPoint.template To<EditorDOMPoint>();
EditorDOMPoint endPoint = aEndPoint.template To<EditorDOMPoint>();
AutoRangeArray::UpdatePointsToSelectAllChildrenIfCollapsedInEmptyBlockElement(
startPoint, endPoint, *editingHost);
if (NS_WARN_IF(!startPoint.IsInContentNode()) ||
NS_WARN_IF(!endPoint.IsInContentNode())) {
NS_WARNING(
"AutoRangeArray::"
"UpdatePointsToSelectAllChildrenIfCollapsedInEmptyBlockElement() "
"failed");
return nullptr;
}
// For text actions, we want to look backwards (or forwards, as
// appropriate) for additional white-space or nbsp's. We may have to act
// on these later even though they are outside of the initial selection.
// Even if they are in another node!
// XXX Those scanners do not treat siblings of the text nodes. Perhaps,
// we should use `WSRunScanner::GetFirstASCIIWhiteSpacePointCollapsedTo()`
// and `WSRunScanner::GetEndOfCollapsibleASCIIWhiteSpaces()` instead.
if (startPoint.IsInTextNode()) {
while (!startPoint.IsStartOfContainer()) {
if (!startPoint.IsPreviousCharASCIISpaceOrNBSP()) {
break;
}
MOZ_ALWAYS_TRUE(startPoint.RewindOffset());
}
}
if (!startPoint.GetChildOrContainerIfDataNode() ||
!startPoint.GetChildOrContainerIfDataNode()->IsInclusiveDescendantOf(
editingHost)) {
return nullptr;
}
if (endPoint.IsInTextNode()) {
while (!endPoint.IsEndOfContainer()) {
if (!endPoint.IsCharASCIISpaceOrNBSP()) {
break;
}
MOZ_ALWAYS_TRUE(endPoint.AdvanceOffset());
}
}
EditorDOMPoint lastRawPoint(endPoint);
if (!lastRawPoint.IsStartOfContainer()) {
lastRawPoint.RewindOffset();
}
if (!lastRawPoint.GetChildOrContainerIfDataNode() ||
!lastRawPoint.GetChildOrContainerIfDataNode()->IsInclusiveDescendantOf(
editingHost)) {
return nullptr;
}
RefPtr<nsRange> range =
nsRange::Create(startPoint.ToRawRangeBoundary(),
endPoint.ToRawRangeBoundary(), IgnoreErrors());
NS_WARNING_ASSERTION(range, "nsRange::Create() failed");
return range.forget();
}
Result<EditorDOMPoint, nsresult> HTMLEditor::MaybeSplitElementsAtEveryBRElement(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents,
EditSubAction aEditSubAction) {
// Post-process the list to break up inline containers that contain br's, but
// only for operations that might care, like making lists or paragraphs
switch (aEditSubAction) {
case EditSubAction::eCreateOrRemoveBlock:
case EditSubAction::eMergeBlockContents:
case EditSubAction::eCreateOrChangeList:
case EditSubAction::eSetOrClearAlignment:
case EditSubAction::eSetPositionToAbsolute:
case EditSubAction::eIndent:
case EditSubAction::eOutdent: {
EditorDOMPoint pointToPutCaret;
for (int32_t i = aArrayOfContents.Length() - 1; i >= 0; i--) {
OwningNonNull<nsIContent>& content = aArrayOfContents[i];
if (HTMLEditUtils::IsInlineElement(content) &&
HTMLEditUtils::IsContainerNode(content) && !content->IsText()) {
AutoTArray<OwningNonNull<nsIContent>, 24> arrayOfInlineContents;
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it
// alive.
Result<EditorDOMPoint, nsresult> splitResult =
SplitElementsAtEveryBRElement(MOZ_KnownLive(content),
arrayOfInlineContents);
if (splitResult.isErr()) {
NS_WARNING("HTMLEditor::SplitElementsAtEveryBRElement() failed");
return splitResult;
}
if (splitResult.inspect().IsSet()) {
pointToPutCaret = splitResult.unwrap();
}
// Put these nodes in aArrayOfContents, replacing the current node
aArrayOfContents.RemoveElementAt(i);
aArrayOfContents.InsertElementsAt(i, arrayOfInlineContents);
}
}
return pointToPutCaret;
}
default:
return EditorDOMPoint();
}
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::SplitParentInlineElementsAtRangeBoundaries(
RangeItem& aRangeItem, const Element& aEditingHost,
const nsIContent* aAncestorLimiter /* = nullptr */) {
MOZ_ASSERT(IsEditActionDataAvailable());
EditorDOMPoint pointToPutCaret;
if (!aRangeItem.Collapsed() && aRangeItem.mEndContainer &&
aRangeItem.mEndContainer->IsContent()) {
nsCOMPtr<nsIContent> mostAncestorInlineContentAtEnd =
HTMLEditUtils::GetMostDistantAncestorInlineElement(
*aRangeItem.mEndContainer->AsContent(), &aEditingHost,
aAncestorLimiter);
if (mostAncestorInlineContentAtEnd) {
Result<SplitNodeResult, nsresult> splitEndInlineResult =
SplitNodeDeepWithTransaction(
*mostAncestorInlineContentAtEnd, aRangeItem.EndPoint(),
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitEndInlineResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) failed");
return splitEndInlineResult.propagateErr();
}
SplitNodeResult unwrappedSplitEndInlineResult =
splitEndInlineResult.unwrap();
unwrappedSplitEndInlineResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
if (pointToPutCaret.IsInContentNode() &&
MOZ_UNLIKELY(
&aEditingHost !=
ComputeEditingHost(*pointToPutCaret.ContainerAs<nsIContent>()))) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) caused changing editing host");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
const auto splitPointAtEnd =
unwrappedSplitEndInlineResult.AtSplitPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!splitPointAtEnd.IsSet())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) didn't return split point");
return Err(NS_ERROR_FAILURE);
}
aRangeItem.mEndContainer = splitPointAtEnd.GetContainer();
aRangeItem.mEndOffset = splitPointAtEnd.Offset();
}
}
if (!aRangeItem.mStartContainer || !aRangeItem.mStartContainer->IsContent()) {
return pointToPutCaret;
}
nsCOMPtr<nsIContent> mostAncestorInlineContentAtStart =
HTMLEditUtils::GetMostDistantAncestorInlineElement(
*aRangeItem.mStartContainer->AsContent(), &aEditingHost,
aAncestorLimiter);
if (mostAncestorInlineContentAtStart) {
Result<SplitNodeResult, nsresult> splitStartInlineResult =
SplitNodeDeepWithTransaction(*mostAncestorInlineContentAtStart,
aRangeItem.StartPoint(),
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitStartInlineResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) failed");
return splitStartInlineResult.propagateErr();
}
SplitNodeResult unwrappedSplitStartInlineResult =
splitStartInlineResult.unwrap();
// XXX Why don't we check editing host like above??
unwrappedSplitStartInlineResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
// XXX If we split only here because of collapsed range, we're modifying
// only start point of aRangeItem. Shouldn't we modify end point here
// if it's collapsed?
const auto splitPointAtStart =
unwrappedSplitStartInlineResult.AtSplitPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!splitPointAtStart.IsSet())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eDoNotCreateEmptyContainer) didn't return split point");
return Err(NS_ERROR_FAILURE);
}
aRangeItem.mStartContainer = splitPointAtStart.GetContainer();
aRangeItem.mStartOffset = splitPointAtStart.Offset();
}
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::SplitElementsAtEveryBRElement(
nsIContent& aMostAncestorToBeSplit,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents) {
MOZ_ASSERT(IsEditActionDataAvailable());
// First build up a list of all the break nodes inside the inline container.
AutoTArray<OwningNonNull<HTMLBRElement>, 24> arrayOfBRElements;
DOMIterator iter(aMostAncestorToBeSplit);
iter.AppendAllNodesToArray(arrayOfBRElements);
// If there aren't any breaks, just put inNode itself in the array
if (arrayOfBRElements.IsEmpty()) {
aOutArrayOfContents.AppendElement(aMostAncestorToBeSplit);
return EditorDOMPoint();
}
// Else we need to bust up aMostAncestorToBeSplit along all the breaks
nsCOMPtr<nsIContent> nextContent = &aMostAncestorToBeSplit;
EditorDOMPoint pointToPutCaret;
for (OwningNonNull<HTMLBRElement>& brElement : arrayOfBRElements) {
EditorDOMPoint atBRNode(brElement);
if (NS_WARN_IF(!atBRNode.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeDeepWithTransaction(
*nextContent, atBRNode, SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
unwrappedSplitNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
// Put previous node at the split point.
if (nsIContent* previousContent =
unwrappedSplitNodeResult.GetPreviousContent()) {
// Might not be a left node. A break might have been at the very
// beginning of inline container, in which case
// SplitNodeDeepWithTransaction() would not actually split anything.
aOutArrayOfContents.AppendElement(*previousContent);
}
// Move break outside of container and also put in node list
// MOZ_KnownLive because 'arrayOfBRElements' is guaranteed to keep it alive.
Result<MoveNodeResult, nsresult> moveBRElementResult =
MoveNodeWithTransaction(
MOZ_KnownLive(brElement),
unwrappedSplitNodeResult.AtNextContent<EditorDOMPoint>());
if (MOZ_UNLIKELY(moveBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveBRElementResult.propagateErr();
}
MoveNodeResult unwrappedMoveBRElementResult = moveBRElementResult.unwrap();
unwrappedMoveBRElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
aOutArrayOfContents.AppendElement(brElement);
nextContent = unwrappedSplitNodeResult.GetNextContent();
}
// Now tack on remaining next node.
aOutArrayOfContents.AppendElement(*nextContent);
return pointToPutCaret;
}
// static
void HTMLEditor::MakeTransitionList(
const nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents,
nsTArray<bool>& aTransitionArray) {
nsINode* prevParent = nullptr;
aTransitionArray.EnsureLengthAtLeast(aArrayOfContents.Length());
for (uint32_t i = 0; i < aArrayOfContents.Length(); i++) {
aTransitionArray[i] = aArrayOfContents[i]->GetParentNode() != prevParent;
prevParent = aArrayOfContents[i]->GetParentNode();
}
}
Result<InsertParagraphResult, nsresult>
HTMLEditor::HandleInsertParagraphInHeadingElement(
Element& aHeadingElement, const EditorDOMPoint& aPointToSplit) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
auto splitHeadingResult =
[this, &aPointToSplit, &aHeadingElement]()
MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
// Normalize collapsible white-spaces around the split point to keep
// them visible after the split. Note that this does not touch
// selection because of using AutoTransactionsConserveSelection in
// WhiteSpaceVisibilityKeeper::ReplaceTextAndRemoveEmptyTextNodes().
Result<EditorDOMPoint, nsresult> preparationResult =
WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement(
*this, aPointToSplit, aHeadingElement);
if (MOZ_UNLIKELY(preparationResult.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement() "
"failed");
return preparationResult.propagateErr();
}
EditorDOMPoint pointToSplit = preparationResult.unwrap();
MOZ_ASSERT(pointToSplit.IsInContentNode());
// Split the header
Result<SplitNodeResult, nsresult> splitResult =
SplitNodeDeepWithTransaction(
aHeadingElement, pointToSplit,
SplitAtEdges::eAllowToCreateEmptyContainer);
NS_WARNING_ASSERTION(
splitResult.isOk(),
"HTMLEditor::SplitNodeDeepWithTransaction(aHeadingElement, "
"SplitAtEdges::eAllowToCreateEmptyContainer) failed");
return splitResult;
}();
if (MOZ_UNLIKELY(splitHeadingResult.isErr())) {
NS_WARNING("Failed to splitting aHeadingElement");
return splitHeadingResult.propagateErr();
}
SplitNodeResult unwrappedSplitHeadingResult = splitHeadingResult.unwrap();
unwrappedSplitHeadingResult.IgnoreCaretPointSuggestion();
if (MOZ_UNLIKELY(!unwrappedSplitHeadingResult.DidSplit())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eAllowToCreateEmptyContainer) didn't split aHeadingElement");
return Err(NS_ERROR_FAILURE);
}
// If the left heading element is empty, put a padding <br> element for empty
// last line into it.
// FYI: leftHeadingElement is grabbed by unwrappedSplitHeadingResult so that
// it's safe to access anytime.
auto* const leftHeadingElement =
unwrappedSplitHeadingResult.GetPreviousContentAs<Element>();
MOZ_ASSERT(leftHeadingElement,
"SplitNodeResult::GetPreviousContent() should return something if "
"DidSplit() returns true");
MOZ_DIAGNOSTIC_ASSERT(HTMLEditUtils::IsHeader(*leftHeadingElement));
if (HTMLEditUtils::IsEmptyNode(
*leftHeadingElement,
{EmptyCheckOption::TreatSingleBRElementAsVisible})) {
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
EditorDOMPoint(leftHeadingElement, 0u));
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction("
") failed");
return insertPaddingBRElementResult.propagateErr();
}
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
}
// Put caret at start of the right head element if it's not empty.
auto* const rightHeadingElement =
unwrappedSplitHeadingResult.GetNextContentAs<Element>();
MOZ_ASSERT(rightHeadingElement,
"SplitNodeResult::GetNextContent() should return something if "
"DidSplit() returns true");
if (!HTMLEditUtils::IsEmptyBlockElement(*rightHeadingElement, {})) {
return InsertParagraphResult(rightHeadingElement,
EditorDOMPoint(rightHeadingElement, 0u));
}
// If the right heading element is empty, delete it.
// TODO: If we know the new heading element becomes empty, we stop spliting
// the heading element.
// MOZ_KnownLive(rightHeadingElement) because it's grabbed by
// unwrappedSplitHeadingResult.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*rightHeadingElement));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
// Layout tells the caret to blink in a weird place if we don't place a
// break after the header.
// XXX This block is dead code unless the removed right heading element is
// reconnected by a mutation event listener. This is a regression of
// bug 1405751:
// https://searchfox.org/mozilla-central/diff/879f3317d1331818718e18776caa47be7f426a22/editor/libeditor/HTMLEditRules.cpp#6389
// However, the traditional behavior is different from the other browsers.
// Chrome creates new paragraph in this case. Therefore, we should just
// drop this block in a follow up bug.
if (rightHeadingElement->GetNextSibling()) {
// XXX Ignoring non-editable <br> element here is odd because non-editable
// <br> elements also work as <br> from point of view of layout.
nsIContent* nextEditableSibling =
HTMLEditUtils::GetNextSibling(*rightHeadingElement->GetNextSibling(),
{WalkTreeOption::IgnoreNonEditableNode});
if (nextEditableSibling &&
nextEditableSibling->IsHTMLElement(nsGkAtoms::br)) {
auto afterEditableBRElement = EditorDOMPoint::After(*nextEditableSibling);
if (NS_WARN_IF(!afterEditableBRElement.IsSet())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// Put caret at the <br> element.
return InsertParagraphResult::NotHandled(
std::move(afterEditableBRElement));
}
}
if (MOZ_UNLIKELY(!leftHeadingElement->IsInComposedDoc())) {
NS_WARNING("The left heading element was unexpectedly removed");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
TopLevelEditSubActionDataRef().mCachedPendingStyles->Clear();
mPendingStylesToApplyToNewContent->ClearAllStyles();
// Create a paragraph if the right heading element is not followed by an
// editable <br> element.
nsStaticAtom& newParagraphTagName =
&DefaultParagraphSeparatorTagName() == nsGkAtoms::br
? *nsGkAtoms::p
: DefaultParagraphSeparatorTagName();
// We want a wrapper element even if we separate with a <br>.
// MOZ_KnownLive(newParagraphTagName) because it's available until shutdown.
Result<CreateElementResult, nsresult> createNewParagraphElementResult =
CreateAndInsertElement(WithTransaction::Yes,
MOZ_KnownLive(newParagraphTagName),
EditorDOMPoint::After(*leftHeadingElement),
HTMLEditor::InsertNewBRElement);
if (MOZ_UNLIKELY(createNewParagraphElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewParagraphElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewParagraphElementResult =
createNewParagraphElementResult.unwrap();
// Put caret at the <br> element in the following paragraph.
unwrappedCreateNewParagraphElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedCreateNewParagraphElementResult.GetNewNode());
EditorDOMPoint pointToPutCaret(
unwrappedCreateNewParagraphElementResult.GetNewNode(), 0u);
return InsertParagraphResult(
unwrappedCreateNewParagraphElementResult.UnwrapNewNode(),
std::move(pointToPutCaret));
}
Result<SplitNodeResult, nsresult> HTMLEditor::HandleInsertParagraphInParagraph(
Element& aParentDivOrP, const EditorDOMPoint& aCandidatePointToSplit,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aCandidatePointToSplit.IsSetAndValid());
// First, get a better split point to avoid to create a new empty link in the
// right paragraph.
EditorDOMPoint pointToSplit = [&]() {
// We shouldn't create new anchor element which has non-empty href unless
// splitting middle of it because we assume that users don't want to create
// *same* anchor element across two or more paragraphs in most cases.
// So, adjust selection start if it's edge of anchor element(s).
// XXX We don't support white-space collapsing in these cases since it needs
// some additional work with WhiteSpaceVisibilityKeeper but it's not
// usual case. E.g., |<a href="foo"><b>foo []</b> </a>|
if (aCandidatePointToSplit.IsStartOfContainer()) {
EditorDOMPoint candidatePoint(aCandidatePointToSplit);
for (nsIContent* container =
aCandidatePointToSplit.GetContainerAs<nsIContent>();
container && container != &aParentDivOrP;
container = container->GetParent()) {
if (HTMLEditUtils::IsLink(container)) {
// Found link should be only in right node. So, we shouldn't split
// it.
candidatePoint.Set(container);
// Even if we found an anchor element, don't break because DOM API
// allows to nest anchor elements.
}
// If the container is middle of its parent, stop adjusting split point.
if (container->GetPreviousSibling()) {
// XXX Should we check if previous sibling is visible content?
// E.g., should we ignore comment node, invisible <br> element?
break;
}
}
return candidatePoint;
}
// We also need to check if selection is at invisible <br> element at end
// of an <a href="foo"> element because editor inserts a <br> element when
// user types Enter key after a white-space which is at middle of
// <a href="foo"> element and when setting selection at end of the element,
// selection becomes referring the <br> element. We may need to change this
// behavior later if it'd be standardized.
if (aCandidatePointToSplit.IsEndOfContainer() ||
aCandidatePointToSplit.IsBRElementAtEndOfContainer()) {
// If there are 2 <br> elements, the first <br> element is visible. E.g.,
// |<a href="foo"><b>boo[]<br></b><br></a>|, we should split the <a>
// element. Otherwise, E.g., |<a href="foo"><b>boo[]<br></b></a>|,
// we should not split the <a> element and ignore inline elements in it.
bool foundBRElement =
aCandidatePointToSplit.IsBRElementAtEndOfContainer();
EditorDOMPoint candidatePoint(aCandidatePointToSplit);
for (nsIContent* container =
aCandidatePointToSplit.GetContainerAs<nsIContent>();
container && container != &aParentDivOrP;
container = container->GetParent()) {
if (HTMLEditUtils::IsLink(container)) {
// Found link should be only in left node. So, we shouldn't split it.
candidatePoint.SetAfter(container);
// Even if we found an anchor element, don't break because DOM API
// allows to nest anchor elements.
}
// If the container is middle of its parent, stop adjusting split point.
if (nsIContent* nextSibling = container->GetNextSibling()) {
if (foundBRElement) {
// If we've already found a <br> element, we assume found node is
// visible <br> or something other node.
// XXX Should we check if non-text data node like comment?
break;
}
// XXX Should we check if non-text data node like comment?
if (!nextSibling->IsHTMLElement(nsGkAtoms::br)) {
break;
}
foundBRElement = true;
}
}
return candidatePoint;
}
return aCandidatePointToSplit;
}();
const bool createNewParagraph = GetReturnInParagraphCreatesNewParagraph();
RefPtr<HTMLBRElement> brElement;
if (createNewParagraph && pointToSplit.GetContainer() == &aParentDivOrP) {
// We are try to split only the current paragraph. Therefore, we don't need
// to create new <br> elements around it (if left and/or right paragraph
// becomes empty, it'll be treated by SplitParagraphWithTransaction().
brElement = nullptr;
} else if (pointToSplit.IsInTextNode()) {
if (pointToSplit.IsStartOfContainer()) {
// If we're splitting the paragraph at start of a text node and there is
// no preceding visible <br> element, we need to create a <br> element to
// keep the inline elements containing this text node.
// TODO: If the parent of the text node is the splitting paragraph,
// obviously we don't need to do this because empty paragraphs will
// be treated by SplitParagraphWithTransaction(). In this case, we
// just need to update pointToSplit for using the same path as the
// previous `if` block.
brElement =
HTMLBRElement::FromNodeOrNull(HTMLEditUtils::GetPreviousSibling(
*pointToSplit.ContainerAs<Text>(),
{WalkTreeOption::IgnoreNonEditableNode}));
if (!brElement || HTMLEditUtils::IsInvisibleBRElement(*brElement) ||
EditorUtils::IsPaddingBRElementForEmptyLastLine(*brElement)) {
// If insertParagraph does not create a new paragraph, default to
// insertLineBreak.
if (!createNewParagraph) {
return SplitNodeResult::NotHandled(pointToSplit,
GetSplitNodeDirection());
}
const EditorDOMPoint pointToInsertBR = pointToSplit.ParentPoint();
MOZ_ASSERT(pointToInsertBR.IsSet());
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToInsertBR);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
// We'll collapse `Selection` to the place suggested by
// SplitParagraphWithTransaction.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
brElement = HTMLBRElement::FromNodeOrNull(
insertBRElementResult.inspect().GetNewNode());
}
} else if (pointToSplit.IsEndOfContainer()) {
// If we're splitting the paragraph at end of a text node and there is not
// following visible <br> element, we need to create a <br> element after
// the text node to make current style specified by parent inline elements
// keep in the right paragraph.
// TODO: Same as above, we don't need to do this if the text node is a
// direct child of the paragraph. For using the simplest path, we
// just need to update `pointToSplit` in the case.
brElement = HTMLBRElement::FromNodeOrNull(HTMLEditUtils::GetNextSibling(
*pointToSplit.ContainerAs<Text>(),
{WalkTreeOption::IgnoreNonEditableNode}));
if (!brElement || HTMLEditUtils::IsInvisibleBRElement(*brElement) ||
EditorUtils::IsPaddingBRElementForEmptyLastLine(*brElement)) {
// If insertParagraph does not create a new paragraph, default to
// insertLineBreak.
if (!createNewParagraph) {
return SplitNodeResult::NotHandled(pointToSplit,
GetSplitNodeDirection());
}
const auto pointToInsertBR =
EditorDOMPoint::After(*pointToSplit.ContainerAs<Text>());
MOZ_ASSERT(pointToInsertBR.IsSet());
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToInsertBR);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
// We'll collapse `Selection` to the place suggested by
// SplitParagraphWithTransaction.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
brElement = HTMLBRElement::FromNodeOrNull(
insertBRElementResult.inspect().GetNewNode());
}
} else {
// If insertParagraph does not create a new paragraph, default to
// insertLineBreak.
if (!createNewParagraph) {
return SplitNodeResult::NotHandled(pointToSplit,
GetSplitNodeDirection());
}
// If we're splitting the paragraph at middle of a text node, we should
// split the text node here and put a <br> element next to the left text
// node.
// XXX Why? I think that this should be handled in
// SplitParagraphWithTransaction() directly because I don't find
// the necessary case of the <br> element.
// XXX We split a text node here if caret is middle of it to insert
// <br> element **before** splitting aParentDivOrP. Then, if
// the <br> element becomes unnecessary, it'll be removed again.
// So this does much more complicated things than what we want to
// do here. We should handle this case separately to make the code
// much simpler.
// Normalize collapsible white-spaces around the split point to keep
// them visible after the split. Note that this does not touch
// selection because of using AutoTransactionsConserveSelection in
// WhiteSpaceVisibilityKeeper::ReplaceTextAndRemoveEmptyTextNodes().
Result<EditorDOMPoint, nsresult> pointToSplitOrError =
WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement(
*this, pointToSplit, aParentDivOrP);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (MOZ_UNLIKELY(pointToSplitOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement() "
"failed");
return pointToSplitOrError.propagateErr();
}
MOZ_ASSERT(pointToSplitOrError.inspect().IsSetAndValid());
if (pointToSplitOrError.inspect().IsSet()) {
pointToSplit = pointToSplitOrError.unwrap();
}
Result<SplitNodeResult, nsresult> splitParentDivOrPResult =
SplitNodeWithTransaction(pointToSplit);
if (MOZ_UNLIKELY(splitParentDivOrPResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitParentDivOrPResult;
}
// We'll collapse `Selection` to the place suggested by
// SplitParagraphWithTransaction.
splitParentDivOrPResult.inspect().IgnoreCaretPointSuggestion();
pointToSplit.SetToEndOf(
splitParentDivOrPResult.inspect().GetPreviousContent());
if (NS_WARN_IF(!pointToSplit.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// We need to put new <br> after the left node if given node was split
// above.
const auto pointToInsertBR =
EditorDOMPoint::After(*pointToSplit.ContainerAs<nsIContent>());
MOZ_ASSERT(pointToInsertBR.IsSet());
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToInsertBR);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
// We'll collapse `Selection` to the place suggested by
// SplitParagraphWithTransaction.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
brElement = HTMLBRElement::FromNodeOrNull(
insertBRElementResult.inspect().GetNewNode());
}
} else {
// If we're splitting in a child element of the paragraph, and there is no
// <br> element around it, we should insert a <br> element at the split
// point and keep splitting the paragraph after the new <br> element.
// XXX Why? We probably need to do this if we're splitting in an inline
// element which and whose parents provide some styles, we should put
// the <br> element for making a placeholder in the left paragraph for
// moving to the caret, but I think that this could be handled in fewer
// cases than this.
brElement = HTMLBRElement::FromNodeOrNull(HTMLEditUtils::GetPreviousContent(
pointToSplit, {WalkTreeOption::IgnoreNonEditableNode}, &aEditingHost));
if (!brElement || HTMLEditUtils::IsInvisibleBRElement(*brElement) ||
EditorUtils::IsPaddingBRElementForEmptyLastLine(*brElement)) {
// is there a BR after it?
brElement = HTMLBRElement::FromNodeOrNull(HTMLEditUtils::GetNextContent(
pointToSplit, {WalkTreeOption::IgnoreNonEditableNode},
&aEditingHost));
if (!brElement || HTMLEditUtils::IsInvisibleBRElement(*brElement) ||
EditorUtils::IsPaddingBRElementForEmptyLastLine(*brElement)) {
// If insertParagraph does not create a new paragraph, default to
// insertLineBreak.
if (!createNewParagraph) {
return SplitNodeResult::NotHandled(pointToSplit,
GetSplitNodeDirection());
}
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, pointToSplit);
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.propagateErr();
}
// We'll collapse `Selection` to the place suggested by
// SplitParagraphWithTransaction.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
brElement = HTMLBRElement::FromNodeOrNull(
insertBRElementResult.inspect().GetNewNode());
// We split the parent after the <br>.
pointToSplit.SetAfter(brElement);
if (NS_WARN_IF(!pointToSplit.IsSet())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
}
}
Result<SplitNodeResult, nsresult> splitParagraphResult =
SplitParagraphWithTransaction(aParentDivOrP, pointToSplit, brElement);
if (MOZ_UNLIKELY(splitParagraphResult.isErr())) {
NS_WARNING("HTMLEditor::SplitParagraphWithTransaction() failed");
return splitParagraphResult;
}
if (MOZ_UNLIKELY(!splitParagraphResult.inspect().DidSplit())) {
NS_WARNING(
"HTMLEditor::SplitParagraphWithTransaction() didn't split the "
"paragraph");
splitParagraphResult.inspect().IgnoreCaretPointSuggestion();
return Err(NS_ERROR_FAILURE);
}
MOZ_ASSERT(splitParagraphResult.inspect().Handled());
return splitParagraphResult;
}
Result<SplitNodeResult, nsresult> HTMLEditor::SplitParagraphWithTransaction(
Element& aParentDivOrP, const EditorDOMPoint& aStartOfRightNode,
HTMLBRElement* aMayBecomeVisibleBRElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
Result<EditorDOMPoint, nsresult> preparationResult =
WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement(
*this, aStartOfRightNode, aParentDivOrP);
if (MOZ_UNLIKELY(preparationResult.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement() failed");
return preparationResult.propagateErr();
}
EditorDOMPoint pointToSplit = preparationResult.unwrap();
MOZ_ASSERT(pointToSplit.IsInContentNode());
// Split the paragraph.
Result<SplitNodeResult, nsresult> splitDivOrPResult =
SplitNodeDeepWithTransaction(aParentDivOrP, pointToSplit,
SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitDivOrPResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitDivOrPResult;
}
SplitNodeResult unwrappedSplitDivOrPResult = splitDivOrPResult.unwrap();
if (MOZ_UNLIKELY(!unwrappedSplitDivOrPResult.DidSplit())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction() didn't split any nodes");
return unwrappedSplitDivOrPResult;
}
// We'll compute caret suggestion later. So the simple result is not needed.
unwrappedSplitDivOrPResult.IgnoreCaretPointSuggestion();
auto* const leftDivOrParagraphElement =
unwrappedSplitDivOrPResult.GetPreviousContentAs<Element>();
MOZ_ASSERT(leftDivOrParagraphElement,
"SplitNodeResult::GetPreviousContent() should return something if "
"DidSplit() returns true");
auto* const rightDivOrParagraphElement =
unwrappedSplitDivOrPResult.GetNextContentAs<Element>();
MOZ_ASSERT(rightDivOrParagraphElement,
"SplitNodeResult::GetNextContent() should return something if "
"DidSplit() returns true");
// Get rid of the break, if it is visible (otherwise it may be needed to
// prevent an empty p).
if (aMayBecomeVisibleBRElement &&
HTMLEditUtils::IsVisibleBRElement(*aMayBecomeVisibleBRElement)) {
nsresult rv = DeleteNodeWithTransaction(*aMayBecomeVisibleBRElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
// Remove ID attribute on the paragraph from the right node.
// MOZ_KnownLive(rightDivOrParagraphElement) because it's grabbed by
// unwrappedSplitDivOrPResult.
nsresult rv = RemoveAttributeWithTransaction(
MOZ_KnownLive(*rightDivOrParagraphElement), *nsGkAtoms::id);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::id) failed");
return Err(rv);
}
// We need to ensure to both paragraphs visible even if they are empty.
// However, padding <br> element for empty last line isn't useful in this
// case because it'll be ignored by PlaintextSerializer. Additionally,
// it'll be exposed as <br> with Element.innerHTML. Therefore, we can use
// normal <br> elements for placeholder in this case. Note that Chromium
// also behaves so.
auto InsertBRElementIfEmptyBlockElement =
[&](Element& aElement) MOZ_CAN_RUN_SCRIPT {
if (!HTMLEditUtils::IsBlockElement(aElement)) {
return NS_OK;
}
if (!HTMLEditUtils::IsEmptyNode(
aElement, {EmptyCheckOption::TreatSingleBRElementAsVisible})) {
return NS_OK;
}
// XXX: Probably, we should use
// InsertPaddingBRElementForEmptyLastLineWithTransaction here, and
// if there are some empty inline container, we should put the <br>
// into the last one.
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes,
EditorDOMPoint(&aElement, 0u));
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.unwrapErr();
}
// After this is called twice, we'll compute new caret position.
// Therefore, we don't need to update selection here.
insertBRElementResult.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
};
// MOZ_KnownLive(leftDivOrParagraphElement) because it's grabbed by
// splitDivOrResult.
rv = InsertBRElementIfEmptyBlockElement(
MOZ_KnownLive(*leftDivOrParagraphElement));
if (NS_FAILED(rv)) {
NS_WARNING(
"InsertBRElementIfEmptyBlockElement(leftDivOrParagraphElement) failed");
return Err(rv);
}
if (HTMLEditUtils::IsEmptyNode(*rightDivOrParagraphElement)) {
// If the right paragraph is empty, it might have an empty inline element
// (which may contain other empty inline containers) and optionally a <br>
// element which may not be in the deepest inline element.
const RefPtr<Element> deepestInlineContainerElement =
[](const Element& aBlockElement) {
Element* result = nullptr;
for (Element* maybeDeepestInlineContainer =
Element::FromNodeOrNull(aBlockElement.GetFirstChild());
maybeDeepestInlineContainer &&
HTMLEditUtils::IsInlineElement(*maybeDeepestInlineContainer) &&
HTMLEditUtils::IsContainerNode(*maybeDeepestInlineContainer);
maybeDeepestInlineContainer =
maybeDeepestInlineContainer->GetFirstElementChild()) {
result = maybeDeepestInlineContainer;
}
return result;
}(*rightDivOrParagraphElement);
if (deepestInlineContainerElement) {
RefPtr<HTMLBRElement> brElement =
HTMLEditUtils::GetFirstBRElement(*rightDivOrParagraphElement);
// If there is a <br> element and it is in the deepest inline container,
// we need to do nothing anymore. Let's suggest caret position as at the
// <br>.
if (brElement &&
brElement->GetParentNode() == deepestInlineContainerElement) {
brElement->SetFlags(NS_PADDING_FOR_EMPTY_LAST_LINE);
return SplitNodeResult(std::move(unwrappedSplitDivOrPResult),
EditorDOMPoint(brElement));
}
// Otherwise, we should put a padding <br> element into the deepest inline
// container and then, existing <br> element (if there is) becomes
// unnecessary.
if (brElement) {
nsresult rv = DeleteNodeWithTransaction(*brElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
EditorDOMPoint::AtEndOf(deepestInlineContainerElement));
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertPaddingBRElementForEmptyLastLineWithTransaction() failed");
return insertPaddingBRElementResult.propagateErr();
}
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
return SplitNodeResult(
std::move(unwrappedSplitDivOrPResult),
EditorDOMPoint(insertPaddingBRElementResult.inspect().GetNewNode()));
}
// If there is no inline container elements, we just need to make the
// right paragraph visible.
nsresult rv = InsertBRElementIfEmptyBlockElement(
MOZ_KnownLive(*rightDivOrParagraphElement));
if (NS_FAILED(rv)) {
NS_WARNING(
"InsertBRElementIfEmptyBlockElement(rightDivOrParagraphElement) "
"failed");
return Err(rv);
}
}
// Let's put caret at start of the first leaf container.
nsIContent* child = HTMLEditUtils::GetFirstLeafContent(
*rightDivOrParagraphElement, {LeafNodeType::LeafNodeOrChildBlock});
if (MOZ_UNLIKELY(!child)) {
return SplitNodeResult(std::move(unwrappedSplitDivOrPResult),
EditorDOMPoint(rightDivOrParagraphElement, 0u));
}
return child->IsText() || HTMLEditUtils::IsContainerNode(*child)
? SplitNodeResult(std::move(unwrappedSplitDivOrPResult),
EditorDOMPoint(child, 0u))
: SplitNodeResult(std::move(unwrappedSplitDivOrPResult),
EditorDOMPoint(child));
}
Result<InsertParagraphResult, nsresult>
HTMLEditor::HandleInsertParagraphInListItemElement(
Element& aListItemElement, const EditorDOMPoint& aPointToSplit,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(HTMLEditUtils::IsListItem(&aListItemElement));
// If aListItemElement is empty, then we want to outdent its content.
if (&aEditingHost != aListItemElement.GetParentElement() &&
HTMLEditUtils::IsEmptyBlockElement(aListItemElement, {})) {
RefPtr<Element> leftListElement = aListItemElement.GetParentElement();
// If the given list item element is not the last list item element of
// its parent nor not followed by sub list elements, split the parent
// before it.
if (!HTMLEditUtils::IsLastChild(aListItemElement,
{WalkTreeOption::IgnoreNonEditableNode})) {
Result<SplitNodeResult, nsresult> splitListItemParentResult =
SplitNodeWithTransaction(EditorDOMPoint(&aListItemElement));
if (MOZ_UNLIKELY(splitListItemParentResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitListItemParentResult.propagateErr();
}
SplitNodeResult unwrappedSplitListItemParentResult =
splitListItemParentResult.unwrap();
if (MOZ_UNLIKELY(!unwrappedSplitListItemParentResult.DidSplit())) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't split the parent of "
"aListItemElement");
MOZ_ASSERT(
!unwrappedSplitListItemParentResult.HasCaretPointSuggestion());
return Err(NS_ERROR_FAILURE);
}
unwrappedSplitListItemParentResult.IgnoreCaretPointSuggestion();
leftListElement =
unwrappedSplitListItemParentResult.GetPreviousContentAs<Element>();
MOZ_DIAGNOSTIC_ASSERT(leftListElement);
}
auto afterLeftListElement = EditorDOMPoint::After(leftListElement);
if (MOZ_UNLIKELY(!afterLeftListElement.IsSet())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If aListItemElement is in an invalid sub-list element, move it into
// the grand parent list element in order to outdent.
if (HTMLEditUtils::IsAnyListElement(afterLeftListElement.GetContainer())) {
Result<MoveNodeResult, nsresult> moveListItemElementResult =
MoveNodeWithTransaction(aListItemElement, afterLeftListElement);
if (MOZ_UNLIKELY(moveListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveListItemElementResult.propagateErr();
}
moveListItemElementResult.inspect().IgnoreCaretPointSuggestion();
return InsertParagraphResult(&aListItemElement,
EditorDOMPoint(&aListItemElement, 0u));
}
// Otherwise, replace the empty aListItemElement with a new paragraph.
nsresult rv = DeleteNodeWithTransaction(aListItemElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
nsStaticAtom& newParagraphTagName =
&DefaultParagraphSeparatorTagName() == nsGkAtoms::br
? *nsGkAtoms::p
: DefaultParagraphSeparatorTagName();
// MOZ_KnownLive(newParagraphTagName) because it's available until shutdown.
Result<CreateElementResult, nsresult> createNewParagraphElementResult =
CreateAndInsertElement(
WithTransaction::Yes, MOZ_KnownLive(newParagraphTagName),
afterLeftListElement, HTMLEditor::InsertNewBRElement);
if (MOZ_UNLIKELY(createNewParagraphElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewParagraphElementResult.propagateErr();
}
createNewParagraphElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(createNewParagraphElementResult.inspect().GetNewNode());
EditorDOMPoint pointToPutCaret(
createNewParagraphElementResult.inspect().GetNewNode(), 0u);
return InsertParagraphResult(
createNewParagraphElementResult.inspect().GetNewNode(),
std::move(pointToPutCaret));
}
// If aListItemElement has some content or aListItemElement is empty but it's
// a child of editing host, we want a new list item at the same list level.
// First, sort out white-spaces.
Result<EditorDOMPoint, nsresult> preparationResult =
WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement(
*this, aPointToSplit, aListItemElement);
if (preparationResult.isErr()) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement() failed");
return Err(preparationResult.unwrapErr());
}
EditorDOMPoint pointToSplit = preparationResult.unwrap();
MOZ_ASSERT(pointToSplit.IsInContentNode());
// Now split the list item.
Result<SplitNodeResult, nsresult> splitListItemResult =
SplitNodeDeepWithTransaction(aListItemElement, pointToSplit,
SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitListItemResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitListItemResult.propagateErr();
}
SplitNodeResult unwrappedSplitListItemElement = splitListItemResult.unwrap();
unwrappedSplitListItemElement.IgnoreCaretPointSuggestion();
if (MOZ_UNLIKELY(!aListItemElement.GetParent())) {
NS_WARNING("Somebody disconnected the target listitem from the parent");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If aListItemElement is not replaced, we should not do anything anymore.
if (MOZ_UNLIKELY(!unwrappedSplitListItemElement.DidSplit()) ||
NS_WARN_IF(!unwrappedSplitListItemElement.GetNewContentAs<Element>()) ||
NS_WARN_IF(
!unwrappedSplitListItemElement.GetOriginalContentAs<Element>())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() didn't split");
return Err(NS_ERROR_FAILURE);
}
// FYI: They are grabbed by unwrappedSplitListItemElement so that they are
// known live
// things.
auto& leftListItemElement =
*unwrappedSplitListItemElement.GetPreviousContentAs<Element>();
auto& rightListItemElement =
*unwrappedSplitListItemElement.GetNextContentAs<Element>();
// Hack: until I can change the damaged doc range code back to being
// extra-inclusive, I have to manually detect certain list items that may be
// left empty.
if (HTMLEditUtils::IsEmptyNode(
leftListItemElement,
{EmptyCheckOption::TreatSingleBRElementAsVisible})) {
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
EditorDOMPoint(&leftListItemElement, 0u));
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction("
") failed");
return insertPaddingBRElementResult.propagateErr();
}
// We're returning a candidate point to put caret so that we don't need to
// update now.
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
return InsertParagraphResult(&rightListItemElement,
EditorDOMPoint(&rightListItemElement, 0u));
}
if (HTMLEditUtils::IsEmptyNode(rightListItemElement)) {
// If aListItemElement is a <dd> or a <dt> and the right list item is empty
// or a direct child of the editing host, replace it a new list item element
// whose type is the other one.
if (aListItemElement.IsAnyOfHTMLElements(nsGkAtoms::dd, nsGkAtoms::dt)) {
nsStaticAtom& nextDefinitionListItemTagName =
aListItemElement.IsHTMLElement(nsGkAtoms::dt) ? *nsGkAtoms::dd
: *nsGkAtoms::dt;
// MOZ_KnownLive(nextDefinitionListItemTagName) because it's available
// until shutdown.
Result<CreateElementResult, nsresult> createNewListItemElementResult =
CreateAndInsertElement(WithTransaction::Yes,
MOZ_KnownLive(nextDefinitionListItemTagName),
EditorDOMPoint::After(rightListItemElement));
if (MOZ_UNLIKELY(createNewListItemElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewListItemElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewListItemElementResult =
createNewListItemElementResult.unwrap();
unwrappedCreateNewListItemElementResult.IgnoreCaretPointSuggestion();
RefPtr<Element> newListItemElement =
unwrappedCreateNewListItemElementResult.UnwrapNewNode();
MOZ_ASSERT(newListItemElement);
// MOZ_KnownLive(rightListItemElement) because it's grabbed by
// unwrappedSplitListItemElement.
nsresult rv =
DeleteNodeWithTransaction(MOZ_KnownLive(rightListItemElement));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
EditorDOMPoint pointToPutCaret(newListItemElement, 0u);
return InsertParagraphResult(std::move(newListItemElement),
std::move(pointToPutCaret));
}
// If aListItemElement is a <li> and the right list item becomes empty or a
// direct child of the editing host, copy all inline elements affecting to
// the style at end of the left list item element to the right list item
// element.
// MOZ_KnownLive(leftListItemElement) and
// MOZ_KnownLive(rightListItemElement) because they are grabbed by
// unwrappedSplitListItemElement.
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
CopyLastEditableChildStylesWithTransaction(
MOZ_KnownLive(leftListItemElement),
MOZ_KnownLive(rightListItemElement), aEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::CopyLastEditableChildStylesWithTransaction() failed");
return pointToPutCaretOrError.propagateErr();
}
return InsertParagraphResult(&rightListItemElement,
pointToPutCaretOrError.unwrap());
}
// If the right list item element is not empty, we need to consider where to
// put caret in it. If it has non-container inline elements, <br> or <hr>, at
// the element is proper position.
WSScanResult forwardScanFromStartOfListItemResult =
WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(
&aEditingHost, EditorRawDOMPoint(&rightListItemElement, 0u));
if (MOZ_UNLIKELY(forwardScanFromStartOfListItemResult.Failed())) {
NS_WARNING("WSRunScanner::ScanNextVisibleNodeOrBlockBoundary() failed");
return Err(NS_ERROR_FAILURE);
}
if (forwardScanFromStartOfListItemResult.ReachedSpecialContent() ||
forwardScanFromStartOfListItemResult.ReachedBRElement() ||
forwardScanFromStartOfListItemResult.ReachedHRElement()) {
auto atFoundElement =
forwardScanFromStartOfListItemResult.PointAtContent<EditorDOMPoint>();
if (NS_WARN_IF(!atFoundElement.IsSetAndValid())) {
return Err(NS_ERROR_FAILURE);
}
return InsertParagraphResult(&rightListItemElement,
std::move(atFoundElement));
}
// If we reached a block boundary (end of the list item or a child block),
// let's put deepest start of the list item or the child block.
if (forwardScanFromStartOfListItemResult.ReachedBlockBoundary()) {
return InsertParagraphResult(
&rightListItemElement,
HTMLEditUtils::GetDeepestEditableStartPointOf<EditorDOMPoint>(
forwardScanFromStartOfListItemResult.GetContent()
? *forwardScanFromStartOfListItemResult.GetContent()
: rightListItemElement));
}
// Otherwise, return the point at first visible thing.
// XXX This may be not meaningful position if it reached block element
// in aListItemElement.
return InsertParagraphResult(
&rightListItemElement,
forwardScanFromStartOfListItemResult.Point<EditorDOMPoint>());
}
Result<CreateElementResult, nsresult>
HTMLEditor::WrapContentsInBlockquoteElementsWithTransaction(
const nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents,
const Element& aEditingHost) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
// The idea here is to put the nodes into a minimal number of blockquotes.
// When the user blockquotes something, they expect one blockquote. That
// may not be possible (for instance, if they have two table cells selected,
// you need two blockquotes inside the cells).
RefPtr<Element> curBlock, blockElementToPutCaret;
nsCOMPtr<nsINode> prevParent;
EditorDOMPoint pointToPutCaret;
for (auto& content : aArrayOfContents) {
// If the node is a table element or list item, dive inside
if (HTMLEditUtils::IsAnyTableElementButNotTable(content) ||
HTMLEditUtils::IsListItem(content)) {
// Forget any previous block
curBlock = nullptr;
// Recursion time
AutoTArray<OwningNonNull<nsIContent>, 24> childContents;
HTMLEditUtils::CollectAllChildren(*content, childContents);
Result<CreateElementResult, nsresult>
wrapChildrenInAnotherBlockquoteResult =
WrapContentsInBlockquoteElementsWithTransaction(childContents,
aEditingHost);
if (MOZ_UNLIKELY(wrapChildrenInAnotherBlockquoteResult.isErr())) {
NS_WARNING(
"HTMLEditor::WrapContentsInBlockquoteElementsWithTransaction() "
"failed");
return wrapChildrenInAnotherBlockquoteResult;
}
CreateElementResult unwrappedWrapChildrenInAnotherBlockquoteResult =
wrapChildrenInAnotherBlockquoteResult.unwrap();
unwrappedWrapChildrenInAnotherBlockquoteResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
if (unwrappedWrapChildrenInAnotherBlockquoteResult.GetNewNode()) {
blockElementToPutCaret =
unwrappedWrapChildrenInAnotherBlockquoteResult.UnwrapNewNode();
}
}
// If the node has different parent than previous node, further nodes in a
// new parent
if (prevParent) {
if (prevParent != content->GetParentNode()) {
// Forget any previous blockquote node we were using
curBlock = nullptr;
prevParent = content->GetParentNode();
}
} else {
prevParent = content->GetParentNode();
}
// If no curBlock, make one
if (!curBlock) {
Result<CreateElementResult, nsresult> createNewBlockquoteElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::blockquote, EditorDOMPoint(content),
BRElementNextToSplitPoint::Keep, aEditingHost);
if (MOZ_UNLIKELY(createNewBlockquoteElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::blockquote) failed");
return createNewBlockquoteElementResult;
}
CreateElementResult unwrappedCreateNewBlockquoteElementResult =
createNewBlockquoteElementResult.unwrap();
unwrappedCreateNewBlockquoteElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
MOZ_ASSERT(unwrappedCreateNewBlockquoteElementResult.GetNewNode());
blockElementToPutCaret =
unwrappedCreateNewBlockquoteElementResult.GetNewNode();
curBlock = unwrappedCreateNewBlockquoteElementResult.UnwrapNewNode();
}
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to/ keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content), *curBlock);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
unwrappedMoveNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
return blockElementToPutCaret
? CreateElementResult(std::move(blockElementToPutCaret),
std::move(pointToPutCaret))
: CreateElementResult::NotHandled(std::move(pointToPutCaret));
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::RemoveBlockContainerElementsWithTransaction(
const nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Intent of this routine is to be used for converting to/from headers,
// paragraphs, pre, and address. Those blocks that pretty much just contain
// inline things...
RefPtr<Element> blockElement;
nsCOMPtr<nsIContent> firstContent, lastContent;
EditorDOMPoint pointToPutCaret;
for (auto& content : aArrayOfContents) {
// If curNode is an <address>, <p>, <hn>, or <pre>, remove it.
if (HTMLEditUtils::IsFormatNode(content)) {
// Process any partial progress saved
if (blockElement) {
Result<SplitRangeOffFromNodeResult, nsresult> unwrapBlockElementResult =
RemoveBlockContainerElementWithTransactionBetween(
*blockElement, *firstContent, *lastContent);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
"failed");
return unwrapBlockElementResult.propagateErr();
}
unwrapBlockElementResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
firstContent = lastContent = blockElement = nullptr;
}
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
continue;
}
// Remove current block
Result<EditorDOMPoint, nsresult> unwrapFormatBlockResult =
RemoveBlockContainerWithTransaction(
MOZ_KnownLive(*content->AsElement()));
if (MOZ_UNLIKELY(unwrapFormatBlockResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapFormatBlockResult;
}
if (unwrapFormatBlockResult.inspect().IsSet()) {
pointToPutCaret = unwrapFormatBlockResult.unwrap();
}
continue;
}
// XXX How about, <th>, <thead>, <tfoot>, <dt>, <dl>?
if (content->IsAnyOfHTMLElements(
nsGkAtoms::table, nsGkAtoms::tr, nsGkAtoms::tbody, nsGkAtoms::td,
nsGkAtoms::li, nsGkAtoms::blockquote, nsGkAtoms::div) ||
HTMLEditUtils::IsAnyListElement(content)) {
// Process any partial progress saved
if (blockElement) {
Result<SplitRangeOffFromNodeResult, nsresult> unwrapBlockElementResult =
RemoveBlockContainerElementWithTransactionBetween(
*blockElement, *firstContent, *lastContent);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
"failed");
return unwrapBlockElementResult.propagateErr();
}
unwrapBlockElementResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
firstContent = lastContent = blockElement = nullptr;
}
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
continue;
}
// Recursion time
AutoTArray<OwningNonNull<nsIContent>, 24> childContents;
HTMLEditUtils::CollectAllChildren(*content, childContents);
Result<EditorDOMPoint, nsresult> removeBlockContainerElementsResult =
RemoveBlockContainerElementsWithTransaction(childContents);
if (MOZ_UNLIKELY(removeBlockContainerElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementsWithTransaction() failed");
return removeBlockContainerElementsResult;
}
if (removeBlockContainerElementsResult.inspect().IsSet()) {
pointToPutCaret = removeBlockContainerElementsResult.unwrap();
}
continue;
}
if (HTMLEditUtils::IsInlineElement(content)) {
if (blockElement) {
// If so, is this node a descendant?
if (EditorUtils::IsDescendantOf(*content, *blockElement)) {
// Then we don't need to do anything different for this node
lastContent = content;
continue;
}
// Otherwise, we have progressed beyond end of blockElement, so let's
// handle it now. We need to remove the portion of blockElement that
// contains [firstContent - lastContent].
Result<SplitRangeOffFromNodeResult, nsresult> unwrapBlockElementResult =
RemoveBlockContainerElementWithTransactionBetween(
*blockElement, *firstContent, *lastContent);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
"failed");
return unwrapBlockElementResult.propagateErr();
}
unwrapBlockElementResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
firstContent = lastContent = blockElement = nullptr;
// Fall out and handle content
}
blockElement = HTMLEditUtils::GetAncestorElement(
content, HTMLEditUtils::ClosestEditableBlockElement);
if (!blockElement || !HTMLEditUtils::IsFormatNode(blockElement) ||
!HTMLEditUtils::IsRemovableNode(*blockElement)) {
// Not a block kind that we care about.
blockElement = nullptr;
} else {
firstContent = lastContent = content;
}
continue;
}
if (blockElement) {
// Some node that is already sans block style. Skip over it and process
// any partial progress saved.
Result<SplitRangeOffFromNodeResult, nsresult> unwrapBlockElementResult =
RemoveBlockContainerElementWithTransactionBetween(
*blockElement, *firstContent, *lastContent);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
"failed");
return unwrapBlockElementResult.propagateErr();
}
unwrapBlockElementResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
firstContent = lastContent = blockElement = nullptr;
continue;
}
}
// Process any partial progress saved
if (blockElement) {
Result<SplitRangeOffFromNodeResult, nsresult> unwrapBlockElementResult =
RemoveBlockContainerElementWithTransactionBetween(
*blockElement, *firstContent, *lastContent);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
"failed");
return unwrapBlockElementResult.propagateErr();
}
unwrapBlockElementResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
firstContent = lastContent = blockElement = nullptr;
}
return pointToPutCaret;
}
Result<CreateElementResult, nsresult>
HTMLEditor::CreateOrChangeBlockContainerElement(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents, nsAtom& aBlockTag,
const Element& aEditingHost) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
// Intent of this routine is to be used for converting to/from headers,
// paragraphs, pre, and address. Those blocks that pretty much just contain
// inline things...
RefPtr<Element> newBlock, curBlock, blockElementToPutCaret;
EditorDOMPoint pointToPutCaret;
for (auto& content : aArrayOfContents) {
EditorDOMPoint atContent(content);
if (NS_WARN_IF(!atContent.IsInContentNode())) {
// If given node has been removed from the document, let's ignore it
// since the following code may need its parent replace it with new
// block.
curBlock = nullptr;
newBlock = nullptr;
continue;
}
// Is it already the right kind of block, or an uneditable block?
if (content->IsHTMLElement(&aBlockTag) ||
(!EditorUtils::IsEditableContent(content, EditorType::HTML) &&
HTMLEditUtils::IsBlockElement(content))) {
// Forget any previous block used for previous inline nodes
curBlock = nullptr;
// Do nothing to this block
continue;
}
// If content is a address, p, header, address, or pre, replace it with a
// new block of correct type.
// XXX: pre can't hold everything the others can
if (HTMLEditUtils::IsMozDiv(content) ||
HTMLEditUtils::IsFormatNode(content)) {
// Forget any previous block used for previous inline nodes
curBlock = nullptr;
Result<CreateElementResult, nsresult> replaceWithNewBlockElementResult =
ReplaceContainerAndCloneAttributesWithTransaction(
MOZ_KnownLive(*content->AsElement()), aBlockTag);
if (MOZ_UNLIKELY(replaceWithNewBlockElementResult.isErr())) {
NS_WARNING(
"EditorBase::ReplaceContainerAndCloneAttributesWithTransaction() "
"failed");
return replaceWithNewBlockElementResult;
}
CreateElementResult unwrappedReplaceWithNewBlockElementResult =
replaceWithNewBlockElementResult.unwrap();
// If the new block element was moved to different element or removed by
// the web app via mutation event listener, we should stop handling this
// action since we cannot handle each of a lot of edge cases.
if (NS_WARN_IF(unwrappedReplaceWithNewBlockElementResult.GetNewNode()
->GetParentNode() != atContent.GetContainer())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
unwrappedReplaceWithNewBlockElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
newBlock = unwrappedReplaceWithNewBlockElementResult.UnwrapNewNode();
continue;
}
if (HTMLEditUtils::IsTable(content) ||
HTMLEditUtils::IsAnyListElement(content) ||
content->IsAnyOfHTMLElements(nsGkAtoms::tbody, nsGkAtoms::tr,
nsGkAtoms::td, nsGkAtoms::li,
nsGkAtoms::blockquote, nsGkAtoms::div)) {
// Forget any previous block used for previous inline nodes
curBlock = nullptr;
// Recursion time
AutoTArray<OwningNonNull<nsIContent>, 24> childContents;
HTMLEditUtils::CollectAllChildren(*content, childContents);
if (!childContents.IsEmpty()) {
Result<CreateElementResult, nsresult> wrapChildrenInBlockElementResult =
CreateOrChangeBlockContainerElement(childContents, aBlockTag,
aEditingHost);
if (MOZ_UNLIKELY(wrapChildrenInBlockElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateOrChangeBlockContainerElement() failed");
return wrapChildrenInBlockElementResult;
}
CreateElementResult unwrappedWrapChildrenInBlockElementResult =
wrapChildrenInBlockElementResult.unwrap();
unwrappedWrapChildrenInBlockElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
if (unwrappedWrapChildrenInBlockElementResult.GetNewNode()) {
blockElementToPutCaret =
unwrappedWrapChildrenInBlockElementResult.UnwrapNewNode();
}
continue;
}
// Make sure we can put a block here
Result<CreateElementResult, nsresult> createNewBlockElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
aBlockTag, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewBlockElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTransaction(%s) failed",
nsAtomCString(&aBlockTag).get())
.get());
return createNewBlockElementResult;
}
CreateElementResult unwrappedCreateNewBlockElementResult =
createNewBlockElementResult.unwrap();
unwrappedCreateNewBlockElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
MOZ_ASSERT(unwrappedCreateNewBlockElementResult.GetNewNode());
blockElementToPutCaret =
unwrappedCreateNewBlockElementResult.UnwrapNewNode();
continue;
}
if (content->IsHTMLElement(nsGkAtoms::br)) {
// If the node is a break, we honor it by putting further nodes in a new
// parent
if (curBlock) {
// Forget any previous block used for previous inline nodes
curBlock = nullptr;
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it
// alive.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*content));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
continue;
}
// The break is the first (or even only) node we encountered. Create a
// block for it.
Result<CreateElementResult, nsresult> createNewBlockElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
aBlockTag, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewBlockElementResult.isErr())) {
NS_WARNING(
nsPrintfCString(
"HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTransaction(%s) failed",
nsAtomCString(&aBlockTag).get())
.get());
return createNewBlockElementResult;
}
CreateElementResult unwrappedCreateNewBlockElementResult =
createNewBlockElementResult.unwrap();
unwrappedCreateNewBlockElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
RefPtr<Element> newBlockElement =
unwrappedCreateNewBlockElementResult.UnwrapNewNode();
MOZ_ASSERT(newBlockElement);
blockElementToPutCaret = newBlockElement;
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it
// alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content),
*newBlockElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
unwrappedMoveNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
curBlock = std::move(newBlockElement);
continue;
}
if (HTMLEditUtils::IsInlineElement(content)) {
// If content is inline, pull it into curBlock. Note: it's assumed that
// consecutive inline nodes in aNodeArray are actually members of the
// same block parent. This happens to be true now as a side effect of
// how aNodeArray is contructed, but some additional logic should be
// added here if that should change
//
// If content is a non editable, drop it if we are going to <pre>.
if (&aBlockTag == nsGkAtoms::pre &&
!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
// Do nothing to this block
continue;
}
// If no curBlock, make one
if (!curBlock) {
Result<CreateElementResult, nsresult> createNewBlockElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
aBlockTag, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewBlockElementResult.isErr())) {
NS_WARNING(nsPrintfCString("HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTr"
"ansaction(%s) failed",
nsAtomCString(&aBlockTag).get())
.get());
return createNewBlockElementResult;
}
CreateElementResult unwrappedCreateNewBlockElementResult =
createNewBlockElementResult.unwrap();
unwrappedCreateNewBlockElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
MOZ_ASSERT(unwrappedCreateNewBlockElementResult.GetNewNode());
blockElementToPutCaret =
unwrappedCreateNewBlockElementResult.GetNewNode();
curBlock = unwrappedCreateNewBlockElementResult.UnwrapNewNode();
// Update container of content.
atContent.Set(content);
}
if (NS_WARN_IF(!atContent.IsSet())) {
// This is possible due to mutation events, let's not assert
return Err(NS_ERROR_UNEXPECTED);
}
// XXX If content is a br, replace it with a return if going to <pre>
// This is a continuation of some inline nodes that belong together in
// the same block item. Use curBlock.
//
// MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it
// alive. We could try to make that a rvalue ref and create a const array
// on the stack here, but callers are passing in auto arrays, and we don't
// want to introduce copies..
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content), *curBlock);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
unwrappedMoveNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
}
return blockElementToPutCaret
? CreateElementResult(std::move(blockElementToPutCaret),
std::move(pointToPutCaret))
: CreateElementResult::NotHandled(std::move(pointToPutCaret));
}
Result<SplitNodeResult, nsresult>
HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction(
nsAtom& aTag, const EditorDOMPoint& aStartOfDeepestRightNode,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aEditingHost.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (NS_WARN_IF(!aStartOfDeepestRightNode.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
MOZ_ASSERT(aStartOfDeepestRightNode.IsSetAndValid());
// The point must be descendant of editing host.
// XXX Isn't it a valid case if it points a direct child of aEditingHost?
if (aStartOfDeepestRightNode.GetContainer() != &aEditingHost &&
!EditorUtils::IsDescendantOf(*aStartOfDeepestRightNode.GetContainer(),
aEditingHost)) {
NS_WARNING("aStartOfDeepestRightNode was not in editing host");
return Err(NS_ERROR_INVALID_ARG);
}
// Look for a node that can legally contain the tag.
EditorDOMPoint pointToInsert(aStartOfDeepestRightNode);
for (; pointToInsert.IsSet();
pointToInsert.Set(pointToInsert.GetContainer())) {
// We cannot split active editing host and its ancestor. So, there is
// no element to contain the specified element.
if (pointToInsert.GetChild() == &aEditingHost) {
NS_WARNING(
"HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction() reached "
"editing host");
return Err(NS_ERROR_FAILURE);
}
if (HTMLEditUtils::CanNodeContain(*pointToInsert.GetContainer(), aTag)) {
// Found an ancestor node which can contain the element.
break;
}
}
// If we got lost the editing host, we can do nothing.
if (NS_WARN_IF(!pointToInsert.IsSet())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If the point itself can contain the tag, we don't need to split any
// ancestor nodes. In this case, we should return the given split point
// as is.
if (pointToInsert.GetContainer() == aStartOfDeepestRightNode.GetContainer()) {
return SplitNodeResult::NotHandled(aStartOfDeepestRightNode,
GetSplitNodeDirection());
}
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeDeepWithTransaction(MOZ_KnownLive(*pointToInsert.GetChild()),
aStartOfDeepestRightNode,
SplitAtEdges::eAllowToCreateEmptyContainer);
NS_WARNING_ASSERTION(splitNodeResult.isOk(),
"HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::"
"eAllowToCreateEmptyContainer) failed");
return splitNodeResult;
}
Result<CreateElementResult, nsresult>
HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction(
nsAtom& aTagName, const EditorDOMPoint& aPointToInsert,
BRElementNextToSplitPoint aBRElementNextToSplitPoint,
const Element& aEditingHost,
const InitializeInsertingElement& aInitializer) {
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
const nsCOMPtr<nsIContent> childAtPointToInsert = aPointToInsert.GetChild();
Result<SplitNodeResult, nsresult> splitNodeResult =
MaybeSplitAncestorsForInsertWithTransaction(aTagName, aPointToInsert,
aEditingHost);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction() failed");
return splitNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
DebugOnly<bool> wasCaretPositionSuggestedAtSplit =
unwrappedSplitNodeResult.HasCaretPointSuggestion();
// We'll update selection below, and nobody touches selection until then.
// Therefore, we don't need to touch selection here.
unwrappedSplitNodeResult.IgnoreCaretPointSuggestion();
// If current handling node has been moved from the container by a
// mutation event listener when we need to do something more for it,
// we should stop handling this action since we cannot handle each
// edge case.
if (childAtPointToInsert &&
NS_WARN_IF(!childAtPointToInsert->IsInclusiveDescendantOf(
unwrappedSplitNodeResult.DidSplit()
? unwrappedSplitNodeResult.GetNextContent()
: aPointToInsert.GetContainer()))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
auto splitPoint = unwrappedSplitNodeResult.AtSplitPoint<EditorDOMPoint>();
if (aBRElementNextToSplitPoint == BRElementNextToSplitPoint::Delete) {
// Consume a trailing br, if any. This is to keep an alignment from
// creating extra lines, if possible.
if (nsCOMPtr<nsIContent> maybeBRContent = HTMLEditUtils::GetNextContent(
splitPoint,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
&aEditingHost)) {
if (maybeBRContent->IsHTMLElement(nsGkAtoms::br) &&
splitPoint.GetChild()) {
// Making use of html structure... if next node after where we are
// putting our div is not a block, then the br we found is in same
// block we are, so it's safe to consume it.
if (nsIContent* nextEditableSibling = HTMLEditUtils::GetNextSibling(
*splitPoint.GetChild(),
{WalkTreeOption::IgnoreNonEditableNode})) {
if (!HTMLEditUtils::IsBlockElement(*nextEditableSibling)) {
AutoEditorDOMPointChildInvalidator lockOffset(splitPoint);
nsresult rv = DeleteNodeWithTransaction(*maybeBRContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
}
}
}
}
Result<CreateElementResult, nsresult> createNewElementResult =
CreateAndInsertElement(WithTransaction::Yes, aTagName, splitPoint,
aInitializer);
if (MOZ_UNLIKELY(createNewElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewElementResult;
}
MOZ_ASSERT_IF(wasCaretPositionSuggestedAtSplit,
createNewElementResult.inspect().HasCaretPointSuggestion());
MOZ_ASSERT(createNewElementResult.inspect().GetNewNode());
// If the new block element was moved to different element or removed by
// the web app via mutation event listener, we should stop handling this
// action since we cannot handle each of a lot of edge cases.
if (NS_WARN_IF(
createNewElementResult.inspect().GetNewNode()->GetParentNode() !=
splitPoint.GetContainer())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return createNewElementResult;
}
nsresult HTMLEditor::JoinNearestEditableNodesWithTransaction(
nsIContent& aNodeLeft, nsIContent& aNodeRight,
EditorDOMPoint* aNewFirstChildOfRightNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aNewFirstChildOfRightNode);
// Caller responsible for left and right node being the same type
if (NS_WARN_IF(!aNodeLeft.GetParentNode())) {
return NS_ERROR_FAILURE;
}
// If they don't have the same parent, first move the right node to after
// the left one
if (aNodeLeft.GetParentNode() != aNodeRight.GetParentNode()) {
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeWithTransaction(aNodeRight, EditorDOMPoint(&aNodeLeft));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveNodeResult.unwrapErr();
}
nsresult rv = moveNodeResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
}
// Separate join rules for differing blocks
if (HTMLEditUtils::IsAnyListElement(&aNodeLeft) || aNodeLeft.IsText()) {
// For lists, merge shallow (wouldn't want to combine list items)
Result<JoinNodesResult, nsresult> joinNodesResult =
JoinNodesWithTransaction(aNodeLeft, aNodeRight);
if (MOZ_UNLIKELY(joinNodesResult.isErr())) {
NS_WARNING("HTMLEditor::JoinNodesWithTransaction failed");
return joinNodesResult.unwrapErr();
}
*aNewFirstChildOfRightNode =
joinNodesResult.inspect().AtJoinedPoint<EditorDOMPoint>();
return NS_OK;
}
// Remember the last left child, and first right child
nsCOMPtr<nsIContent> lastEditableChildOfLeftContent =
HTMLEditUtils::GetLastChild(aNodeLeft,
{WalkTreeOption::IgnoreNonEditableNode});
if (MOZ_UNLIKELY(NS_WARN_IF(!lastEditableChildOfLeftContent))) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIContent> firstEditableChildOfRightContent =
HTMLEditUtils::GetFirstChild(aNodeRight,
{WalkTreeOption::IgnoreNonEditableNode});
if (NS_WARN_IF(!firstEditableChildOfRightContent)) {
return NS_ERROR_FAILURE;
}
// For list items, divs, etc., merge smart
Result<JoinNodesResult, nsresult> joinNodesResult =
JoinNodesWithTransaction(aNodeLeft, aNodeRight);
if (MOZ_UNLIKELY(joinNodesResult.isErr())) {
NS_WARNING("HTMLEditor::JoinNodesWithTransaction() failed");
return joinNodesResult.unwrapErr();
}
if ((lastEditableChildOfLeftContent->IsText() ||
lastEditableChildOfLeftContent->IsElement()) &&
HTMLEditUtils::CanContentsBeJoined(*lastEditableChildOfLeftContent,
*firstEditableChildOfRightContent)) {
nsresult rv = JoinNearestEditableNodesWithTransaction(
*lastEditableChildOfLeftContent, *firstEditableChildOfRightContent,
aNewFirstChildOfRightNode);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::JoinNearestEditableNodesWithTransaction() failed");
return rv;
}
*aNewFirstChildOfRightNode =
joinNodesResult.inspect().AtJoinedPoint<EditorDOMPoint>();
return NS_OK;
}
Element* HTMLEditor::GetMostDistantAncestorMailCiteElement(
const nsINode& aNode) const {
Element* mailCiteElement = nullptr;
const bool isPlaintextEditor = IsInPlaintextMode();
for (Element* element : aNode.InclusiveAncestorsOfType<Element>()) {
if ((isPlaintextEditor && element->IsHTMLElement(nsGkAtoms::pre)) ||
HTMLEditUtils::IsMailCite(*element)) {
mailCiteElement = element;
continue;
}
if (element->IsHTMLElement(nsGkAtoms::body)) {
break;
}
}
return mailCiteElement;
}
nsresult HTMLEditor::CacheInlineStyles(Element& Element) {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
nsresult rv = GetInlineStyles(
Element, *TopLevelEditSubActionDataRef().mCachedPendingStyles);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetInlineStyles() failed");
return rv;
}
nsresult HTMLEditor::GetInlineStyles(
Element& aElement, AutoPendingStyleCacheArray& aPendingStyleCacheArray) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPendingStyleCacheArray.IsEmpty());
if (!IsCSSEnabled()) {
// In the HTML styling mode, we should preserve the order of inline styles
// specified with HTML elements, then, we can keep same order as original
// one when we create new elements to apply the styles at new place.
// XXX Currently, we don't preserve all inline parents, therefore, we cannot
// restore all inline elements as-is. Perhaps, we should store all
// inline elements with more details (e.g., all attributes), and store
// same elements. For example, web apps may give style as:
// em {
// font-style: italic;
// }
// em em {
// font-style: normal;
// font-weight: bold;
// }
// but we cannot restore the style as-is.
nsString value;
const bool givenElementIsEditable =
HTMLEditUtils::IsSimplyEditableNode(aElement);
auto NeedToAppend = [&](nsStaticAtom& aTagName, nsStaticAtom* aAttribute) {
if (mPendingStylesToApplyToNewContent->GetStyleState(
aTagName, aAttribute) != PendingStyleState::NotUpdated) {
return false; // The style has already been changed.
}
if (aPendingStyleCacheArray.Contains(aTagName, aAttribute)) {
return false; // Already preserved
}
return true;
};
for (Element* const inclusiveAncestor :
aElement.InclusiveAncestorsOfType<Element>()) {
if (HTMLEditUtils::IsBlockElement(*inclusiveAncestor) ||
(givenElementIsEditable &&
!HTMLEditUtils::IsSimplyEditableNode(*inclusiveAncestor))) {
break;
}
if (inclusiveAncestor->IsAnyOfHTMLElements(
nsGkAtoms::b, nsGkAtoms::i, nsGkAtoms::u, nsGkAtoms::s,
nsGkAtoms::strike, nsGkAtoms::tt, nsGkAtoms::em,
nsGkAtoms::strong, nsGkAtoms::dfn, nsGkAtoms::code,
nsGkAtoms::samp, nsGkAtoms::var, nsGkAtoms::cite, nsGkAtoms::abbr,
nsGkAtoms::acronym, nsGkAtoms::sub, nsGkAtoms::sup)) {
nsStaticAtom& tagName = const_cast<nsStaticAtom&>(
*inclusiveAncestor->NodeInfo()->NameAtom()->AsStatic());
if (NeedToAppend(tagName, nullptr)) {
aPendingStyleCacheArray.AppendElement(
PendingStyleCache(tagName, nullptr, EmptyString()));
}
continue;
}
if (inclusiveAncestor->IsHTMLElement(nsGkAtoms::font)) {
if (NeedToAppend(*nsGkAtoms::font, nsGkAtoms::face)) {
inclusiveAncestor->GetAttr(kNameSpaceID_None, nsGkAtoms::face, value);
if (!value.IsEmpty()) {
aPendingStyleCacheArray.AppendElement(
PendingStyleCache(*nsGkAtoms::font, nsGkAtoms::face, value));
value.Truncate();
}
}
if (NeedToAppend(*nsGkAtoms::font, nsGkAtoms::size)) {
inclusiveAncestor->GetAttr(kNameSpaceID_None, nsGkAtoms::size, value);
if (!value.IsEmpty()) {
aPendingStyleCacheArray.AppendElement(
PendingStyleCache(*nsGkAtoms::font, nsGkAtoms::size, value));
value.Truncate();
}
}
if (NeedToAppend(*nsGkAtoms::font, nsGkAtoms::color)) {
inclusiveAncestor->GetAttr(kNameSpaceID_None, nsGkAtoms::color,
value);
if (!value.IsEmpty()) {
aPendingStyleCacheArray.AppendElement(
PendingStyleCache(*nsGkAtoms::font, nsGkAtoms::color, value));
value.Truncate();
}
}
continue;
}
}
return NS_OK;
}
for (nsStaticAtom* property : {nsGkAtoms::b,
nsGkAtoms::i,
nsGkAtoms::u,
nsGkAtoms::s,
nsGkAtoms::strike,
nsGkAtoms::face,
nsGkAtoms::size,
nsGkAtoms::color,
nsGkAtoms::tt,
nsGkAtoms::em,
nsGkAtoms::strong,
nsGkAtoms::dfn,
nsGkAtoms::code,
nsGkAtoms::samp,
nsGkAtoms::var,
nsGkAtoms::cite,
nsGkAtoms::abbr,
nsGkAtoms::acronym,
nsGkAtoms::backgroundColor,
nsGkAtoms::sub,
nsGkAtoms::sup}) {
const EditorInlineStyle style =
property == nsGkAtoms::face || property == nsGkAtoms::size ||
property == nsGkAtoms::color
? EditorInlineStyle(*nsGkAtoms::font, property)
: EditorInlineStyle(*property);
// If type-in state is set, don't intervene
const PendingStyleState styleState =
mPendingStylesToApplyToNewContent->GetStyleState(*style.mHTMLProperty,
style.mAttribute);
if (styleState != PendingStyleState::NotUpdated) {
continue;
}
bool isSet = false;
nsString value; // Don't use nsAutoString here because it requires memcpy
// at creating new PendingStyleCache instance.
// Don't use CSS for <font size>, we don't support it usefully (bug 780035)
if (property == nsGkAtoms::size) {
isSet = HTMLEditUtils::IsInlineStyleSetByElement(aElement, style, nullptr,
&value);
} else if (style.IsCSSSettable(aElement)) {
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(*this, aElement, style,
value);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.unwrapErr();
}
isSet = isComputedCSSEquivalentToStyleOrError.unwrap();
}
if (isSet) {
aPendingStyleCacheArray.AppendElement(
style.ToPendingStyleCache(std::move(value)));
}
}
return NS_OK;
}
nsresult HTMLEditor::ReapplyCachedStyles() {
MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable());
// The idea here is to examine our cached list of styles and see if any have
// been removed. If so, add typeinstate for them, so that they will be
// reinserted when new content is added.
if (TopLevelEditSubActionDataRef().mCachedPendingStyles->IsEmpty() ||
!SelectionRef().RangeCount()) {
return NS_OK;
}
// remember if we are in css mode
const bool useCSS = IsCSSEnabled();
const RangeBoundary& atStartOfSelection =
SelectionRef().GetRangeAt(0)->StartRef();
const RefPtr<Element> startContainerElement =
atStartOfSelection.Container() &&
atStartOfSelection.Container()->IsContent()
? atStartOfSelection.Container()->GetAsElementOrParentElement()
: nullptr;
if (NS_WARN_IF(!startContainerElement)) {
return NS_OK;
}
AutoPendingStyleCacheArray styleCacheArrayAtInsertionPoint;
nsresult rv =
GetInlineStyles(*startContainerElement, styleCacheArrayAtInsertionPoint);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::GetInlineStyles() failed, but ignored");
return NS_OK;
}
for (PendingStyleCache& styleCacheBeforeEdit :
Reversed(*TopLevelEditSubActionDataRef().mCachedPendingStyles)) {
bool isFirst = false, isAny = false, isAll = false;
nsAutoString currentValue;
const EditorInlineStyle inlineStyle = styleCacheBeforeEdit.ToInlineStyle();
if (useCSS && inlineStyle.IsCSSSettable(*startContainerElement)) {
// check computed style first in css case
// MOZ_KnownLive(styleCacheBeforeEdit.*) because they are nsStaticAtom
// and its instances are alive until shutting down.
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(*this, *startContainerElement,
inlineStyle, currentValue);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.unwrapErr();
}
isAny = isComputedCSSEquivalentToStyleOrError.unwrap();
}
if (!isAny) {
// then check typeinstate and html style
nsresult rv = GetInlinePropertyBase(
inlineStyle, &styleCacheBeforeEdit.AttributeValueOrCSSValueRef(),
&isFirst, &isAny, &isAll, ¤tValue);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::GetInlinePropertyBase() failed");
return rv;
}
}
// This style has disappeared through deletion. Let's add the styles to
// mPendingStylesToApplyToNewContent when same style isn't applied to the
// node already.
if (isAny &&
!IsPendingStyleCachePreservingSubAction(GetTopLevelEditSubAction())) {
continue;
}
AutoPendingStyleCacheArray::index_type index =
styleCacheArrayAtInsertionPoint.IndexOf(
styleCacheBeforeEdit.TagRef(), styleCacheBeforeEdit.GetAttribute());
if (index == AutoPendingStyleCacheArray::NoIndex ||
styleCacheBeforeEdit.AttributeValueOrCSSValueRef() !=
styleCacheArrayAtInsertionPoint.ElementAt(index)
.AttributeValueOrCSSValueRef()) {
mPendingStylesToApplyToNewContent->PreserveStyle(styleCacheBeforeEdit);
}
}
return NS_OK;
}
nsresult HTMLEditor::InsertBRElementToEmptyListItemsAndTableCellsInRange(
const RawRangeBoundary& aStartRef, const RawRangeBoundary& aEndRef) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoTArray<OwningNonNull<Element>, 64> arrayOfEmptyElements;
DOMIterator iter;
if (NS_FAILED(iter.Init(aStartRef, aEndRef))) {
NS_WARNING("DOMIterator::Init() failed");
return NS_ERROR_FAILURE;
}
iter.AppendNodesToArray(
+[](nsINode& aNode, void* aSelf) {
MOZ_ASSERT(Element::FromNode(&aNode));
MOZ_ASSERT(aSelf);
Element* element = aNode.AsElement();
if (!EditorUtils::IsEditableContent(*element, EditorType::HTML) ||
(!HTMLEditUtils::IsListItem(element) &&
!HTMLEditUtils::IsTableCellOrCaption(*element))) {
return false;
}
return HTMLEditUtils::IsEmptyNode(
*element, {EmptyCheckOption::TreatSingleBRElementAsVisible});
},
arrayOfEmptyElements, this);
// Put padding <br> elements for empty <li> and <td>.
EditorDOMPoint pointToPutCaret;
for (auto& emptyElement : arrayOfEmptyElements) {
// Need to put br at END of node. It may have empty containers in it and
// still pass the "IsEmptyNode" test, and we want the br's to be after
// them. Also, we want the br to be after the selection if the selection
// is in this node.
EditorDOMPoint endOfNode(EditorDOMPoint::AtEndOf(emptyElement));
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(endOfNode);
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction() "
"failed");
return insertPaddingBRElementResult.unwrapErr();
}
CreateElementResult unwrappedInsertPaddingBRElementResult =
insertPaddingBRElementResult.unwrap();
unwrappedInsertPaddingBRElementResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
}
if (pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
return NS_OK;
}
void HTMLEditor::SetSelectionInterlinePosition() {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(SelectionRef().IsCollapsed());
// Get the (collapsed) selection location
const nsRange* firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return;
}
EditorDOMPoint atCaret(firstRange->StartRef());
if (NS_WARN_IF(!atCaret.IsSet())) {
return;
}
MOZ_ASSERT(atCaret.IsSetAndValid());
// First, let's check to see if we are after a `<br>`. We take care of this
// special-case first so that we don't accidentally fall through into one of
// the other conditionals.
// XXX Although I don't understand "interline position", if caret is
// immediately after non-editable contents, but previous editable
// content is `<br>`, does this do right thing?
if (Element* editingHost = ComputeEditingHost()) {
if (nsIContent* previousEditableContentInBlock =
HTMLEditUtils::GetPreviousContent(
atCaret,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
editingHost)) {
if (previousEditableContentInBlock->IsHTMLElement(nsGkAtoms::br)) {
DebugOnly<nsresult> rvIgnored = SelectionRef().SetInterlinePosition(
InterlinePosition::StartOfNextLine);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"StartOfNextLine) failed, but ignored");
return;
}
}
}
if (!atCaret.GetChild()) {
return;
}
// If caret is immediately after a block, set interline position to "right".
// XXX Although I don't understand "interline position", if caret is
// immediately after non-editable contents, but previous editable
// content is a block, does this do right thing?
if (nsIContent* previousEditableContentInBlockAtCaret =
HTMLEditUtils::GetPreviousSibling(
*atCaret.GetChild(), {WalkTreeOption::IgnoreNonEditableNode})) {
if (HTMLEditUtils::IsBlockElement(*previousEditableContentInBlockAtCaret)) {
DebugOnly<nsresult> rvIgnored = SelectionRef().SetInterlinePosition(
InterlinePosition::StartOfNextLine);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"StartOfNextLine) failed, but ignored");
return;
}
}
// If caret is immediately before a block, set interline position to "left".
// XXX Although I don't understand "interline position", if caret is
// immediately before non-editable contents, but next editable
// content is a block, does this do right thing?
if (nsIContent* nextEditableContentInBlockAtCaret =
HTMLEditUtils::GetNextSibling(
*atCaret.GetChild(), {WalkTreeOption::IgnoreNonEditableNode})) {
if (HTMLEditUtils::IsBlockElement(*nextEditableContentInBlockAtCaret)) {
DebugOnly<nsresult> rvIgnored =
SelectionRef().SetInterlinePosition(InterlinePosition::EndOfLine);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"EndOfLine) failed, but ignored");
}
}
}
nsresult HTMLEditor::AdjustCaretPositionAndEnsurePaddingBRElement(
nsIEditor::EDirection aDirectionAndAmount) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(SelectionRef().IsCollapsed());
auto point = GetFirstSelectionStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!point.IsInContentNode())) {
return NS_ERROR_FAILURE;
}
// If selection start is not editable, climb up the tree until editable one.
while (!EditorUtils::IsEditableContent(*point.ContainerAs<nsIContent>(),
EditorType::HTML)) {
point.Set(point.GetContainer());
if (NS_WARN_IF(!point.IsInContentNode())) {
return NS_ERROR_FAILURE;
}
}
// If caret is in empty block element, we need to insert a `<br>` element
// because the block should have one-line height.
// XXX Even if only a part of the block is editable, shouldn't we put
// caret if the block element is now empty?
if (Element* const editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*point.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement)) {
if (editableBlockElement &&
HTMLEditUtils::IsEmptyNode(
*editableBlockElement,
{EmptyCheckOption::TreatSingleBRElementAsVisible}) &&
HTMLEditUtils::CanNodeContain(*point.GetContainer(), *nsGkAtoms::br)) {
Element* bodyOrDocumentElement = GetRoot();
if (NS_WARN_IF(!bodyOrDocumentElement)) {
return NS_ERROR_FAILURE;
}
if (point.GetContainer() == bodyOrDocumentElement) {
// Our root node is completely empty. Don't add a <br> here.
// AfterEditInner() will add one for us when it calls
// EditorBase::MaybeCreatePaddingBRElementForEmptyEditor().
// XXX This kind of dependency between methods makes us spaghetti.
// Let's handle it here later.
// XXX This looks odd check. If active editing host is not a
// `<body>`, what are we doing?
return NS_OK;
}
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(point);
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction("
") failed");
return insertPaddingBRElementResult.unwrapErr();
}
nsresult rv = insertPaddingBRElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateElementResult::SuggestCaretPointTo() failed, but ignored");
return NS_OK;
}
}
// XXX Perhaps, we should do something if we're in a data node but not
// a text node.
if (point.IsInTextNode()) {
return NS_OK;
}
// Do we need to insert a padding <br> element for empty last line? We do
// if we are:
// 1) prior node is in same block where selection is AND
// 2) prior node is a br AND
// 3) that br is not visible
RefPtr<Element> editingHost = ComputeEditingHost();
if (!editingHost) {
return NS_OK;
}
if (nsCOMPtr<nsIContent> previousEditableContent =
HTMLEditUtils::GetPreviousContent(
point, {WalkTreeOption::IgnoreNonEditableNode}, editingHost)) {
// If caret and previous editable content are in same block element
// (even if it's a non-editable element), we should put a padding <br>
// element at end of the block.
const Element* const blockElementContainingCaret =
HTMLEditUtils::GetInclusiveAncestorElement(
*point.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestBlockElement);
const Element* const blockElementContainingPreviousEditableContent =
HTMLEditUtils::GetAncestorElement(*previousEditableContent,
HTMLEditUtils::ClosestBlockElement);
// If previous editable content of caret is in same block and a `<br>`
// element, we need to adjust interline position.
if (blockElementContainingCaret &&
blockElementContainingCaret ==
blockElementContainingPreviousEditableContent &&
point.ContainerAs<nsIContent>()->GetEditingHost() ==
previousEditableContent->GetEditingHost() &&
previousEditableContent &&
previousEditableContent->IsHTMLElement(nsGkAtoms::br)) {
// If it's an invisible `<br>` element, we need to insert a padding
// `<br>` element for making empty line have one-line height.
if (HTMLEditUtils::IsInvisibleBRElement(*previousEditableContent) &&
!EditorUtils::IsPaddingBRElementForEmptyLastLine(
*previousEditableContent)) {
AutoEditorDOMPointChildInvalidator lockOffset(point);
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(point);
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertPaddingBRElementForEmptyLastLineWithTransaction() failed");
return insertPaddingBRElementResult.unwrapErr();
}
insertPaddingBRElementResult.inspect().IgnoreCaretPointSuggestion();
nsresult rv = CollapseSelectionTo(EditorRawDOMPoint(
insertPaddingBRElementResult.inspect().GetNewNode(),
InterlinePosition::StartOfNextLine));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return rv;
}
}
// If it's a visible `<br>` element and next editable content is a
// padding `<br>` element, we need to set interline position.
else if (nsIContent* nextEditableContentInBlock =
HTMLEditUtils::GetNextContent(
*previousEditableContent,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
editingHost)) {
if (EditorUtils::IsPaddingBRElementForEmptyLastLine(
*nextEditableContentInBlock)) {
// Make it stick to the padding `<br>` element so that it will be
// on blank line.
DebugOnly<nsresult> rvIgnored = SelectionRef().SetInterlinePosition(
InterlinePosition::StartOfNextLine);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Selection::SetInterlinePosition(InterlinePosition::"
"StartOfNextLine) failed, but ignored");
}
}
}
}
// If previous editable content in same block is `<br>`, text node, `<img>`
// or `<hr>`, current caret position is fine.
if (nsIContent* previousEditableContentInBlock =
HTMLEditUtils::GetPreviousContent(
point,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
editingHost)) {
if (previousEditableContentInBlock->IsHTMLElement(nsGkAtoms::br) ||
previousEditableContentInBlock->IsText() ||
HTMLEditUtils::IsImage(previousEditableContentInBlock) ||
previousEditableContentInBlock->IsHTMLElement(nsGkAtoms::hr)) {
return NS_OK;
}
}
// If next editable content in same block is `<br>`, text node, `<img>` or
// `<hr>`, current caret position is fine.
if (nsIContent* nextEditableContentInBlock =
HTMLEditUtils::GetNextContent(point,
{WalkTreeOption::IgnoreNonEditableNode,
WalkTreeOption::StopAtBlockBoundary},
editingHost)) {
if (nextEditableContentInBlock->IsText() ||
nextEditableContentInBlock->IsAnyOfHTMLElements(
nsGkAtoms::br, nsGkAtoms::img, nsGkAtoms::hr)) {
return NS_OK;
}
}
// Otherwise, look for a near editable content towards edit action direction.
// If there is no editable content, keep current caret position.
// XXX Why do we treat `nsIEditor::ePreviousWord` etc as forward direction?
nsIContent* nearEditableContent = HTMLEditUtils::GetAdjacentContentToPutCaret(
point,
aDirectionAndAmount == nsIEditor::ePrevious ? WalkTreeDirection::Backward
: WalkTreeDirection::Forward,
*editingHost);
if (!nearEditableContent) {
return NS_OK;
}
EditorRawDOMPoint pointToPutCaret =
HTMLEditUtils::GetGoodCaretPointFor<EditorRawDOMPoint>(
*nearEditableContent, aDirectionAndAmount);
if (!pointToPutCaret.IsSet()) {
NS_WARNING("HTMLEditUtils::GetGoodCaretPointFor() failed");
return NS_ERROR_FAILURE;
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
nsresult HTMLEditor::RemoveEmptyNodesIn(const EditorDOMRange& aRange) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aRange.IsPositioned());
// Some general notes on the algorithm used here: the goal is to examine all
// the nodes in aRange, and remove the empty ones. We do this by
// using a content iterator to traverse all the nodes in the range, and
// placing the empty nodes into an array. After finishing the iteration,
// we delete the empty nodes in the array. (They cannot be deleted as we
// find them because that would invalidate the iterator.)
//
// Since checking to see if a node is empty can be costly for nodes with
// many descendants, there are some optimizations made. I rely on the fact
// that the iterator is post-order: it will visit children of a node before
// visiting the parent node. So if I find that a child node is not empty, I
// know that its parent is not empty without even checking. So I put the
// parent on a "skipList" which is just a voidArray of nodes I can skip the
// empty check on. If I encounter a node on the skiplist, i skip the
// processing for that node and replace its slot in the skiplist with that
// node's parent.
//
// An interesting idea is to go ahead and regard parent nodes that are NOT
// on the skiplist as being empty (without even doing the IsEmptyNode check)
// on the theory that if they weren't empty, we would have encountered a
// non-empty child earlier and thus put this parent node on the skiplist.
//
// Unfortunately I can't use that strategy here, because the range may
// include some children of a node while excluding others. Thus I could
// find all the _examined_ children empty, but still not have an empty
// parent.
const RawRangeBoundary endOfRange = [&]() {
// If the range is not collapsed and end of the range is start of a
// container, it means that the inclusive ancestor empty element may be
// created by splitting the left nodes.
if (aRange.Collapsed() || !aRange.IsInContentNodes() ||
!aRange.EndRef().IsStartOfContainer()) {
return aRange.EndRef().ToRawRangeBoundary();
}
nsINode* const commonAncestor =
nsContentUtils::GetClosestCommonInclusiveAncestor(
aRange.StartRef().ContainerAs<nsIContent>(),
aRange.EndRef().ContainerAs<nsIContent>());
if (!commonAncestor) {
return aRange.EndRef().ToRawRangeBoundary();
}
nsIContent* maybeRightContent = nullptr;
for (nsIContent* content : aRange.EndRef()
.ContainerAs<nsIContent>()
->InclusiveAncestorsOfType<nsIContent>()) {
if (!HTMLEditUtils::IsSimplyEditableNode(*content) ||
content == commonAncestor) {
break;
}
if (aRange.StartRef().ContainerAs<nsIContent>() == content) {
break;
}
EmptyCheckOptions options = {EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible};
if (!HTMLEditUtils::IsBlockElement(*content)) {
options += EmptyCheckOption::TreatSingleBRElementAsVisible;
}
if (!HTMLEditUtils::IsEmptyNode(*content, options)) {
break;
}
maybeRightContent = content;
}
if (!maybeRightContent) {
return aRange.EndRef().ToRawRangeBoundary();
}
return EditorRawDOMPoint::After(*maybeRightContent).ToRawRangeBoundary();
}();
PostContentIterator postOrderIter;
nsresult rv =
postOrderIter.Init(aRange.StartRef().ToRawRangeBoundary(), endOfRange);
if (NS_FAILED(rv)) {
NS_WARNING("PostContentIterator::Init() failed");
return rv;
}
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfEmptyContents,
arrayOfEmptyCites;
// Collect empty nodes first.
{
const bool isMailEditor = IsMailEditor();
AutoTArray<OwningNonNull<nsIContent>, 64> knownNonEmptyContents;
Maybe<AutoRangeArray> maybeSelectionRanges;
for (; !postOrderIter.IsDone(); postOrderIter.Next()) {
MOZ_ASSERT(postOrderIter.GetCurrentNode()->IsContent());
nsIContent* content = postOrderIter.GetCurrentNode()->AsContent();
nsIContent* parentContent = content->GetParent();
size_t idx = knownNonEmptyContents.IndexOf(content);
if (idx != decltype(knownNonEmptyContents)::NoIndex) {
// This node is on our skip list. Skip processing for this node, and
// replace its value in the skip list with the value of its parent
if (parentContent) {
knownNonEmptyContents[idx] = parentContent;
}
continue;
}
const bool isEmptyNode = [&]() {
if (!content->IsElement()) {
return false;
}
const bool isMailCite =
isMailEditor && HTMLEditUtils::IsMailCite(*content->AsElement());
const bool isCandidate = [&]() {
if (content->IsHTMLElement(nsGkAtoms::body)) {
// Don't delete the body
return false;
}
if (isMailCite || content->IsHTMLElement(nsGkAtoms::a) ||
HTMLEditUtils::IsInlineStyle(content) ||
HTMLEditUtils::IsAnyListElement(content) ||
content->IsHTMLElement(nsGkAtoms::div)) {
// Only consider certain nodes to be empty for purposes of removal
return true;
}
if (HTMLEditUtils::IsFormatNode(content) ||
HTMLEditUtils::IsListItem(content) ||
content->IsHTMLElement(nsGkAtoms::blockquote)) {
// These node types are candidates if selection is not in them. If
// it is one of these, don't delete if selection inside. This is so
// we can create empty headings, etc., for the user to type into.
if (maybeSelectionRanges.isNothing()) {
maybeSelectionRanges.emplace(SelectionRef());
}
return !maybeSelectionRanges
->IsAtLeastOneContainerOfRangeBoundariesInclusiveDescendantOf(
*content);
}
return false;
}();
if (!isCandidate) {
return false;
}
// We delete mailcites even if they have a solo br in them. Other
// nodes we require to be empty.
HTMLEditUtils::EmptyCheckOptions options{
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible};
if (!isMailCite) {
options += EmptyCheckOption::TreatSingleBRElementAsVisible;
}
if (!HTMLEditUtils::IsEmptyNode(*content, options)) {
return false;
}
if (isMailCite) {
// mailcites go on a separate list from other empty nodes
arrayOfEmptyCites.AppendElement(*content);
}
// Don't delete non-editable nodes in this method because this is a
// clean up method to remove unnecessary nodes of the result of
// editing. So, we shouldn't delete non-editable nodes which were
// there before editing. Additionally, if the element is some special
// elements such as <body>, we shouldn't delete it.
else if (HTMLEditUtils::IsSimplyEditableNode(*content) &&
HTMLEditUtils::IsRemovableNode(*content)) {
arrayOfEmptyContents.AppendElement(*content);
}
return true;
}();
if (!isEmptyNode && parentContent) {
knownNonEmptyContents.AppendElement(*parentContent);
}
} // end of the for-loop iterating with postOrderIter
}
// now delete the empty nodes
for (OwningNonNull<nsIContent>& emptyContent : arrayOfEmptyContents) {
// MOZ_KnownLive due to bug 1622253
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(emptyContent));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
// Now delete the empty mailcites. This is a separate step because we want
// to pull out any br's and preserve them.
EditorDOMPoint pointToPutCaret;
for (OwningNonNull<nsIContent>& emptyCite : arrayOfEmptyCites) {
if (!HTMLEditUtils::IsEmptyNode(
emptyCite, {EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible})) {
// We are deleting a cite that has just a `<br>`. We want to delete cite,
// but preserve `<br>`.
Result<CreateElementResult, nsresult> insertBRElementResult =
InsertBRElement(WithTransaction::Yes, EditorDOMPoint(emptyCite));
if (MOZ_UNLIKELY(insertBRElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult.unwrapErr();
}
CreateElementResult unwrappedInsertBRElementResult =
insertBRElementResult.unwrap();
// XXX Is this intentional selection change?
unwrappedInsertBRElementResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
MOZ_ASSERT(unwrappedInsertBRElementResult.GetNewNode());
}
// MOZ_KnownLive because 'arrayOfEmptyCites' is guaranteed to keep it alive.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(emptyCite));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
// XXX Is this intentional selection change?
if (pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
return NS_OK;
}
nsresult HTMLEditor::LiftUpListItemElement(
Element& aListItemElement,
LiftUpFromAllParentListElements aLiftUpFromAllParentListElements) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!HTMLEditUtils::IsListItem(&aListItemElement)) {
return NS_ERROR_INVALID_ARG;
}
if (NS_WARN_IF(!aListItemElement.GetParentElement()) ||
NS_WARN_IF(!aListItemElement.GetParentElement()->GetParentNode())) {
return NS_ERROR_FAILURE;
}
// if it's first or last list item, don't need to split the list
// otherwise we do.
bool isFirstListItem = HTMLEditUtils::IsFirstChild(
aListItemElement, {WalkTreeOption::IgnoreNonEditableNode});
bool isLastListItem = HTMLEditUtils::IsLastChild(
aListItemElement, {WalkTreeOption::IgnoreNonEditableNode});
Element* leftListElement = aListItemElement.GetParentElement();
if (NS_WARN_IF(!leftListElement)) {
return NS_ERROR_FAILURE;
}
// If it's at middle of parent list element, split the parent list element.
// Then, aListItem becomes the first list item of the right list element.
if (!isFirstListItem && !isLastListItem) {
EditorDOMPoint atListItemElement(&aListItemElement);
if (NS_WARN_IF(!atListItemElement.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atListItemElement.IsSetAndValid());
Result<SplitNodeResult, nsresult> splitListItemParentResult =
SplitNodeWithTransaction(atListItemElement);
if (MOZ_UNLIKELY(splitListItemParentResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitListItemParentResult.unwrapErr();
}
nsresult rv = splitListItemParentResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return rv;
}
leftListElement =
splitListItemParentResult.inspect().GetPreviousContentAs<Element>();
if (MOZ_UNLIKELY(!leftListElement)) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't return left list "
"element");
return NS_ERROR_FAILURE;
}
}
// In most cases, insert the list item into the new left list node..
EditorDOMPoint pointToInsertListItem(leftListElement);
if (NS_WARN_IF(!pointToInsertListItem.IsSet())) {
return NS_ERROR_FAILURE;
}
// But when the list item was the first child of the right list, it should
// be inserted between the both list elements. This allows user to hit
// Enter twice at a list item breaks the parent list node.
if (!isFirstListItem) {
DebugOnly<bool> advanced = pointToInsertListItem.AdvanceOffset();
NS_WARNING_ASSERTION(advanced,
"Failed to advance offset to right list node");
}
EditorDOMPoint pointToPutCaret;
{
Result<MoveNodeResult, nsresult> moveListItemElementResult =
MoveNodeWithTransaction(aListItemElement, pointToInsertListItem);
if (MOZ_UNLIKELY(moveListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveListItemElementResult.unwrapErr();
}
MoveNodeResult unwrappedMoveListItemElementResult =
moveListItemElementResult.unwrap();
unwrappedMoveListItemElementResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
}
// Unwrap list item contents if they are no longer in a list
// XXX If the parent list element is a child of another list element
// (although invalid tree), the list item element won't be unwrapped.
// That makes the parent ancestor element tree valid, but might be
// unexpected result.
// XXX If aListItemElement is <dl> or <dd> and current parent is <ul> or <ol>,
// the list items won't be unwrapped. If aListItemElement is <li> and its
// current parent is <dl>, there is same issue.
if (!HTMLEditUtils::IsAnyListElement(pointToInsertListItem.GetContainer()) &&
HTMLEditUtils::IsListItem(&aListItemElement)) {
Result<EditorDOMPoint, nsresult> unwrapOrphanListItemElementResult =
RemoveBlockContainerWithTransaction(aListItemElement);
if (MOZ_UNLIKELY(unwrapOrphanListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapOrphanListItemElementResult.unwrapErr();
}
if (AllowsTransactionsToChangeSelection() &&
unwrapOrphanListItemElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapOrphanListItemElementResult.unwrap();
}
if (!pointToPutCaret.IsSet()) {
return NS_OK;
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
if (pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
if (aLiftUpFromAllParentListElements == LiftUpFromAllParentListElements::No) {
return NS_OK;
}
// XXX If aListItemElement is moved to unexpected element by mutation event
// listener, shouldn't we stop calling this?
nsresult rv = LiftUpListItemElement(aListItemElement,
LiftUpFromAllParentListElements::Yes);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::LiftUpListItemElement("
"LiftUpFromAllParentListElements::Yes) failed");
return rv;
}
nsresult HTMLEditor::DestroyListStructureRecursively(Element& aListElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(HTMLEditUtils::IsAnyListElement(&aListElement));
// XXX If mutation event listener inserts new child into `aListElement`,
// this becomes infinite loop so that we should set limit of the
// loop count from original child count.
while (aListElement.GetFirstChild()) {
OwningNonNull<nsIContent> child = *aListElement.GetFirstChild();
if (HTMLEditUtils::IsListItem(child)) {
// XXX Using LiftUpListItemElement() is too expensive for this purpose.
// Looks like the reason why this method uses it is, only this loop
// wants to work with first child of aListElement. However, what it
// actually does is removing <li> as container. Perhaps, we should
// decide destination first, and then, move contents in `child`.
// XXX If aListElement is is a child of another list element (although
// it's invalid tree), this moves the list item to outside of
// aListElement's parent. Is that really intentional behavior?
nsresult rv = LiftUpListItemElement(
MOZ_KnownLive(*child->AsElement()),
HTMLEditor::LiftUpFromAllParentListElements::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::LiftUpListItemElement(LiftUpFromAllParentListElements:"
":Yes) failed");
return rv;
}
continue;
}
if (HTMLEditUtils::IsAnyListElement(child)) {
nsresult rv =
DestroyListStructureRecursively(MOZ_KnownLive(*child->AsElement()));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DestroyListStructureRecursively() failed");
return rv;
}
continue;
}
// Delete any non-list items for now
// XXX This is not HTML5 aware. HTML5 allows all list elements to have
// <script> and <template> and <dl> element to have <div> to group
// some <dt> and <dd> elements. So, this may break valid children.
nsresult rv = DeleteNodeWithTransaction(*child);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
// Delete the now-empty list
const Result<EditorDOMPoint, nsresult> unwrapListElementResult =
RemoveBlockContainerWithTransaction(aListElement);
if (MOZ_UNLIKELY(unwrapListElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
return unwrapListElementResult.inspectErr();
}
const EditorDOMPoint& pointToPutCaret = unwrapListElementResult.inspect();
if (!AllowsTransactionsToChangeSelection() || !pointToPutCaret.IsSet()) {
return NS_OK;
}
nsresult rv = CollapseSelectionTo(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
nsresult HTMLEditor::EnsureSelectionInBodyOrDocumentElement() {
MOZ_ASSERT(IsEditActionDataAvailable());
RefPtr<Element> bodyOrDocumentElement = GetRoot();
if (NS_WARN_IF(!bodyOrDocumentElement)) {
return NS_ERROR_FAILURE;
}
const auto atCaret = GetFirstSelectionStartPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!atCaret.IsSet())) {
return NS_ERROR_FAILURE;
}
// XXX This does wrong things. Web apps can put any elements as sibling
// of `<body>` element. Therefore, this collapses `Selection` into
// the `<body>` element which `HTMLDocument.body` is set to. So,
// this makes users impossible to modify content outside of the
// `<body>` element even if caret is in an editing host.
// Check that selection start container is inside the <body> element.
// XXXsmaug this code is insane.
nsINode* temp = atCaret.GetContainer();
while (temp && !temp->IsHTMLElement(nsGkAtoms::body)) {
temp = temp->GetParentOrShadowHostNode();
}
// If we aren't in the <body> element, force the issue.
if (!temp) {
nsresult rv = CollapseSelectionToStartOf(*bodyOrDocumentElement);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionToStartOf() caused destroying the "
"editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed, but ignored");
return NS_OK;
}
const auto selectionEndPoint = GetFirstSelectionEndPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!selectionEndPoint.IsSet())) {
return NS_ERROR_FAILURE;
}
// check that selNode is inside body
// XXXsmaug this code is insane.
temp = selectionEndPoint.GetContainer();
while (temp && !temp->IsHTMLElement(nsGkAtoms::body)) {
temp = temp->GetParentOrShadowHostNode();
}
// If we aren't in the <body> element, force the issue.
if (!temp) {
nsresult rv = CollapseSelectionToStartOf(*bodyOrDocumentElement);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionToStartOf() caused destroying the "
"editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed, but ignored");
}
return NS_OK;
}
nsresult HTMLEditor::InsertPaddingBRElementForEmptyLastLineIfNeeded(
Element& aElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!HTMLEditUtils::IsBlockElement(aElement)) {
return NS_OK;
}
if (!HTMLEditUtils::IsEmptyNode(
aElement, {EmptyCheckOption::TreatSingleBRElementAsVisible})) {
return NS_OK;
}
Result<CreateElementResult, nsresult> insertPaddingBRElementResult =
InsertPaddingBRElementForEmptyLastLineWithTransaction(
EditorDOMPoint(&aElement, 0u));
if (MOZ_UNLIKELY(insertPaddingBRElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementForEmptyLastLineWithTransaction() "
"failed");
return insertPaddingBRElementResult.unwrapErr();
}
nsresult rv = insertPaddingBRElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateElementResult::SuggestCaretPointTo() failed, but ignored");
return NS_OK;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::RemoveAlignFromDescendants(
Element& aElement, const nsAString& aAlignType, EditTarget aEditTarget) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aElement.IsHTMLElement(nsGkAtoms::table));
const bool useCSS = IsCSSEnabled();
EditorDOMPoint pointToPutCaret;
// Let's remove all alignment hints in the children of aNode; it can
// be an ALIGN attribute (in case we just remove it) or a CENTER
// element (here we have to remove the container and keep its
// children). We break on tables and don't look at their children.
nsCOMPtr<nsIContent> nextSibling;
for (nsIContent* content =
aEditTarget == EditTarget::NodeAndDescendantsExceptTable
? &aElement
: aElement.GetFirstChild();
content; content = nextSibling) {
// Get the next sibling before removing content from the DOM tree.
// XXX If next sibling is removed from the parent and/or inserted to
// different parent, we will behave unexpectedly. I think that
// we should create child list and handle it with checking whether
// it's still a child of expected parent.
nextSibling = aEditTarget == EditTarget::NodeAndDescendantsExceptTable
? nullptr
: content->GetNextSibling();
if (content->IsHTMLElement(nsGkAtoms::center)) {
OwningNonNull<Element> centerElement = *content->AsElement();
{
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
RemoveAlignFromDescendants(centerElement, aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditor::RemoveAlignFromDescendants(EditTarget::"
"OnlyDescendantsExceptTable) failed");
return pointToPutCaretOrError;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
// We may have to insert a `<br>` element before first child of the
// `<center>` element because it should be first element of a hard line
// even after removing the `<center>` element.
{
Result<CreateElementResult, nsresult>
maybeInsertBRElementBeforeFirstChildResult =
EnsureHardLineBeginsWithFirstChildOf(centerElement);
if (MOZ_UNLIKELY(maybeInsertBRElementBeforeFirstChildResult.isErr())) {
NS_WARNING(
"HTMLEditor::EnsureHardLineBeginsWithFirstChildOf() failed");
return maybeInsertBRElementBeforeFirstChildResult.propagateErr();
}
CreateElementResult unwrappedResult =
maybeInsertBRElementBeforeFirstChildResult.unwrap();
if (unwrappedResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedResult.UnwrapCaretPoint();
}
}
// We may have to insert a `<br>` element after last child of the
// `<center>` element because it should be last element of a hard line
// even after removing the `<center>` element.
{
Result<CreateElementResult, nsresult>
maybeInsertBRElementAfterLastChildResult =
EnsureHardLineEndsWithLastChildOf(centerElement);
if (MOZ_UNLIKELY(maybeInsertBRElementAfterLastChildResult.isErr())) {
NS_WARNING("HTMLEditor::EnsureHardLineEndsWithLastChildOf() failed");
return maybeInsertBRElementAfterLastChildResult.propagateErr();
}
CreateElementResult unwrappedResult =
maybeInsertBRElementAfterLastChildResult.unwrap();
if (unwrappedResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedResult.UnwrapCaretPoint();
}
}
{
Result<EditorDOMPoint, nsresult> unwrapCenterElementResult =
RemoveContainerWithTransaction(centerElement);
if (MOZ_UNLIKELY(unwrapCenterElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapCenterElementResult;
}
if (unwrapCenterElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapCenterElementResult.unwrap();
}
}
continue;
}
if (!HTMLEditUtils::IsBlockElement(*content) &&
!content->IsHTMLElement(nsGkAtoms::hr)) {
continue;
}
const OwningNonNull<Element> blockOrHRElement = *content->AsElement();
if (HTMLEditUtils::SupportsAlignAttr(blockOrHRElement)) {
nsresult rv =
RemoveAttributeWithTransaction(blockOrHRElement, *nsGkAtoms::align);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::align) "
"failed");
return Err(rv);
}
}
if (useCSS) {
if (blockOrHRElement->IsAnyOfHTMLElements(nsGkAtoms::table,
nsGkAtoms::hr)) {
nsresult rv = SetAttributeOrEquivalent(
blockOrHRElement, nsGkAtoms::align, aAlignType, false);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::SetAttributeOrEquivalent(nsGkAtoms::align) failed");
return Err(rv);
}
} else {
nsStyledElement* styledBlockOrHRElement =
nsStyledElement::FromNode(blockOrHRElement);
if (NS_WARN_IF(!styledBlockOrHRElement)) {
return Err(NS_ERROR_FAILURE);
}
// MOZ_KnownLive(*styledBlockOrHRElement): It's `blockOrHRElement
// which is OwningNonNull.
nsAutoString dummyCssValue;
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
CSSEditUtils::RemoveCSSInlineStyleWithTransaction(
*this, MOZ_KnownLive(*styledBlockOrHRElement),
nsGkAtoms::textAlign, dummyCssValue);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"CSSEditUtils::RemoveCSSInlineStyleWithTransaction(nsGkAtoms::"
"textAlign) failed");
return pointToPutCaretOrError;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
}
if (!blockOrHRElement->IsHTMLElement(nsGkAtoms::table)) {
// unless this is a table, look at children
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
RemoveAlignFromDescendants(blockOrHRElement, aAlignType,
EditTarget::OnlyDescendantsExceptTable);
if (pointToPutCaretOrError.isErr()) {
NS_WARNING(
"HTMLEditor::RemoveAlignFromDescendants(EditTarget::"
"OnlyDescendantsExceptTable) failed");
return pointToPutCaretOrError;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
}
return pointToPutCaret;
}
Result<CreateElementResult, nsresult>
HTMLEditor::EnsureHardLineBeginsWithFirstChildOf(
Element& aRemovingContainerElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
nsIContent* firstEditableChild = HTMLEditUtils::GetFirstChild(
aRemovingContainerElement, {WalkTreeOption::IgnoreNonEditableNode});
if (!firstEditableChild) {
return CreateElementResult::NotHandled();
}
if (HTMLEditUtils::IsBlockElement(*firstEditableChild) ||
firstEditableChild->IsHTMLElement(nsGkAtoms::br)) {
return CreateElementResult::NotHandled();
}
nsIContent* previousEditableContent = HTMLEditUtils::GetPreviousSibling(
aRemovingContainerElement, {WalkTreeOption::IgnoreNonEditableNode});
if (!previousEditableContent) {
return CreateElementResult::NotHandled();
}
if (HTMLEditUtils::IsBlockElement(*previousEditableContent) ||
previousEditableContent->IsHTMLElement(nsGkAtoms::br)) {
return CreateElementResult::NotHandled();
}
Result<CreateElementResult, nsresult> insertBRElementResult = InsertBRElement(
WithTransaction::Yes, EditorDOMPoint(&aRemovingContainerElement, 0u));
NS_WARNING_ASSERTION(
insertBRElementResult.isOk(),
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult;
}
Result<CreateElementResult, nsresult>
HTMLEditor::EnsureHardLineEndsWithLastChildOf(
Element& aRemovingContainerElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
nsIContent* firstEditableContent = HTMLEditUtils::GetLastChild(
aRemovingContainerElement, {WalkTreeOption::IgnoreNonEditableNode});
if (!firstEditableContent) {
return CreateElementResult::NotHandled();
}
if (HTMLEditUtils::IsBlockElement(*firstEditableContent) ||
firstEditableContent->IsHTMLElement(nsGkAtoms::br)) {
return CreateElementResult::NotHandled();
}
nsIContent* nextEditableContent = HTMLEditUtils::GetPreviousSibling(
aRemovingContainerElement, {WalkTreeOption::IgnoreNonEditableNode});
if (!nextEditableContent) {
return CreateElementResult::NotHandled();
}
if (HTMLEditUtils::IsBlockElement(*nextEditableContent) ||
nextEditableContent->IsHTMLElement(nsGkAtoms::br)) {
return CreateElementResult::NotHandled();
}
Result<CreateElementResult, nsresult> insertBRElementResult = InsertBRElement(
WithTransaction::Yes, EditorDOMPoint::AtEndOf(aRemovingContainerElement));
NS_WARNING_ASSERTION(
insertBRElementResult.isOk(),
"HTMLEditor::InsertBRElement(WithTransaction::Yes) failed");
return insertBRElementResult;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::SetBlockElementAlign(
Element& aBlockOrHRElement, const nsAString& aAlignType,
EditTarget aEditTarget) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(HTMLEditUtils::IsBlockElement(aBlockOrHRElement) ||
aBlockOrHRElement.IsHTMLElement(nsGkAtoms::hr));
MOZ_ASSERT(IsCSSEnabled() ||
HTMLEditUtils::SupportsAlignAttr(aBlockOrHRElement));
EditorDOMPoint pointToPutCaret;
if (!aBlockOrHRElement.IsHTMLElement(nsGkAtoms::table)) {
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
RemoveAlignFromDescendants(aBlockOrHRElement, aAlignType, aEditTarget);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::RemoveAlignFromDescendants() failed");
return pointToPutCaretOrError;
}
if (pointToPutCaretOrError.inspect().IsSet()) {
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
}
nsresult rv = SetAttributeOrEquivalent(&aBlockOrHRElement, nsGkAtoms::align,
aAlignType, false);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::SetAttributeOrEquivalent(nsGkAtoms::align) failed");
return Err(rv);
}
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::ChangeMarginStart(
Element& aElement, ChangeMargin aChangeMargin,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
nsStaticAtom& marginProperty = MarginPropertyAtomForIndent(aElement);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
nsAutoString value;
DebugOnly<nsresult> rvIgnored =
CSSEditUtils::GetSpecifiedProperty(aElement, marginProperty, value);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetSpecifiedProperty() failed, but ignored");
float f;
RefPtr<nsAtom> unit;
CSSEditUtils::ParseLength(value, &f, getter_AddRefs(unit));
if (!f) {
unit = nsGkAtoms::px;
}
int8_t multiplier = aChangeMargin == ChangeMargin::Increase ? 1 : -1;
if (nsGkAtoms::in == unit) {
f += NS_EDITOR_INDENT_INCREMENT_IN * multiplier;
} else if (nsGkAtoms::cm == unit) {
f += NS_EDITOR_INDENT_INCREMENT_CM * multiplier;
} else if (nsGkAtoms::mm == unit) {
f += NS_EDITOR_INDENT_INCREMENT_MM * multiplier;
} else if (nsGkAtoms::pt == unit) {
f += NS_EDITOR_INDENT_INCREMENT_PT * multiplier;
} else if (nsGkAtoms::pc == unit) {
f += NS_EDITOR_INDENT_INCREMENT_PC * multiplier;
} else if (nsGkAtoms::em == unit) {
f += NS_EDITOR_INDENT_INCREMENT_EM * multiplier;
} else if (nsGkAtoms::ex == unit) {
f += NS_EDITOR_INDENT_INCREMENT_EX * multiplier;
} else if (nsGkAtoms::px == unit) {
f += NS_EDITOR_INDENT_INCREMENT_PX * multiplier;
} else if (nsGkAtoms::percentage == unit) {
f += NS_EDITOR_INDENT_INCREMENT_PERCENT * multiplier;
}
if (0 < f) {
if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
nsAutoString newValue;
newValue.AppendFloat(f);
newValue.Append(nsDependentAtomString(unit));
// MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
// be guaranteed by caller because of MOZ_CAN_RUN_SCRIPT method.
// MOZ_KnownLive(merginProperty): It's nsStaticAtom.
nsresult rv = CSSEditUtils::SetCSSPropertyWithTransaction(
*this, MOZ_KnownLive(*styledElement), MOZ_KnownLive(marginProperty),
newValue);
if (rv == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING(
"CSSEditUtils::SetCSSPropertyWithTransaction() destroyed the "
"editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"CSSEditUtils::SetCSSPropertyWithTransaction() failed, but ignored");
}
return EditorDOMPoint();
}
if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
// MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
// be guaranteed by caller because of MOZ_CAN_RUN_SCRIPT method.
// MOZ_KnownLive(merginProperty): It's nsStaticAtom.
nsresult rv = CSSEditUtils::RemoveCSSPropertyWithTransaction(
*this, MOZ_KnownLive(*styledElement), MOZ_KnownLive(marginProperty),
value);
if (rv == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING(
"CSSEditUtils::RemoveCSSPropertyWithTransaction() destroyed the "
"editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"CSSEditUtils::RemoveCSSPropertyWithTransaction() failed, but ignored");
}
// Remove unnecessary divs
if (!aElement.IsHTMLElement(nsGkAtoms::div) ||
HTMLEditUtils::ElementHasAttribute(aElement)) {
return EditorDOMPoint();
}
// Don't touch editing host nor node which is outside of it.
if (&aElement == &aEditingHost ||
!aElement.IsInclusiveDescendantOf(&aEditingHost)) {
return EditorDOMPoint();
}
Result<EditorDOMPoint, nsresult> unwrapDivElementResult =
RemoveContainerWithTransaction(aElement);
NS_WARNING_ASSERTION(unwrapDivElementResult.isOk(),
"HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapDivElementResult;
}
Result<EditActionResult, nsresult>
HTMLEditor::SetSelectionToAbsoluteAsSubAction(const Element& aEditingHost) {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eSetPositionToAbsolute, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
auto EnsureCaretInElementIfCollapsedOutside =
[&](Element& aElement) MOZ_CAN_RUN_SCRIPT {
if (!SelectionRef().IsCollapsed() || !SelectionRef().RangeCount()) {
return NS_OK;
}
const auto firstRangeStartPoint =
GetFirstSelectionStartPoint<EditorRawDOMPoint>();
if (MOZ_UNLIKELY(!firstRangeStartPoint.IsSet())) {
return NS_OK;
}
const Result<EditorRawDOMPoint, nsresult> pointToPutCaretOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(aElement, firstRangeStartPoint);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() "
"failed, but ignored");
return NS_OK;
}
if (!pointToPutCaretOrError.inspect().IsSet()) {
return NS_OK;
}
nsresult rv = CollapseSelectionTo(pointToPutCaretOrError.inspect());
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
return NS_OK;
};
RefPtr<Element> focusElement = GetSelectionContainerElement();
if (focusElement && HTMLEditUtils::IsImage(focusElement)) {
nsresult rv = EnsureCaretInElementIfCollapsedOutside(*focusElement);
if (NS_FAILED(rv)) {
NS_WARNING("EnsureCaretInElementIfCollapsedOutside() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
// XXX Why do we do this only when there is only one selection range?
if (!SelectionRef().IsCollapsed() && SelectionRef().RangeCount() == 1u) {
Result<EditorRawDOMRange, nsresult> extendedRange =
GetRangeExtendedToHardLineEdgesForBlockEditAction(
SelectionRef().GetRangeAt(0u), aEditingHost);
if (MOZ_UNLIKELY(extendedRange.isErr())) {
NS_WARNING(
"HTMLEditor::GetRangeExtendedToHardLineEdgesForBlockEditAction() "
"failed");
return extendedRange.propagateErr();
}
// Note that end point may be prior to start point. So, we
// cannot use Selection::SetStartAndEndInLimit() here.
IgnoredErrorResult error;
SelectionRef().SetBaseAndExtentInLimiter(
extendedRange.inspect().StartRef().ToRawRangeBoundary(),
extendedRange.inspect().EndRef().ToRawRangeBoundary(), error);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("Selection::SetBaseAndExtentInLimiter() failed");
return Err(error.StealNSResult());
}
}
RefPtr<Element> divElement;
rv = MoveSelectedContentsToDivElementToMakeItAbsolutePosition(
address_of(divElement), aEditingHost);
// MoveSelectedContentsToDivElementToMakeItAbsolutePosition() may restore
// selection with AutoSelectionRestorer. Therefore, the editor might have
// already been destroyed now.
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::MoveSelectedContentsToDivElementToMakeItAbsolutePosition()"
" failed");
return Err(rv);
}
if (IsSelectionRangeContainerNotContent()) {
NS_WARNING("Mutation event listener might have changed the selection");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
rv = MaybeInsertPaddingBRElementForEmptyLastLineAtSelection();
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() "
"failed");
return Err(rv);
}
if (!divElement) {
return EditActionResult::HandledResult();
}
rv = SetPositionToAbsoluteOrStatic(*divElement, true);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::SetPositionToAbsoluteOrStatic() failed");
return Err(rv);
}
rv = EnsureCaretInElementIfCollapsedOutside(*divElement);
if (NS_FAILED(rv)) {
NS_WARNING("EnsureCaretInElementIfCollapsedOutside() failed");
return Err(rv);
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::MoveSelectedContentsToDivElementToMakeItAbsolutePosition(
RefPtr<Element>* aTargetElement, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aTargetElement);
AutoSelectionRestorer restoreSelectionLater(*this);
EditorDOMPoint pointToPutCaret;
// Use these ranges to construct a list of nodes to act on.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
AutoRangeArray extendedSelectionRanges(SelectionRef());
extendedSelectionRanges.ExtendRangesToWrapLinesToHandleBlockLevelEditAction(
EditSubAction::eSetPositionToAbsolute, aEditingHost);
Result<EditorDOMPoint, nsresult> splitResult =
extendedSelectionRanges
.SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
*this, aEditingHost);
if (MOZ_UNLIKELY(splitResult.isErr())) {
NS_WARNING(
"AutoRangeArray::"
"SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries() "
"failed");
return splitResult.unwrapErr();
}
if (splitResult.inspect().IsSet()) {
pointToPutCaret = splitResult.unwrap();
}
nsresult rv = extendedSelectionRanges.CollectEditTargetNodes(
*this, arrayOfContents, EditSubAction::eSetPositionToAbsolute,
AutoRangeArray::CollectNonEditableNodes::Yes);
if (NS_FAILED(rv)) {
NS_WARNING(
"AutoRangeArray::CollectEditTargetNodes(EditSubAction::"
"eSetPositionToAbsolute, CollectNonEditableNodes::Yes) failed");
return rv;
}
}
Result<EditorDOMPoint, nsresult> splitAtBRElementsResult =
MaybeSplitElementsAtEveryBRElement(arrayOfContents,
EditSubAction::eSetPositionToAbsolute);
if (MOZ_UNLIKELY(splitAtBRElementsResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitElementsAtEveryBRElement(EditSubAction::"
"eSetPositionToAbsolute) failed");
return splitAtBRElementsResult.inspectErr();
}
if (splitAtBRElementsResult.inspect().IsSet()) {
pointToPutCaret = splitAtBRElementsResult.unwrap();
}
if (AllowsTransactionsToChangeSelection() &&
pointToPutCaret.IsSetAndValid()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return rv;
}
}
// If there is no visible and editable nodes in the edit targets, make an
// empty block.
// XXX Isn't this odd if there are only non-editable visible nodes?
if (HTMLEditUtils::IsEmptyOneHardLine(arrayOfContents)) {
const auto atCaret =
EditorBase::GetFirstSelectionStartPoint<EditorDOMPoint>();
if (NS_WARN_IF(!atCaret.IsSet())) {
return NS_ERROR_FAILURE;
}
// Make sure we can put a block here.
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atCaret, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult.unwrapErr();
}
CreateElementResult unwrappedCreateNewDivElementResult =
createNewDivElementResult.unwrap();
// We'll update selection after deleting the content nodes and nobody
// refers selection until then. Therefore, we don't need to update
// selection here.
unwrappedCreateNewDivElementResult.IgnoreCaretPointSuggestion();
RefPtr<Element> newDivElement =
unwrappedCreateNewDivElementResult.UnwrapNewNode();
MOZ_ASSERT(newDivElement);
// Delete anything that was in the list of nodes
// XXX We don't need to remove items from the array.
for (OwningNonNull<nsIContent>& curNode : arrayOfContents) {
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to keep it alive.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*curNode));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
// Don't restore the selection
restoreSelectionLater.Abort();
nsresult rv = CollapseSelectionToStartOf(*newDivElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
*aTargetElement = std::move(newDivElement);
return rv;
}
// `<div>` element to be positioned absolutely. This may have already
// existed or newly created by this method.
RefPtr<Element> targetDivElement;
// Newly created list element for moving selected list item elements into
// targetDivElement. I.e., this is created in the `<div>` element.
RefPtr<Element> createdListElement;
// If we handle a parent list item element, this is set to it. In such case,
// we should handle its children again.
RefPtr<Element> handledListItemElement;
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
// Here's where we actually figure out what to do.
EditorDOMPoint atContent(content);
if (NS_WARN_IF(!atContent.IsSet())) {
return NS_ERROR_FAILURE; // XXX not continue??
}
// Ignore all non-editable nodes. Leave them be.
if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
continue;
}
// If current node is a child of a list element, we need another list
// element in absolute-positioned `<div>` element to avoid non-selected
// list items are moved into the `<div>` element.
if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
// If we cannot move current node to created list element, we need a
// list element in the target `<div>` element for the destination.
// Therefore, duplicate same list element into the target `<div>`
// element.
nsIContent* previousEditableContent =
createdListElement
? HTMLEditUtils::GetPreviousSibling(
content, {WalkTreeOption::IgnoreNonEditableNode})
: nullptr;
if (!createdListElement ||
(previousEditableContent &&
previousEditableContent != createdListElement)) {
nsAtom* ULOrOLOrDLTagName =
atContent.GetContainer()->NodeInfo()->NameAtom();
if (targetDivElement) {
// XXX Do we need to split the container? Since we'll append new
// element at end of the <div> element.
Result<SplitNodeResult, nsresult> splitNodeResult =
MaybeSplitAncestorsForInsertWithTransaction(
MOZ_KnownLive(*ULOrOLOrDLTagName), atContent, aEditingHost);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction() "
"failed");
return splitNodeResult.unwrapErr();
}
// We'll update selection after creating a list element below.
// Therefore, we don't need to touch selection here.
splitNodeResult.inspect().IgnoreCaretPointSuggestion();
} else {
// If we've not had a target <div> element yet, let's insert a <div>
// element with splitting the ancestors.
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTransaction(nsGkAtoms::"
"div) failed");
return createNewDivElementResult.unwrapErr();
}
// We'll update selection after creating a list element below.
// Therefor, we don't need to touch selection here.
createNewDivElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(createNewDivElementResult.inspect().GetNewNode());
targetDivElement = createNewDivElementResult.unwrap().UnwrapNewNode();
}
Result<CreateElementResult, nsresult> createNewListElementResult =
CreateAndInsertElement(WithTransaction::Yes,
MOZ_KnownLive(*ULOrOLOrDLTagName),
EditorDOMPoint::AtEndOf(targetDivElement));
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) "
"failed");
return createNewListElementResult.unwrapErr();
}
nsresult rv = createNewListElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateElementResult::SuggestCaretPointTo() failed, but ignored");
createdListElement =
createNewListElementResult.unwrap().UnwrapNewNode();
MOZ_ASSERT(createdListElement);
}
// Move current node (maybe, assumed as a list item element) into the
// new list element in the target `<div>` element to be positioned
// absolutely.
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content),
*createdListElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
nsresult rv = moveNodeResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
continue;
}
// If contents in a list item element is selected, we should move current
// node into the target `<div>` element with the list item element itself
// because we want to keep indent level of the contents.
if (RefPtr<Element> listItemElement =
HTMLEditUtils::GetClosestAncestorListItemElement(content,
&aEditingHost)) {
if (handledListItemElement == listItemElement) {
// Current node has already been moved into the `<div>` element.
continue;
}
// If we cannot move the list item element into created list element,
// we need another list element in the target `<div>` element.
nsIContent* previousEditableContent =
createdListElement
? HTMLEditUtils::GetPreviousSibling(
*listItemElement, {WalkTreeOption::IgnoreNonEditableNode})
: nullptr;
if (!createdListElement ||
(previousEditableContent &&
previousEditableContent != createdListElement)) {
EditorDOMPoint atListItem(listItemElement);
if (NS_WARN_IF(!atListItem.IsSet())) {
return NS_ERROR_FAILURE;
}
// XXX If content is the listItemElement and not in a list element,
// we duplicate wrong element into the target `<div>` element.
nsAtom* containerName =
atListItem.GetContainer()->NodeInfo()->NameAtom();
if (targetDivElement) {
// XXX Do we need to split the container? Since we'll append new
// element at end of the <div> element.
Result<SplitNodeResult, nsresult> splitNodeResult =
MaybeSplitAncestorsForInsertWithTransaction(
MOZ_KnownLive(*containerName), atListItem, aEditingHost);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING(
"HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction() "
"failed");
return splitNodeResult.unwrapErr();
}
// We'll update selection after creating a list element below.
// Therefore, we don't need to touch selection here.
splitNodeResult.inspect().IgnoreCaretPointSuggestion();
} else {
// If we've not had a target <div> element yet, let's insert a <div>
// element with splitting the ancestors.
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::"
"InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult.unwrapErr();
}
// We'll update selection after creating a list element below.
// Therefore, we don't need to touch selection here.
createNewDivElementResult.inspect().IgnoreCaretPointSuggestion();
MOZ_ASSERT(createNewDivElementResult.inspect().GetNewNode());
targetDivElement = createNewDivElementResult.unwrap().UnwrapNewNode();
}
// XXX So, createdListElement may be set to a non-list element.
Result<CreateElementResult, nsresult> createNewListElementResult =
CreateAndInsertElement(WithTransaction::Yes,
MOZ_KnownLive(*containerName),
EditorDOMPoint::AtEndOf(targetDivElement));
if (MOZ_UNLIKELY(createNewListElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) "
"failed");
return createNewListElementResult.unwrapErr();
}
nsresult rv = createNewListElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateElementResult::SuggestCaretPointTo() failed, but ignored");
createdListElement =
createNewListElementResult.unwrap().UnwrapNewNode();
MOZ_ASSERT(createdListElement);
}
// Move current list item element into the createdListElement (could be
// non-list element due to the above bug) in a candidate `<div>` element
// to be positioned absolutely.
Result<MoveNodeResult, nsresult> moveListItemElementResult =
MoveNodeToEndWithTransaction(*listItemElement, *createdListElement);
if (MOZ_UNLIKELY(moveListItemElementResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveListItemElementResult.unwrapErr();
}
nsresult rv = moveListItemElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
handledListItemElement = std::move(listItemElement);
continue;
}
if (!targetDivElement) {
// If we meet a `<div>` element, use it as the absolute-position
// container.
// XXX This looks odd. If there are 2 or more `<div>` elements are
// selected, first found `<div>` element will have all other
// selected nodes.
if (content->IsHTMLElement(nsGkAtoms::div)) {
targetDivElement = content->AsElement();
MOZ_ASSERT(!createdListElement);
MOZ_ASSERT(!handledListItemElement);
continue;
}
// Otherwise, create new `<div>` element to be positioned absolutely
// and to contain all selected nodes.
Result<CreateElementResult, nsresult> createNewDivElementResult =
InsertElementWithSplittingAncestorsWithTransaction(
*nsGkAtoms::div, atContent, BRElementNextToSplitPoint::Keep,
aEditingHost);
if (MOZ_UNLIKELY(createNewDivElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertElementWithSplittingAncestorsWithTransaction("
"nsGkAtoms::div) failed");
return createNewDivElementResult.unwrapErr();
}
nsresult rv = createNewDivElementResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed");
return rv;
}
MOZ_ASSERT(createNewDivElementResult.inspect().GetNewNode());
targetDivElement = createNewDivElementResult.unwrap().UnwrapNewNode();
}
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to keep it alive.
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(MOZ_KnownLive(content), *targetDivElement);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.unwrapErr();
}
nsresult rv = moveNodeResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
return rv;
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
// Forget createdListElement, if any
createdListElement = nullptr;
}
*aTargetElement = std::move(targetDivElement);
return NS_OK;
}
Result<EditActionResult, nsresult>
HTMLEditor::SetSelectionToStaticAsSubAction() {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eSetPositionToStatic, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
RefPtr<Element> element = GetAbsolutelyPositionedSelectionContainer();
if (!element) {
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::GetAbsolutelyPositionedSelectionContainer() returned "
"nullptr");
return Err(NS_ERROR_FAILURE);
}
{
AutoSelectionRestorer restoreSelectionLater(*this);
nsresult rv = SetPositionToAbsoluteOrStatic(*element, false);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::SetPositionToAbsoluteOrStatic() failed");
return Err(rv);
}
}
// Restoring Selection might cause destroying the HTML editor.
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING("Destroying AutoSelectionRestorer caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return EditActionResult::HandledResult();
}
Result<EditActionResult, nsresult> HTMLEditor::AddZIndexAsSubAction(
int32_t aChange) {
MOZ_ASSERT(IsEditActionDataAvailable());
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this,
aChange < 0 ? EditSubAction::eDecreaseZIndex
: EditSubAction::eIncreaseZIndex,
nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
RefPtr<Element> absolutelyPositionedElement =
GetAbsolutelyPositionedSelectionContainer();
if (!absolutelyPositionedElement) {
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::GetAbsolutelyPositionedSelectionContainer() returned "
"nullptr");
return Err(NS_ERROR_FAILURE);
}
nsStyledElement* absolutelyPositionedStyledElement =
nsStyledElement::FromNode(absolutelyPositionedElement);
if (NS_WARN_IF(!absolutelyPositionedStyledElement)) {
return Err(NS_ERROR_FAILURE);
}
{
AutoSelectionRestorer restoreSelectionLater(*this);
// MOZ_KnownLive(*absolutelyPositionedStyledElement): It's
// absolutelyPositionedElement whose type is RefPtr.
Result<int32_t, nsresult> result = AddZIndexWithTransaction(
MOZ_KnownLive(*absolutelyPositionedStyledElement), aChange);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::AddZIndexWithTransaction() failed");
return result.propagateErr();
}
}
// Restoring Selection might cause destroying the HTML editor.
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING("Destroying AutoSelectionRestorer caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return EditActionResult::HandledResult();
}
nsresult HTMLEditor::OnDocumentModified() {
if (mPendingDocumentModifiedRunner) {
return NS_OK; // We've already posted same runnable into the queue.
}
mPendingDocumentModifiedRunner = NewRunnableMethod(
"HTMLEditor::OnModifyDocument", this, &HTMLEditor::OnModifyDocument);
nsContentUtils::AddScriptRunner(do_AddRef(mPendingDocumentModifiedRunner));
// Be aware, if OnModifyDocument() may be called synchronously, the
// editor might have been destroyed here.
return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : NS_OK;
}
} // namespace mozilla
|