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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Implementation of mozilla::dom::Selection
*/
#include "mozilla/dom/Selection.h"
#include "mozilla/AccessibleCaretEventHub.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoCopyListener.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/SelectionBinding.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventStates.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/Logging.h"
#include "mozilla/layers/ScrollInputMethods.h"
#include "mozilla/PresShell.h"
#include "mozilla/RangeBoundary.h"
#include "mozilla/RangeUtils.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/Telemetry.h"
#include "nsCOMPtr.h"
#include "nsDebug.h"
#include "nsString.h"
#include "nsFrameSelection.h"
#include "nsISelectionListener.h"
#include "nsContentCID.h"
#include "nsDeviceContext.h"
#include "nsIContent.h"
#include "nsRange.h"
#include "nsITableCellLayout.h"
#include "nsTArray.h"
#include "nsTableWrapperFrame.h"
#include "nsTableCellFrame.h"
#include "nsIScrollableFrame.h"
#include "nsCCUncollectableMarker.h"
#include "nsIDocumentEncoder.h"
#include "nsTextFragment.h"
#include <algorithm>
#include "nsContentUtils.h"
#include "nsGkAtoms.h"
#include "nsLayoutUtils.h"
#include "nsBidiPresUtils.h"
#include "nsTextFrame.h"
#include "nsContentUtils.h"
#include "nsThreadUtils.h"
#include "nsPresContext.h"
#include "nsCaret.h"
#include "nsITimer.h"
#include "mozilla/dom/Document.h"
#include "nsINamed.h"
#include "nsISelectionController.h" //for the enums
#include "nsCopySupport.h"
#include "nsIFrameInlines.h"
#include "nsRefreshDriver.h"
#include "nsError.h"
#include "nsViewManager.h"
#include "nsFocusManager.h"
#include "nsPIDOMWindow.h"
using namespace mozilla;
using namespace mozilla::dom;
using mozilla::layers::ScrollInputMethod;
static LazyLogModule sSelectionLog("Selection");
//#define DEBUG_TABLE 1
#ifdef PRINT_RANGE
static void printRange(nsRange* aDomRange);
# define DEBUG_OUT_RANGE(x) printRange(x)
#else
# define DEBUG_OUT_RANGE(x)
#endif // PRINT_RANGE
/******************************************************************************
* Utility methods defined in nsISelectionController.idl
******************************************************************************/
namespace mozilla {
const char* ToChar(SelectionType aSelectionType) {
switch (aSelectionType) {
case SelectionType::eInvalid:
return "SelectionType::eInvalid";
case SelectionType::eNone:
return "SelectionType::eNone";
case SelectionType::eNormal:
return "SelectionType::eNormal";
case SelectionType::eSpellCheck:
return "SelectionType::eSpellCheck";
case SelectionType::eIMERawClause:
return "SelectionType::eIMERawClause";
case SelectionType::eIMESelectedRawClause:
return "SelectionType::eIMESelectedRawClause";
case SelectionType::eIMEConvertedClause:
return "SelectionType::eIMEConvertedClause";
case SelectionType::eIMESelectedClause:
return "SelectionType::eIMESelectedClause";
case SelectionType::eAccessibility:
return "SelectionType::eAccessibility";
case SelectionType::eFind:
return "SelectionType::eFind";
case SelectionType::eURLSecondary:
return "SelectionType::eURLSecondary";
case SelectionType::eURLStrikeout:
return "SelectionType::eURLStrikeout";
default:
return "Invalid SelectionType";
}
}
} // namespace mozilla
//#define DEBUG_SELECTION // uncomment for printf describing every collapse and
// extend. #define DEBUG_NAVIGATION
//#define DEBUG_TABLE_SELECTION 1
struct CachedOffsetForFrame {
CachedOffsetForFrame()
: mCachedFrameOffset(0, 0) // nsPoint ctor
,
mLastCaretFrame(nullptr),
mLastContentOffset(0),
mCanCacheFrameOffset(false) {}
nsPoint mCachedFrameOffset; // cached frame offset
nsIFrame* mLastCaretFrame; // store the frame the caret was last drawn in.
int32_t mLastContentOffset; // store last content offset
bool mCanCacheFrameOffset; // cached frame offset is valid?
};
class AutoScroller final : public nsITimerCallback, public nsINamed {
public:
NS_DECL_ISUPPORTS
explicit AutoScroller(nsFrameSelection* aFrameSelection)
: mFrameSelection(aFrameSelection),
mPresContext(0),
mPoint(0, 0),
mDelayInMs(30),
mFurtherScrollingAllowed(FurtherScrollingAllowed::kYes) {
MOZ_ASSERT(mFrameSelection);
}
MOZ_CAN_RUN_SCRIPT nsresult DoAutoScroll(nsIFrame* aFrame, nsPoint aPoint);
private:
// aPoint is relative to aPresContext's root frame
nsresult ScheduleNextDoAutoScroll(nsPresContext* aPresContext,
nsPoint& aPoint) {
if (NS_WARN_IF(mFurtherScrollingAllowed == FurtherScrollingAllowed::kNo)) {
return NS_ERROR_FAILURE;
}
mPoint = aPoint;
// Store the presentation context. The timer will be
// stopped by the selection if the prescontext is destroyed.
mPresContext = aPresContext;
mContent = PresShell::GetCapturingContent();
if (!mTimer) {
mTimer = NS_NewTimer(
mPresContext->Document()->EventTargetFor(TaskCategory::Other));
if (!mTimer) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
return mTimer->InitWithCallback(this, mDelayInMs, nsITimer::TYPE_ONE_SHOT);
}
public:
enum class FurtherScrollingAllowed { kYes, kNo };
void Stop(const FurtherScrollingAllowed aFurtherScrollingAllowed) {
MOZ_ASSERT((aFurtherScrollingAllowed == FurtherScrollingAllowed::kNo) ||
(mFurtherScrollingAllowed == FurtherScrollingAllowed::kYes));
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
mContent = nullptr;
mFurtherScrollingAllowed = aFurtherScrollingAllowed;
}
void SetDelay(uint32_t aDelayInMs) { mDelayInMs = aDelayInMs; }
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Notify(nsITimer* timer) override {
if (mPresContext) {
AutoWeakFrame frame =
mContent ? mPresContext->GetPrimaryFrameFor(mContent) : nullptr;
if (!frame) {
return NS_OK;
}
mContent = nullptr;
nsPoint pt = mPoint - frame->GetOffsetTo(
mPresContext->PresShell()->GetRootFrame());
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->HandleDrag(frame, pt);
if (!frame.IsAlive()) {
return NS_OK;
}
NS_ASSERTION(frame->PresContext() == mPresContext, "document mismatch?");
DoAutoScroll(frame, pt);
}
return NS_OK;
}
NS_IMETHOD GetName(nsACString& aName) override {
aName.AssignLiteral("AutoScroller");
return NS_OK;
}
protected:
virtual ~AutoScroller() {
if (mTimer) {
mTimer->Cancel();
}
}
private:
nsFrameSelection* const mFrameSelection;
nsPresContext* mPresContext;
// relative to mPresContext's root frame
nsPoint mPoint;
nsCOMPtr<nsITimer> mTimer;
nsCOMPtr<nsIContent> mContent;
uint32_t mDelayInMs;
FurtherScrollingAllowed mFurtherScrollingAllowed;
};
NS_IMPL_ISUPPORTS(AutoScroller, nsITimerCallback, nsINamed)
#ifdef PRINT_RANGE
void printRange(nsRange* aDomRange) {
if (!aDomRange) {
printf("NULL Range\n");
}
nsINode* startNode = aDomRange->GetStartContainer();
nsINode* endNode = aDomRange->GetEndContainer();
int32_t startOffset = aDomRange->StartOffset();
int32_t endOffset = aDomRange->EndOffset();
printf("range: 0x%lx\t start: 0x%lx %ld, \t end: 0x%lx,%ld\n",
(unsigned long)aDomRange, (unsigned long)startNode, (long)startOffset,
(unsigned long)endNode, (long)endOffset);
}
#endif /* PRINT_RANGE */
void Selection::Stringify(nsAString& aResult, FlushFrames aFlushFrames) {
if (aFlushFrames == FlushFrames::Yes) {
// We need FlushType::Frames here to make sure frames have been created for
// the selected content. Use mFrameSelection->GetPresShell() which returns
// null if the Selection has been disconnected (the shell is Destroyed).
RefPtr<PresShell> presShell =
mFrameSelection ? mFrameSelection->GetPresShell() : nullptr;
if (!presShell) {
aResult.Truncate();
return;
}
presShell->FlushPendingNotifications(FlushType::Frames);
}
IgnoredErrorResult rv;
ToStringWithFormat(u"text/plain"_ns, nsIDocumentEncoder::SkipInvisibleContent,
0, aResult, rv);
if (rv.Failed()) {
aResult.Truncate();
}
}
void Selection::ToStringWithFormat(const nsAString& aFormatType,
uint32_t aFlags, int32_t aWrapCol,
nsAString& aReturn, ErrorResult& aRv) {
nsCOMPtr<nsIDocumentEncoder> encoder =
do_createDocumentEncoder(NS_ConvertUTF16toUTF8(aFormatType).get());
if (!encoder) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
PresShell* presShell = GetPresShell();
if (!presShell) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
Document* doc = presShell->GetDocument();
// Flags should always include OutputSelectionOnly if we're coming from here:
aFlags |= nsIDocumentEncoder::OutputSelectionOnly;
nsAutoString readstring;
readstring.Assign(aFormatType);
nsresult rv = encoder->Init(doc, readstring, aFlags);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
encoder->SetSelection(this);
if (aWrapCol != 0) encoder->SetWrapColumn(aWrapCol);
rv = encoder->EncodeToString(aReturn);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
}
}
void Selection::SetInterlinePosition(bool aHintRight, ErrorResult& aRv) {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED); // Can't do selection
return;
}
mFrameSelection->SetHint(aHintRight ? CARET_ASSOCIATE_AFTER
: CARET_ASSOCIATE_BEFORE);
}
bool Selection::GetInterlinePosition(ErrorResult& aRv) {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED); // Can't do selection
return false;
}
return mFrameSelection->GetHint() == CARET_ASSOCIATE_AFTER;
}
static bool IsEditorNode(const nsINode* aNode) {
if (!aNode) {
return false;
}
if (aNode->IsEditable()) {
return true;
}
auto* element = Element::FromNode(aNode);
return element && element->State().HasState(NS_EVENT_STATE_READWRITE);
}
bool Selection::IsEditorSelection() const {
return IsEditorNode(GetFocusNode());
}
Nullable<int16_t> Selection::GetCaretBidiLevel(
mozilla::ErrorResult& aRv) const {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return Nullable<int16_t>();
}
nsBidiLevel caretBidiLevel = mFrameSelection->GetCaretBidiLevel();
return (caretBidiLevel & BIDI_LEVEL_UNDEFINED)
? Nullable<int16_t>()
: Nullable<int16_t>(caretBidiLevel);
}
void Selection::SetCaretBidiLevel(const Nullable<int16_t>& aCaretBidiLevel,
mozilla::ErrorResult& aRv) {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return;
}
if (aCaretBidiLevel.IsNull()) {
mFrameSelection->UndefineCaretBidiLevel();
} else {
mFrameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(
aCaretBidiLevel.Value());
}
}
/**
* Test whether the supplied range points to a single table element.
* Result is one of the TableSelectionMode constants. "None" means
* a table element isn't selected.
*/
// TODO: Figure out TableSelectionMode::Column and TableSelectionMode::AllCells
static nsresult GetTableSelectionMode(const nsRange& aRange,
TableSelectionMode* aTableSelectionType) {
if (!aTableSelectionType) {
return NS_ERROR_NULL_POINTER;
}
*aTableSelectionType = TableSelectionMode::None;
nsINode* startNode = aRange.GetStartContainer();
if (!startNode) {
return NS_ERROR_FAILURE;
}
nsINode* endNode = aRange.GetEndContainer();
if (!endNode) {
return NS_ERROR_FAILURE;
}
// Not a single selected node
if (startNode != endNode) {
return NS_OK;
}
nsIContent* child = aRange.GetChildAtStartOffset();
// Not a single selected node
if (!child || child->GetNextSibling() != aRange.GetChildAtEndOffset()) {
return NS_OK;
}
nsIContent* startContent = static_cast<nsIContent*>(startNode);
if (!(startNode->IsElement() && startContent->IsHTMLElement())) {
// Implies a check for being an element; if we ever make this work
// for non-HTML, need to keep checking for elements.
return NS_OK;
}
if (startContent->IsHTMLElement(nsGkAtoms::tr)) {
*aTableSelectionType = TableSelectionMode::Cell;
} else // check to see if we are selecting a table or row (column and all
// cells not done yet)
{
if (child->IsHTMLElement(nsGkAtoms::table)) {
*aTableSelectionType = TableSelectionMode::Table;
} else if (child->IsHTMLElement(nsGkAtoms::tr)) {
*aTableSelectionType = TableSelectionMode::Row;
}
}
return NS_OK;
}
nsresult Selection::MaybeAddTableCellRange(nsRange& aRange, bool* aDidAddRange,
int32_t* aOutIndex) {
if (!aDidAddRange || !aOutIndex) {
return NS_ERROR_NULL_POINTER;
}
*aDidAddRange = false;
*aOutIndex = -1;
if (!mFrameSelection) return NS_OK;
// Get if we are adding a cell selection and the row, col of cell if we are
TableSelectionMode tableMode;
nsresult result = GetTableSelectionMode(aRange, &tableMode);
if (NS_FAILED(result)) return result;
// If not adding a cell range, we are done here
if (tableMode != TableSelectionMode::Cell) {
mFrameSelection->mTableSelection.mMode = tableMode;
// Don't fail if range isn't a selected cell, aDidAddRange tells caller if
// we didn't proceed
return NS_OK;
}
// Set frame selection mode only if not already set to a table mode
// so we don't lose the select row and column flags (not detected by
// getTableCellLocation)
if (mFrameSelection->mTableSelection.mMode == TableSelectionMode::None) {
mFrameSelection->mTableSelection.mMode = tableMode;
}
result = AddRangesForSelectableNodes(&aRange, aOutIndex,
DispatchSelectstartEvent::Maybe);
*aDidAddRange = *aOutIndex != -1;
return result;
}
Selection::Selection(SelectionType aSelectionType,
nsFrameSelection* aFrameSelection)
: mFrameSelection(aFrameSelection),
mCachedOffsetForFrame(nullptr),
mDirection(eDirNext),
mSelectionType(aSelectionType),
mCustomColors(nullptr),
mSelectionChangeBlockerCount(0),
mUserInitiated(false),
mCalledByJS(false),
mNotifyAutoCopy(false) {}
Selection::~Selection() { Disconnect(); }
void Selection::Disconnect() {
SetAnchorFocusRange(-1);
mStyledRanges.UnregisterSelection();
if (mAutoScroller) {
mAutoScroller->Stop(AutoScroller::FurtherScrollingAllowed::kNo);
mAutoScroller = nullptr;
}
mScrollEvent.Revoke();
if (mCachedOffsetForFrame) {
delete mCachedOffsetForFrame;
mCachedOffsetForFrame = nullptr;
}
}
Document* Selection::GetParentObject() const {
PresShell* presShell = GetPresShell();
return presShell ? presShell->GetDocument() : nullptr;
}
DocGroup* Selection::GetDocGroup() const {
PresShell* presShell = GetPresShell();
if (!presShell) {
return nullptr;
}
Document* doc = presShell->GetDocument();
return doc ? doc->GetDocGroup() : nullptr;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(Selection)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Selection)
// Unlink the selection listeners *before* we do RemoveAllRanges since
// we don't want to notify the listeners during JS GC (they could be
// in JS!).
tmp->mNotifyAutoCopy = false;
if (tmp->mAccessibleCaretEventHub) {
tmp->StopNotifyingAccessibleCaretEventHub();
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionChangeEventDispatcher)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionListeners)
tmp->RemoveAllRanges(IgnoreErrors());
NS_IMPL_CYCLE_COLLECTION_UNLINK(mFrameSelection)
NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_PTR
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Selection)
{
uint32_t i, count = tmp->mStyledRanges.Length();
for (i = 0; i < count; ++i) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyledRanges.mRanges[i].mRange)
}
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAnchorFocusRange)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFrameSelection)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionChangeEventDispatcher)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionListeners)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(Selection)
// QueryInterface implementation for Selection
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Selection)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_MAIN_THREAD_ONLY_CYCLE_COLLECTING_ADDREF(Selection)
NS_IMPL_MAIN_THREAD_ONLY_CYCLE_COLLECTING_RELEASE_WITH_LAST_RELEASE(
Selection, Disconnect())
const RangeBoundary& Selection::AnchorRef() const {
if (!mAnchorFocusRange) {
static RangeBoundary sEmpty;
return sEmpty;
}
if (GetDirection() == eDirNext) {
return mAnchorFocusRange->StartRef();
}
return mAnchorFocusRange->EndRef();
}
const RangeBoundary& Selection::FocusRef() const {
if (!mAnchorFocusRange) {
static RangeBoundary sEmpty;
return sEmpty;
}
if (GetDirection() == eDirNext) {
return mAnchorFocusRange->EndRef();
}
return mAnchorFocusRange->StartRef();
}
void Selection::SetAnchorFocusRange(int32_t indx) {
if (indx >= (int32_t)mStyledRanges.Length()) {
return;
}
if (indx < 0) // release all
{
mAnchorFocusRange = nullptr;
} else {
mAnchorFocusRange = mStyledRanges.mRanges[indx].mRange;
}
}
static int32_t CompareToRangeStart(const nsINode& aCompareNode,
int32_t aCompareOffset,
const nsRange& aRange) {
MOZ_ASSERT(aRange.GetStartContainer());
nsINode* start = aRange.GetStartContainer();
// If the nodes that we're comparing are not in the same document or in the
// same subtree, assume that aCompareNode will fall at the end of the ranges.
// NOTE(emilio): This is broken (bug 1590379). When fixed, shadow-including
// tree order[1] seems the most reasonable order, but if we choose other order
// than that code in nsPrintJob.cpp to deal with selection printing might need
// to be fixed.
//
// [1]: https://dom.spec.whatwg.org/#concept-shadow-including-tree-order
if (aCompareNode.GetComposedDoc() != start->GetComposedDoc() ||
!start->GetComposedDoc() ||
aCompareNode.SubtreeRoot() != start->SubtreeRoot()) {
NS_WARNING(
"`CompareToRangeStart` couldn't compare nodes, pretending some order.");
return 1;
}
// The points are in the same subtree, hence there has to be an order.
return *nsContentUtils::ComparePoints(&aCompareNode, aCompareOffset, start,
aRange.StartOffset());
}
static int32_t CompareToRangeEnd(const nsINode& aCompareNode,
int32_t aCompareOffset,
const nsRange& aRange) {
MOZ_ASSERT(aRange.IsPositioned());
nsINode* end = aRange.GetEndContainer();
// If the nodes that we're comparing are not in the same document or in the
// same subtree, assume that aCompareNode will fall at the end of the ranges.
if (aCompareNode.GetComposedDoc() != end->GetComposedDoc() ||
!end->GetComposedDoc() ||
aCompareNode.SubtreeRoot() != end->SubtreeRoot()) {
NS_WARNING(
"`CompareToRangeEnd` couldn't compare nodes, pretending some order.");
return 1;
}
// The points are in the same subtree, hence there has to be an order.
return *nsContentUtils::ComparePoints(&aCompareNode, aCompareOffset, end,
aRange.EndOffset());
}
// static
int32_t Selection::StyledRanges::FindInsertionPoint(
const nsTArray<StyledRange>* aElementArray, const nsINode& aPointNode,
int32_t aPointOffset,
int32_t (*aComparator)(const nsINode&, int32_t, const nsRange&)) {
int32_t beginSearch = 0;
int32_t endSearch = aElementArray->Length(); // one beyond what to check
if (endSearch) {
int32_t center = endSearch - 1; // Check last index, then binary search
do {
const nsRange* range = (*aElementArray)[center].mRange;
int32_t cmp{aComparator(aPointNode, aPointOffset, *range)};
if (cmp < 0) { // point < cur
endSearch = center;
} else if (cmp > 0) { // point > cur
beginSearch = center + 1;
} else { // found match, done
beginSearch = center;
break;
}
center = (endSearch - beginSearch) / 2 + beginSearch;
} while (endSearch - beginSearch > 0);
}
return beginSearch;
}
// Selection::SubtractRange
//
// A helper function that subtracts aSubtract from aRange, and adds
// 1 or 2 StyledRange objects representing the remaining non-overlapping
// difference to aOutput. It is assumed that the caller has checked that
// aRange and aSubtract do indeed overlap
// static
nsresult Selection::StyledRanges::SubtractRange(
StyledRange& aRange, nsRange& aSubtract, nsTArray<StyledRange>* aOutput) {
nsRange* range = aRange.mRange;
if (NS_WARN_IF(!range->IsPositioned())) {
return NS_ERROR_UNEXPECTED;
}
// First we want to compare to the range start
int32_t cmp{CompareToRangeStart(*range->GetStartContainer(),
range->StartOffset(), aSubtract)};
// Also, make a comparison to the range end
int32_t cmp2{CompareToRangeEnd(*range->GetEndContainer(), range->EndOffset(),
aSubtract)};
// If the existing range left overlaps the new range (aSubtract) then
// cmp < 0, and cmp2 < 0
// If it right overlaps the new range then cmp > 0 and cmp2 > 0
// If it fully contains the new range, then cmp < 0 and cmp2 > 0
if (cmp2 > 0) {
// We need to add a new StyledRange to the output, running from
// the end of aSubtract to the end of range
ErrorResult error;
RefPtr<nsRange> postOverlap =
nsRange::Create(aSubtract.EndRef(), range->EndRef(), error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
MOZ_ASSERT(postOverlap);
if (!postOverlap->Collapsed()) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
aOutput->InsertElementAt(0, StyledRange(postOverlap));
(*aOutput)[0].mTextRangeStyle = aRange.mTextRangeStyle;
}
}
if (cmp < 0) {
// We need to add a new StyledRange to the output, running from
// the start of the range to the start of aSubtract
ErrorResult error;
RefPtr<nsRange> preOverlap =
nsRange::Create(range->StartRef(), aSubtract.StartRef(), error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
MOZ_ASSERT(preOverlap);
if (!preOverlap->Collapsed()) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
aOutput->InsertElementAt(0, StyledRange(preOverlap));
(*aOutput)[0].mTextRangeStyle = aRange.mTextRangeStyle;
}
}
return NS_OK;
}
static void UserSelectRangesToAdd(nsRange* aItem,
nsTArray<RefPtr<nsRange>>& aRangesToAdd) {
// We cannot directly call IsEditorSelection() because we may be in an
// inconsistent state during Collapse() (we're cleared already but we haven't
// got a new focus node yet).
if (IsEditorNode(aItem->GetStartContainer()) &&
IsEditorNode(aItem->GetEndContainer())) {
// Don't mess with the selection ranges for editing, editor doesn't really
// deal well with multi-range selections.
aRangesToAdd.AppendElement(aItem);
} else {
aItem->ExcludeNonSelectableNodes(&aRangesToAdd);
}
}
static nsINode* DetermineSelectstartEventTarget(
const bool aSelectionEventsOnTextControlsEnabled, const nsRange& aRange) {
nsINode* target = aRange.GetStartContainer();
if (aSelectionEventsOnTextControlsEnabled) {
// Get the first element which isn't in a native anonymous subtree
while (target && target->IsInNativeAnonymousSubtree()) {
target = target->GetParent();
}
} else {
if (target->IsInNativeAnonymousSubtree()) {
// This is a selection under a text control, so don't dispatch the
// event.
target = nullptr;
}
}
return target;
}
/**
* @return true, iff the default action should be executed.
*/
static bool MaybeDispatchSelectstartEvent(
const nsRange& aRange, const bool aSelectionEventsOnTextControlsEnabled,
Document* aDocument) {
nsCOMPtr<nsINode> selectstartEventTarget = DetermineSelectstartEventTarget(
aSelectionEventsOnTextControlsEnabled, aRange);
bool executeDefaultAction = true;
if (selectstartEventTarget) {
nsContentUtils::DispatchTrustedEvent(
aDocument, selectstartEventTarget, u"selectstart"_ns, CanBubble::eYes,
Cancelable::eYes, &executeDefaultAction);
}
return executeDefaultAction;
}
// static
bool Selection::IsUserSelectionCollapsed(
const nsRange& aRange, nsTArray<RefPtr<nsRange>>& aTempRangesToAdd) {
MOZ_ASSERT(aTempRangesToAdd.IsEmpty());
RefPtr<nsRange> scratchRange = aRange.CloneRange();
UserSelectRangesToAdd(scratchRange, aTempRangesToAdd);
const bool userSelectionCollapsed =
(aTempRangesToAdd.Length() == 0) ||
((aTempRangesToAdd.Length() == 1) && aTempRangesToAdd[0]->Collapsed());
aTempRangesToAdd.ClearAndRetainStorage();
return userSelectionCollapsed;
}
nsresult Selection::AddRangesForUserSelectableNodes(
nsRange* aRange, int32_t* aOutIndex,
const DispatchSelectstartEvent aDispatchSelectstartEvent) {
MOZ_ASSERT(mUserInitiated);
MOZ_ASSERT(aOutIndex);
if (!aRange) {
return NS_ERROR_NULL_POINTER;
}
if (!aRange->IsPositioned()) {
return NS_ERROR_UNEXPECTED;
}
AutoTArray<RefPtr<nsRange>, 4> rangesToAdd;
*aOutIndex = int32_t(mStyledRanges.Length()) - 1;
Document* doc = GetDocument();
bool selectEventsEnabled = StaticPrefs::dom_select_events_enabled() ||
(doc && doc->NodePrincipal()->IsSystemPrincipal());
if (aDispatchSelectstartEvent == DispatchSelectstartEvent::Maybe &&
mSelectionType == SelectionType::eNormal && selectEventsEnabled &&
IsCollapsed() && !IsBlockingSelectionChangeEvents()) {
// We consider a selection to be starting if we are currently collapsed,
// and the selection is becoming uncollapsed, and this is caused by a
// user initiated event.
// First, we generate the ranges to add with a scratch range, which is a
// clone of the original range passed in. We do this seperately, because
// the selectstart event could have caused the world to change, and
// required ranges to be re-generated
const bool userSelectionCollapsed =
IsUserSelectionCollapsed(*aRange, rangesToAdd);
MOZ_ASSERT(userSelectionCollapsed || nsContentUtils::IsSafeToRunScript());
if (!userSelectionCollapsed && nsContentUtils::IsSafeToRunScript()) {
// The spec currently doesn't say that we should dispatch this event
// on text controls, so for now we only support doing that under a
// pref, disabled by default.
// See https://github.com/w3c/selection-api/issues/53.
const bool executeDefaultAction = MaybeDispatchSelectstartEvent(
*aRange, StaticPrefs::dom_select_events_textcontrols_enabled(), doc);
if (!executeDefaultAction) {
return NS_OK;
}
// As we potentially dispatched an event to the DOM, something could have
// changed under our feet. Re-generate the rangesToAdd array, and
// ensure that the range we are about to add is still valid.
if (!aRange->IsPositioned()) {
return NS_ERROR_UNEXPECTED;
}
}
}
// Generate the ranges to add
UserSelectRangesToAdd(aRange, rangesToAdd);
size_t newAnchorFocusIndex =
GetDirection() == eDirPrevious ? 0 : rangesToAdd.Length() - 1;
for (size_t i = 0; i < rangesToAdd.Length(); ++i) {
int32_t index;
const RefPtr<Selection> selection{this};
// `MOZ_KnownLive` needed because of broken static analysis
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1622253#c1).
nsresult rv = mStyledRanges.MaybeAddRangeAndTruncateOverlaps(
MOZ_KnownLive(rangesToAdd[i]), &index, *selection);
NS_ENSURE_SUCCESS(rv, rv);
if (i == newAnchorFocusIndex) {
*aOutIndex = index;
rangesToAdd[i]->SetIsGenerated(false);
} else {
rangesToAdd[i]->SetIsGenerated(true);
}
}
return NS_OK;
}
nsresult Selection::AddRangesForSelectableNodes(
nsRange* aRange, int32_t* aOutIndex,
const DispatchSelectstartEvent aDispatchSelectstartEvent) {
if (!aRange) {
return NS_ERROR_NULL_POINTER;
}
if (!aRange->IsPositioned()) {
return NS_ERROR_UNEXPECTED;
}
NS_ASSERTION(aOutIndex, "aOutIndex can't be null");
MOZ_LOG(
sSelectionLog, LogLevel::Debug,
("%s: selection=%p, type=%i, range=(%p, StartOffset=%u, EndOffset=%u)",
__FUNCTION__, this, static_cast<int>(GetType()), aRange,
aRange->StartOffset(), aRange->EndOffset()));
if (mUserInitiated) {
return AddRangesForUserSelectableNodes(aRange, aOutIndex,
aDispatchSelectstartEvent);
}
const RefPtr<Selection> selection{this};
return mStyledRanges.MaybeAddRangeAndTruncateOverlaps(aRange, aOutIndex,
*selection);
}
nsresult Selection::StyledRanges::MaybeAddRangeAndTruncateOverlaps(
nsRange* aRange, int32_t* aOutIndex, Selection& aSelection) {
MOZ_ASSERT(aRange);
MOZ_ASSERT(aRange->IsPositioned());
MOZ_ASSERT(aOutIndex);
*aOutIndex = -1;
// a common case is that we have no ranges yet
if (mRanges.Length() == 0) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
mRanges.AppendElement(StyledRange(aRange));
aRange->RegisterSelection(aSelection);
*aOutIndex = 0;
return NS_OK;
}
int32_t startIndex, endIndex;
nsresult rv =
GetIndicesForInterval(aRange->GetStartContainer(), aRange->StartOffset(),
aRange->GetEndContainer(), aRange->EndOffset(),
false, startIndex, endIndex);
NS_ENSURE_SUCCESS(rv, rv);
if (endIndex == -1) {
// All ranges start after the given range. We can insert our range at
// position 0, knowing there are no overlaps (handled below)
startIndex = 0;
endIndex = 0;
} else if (startIndex == -1) {
// All ranges end before the given range. We can insert our range at
// the end of the array, knowing there are no overlaps (handled below)
startIndex = mRanges.Length();
endIndex = startIndex;
}
// If the range is already contained in mRanges, silently
// succeed
const bool sameRange = HasEqualRangeBoundariesAt(*aRange, startIndex);
if (sameRange) {
*aOutIndex = startIndex;
return NS_OK;
}
if (startIndex == endIndex) {
// The new range doesn't overlap any existing ranges
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
mRanges.InsertElementAt(startIndex, StyledRange(aRange));
aRange->RegisterSelection(aSelection);
*aOutIndex = startIndex;
return NS_OK;
}
// We now know that at least 1 existing range overlaps with the range that
// we are trying to add. In fact, the only ranges of interest are those at
// the two end points, startIndex and endIndex - 1 (which may point to the
// same range) as these may partially overlap the new range. Any ranges
// between these indices are fully overlapped by the new range, and so can be
// removed
nsTArray<StyledRange> overlaps;
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
overlaps.InsertElementAt(0, mRanges[startIndex]);
if (endIndex - 1 != startIndex) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
overlaps.InsertElementAt(1, mRanges[endIndex - 1]);
}
// Remove all the overlapping ranges
for (int32_t i = startIndex; i < endIndex; ++i) {
mRanges[i].mRange->UnregisterSelection();
}
mRanges.RemoveElementsAt(startIndex, endIndex - startIndex);
nsTArray<StyledRange> temp;
for (int32_t i = overlaps.Length() - 1; i >= 0; i--) {
nsresult rv = SubtractRange(overlaps[i], *aRange, &temp);
NS_ENSURE_SUCCESS(rv, rv);
}
// Insert the new element into our "leftovers" array
// `aRange` is positioned, so it has to have a start container.
int32_t insertionPoint{FindInsertionPoint(&temp, *aRange->GetStartContainer(),
aRange->StartOffset(),
CompareToRangeStart)};
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
temp.InsertElementAt(insertionPoint, StyledRange(aRange));
// Merge the leftovers back in to mRanges
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
mRanges.InsertElementsAt(startIndex, temp);
for (uint32_t i = 0; i < temp.Length(); ++i) {
MOZ_KnownLive(temp[i].mRange)->RegisterSelection(aSelection);
// `MOZ_KnownLive` is required because of
// https://bugzilla.mozilla.org/show_bug.cgi?id=1622253.
}
*aOutIndex = startIndex + insertionPoint;
return NS_OK;
}
nsresult Selection::StyledRanges::RemoveRangeAndUnregisterSelection(
nsRange& aRange) {
// Find the range's index & remove it. We could use FindInsertionPoint to
// get O(log n) time, but that requires many expensive DOM comparisons.
// For even several thousand items, this is probably faster because the
// comparisons are so fast.
int32_t idx = -1;
uint32_t i;
for (i = 0; i < mRanges.Length(); i++) {
if (mRanges[i].mRange == &aRange) {
idx = (int32_t)i;
break;
}
}
if (idx < 0) return NS_ERROR_DOM_NOT_FOUND_ERR;
mRanges.RemoveElementAt(idx);
aRange.UnregisterSelection();
return NS_OK;
}
nsresult Selection::RemoveCollapsedRanges() {
return mStyledRanges.RemoveCollapsedRanges();
}
nsresult Selection::StyledRanges::RemoveCollapsedRanges() {
uint32_t i = 0;
while (i < mRanges.Length()) {
if (mRanges[i].mRange->Collapsed()) {
nsresult rv = RemoveRangeAndUnregisterSelection(*mRanges[i].mRange);
NS_ENSURE_SUCCESS(rv, rv);
} else {
++i;
}
}
return NS_OK;
}
nsresult Selection::Clear(nsPresContext* aPresContext) {
SetAnchorFocusRange(-1);
mStyledRanges.UnregisterSelection();
for (uint32_t i = 0; i < mStyledRanges.Length(); ++i) {
SelectFrames(aPresContext, mStyledRanges.mRanges[i].mRange, false);
}
mStyledRanges.Clear();
// Reset direction so for more dependable table selection range handling
SetDirection(eDirNext);
// If this was an ATTENTION selection, change it back to normal now
if (mFrameSelection && mFrameSelection->GetDisplaySelection() ==
nsISelectionController::SELECTION_ATTENTION) {
mFrameSelection->SetDisplaySelection(nsISelectionController::SELECTION_ON);
}
return NS_OK;
}
bool Selection::StyledRanges::HasEqualRangeBoundariesAt(
const nsRange& aRange, int32_t aRangeIndex) const {
if (aRangeIndex >= 0 && aRangeIndex < (int32_t)mRanges.Length()) {
const nsRange* range = mRanges[aRangeIndex].mRange;
return range->HasEqualBoundaries(aRange);
}
return false;
}
void Selection::GetRangesForInterval(nsINode& aBeginNode, int32_t aBeginOffset,
nsINode& aEndNode, int32_t aEndOffset,
bool aAllowAdjacent,
nsTArray<RefPtr<nsRange>>& aReturn,
mozilla::ErrorResult& aRv) {
nsTArray<nsRange*> results;
nsresult rv = GetRangesForIntervalArray(&aBeginNode, aBeginOffset, &aEndNode,
aEndOffset, aAllowAdjacent, &results);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
aReturn.SetLength(results.Length());
for (uint32_t i = 0; i < results.Length(); ++i) {
aReturn[i] = results[i]; // AddRefs
}
}
nsresult Selection::GetRangesForIntervalArray(
nsINode* aBeginNode, int32_t aBeginOffset, nsINode* aEndNode,
int32_t aEndOffset, bool aAllowAdjacent, nsTArray<nsRange*>* aRanges) {
if (NS_WARN_IF(!aBeginNode)) {
return NS_ERROR_UNEXPECTED;
}
if (NS_WARN_IF(!aEndNode)) {
return NS_ERROR_UNEXPECTED;
}
aRanges->Clear();
int32_t startIndex, endIndex;
nsresult res = mStyledRanges.GetIndicesForInterval(
aBeginNode, aBeginOffset, aEndNode, aEndOffset, aAllowAdjacent,
startIndex, endIndex);
NS_ENSURE_SUCCESS(res, res);
if (startIndex == -1 || endIndex == -1) return NS_OK;
for (int32_t i = startIndex; i < endIndex; i++) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
aRanges->AppendElement(mStyledRanges.mRanges[i].mRange);
}
return NS_OK;
}
nsresult Selection::StyledRanges::GetIndicesForInterval(
const nsINode* aBeginNode, int32_t aBeginOffset, const nsINode* aEndNode,
int32_t aEndOffset, bool aAllowAdjacent, int32_t& aStartIndex,
int32_t& aEndIndex) const {
if (NS_WARN_IF(!aBeginNode)) {
return NS_ERROR_INVALID_POINTER;
}
if (NS_WARN_IF(!aEndNode)) {
return NS_ERROR_INVALID_POINTER;
}
aStartIndex = -1;
aEndIndex = -1;
if (mRanges.Length() == 0) return NS_OK;
const bool intervalIsCollapsed =
aBeginNode == aEndNode && aBeginOffset == aEndOffset;
// Ranges that end before the given interval and begin after the given
// interval can be discarded
int32_t endsBeforeIndex{FindInsertionPoint(&mRanges, *aEndNode, aEndOffset,
&CompareToRangeStart)};
if (endsBeforeIndex == 0) {
const nsRange* endRange = mRanges[endsBeforeIndex].mRange;
// If the interval is strictly before the range at index 0, we can optimize
// by returning now - all ranges start after the given interval
if (!endRange->StartRef().Equals(aEndNode, aEndOffset)) {
return NS_OK;
}
// We now know that the start point of mRanges[0].mRange
// equals the end of the interval. Thus, when aAllowadjacent is true, the
// caller is always interested in this range. However, when excluding
// adjacencies, we must remember to include the range when both it and the
// given interval are collapsed to the same point
if (!aAllowAdjacent && !(endRange->Collapsed() && intervalIsCollapsed))
return NS_OK;
}
aEndIndex = endsBeforeIndex;
int32_t beginsAfterIndex{FindInsertionPoint(
&mRanges, *aBeginNode, aBeginOffset, &CompareToRangeEnd)};
if (beginsAfterIndex == (int32_t)mRanges.Length())
return NS_OK; // optimization: all ranges are strictly before us
if (aAllowAdjacent) {
// At this point, one of the following holds:
// endsBeforeIndex == mRanges.Length(),
// endsBeforeIndex points to a range whose start point does not equal the
// given interval's start point
// endsBeforeIndex points to a range whose start point equals the given
// interval's start point
// In the final case, there can be two such ranges, a collapsed range, and
// an adjacent range (they will appear in mRanges in that
// order). For this final case, we need to increment endsBeforeIndex, until
// one of the first two possibilites hold
while (endsBeforeIndex < (int32_t)mRanges.Length()) {
const nsRange* endRange = mRanges[endsBeforeIndex].mRange;
if (!endRange->StartRef().Equals(aEndNode, aEndOffset)) {
break;
}
endsBeforeIndex++;
}
// Likewise, one of the following holds:
// beginsAfterIndex == 0,
// beginsAfterIndex points to a range whose end point does not equal
// the given interval's end point
// beginsOnOrAfter points to a range whose end point equals the given
// interval's end point
// In the final case, there can be two such ranges, an adjacent range, and
// a collapsed range (they will appear in mRanges in that
// order). For this final case, we only need to take action if both those
// ranges exist, and we are pointing to the collapsed range - we need to
// point to the adjacent range
const nsRange* beginRange = mRanges[beginsAfterIndex].mRange;
if (beginsAfterIndex > 0 && beginRange->Collapsed() &&
beginRange->EndRef().Equals(aBeginNode, aBeginOffset)) {
beginRange = mRanges[beginsAfterIndex - 1].mRange;
if (beginRange->EndRef().Equals(aBeginNode, aBeginOffset)) {
beginsAfterIndex--;
}
}
} else {
// See above for the possibilities at this point. The only case where we
// need to take action is when the range at beginsAfterIndex ends on
// the given interval's start point, but that range isn't collapsed (a
// collapsed range should be included in the returned results).
const nsRange* beginRange = mRanges[beginsAfterIndex].mRange;
if (beginRange->EndRef().Equals(aBeginNode, aBeginOffset) &&
!beginRange->Collapsed()) {
beginsAfterIndex++;
}
// Again, see above for the meaning of endsBeforeIndex at this point.
// In particular, endsBeforeIndex may point to a collaped range which
// represents the point at the end of the interval - this range should be
// included
if (endsBeforeIndex < (int32_t)mRanges.Length()) {
const nsRange* endRange = mRanges[endsBeforeIndex].mRange;
if (endRange->StartRef().Equals(aEndNode, aEndOffset) &&
endRange->Collapsed()) {
endsBeforeIndex++;
}
}
}
NS_ASSERTION(beginsAfterIndex <= endsBeforeIndex, "Is mRanges not ordered?");
NS_ENSURE_STATE(beginsAfterIndex <= endsBeforeIndex);
aStartIndex = beginsAfterIndex;
aEndIndex = endsBeforeIndex;
return NS_OK;
}
nsIFrame* Selection::GetPrimaryFrameForAnchorNode() const {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
int32_t frameOffset = 0;
nsCOMPtr<nsIContent> content = do_QueryInterface(GetAnchorNode());
if (content && mFrameSelection) {
return nsFrameSelection::GetFrameForNodeOffset(
content, AnchorOffset(), mFrameSelection->GetHint(), &frameOffset);
}
return nullptr;
}
nsIFrame* Selection::GetPrimaryFrameForFocusNode(bool aVisual,
int32_t* aOffsetUsed) const {
nsINode* focusNode = GetFocusNode();
if (!focusNode || !focusNode->IsContent() || !mFrameSelection) {
return nullptr;
}
nsCOMPtr<nsIContent> content = focusNode->AsContent();
int32_t frameOffset = 0;
if (!aOffsetUsed) {
aOffsetUsed = &frameOffset;
}
nsIFrame* frame = GetPrimaryOrCaretFrameForNodeOffset(content, FocusOffset(),
aOffsetUsed, aVisual);
if (frame) {
return frame;
}
// If content is whitespace only, we promote focus node to parent because
// whitespace only node might have no frame.
if (!content->TextIsOnlyWhitespace()) {
return nullptr;
}
nsCOMPtr<nsIContent> parent = content->GetParent();
if (NS_WARN_IF(!parent)) {
return nullptr;
}
int32_t offset = parent->ComputeIndexOf(content);
return GetPrimaryOrCaretFrameForNodeOffset(parent, offset, aOffsetUsed,
aVisual);
}
nsIFrame* Selection::GetPrimaryOrCaretFrameForNodeOffset(nsIContent* aContent,
uint32_t aOffset,
int32_t* aOffsetUsed,
bool aVisual) const {
MOZ_ASSERT(aOffsetUsed);
if (!mFrameSelection) {
return nullptr;
}
CaretAssociationHint hint = mFrameSelection->GetHint();
if (aVisual) {
nsBidiLevel caretBidiLevel = mFrameSelection->GetCaretBidiLevel();
return nsCaret::GetCaretFrameForNodeOffset(
mFrameSelection, aContent, aOffset, hint, caretBidiLevel,
/* aReturnUnadjustedFrame = */ nullptr, aOffsetUsed);
}
return nsFrameSelection::GetFrameForNodeOffset(aContent, aOffset, hint,
aOffsetUsed);
}
void Selection::SelectFramesOf(nsIContent* aContent, bool aSelected) const {
nsIFrame* frame = aContent->GetPrimaryFrame();
if (!frame) {
return;
}
// The frame could be an SVG text frame, in which case we don't treat it
// as a text frame.
if (frame->IsTextFrame()) {
nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
textFrame->SelectionStateChanged(0, textFrame->TextFragment()->GetLength(),
aSelected, mSelectionType);
} else {
frame->SelectionStateChanged();
}
}
nsresult Selection::SelectFramesOfInclusiveDescendantsOfContent(
PostContentIterator& aPostOrderIter, nsIContent* aContent,
bool aSelected) const {
// If aContent doesn't have children, we should avoid to use the content
// iterator for performance reason.
if (!aContent->HasChildren()) {
SelectFramesOf(aContent, aSelected);
return NS_OK;
}
if (NS_WARN_IF(NS_FAILED(aPostOrderIter.Init(aContent)))) {
return NS_ERROR_FAILURE;
}
for (; !aPostOrderIter.IsDone(); aPostOrderIter.Next()) {
nsINode* node = aPostOrderIter.GetCurrentNode();
MOZ_ASSERT(node);
nsIContent* innercontent = node->IsContent() ? node->AsContent() : nullptr;
SelectFramesOf(innercontent, aSelected);
}
return NS_OK;
}
void Selection::SelectFramesInAllRanges(nsPresContext* aPresContext) {
for (size_t i = 0; i < mStyledRanges.Length(); ++i) {
nsRange* range = mStyledRanges.mRanges[i].mRange;
MOZ_ASSERT(range->IsInSelection());
SelectFrames(aPresContext, range, range->IsInSelection());
}
}
/**
* The idea of this helper method is to select or deselect "top to bottom",
* traversing through the frames
*/
nsresult Selection::SelectFrames(nsPresContext* aPresContext, nsRange* aRange,
bool aSelect) const {
if (!mFrameSelection || !aPresContext || !aPresContext->GetPresShell()) {
// nothing to do
return NS_OK;
}
MOZ_ASSERT(aRange && aRange->IsPositioned());
if (mFrameSelection->IsInTableSelectionMode()) {
nsINode* node = aRange->GetClosestCommonInclusiveAncestor();
nsIFrame* frame = node->IsContent()
? node->AsContent()->GetPrimaryFrame()
: aPresContext->PresShell()->GetRootFrame();
if (frame) {
if (frame->IsTextFrame()) {
nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
MOZ_ASSERT(node == aRange->GetStartContainer());
MOZ_ASSERT(node == aRange->GetEndContainer());
textFrame->SelectionStateChanged(aRange->StartOffset(),
aRange->EndOffset(), aSelect,
mSelectionType);
} else {
frame->SelectionStateChanged();
}
}
return NS_OK;
}
// Loop through the content iterator for each content node; for each text
// node, call SetSelected on it:
nsINode* startNode = aRange->GetStartContainer();
nsIContent* startContent =
startNode->IsContent() ? startNode->AsContent() : nullptr;
if (!startContent) {
// Don't warn, bug 1055722
// XXX The range can start from a document node and such range can be
// added to Selection with JS. Therefore, even in such cases,
// shouldn't we handle selection in the range?
return NS_ERROR_UNEXPECTED;
}
// We must call first one explicitly
bool isFirstContentTextNode = startContent->IsText();
nsINode* endNode = aRange->GetEndContainer();
if (isFirstContentTextNode) {
nsIFrame* frame = startContent->GetPrimaryFrame();
// The frame could be an SVG text frame, in which case we don't treat it
// as a text frame.
if (frame) {
if (frame->IsTextFrame()) {
nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
uint32_t startOffset = aRange->StartOffset();
uint32_t endOffset;
if (endNode == startContent) {
endOffset = aRange->EndOffset();
} else {
endOffset = startContent->Length();
}
textFrame->SelectionStateChanged(startOffset, endOffset, aSelect,
mSelectionType);
} else {
frame->SelectionStateChanged();
}
}
}
// If the range is in a node and the node is a leaf node, we don't need to
// walk the subtree.
if (aRange->Collapsed() ||
(startNode == endNode && !startNode->HasChildren())) {
if (!isFirstContentTextNode) {
SelectFramesOf(startContent, aSelect);
}
return NS_OK;
}
ContentSubtreeIterator subtreeIter;
subtreeIter.Init(aRange);
if (isFirstContentTextNode && !subtreeIter.IsDone() &&
subtreeIter.GetCurrentNode() == startNode) {
subtreeIter.Next(); // first content has already been handled.
}
PostContentIterator postOrderIter;
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
nsINode* node = subtreeIter.GetCurrentNode();
MOZ_ASSERT(node);
nsIContent* content = node->IsContent() ? node->AsContent() : nullptr;
SelectFramesOfInclusiveDescendantsOfContent(postOrderIter, content,
aSelect);
}
// We must now do the last one if it is not the same as the first
if (endNode != startNode) {
nsIContent* endContent =
endNode->IsContent() ? endNode->AsContent() : nullptr;
// XXX The range can end at a document node and such range can be
// added to Selection with JS. Therefore, even in such cases,
// shouldn't we handle selection in the range?
if (NS_WARN_IF(!endContent)) {
return NS_ERROR_UNEXPECTED;
}
if (endContent->IsText()) {
nsIFrame* frame = endContent->GetPrimaryFrame();
// The frame could be an SVG text frame, in which case we'll ignore it.
if (frame && frame->IsTextFrame()) {
nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
textFrame->SelectionStateChanged(0, aRange->EndOffset(), aSelect,
mSelectionType);
}
}
}
return NS_OK;
}
// Selection::LookUpSelection
//
// This function is called when a node wants to know where the selection is
// over itself.
//
// Usually, this is called when we already know there is a selection over
// the node in question, and we only need to find the boundaries of it on
// that node. This is when slowCheck is false--a strict test is not needed.
// Other times, the caller has no idea, and wants us to test everything,
// so we are supposed to determine whether there is a selection over the
// node at all.
//
// A previous version of this code used this flag to do less work when
// inclusion was already known (slowCheck=false). However, our tree
// structure allows us to quickly determine ranges overlapping the node,
// so we just ignore the slowCheck flag and do the full test every time.
//
// PERFORMANCE: a common case is that we are doing a fast check with exactly
// one range in the selection. In this case, this function is slower than
// brute force because of the overhead of checking the tree. We can optimize
// this case to make it faster by doing the same thing the previous version
// of this function did in the case of 1 range. This would also mean that
// the aSlowCheck flag would have meaning again.
UniquePtr<SelectionDetails> Selection::LookUpSelection(
nsIContent* aContent, int32_t aContentOffset, int32_t aContentLength,
UniquePtr<SelectionDetails> aDetailsHead, SelectionType aSelectionType,
bool aSlowCheck) {
if (!aContent) {
return aDetailsHead;
}
// it is common to have no ranges, to optimize that
if (mStyledRanges.Length() == 0) {
return aDetailsHead;
}
nsTArray<nsRange*> overlappingRanges;
nsresult rv = GetRangesForIntervalArray(aContent, aContentOffset, aContent,
aContentOffset + aContentLength,
false, &overlappingRanges);
if (NS_FAILED(rv)) {
return aDetailsHead;
}
if (overlappingRanges.Length() == 0) {
return aDetailsHead;
}
UniquePtr<SelectionDetails> detailsHead = std::move(aDetailsHead);
for (uint32_t i = 0; i < overlappingRanges.Length(); i++) {
nsRange* range = overlappingRanges[i];
nsINode* startNode = range->GetStartContainer();
nsINode* endNode = range->GetEndContainer();
int32_t startOffset = range->StartOffset();
int32_t endOffset = range->EndOffset();
int32_t start = -1, end = -1;
if (startNode == aContent && endNode == aContent) {
if (startOffset < (aContentOffset + aContentLength) &&
endOffset > aContentOffset) {
// this range is totally inside the requested content range
start = std::max(0, startOffset - aContentOffset);
end = std::min(aContentLength, endOffset - aContentOffset);
}
// otherwise, range is inside the requested node, but does not intersect
// the requested content range, so ignore it
} else if (startNode == aContent) {
if (startOffset < (aContentOffset + aContentLength)) {
// the beginning of the range is inside the requested node, but the
// end is outside, select everything from there to the end
start = std::max(0, startOffset - aContentOffset);
end = aContentLength;
}
} else if (endNode == aContent) {
if (endOffset > aContentOffset) {
// the end of the range is inside the requested node, but the beginning
// is outside, select everything from the beginning to there
start = 0;
end = std::min(aContentLength, endOffset - aContentOffset);
}
} else {
// this range does not begin or end in the requested node, but since
// GetRangesForInterval returned this range, we know it overlaps.
// Therefore, this node is enclosed in the range, and we select all
// of it.
start = 0;
end = aContentLength;
}
if (start < 0) continue; // the ranges do not overlap the input range
auto newHead = MakeUnique<SelectionDetails>();
newHead->mNext = std::move(detailsHead);
newHead->mStart = start;
newHead->mEnd = end;
newHead->mSelectionType = aSelectionType;
StyledRange* rd = mStyledRanges.FindRangeData(range);
if (rd) {
newHead->mTextRangeStyle = rd->mTextRangeStyle;
}
detailsHead = std::move(newHead);
}
return detailsHead;
}
NS_IMETHODIMP
Selection::Repaint(nsPresContext* aPresContext) {
int32_t arrCount = (int32_t)mStyledRanges.Length();
if (arrCount < 1) return NS_OK;
int32_t i;
for (i = 0; i < arrCount; i++) {
nsresult rv =
SelectFrames(aPresContext, mStyledRanges.mRanges[i].mRange, true);
if (NS_FAILED(rv)) {
return rv;
}
}
return NS_OK;
}
void Selection::SetCanCacheFrameOffset(bool aCanCacheFrameOffset) {
if (!mCachedOffsetForFrame) {
mCachedOffsetForFrame = new CachedOffsetForFrame;
}
mCachedOffsetForFrame->mCanCacheFrameOffset = aCanCacheFrameOffset;
// clean up cached frame when turn off cache
// fix bug 207936
if (!aCanCacheFrameOffset) {
mCachedOffsetForFrame->mLastCaretFrame = nullptr;
}
}
nsresult Selection::GetCachedFrameOffset(nsIFrame* aFrame, int32_t inOffset,
nsPoint& aPoint) {
if (!mCachedOffsetForFrame) {
mCachedOffsetForFrame = new CachedOffsetForFrame;
}
nsresult rv = NS_OK;
if (mCachedOffsetForFrame->mCanCacheFrameOffset &&
mCachedOffsetForFrame->mLastCaretFrame &&
(aFrame == mCachedOffsetForFrame->mLastCaretFrame) &&
(inOffset == mCachedOffsetForFrame->mLastContentOffset)) {
// get cached frame offset
aPoint = mCachedOffsetForFrame->mCachedFrameOffset;
} else {
// Recalculate frame offset and cache it. Don't cache a frame offset if
// GetPointFromOffset fails, though.
rv = aFrame->GetPointFromOffset(inOffset, &aPoint);
if (NS_SUCCEEDED(rv) && mCachedOffsetForFrame->mCanCacheFrameOffset) {
mCachedOffsetForFrame->mCachedFrameOffset = aPoint;
mCachedOffsetForFrame->mLastCaretFrame = aFrame;
mCachedOffsetForFrame->mLastContentOffset = inOffset;
}
}
return rv;
}
nsIContent* Selection::GetAncestorLimiter() const {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (mFrameSelection) {
return mFrameSelection->GetAncestorLimiter();
}
return nullptr;
}
void Selection::SetAncestorLimiter(nsIContent* aLimiter) {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (mFrameSelection) {
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->SetAncestorLimiter(aLimiter);
}
}
void Selection::StyledRanges::UnregisterSelection() {
uint32_t count = mRanges.Length();
for (uint32_t i = 0; i < count; ++i) {
mRanges[i].mRange->UnregisterSelection();
}
}
void Selection::StyledRanges::Clear() { mRanges.Clear(); }
StyledRange* Selection::StyledRanges::FindRangeData(nsRange* aRange) {
NS_ENSURE_TRUE(aRange, nullptr);
for (uint32_t i = 0; i < mRanges.Length(); i++) {
if (mRanges[i].mRange == aRange) {
return &mRanges[i];
}
}
return nullptr;
}
Selection::StyledRanges::Elements::size_type Selection::StyledRanges::Length()
const {
return mRanges.Length();
}
nsresult Selection::SetTextRangeStyle(nsRange* aRange,
const TextRangeStyle& aTextRangeStyle) {
NS_ENSURE_ARG_POINTER(aRange);
StyledRange* rd = mStyledRanges.FindRangeData(aRange);
if (rd) {
rd->mTextRangeStyle = aTextRangeStyle;
}
return NS_OK;
}
nsresult Selection::StartAutoScrollTimer(nsIFrame* aFrame,
const nsPoint& aPoint,
uint32_t aDelayInMs) {
MOZ_ASSERT(aFrame, "Need a frame");
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mFrameSelection) {
return NS_OK; // nothing to do
}
if (!mAutoScroller) {
mAutoScroller = new AutoScroller(mFrameSelection);
}
mAutoScroller->SetDelay(aDelayInMs);
RefPtr<AutoScroller> autoScroller{mAutoScroller};
return autoScroller->DoAutoScroll(aFrame, aPoint);
}
nsresult Selection::StopAutoScrollTimer() {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (mAutoScroller) {
mAutoScroller->Stop(AutoScroller::FurtherScrollingAllowed::kYes);
}
return NS_OK;
}
nsresult AutoScroller::DoAutoScroll(nsIFrame* aFrame, nsPoint aPoint) {
MOZ_ASSERT(aFrame, "Need a frame");
Stop(FurtherScrollingAllowed::kYes);
nsPresContext* presContext = aFrame->PresContext();
RefPtr<PresShell> presShell = presContext->PresShell();
nsRootPresContext* rootPC = presContext->GetRootPresContext();
if (!rootPC) return NS_OK;
nsIFrame* rootmostFrame = rootPC->PresShell()->GetRootFrame();
AutoWeakFrame weakRootFrame(rootmostFrame);
AutoWeakFrame weakFrame(aFrame);
// Get the point relative to the root most frame because the scroll we are
// about to do will change the coordinates of aFrame.
nsPoint globalPoint = aPoint + aFrame->GetOffsetToCrossDoc(rootmostFrame);
bool done = false;
bool didScroll;
while (true) {
didScroll = presShell->ScrollFrameRectIntoView(
aFrame, nsRect(aPoint, nsSize(0, 0)), ScrollAxis(), ScrollAxis(),
ScrollFlags::IgnoreMarginAndPadding);
if (!weakFrame || !weakRootFrame) {
return NS_OK;
}
if (!didScroll && !done) {
// If aPoint is at the screen edge then try to scroll anyway, once.
RefPtr<nsDeviceContext> dx =
presShell->GetViewManager()->GetDeviceContext();
nsRect screen;
dx->GetRect(screen);
nsPoint screenPoint =
globalPoint + rootmostFrame->GetScreenRectInAppUnits().TopLeft();
nscoord onePx = AppUnitsPerCSSPixel();
nscoord scrollAmount = 10 * onePx;
if (std::abs(screen.x - screenPoint.x) <= onePx) {
aPoint.x -= scrollAmount;
} else if (std::abs(screen.XMost() - screenPoint.x) <= onePx) {
aPoint.x += scrollAmount;
} else if (std::abs(screen.y - screenPoint.y) <= onePx) {
aPoint.y -= scrollAmount;
} else if (std::abs(screen.YMost() - screenPoint.y) <= onePx) {
aPoint.y += scrollAmount;
} else {
break;
}
done = true;
continue;
}
break;
}
// Start the AutoScroll timer if necessary.
// `ScrollFrameRectIntoView` above may have run script and this may have
// forbidden to continue scrolling.
if (didScroll &&
(mFurtherScrollingAllowed == FurtherScrollingAllowed::kYes)) {
nsPoint presContextPoint =
globalPoint -
presShell->GetRootFrame()->GetOffsetToCrossDoc(rootmostFrame);
ScheduleNextDoAutoScroll(presContext, presContextPoint);
}
return NS_OK;
}
void Selection::RemoveAllRanges(ErrorResult& aRv) {
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return;
}
RefPtr<nsPresContext> presContext = GetPresContext();
nsresult result = Clear(presContext);
if (NS_FAILED(result)) {
aRv.Throw(result);
return;
}
// Turn off signal for table selection
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->ClearTableCellSelection();
RefPtr<Selection> kungFuDeathGrip{this};
// Be aware, this instance may be destroyed after this call.
result = NotifySelectionListeners();
// Also need to notify the frames!
// PresShell::CharacterDataChanged should do that on DocumentChanged
if (NS_FAILED(result)) {
aRv.Throw(result);
}
}
void Selection::AddRangeJS(nsRange& aRange, ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
AddRangeAndSelectFramesAndNotifyListeners(aRange, aRv);
}
void Selection::AddRangeAndSelectFramesAndNotifyListeners(nsRange& aRange,
ErrorResult& aRv) {
RefPtr<Document> document(GetDocument());
return AddRangeAndSelectFramesAndNotifyListeners(aRange, document, aRv);
}
void Selection::AddRangeAndSelectFramesAndNotifyListeners(nsRange& aRange,
Document* aDocument,
ErrorResult& aRv) {
// If the given range is part of another Selection, we need to clone the
// range first.
RefPtr<nsRange> range;
if (aRange.IsInSelection() && aRange.GetSelection() != this) {
// Because of performance reason, when there is a cached range, let's use
// it. Otherwise, clone the range.
range = aRange.CloneRange();
} else {
range = &aRange;
}
nsINode* rangeRoot = range->GetRoot();
if (aDocument != rangeRoot &&
(!rangeRoot || aDocument != rangeRoot->GetComposedDoc())) {
// http://w3c.github.io/selection-api/#dom-selection-addrange
// "... if the root of the range's boundary points are the document
// associated with context object. Otherwise, this method must do nothing."
return;
}
// MaybeAddTableCellRange might flush frame and `NotifySelectionListeners`
// below might destruct `this`.
RefPtr<Selection> kungFuDeathGrip(this);
// This inserts a table cell range in proper document order
// and returns NS_OK if range doesn't contain just one table cell
bool didAddRange;
int32_t rangeIndex;
nsresult result = MaybeAddTableCellRange(*range, &didAddRange, &rangeIndex);
if (NS_FAILED(result)) {
aRv.Throw(result);
return;
}
if (!didAddRange) {
result = AddRangesForSelectableNodes(range, &rangeIndex,
DispatchSelectstartEvent::Maybe);
if (NS_FAILED(result)) {
aRv.Throw(result);
return;
}
}
if (rangeIndex < 0) {
return;
}
MOZ_ASSERT(rangeIndex < static_cast<int32_t>(mStyledRanges.Length()));
SetAnchorFocusRange(rangeIndex);
// Make sure the caret appears on the next line, if at a newline
if (mSelectionType == SelectionType::eNormal) {
SetInterlinePosition(true, IgnoreErrors());
}
if (!mFrameSelection) {
return; // nothing to do
}
RefPtr<nsPresContext> presContext = GetPresContext();
SelectFrames(presContext, range, true);
// Be aware, this instance may be destroyed after this call.
result = NotifySelectionListeners();
if (NS_FAILED(result)) {
aRv.Throw(result);
}
}
// Selection::RemoveRangeAndUnselectFramesAndNotifyListeners
//
// Removes the given range from the selection. The tricky part is updating
// the flags on the frames that indicate whether they have a selection or
// not. There could be several selection ranges on the frame, and clearing
// the bit would cause the selection to not be drawn, even when there is
// another range on the frame (bug 346185).
//
// We therefore find any ranges that intersect the same nodes as the range
// being removed, and cause them to set the selected bits back on their
// selected frames after we've cleared the bit from ours.
void Selection::RemoveRangeAndUnselectFramesAndNotifyListeners(
nsRange& aRange, ErrorResult& aRv) {
nsresult rv = mStyledRanges.RemoveRangeAndUnregisterSelection(aRange);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
nsINode* beginNode = aRange.GetStartContainer();
nsINode* endNode = aRange.GetEndContainer();
if (!beginNode || !endNode) {
// Detached range; nothing else to do here.
return;
}
// find out the length of the end node, so we can select all of it
int32_t beginOffset, endOffset;
if (endNode->IsText()) {
// Get the length of the text. We can't just use the offset because
// another range could be touching this text node but not intersect our
// range.
beginOffset = 0;
endOffset = endNode->AsText()->TextLength();
} else {
// For non-text nodes, the given offsets should be sufficient.
beginOffset = aRange.StartOffset();
endOffset = aRange.EndOffset();
}
// clear the selected bit from the removed range's frames
RefPtr<nsPresContext> presContext = GetPresContext();
SelectFrames(presContext, &aRange, false);
// add back the selected bit for each range touching our nodes
nsTArray<nsRange*> affectedRanges;
rv = GetRangesForIntervalArray(beginNode, beginOffset, endNode, endOffset,
true, &affectedRanges);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
for (uint32_t i = 0; i < affectedRanges.Length(); i++) {
SelectFrames(presContext, affectedRanges[i], true);
}
int32_t cnt = mStyledRanges.Length();
if (&aRange == mAnchorFocusRange) {
// Reset anchor to LAST range or clear it if there are no ranges.
SetAnchorFocusRange(cnt - 1);
// When the selection is user-created it makes sense to scroll the range
// into view. The spell-check selection, however, is created and destroyed
// in the background. We don't want to scroll in this case or the view
// might appear to be moving randomly (bug 337871).
if (mSelectionType != SelectionType::eSpellCheck && cnt > 0) {
ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION);
}
}
if (!mFrameSelection) return; // nothing to do
RefPtr<Selection> kungFuDeathGrip{this};
// Be aware, this instance may be destroyed after this call.
rv = NotifySelectionListeners();
if (NS_FAILED(rv)) {
aRv.Throw(rv);
}
}
/*
* Collapse sets the whole selection to be one point.
*/
void Selection::CollapseJS(nsINode* aContainer, uint32_t aOffset,
ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
if (!aContainer) {
RemoveAllRanges(aRv);
return;
}
CollapseInternal(InLimiter::eNo, RawRangeBoundary(aContainer, aOffset), aRv);
}
void Selection::CollapseInternal(InLimiter aInLimiter,
const RawRangeBoundary& aPoint,
ErrorResult& aRv) {
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED); // Can't do selection
return;
}
if (!aPoint.IsSet()) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
if (aPoint.Container()->NodeType() == nsINode::DOCUMENT_TYPE_NODE) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
// RawRangeBoundary::IsSetAndValid() checks if the point actually refers
// a child of the container when IsSet() is true. If its offset hasn't been
// computed yet, this just checks it with its mRef. So, we can avoid
// computing offset here.
if (!aPoint.IsSetAndValid()) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
if (!HasSameRootOrSameComposedDoc(*aPoint.Container())) {
// Return with no error
return;
}
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->InvalidateDesiredCaretPos();
if (aInLimiter == InLimiter::eYes &&
!frameSelection->IsValidSelectionPoint(aPoint.Container())) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
nsresult result;
RefPtr<nsPresContext> presContext = GetPresContext();
if (!presContext ||
presContext->Document() != aPoint.Container()->OwnerDoc()) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
// Delete all of the current ranges
Clear(presContext);
// Turn off signal for table selection
frameSelection->ClearTableCellSelection();
// Hack to display the caret on the right line (bug 1237236).
if (frameSelection->GetHint() != CARET_ASSOCIATE_AFTER &&
aPoint.Container()->IsContent()) {
int32_t frameOffset;
nsTextFrame* f = do_QueryFrame(nsCaret::GetFrameAndOffset(
this, aPoint.Container(),
*aPoint.Offset(RawRangeBoundary::OffsetFilter::kValidOffsets),
&frameOffset));
if (f && f->IsAtEndOfLine() && f->HasSignificantTerminalNewline()) {
// RawRangeBounary::Offset() causes computing offset if it's not been
// done yet. However, it's called only when the container is a text
// node. In such case, offset has always been set since it cannot have
// any children. So, this doesn't cause computing offset with expensive
// method, nsINode::ComputeIndexOf().
if ((aPoint.Container()->AsContent() == f->GetContent() &&
f->GetContentEnd() ==
static_cast<int32_t>(*aPoint.Offset(
RawRangeBoundary::OffsetFilter::kValidOffsets))) ||
(aPoint.Container() == f->GetContent()->GetParentNode() &&
f->GetContent() == aPoint.GetPreviousSiblingOfChildAtOffset())) {
frameSelection->SetHint(CARET_ASSOCIATE_AFTER);
}
}
}
RefPtr<nsRange> range = nsRange::Create(aPoint.Container());
result = range->CollapseTo(aPoint);
if (NS_FAILED(result)) {
aRv.Throw(result);
return;
}
#ifdef DEBUG_SELECTION
nsCOMPtr<nsIContent> content = do_QueryInterface(aPoint.Container());
nsCOMPtr<Document> doc = do_QueryInterface(aPoint.Container());
printf("Sel. Collapse to %p %s %d\n", container.get(),
content ? nsAtomCString(content->NodeInfo()->NameAtom()).get()
: (doc ? "DOCUMENT" : "???"),
aPoint.Offset());
#endif
int32_t rangeIndex = -1;
result = AddRangesForSelectableNodes(range, &rangeIndex,
DispatchSelectstartEvent::Maybe);
if (NS_FAILED(result)) {
aRv.Throw(result);
return;
}
SetAnchorFocusRange(0);
SelectFrames(presContext, range, true);
RefPtr<Selection> kungFuDeathGrip{this};
// Be aware, this instance may be destroyed after this call.
result = NotifySelectionListeners();
if (NS_FAILED(result)) {
aRv.Throw(result);
}
}
/*
* Sets the whole selection to be one point
* at the start of the current selection
*/
void Selection::CollapseToStartJS(ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
CollapseToStart(aRv);
}
void Selection::CollapseToStart(ErrorResult& aRv) {
if (RangeCount() == 0) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
// Get the first range
const nsRange* firstRange = mStyledRanges.mRanges[0].mRange;
if (!firstRange) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
if (mFrameSelection) {
mFrameSelection->AddChangeReasons(
nsISelectionListener::COLLAPSETOSTART_REASON);
}
nsINode* container = firstRange->GetStartContainer();
if (!container) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
CollapseInternal(InLimiter::eNo,
RawRangeBoundary(container, firstRange->StartOffset()), aRv);
}
/*
* Sets the whole selection to be one point
* at the end of the current selection
*/
void Selection::CollapseToEndJS(ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
CollapseToEnd(aRv);
}
void Selection::CollapseToEnd(ErrorResult& aRv) {
uint32_t cnt = RangeCount();
if (cnt == 0) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
// Get the last range
const nsRange* lastRange = mStyledRanges.mRanges[cnt - 1].mRange;
if (!lastRange) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
if (mFrameSelection) {
mFrameSelection->AddChangeReasons(
nsISelectionListener::COLLAPSETOEND_REASON);
}
nsINode* container = lastRange->GetEndContainer();
if (!container) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
CollapseInternal(InLimiter::eNo,
RawRangeBoundary(container, lastRange->EndOffset()), aRv);
}
void Selection::GetType(nsAString& aOutType) const {
if (!RangeCount()) {
aOutType.AssignLiteral("None");
} else if (IsCollapsed()) {
aOutType.AssignLiteral("Caret");
} else {
aOutType.AssignLiteral("Range");
}
}
nsRange* Selection::GetRangeAt(uint32_t aIndex, ErrorResult& aRv) {
nsRange* range = GetRangeAt(aIndex);
if (!range) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return nullptr;
}
return range;
}
nsRange* Selection::GetRangeAt(int32_t aIndex) const {
StyledRange empty(nullptr);
return mStyledRanges.mRanges.SafeElementAt(aIndex, empty).mRange;
}
nsresult Selection::SetAnchorFocusToRange(nsRange* aRange) {
NS_ENSURE_STATE(mAnchorFocusRange);
const DispatchSelectstartEvent dispatchSelectstartEvent =
IsCollapsed() ? DispatchSelectstartEvent::Maybe
: DispatchSelectstartEvent::No;
nsresult res =
mStyledRanges.RemoveRangeAndUnregisterSelection(*mAnchorFocusRange);
if (NS_FAILED(res)) return res;
int32_t aOutIndex = -1;
res =
AddRangesForSelectableNodes(aRange, &aOutIndex, dispatchSelectstartEvent);
if (NS_FAILED(res)) return res;
SetAnchorFocusRange(aOutIndex);
return NS_OK;
}
void Selection::ReplaceAnchorFocusRange(nsRange* aRange) {
NS_ENSURE_TRUE_VOID(mAnchorFocusRange);
RefPtr<nsPresContext> presContext = GetPresContext();
if (presContext) {
SelectFrames(presContext, mAnchorFocusRange, false);
SetAnchorFocusToRange(aRange);
SelectFrames(presContext, mAnchorFocusRange, true);
}
}
void Selection::AdjustAnchorFocusForMultiRange(nsDirection aDirection) {
if (aDirection == mDirection) {
return;
}
SetDirection(aDirection);
if (RangeCount() <= 1) {
return;
}
nsRange* firstRange = GetRangeAt(0);
nsRange* lastRange = GetRangeAt(RangeCount() - 1);
if (mDirection == eDirPrevious) {
firstRange->SetIsGenerated(false);
lastRange->SetIsGenerated(true);
SetAnchorFocusRange(0);
} else { // aDir == eDirNext
firstRange->SetIsGenerated(true);
lastRange->SetIsGenerated(false);
SetAnchorFocusRange(RangeCount() - 1);
}
}
/*
* Extend extends the selection away from the anchor.
* We don't need to know the direction, because we always change the focus.
*/
void Selection::ExtendJS(nsINode& aContainer, uint32_t aOffset,
ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
Extend(aContainer, aOffset, aRv);
}
nsresult Selection::Extend(nsINode* aContainer, int32_t aOffset) {
if (!aContainer) {
return NS_ERROR_INVALID_ARG;
}
ErrorResult result;
Extend(*aContainer, static_cast<uint32_t>(aOffset), result);
return result.StealNSResult();
}
void Selection::Extend(nsINode& aContainer, uint32_t aOffset,
ErrorResult& aRv) {
/*
Notes which might come in handy for extend:
We can tell the direction of the selection by asking for the anchors
selection if the begin is less than the end then we know the selection is to
the "right", else it is a backwards selection. Notation: a = anchor, 1 = old
cursor, 2 = new cursor.
if (a <= 1 && 1 <=2) a,1,2 or (a1,2)
if (a < 2 && 1 > 2) a,2,1
if (1 < a && a <2) 1,a,2
if (a > 2 && 2 >1) 1,2,a
if (2 < a && a <1) 2,a,1
if (a > 1 && 1 >2) 2,1,a
then execute
a 1 2 select from 1 to 2
a 2 1 deselect from 2 to 1
1 a 2 deselect from 1 to a select from a to 2
1 2 a deselect from 1 to 2
2 1 a = continue selection from 2 to 1
*/
// First, find the range containing the old focus point:
if (!mAnchorFocusRange) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED); // Can't do selection
return;
}
if (!HasSameRootOrSameComposedDoc(aContainer)) {
// Return with no error
return;
}
nsresult res;
if (!mFrameSelection->IsValidSelectionPoint(&aContainer)) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
RefPtr<nsPresContext> presContext = GetPresContext();
if (!presContext || presContext->Document() != aContainer.OwnerDoc()) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
#ifdef DEBUG_SELECTION
nsDirection oldDirection = GetDirection();
#endif
nsINode* anchorNode = GetAnchorNode();
nsINode* focusNode = GetFocusNode();
uint32_t anchorOffset = AnchorOffset();
uint32_t focusOffset = FocusOffset();
RefPtr<nsRange> range = mAnchorFocusRange->CloneRange();
nsINode* startNode = range->GetStartContainer();
nsINode* endNode = range->GetEndContainer();
int32_t startOffset = range->StartOffset();
int32_t endOffset = range->EndOffset();
bool shouldClearRange = false;
const Maybe<int32_t> anchorOldFocusOrder = nsContentUtils::ComparePoints(
anchorNode, anchorOffset, focusNode, focusOffset);
shouldClearRange |= !anchorOldFocusOrder;
const Maybe<int32_t> oldFocusNewFocusOrder = nsContentUtils::ComparePoints(
focusNode, focusOffset, &aContainer, aOffset);
shouldClearRange |= !oldFocusNewFocusOrder;
const Maybe<int32_t> anchorNewFocusOrder = nsContentUtils::ComparePoints(
anchorNode, anchorOffset, &aContainer, aOffset);
shouldClearRange |= !anchorNewFocusOrder;
// If the points are disconnected, the range will be collapsed below,
// resulting in a range that selects nothing.
if (shouldClearRange) {
// Repaint the current range with the selection removed.
SelectFrames(presContext, range, false);
res = range->CollapseTo(&aContainer, aOffset);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
} else {
RefPtr<nsRange> difRange = nsRange::Create(&aContainer);
if ((*anchorOldFocusOrder == 0 && *anchorNewFocusOrder < 0) ||
(*anchorOldFocusOrder <= 0 &&
*oldFocusNewFocusOrder < 0)) { // a1,2 a,1,2
// select from 1 to 2 unless they are collapsed
range->SetEnd(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
SetDirection(eDirNext);
res = difRange->SetStartAndEnd(
focusNode, focusOffset, range->GetEndContainer(), range->EndOffset());
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SelectFrames(presContext, difRange, true);
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
} else if (*anchorOldFocusOrder == 0 &&
*anchorNewFocusOrder > 0) { // 2, a1
// select from 2 to 1a
SetDirection(eDirPrevious);
range->SetStart(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
SelectFrames(presContext, range, true);
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
} else if (*anchorNewFocusOrder <= 0 &&
*oldFocusNewFocusOrder >= 0) { // a,2,1 or a2,1 or a,21 or a21
// deselect from 2 to 1
res = difRange->SetStartAndEnd(&aContainer, aOffset, focusNode,
focusOffset);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
range->SetEnd(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SelectFrames(presContext, difRange, false); // deselect now
difRange->SetEnd(range->GetEndContainer(), range->EndOffset());
SelectFrames(presContext, difRange, true); // must reselect last node
// maybe more
} else if (*anchorOldFocusOrder >= 0 &&
*anchorNewFocusOrder <= 0) { // 1,a,2 or 1a,2 or 1,a2 or 1a2
if (GetDirection() == eDirPrevious) {
res = range->SetStart(endNode, endOffset);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
}
SetDirection(eDirNext);
range->SetEnd(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
if (focusNode != anchorNode ||
focusOffset != anchorOffset) { // if collapsed diff dont do anything
res = difRange->SetStart(focusNode, focusOffset);
nsresult tmp = difRange->SetEnd(anchorNode, anchorOffset);
if (NS_FAILED(tmp)) {
res = tmp;
}
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
// deselect from 1 to a
SelectFrames(presContext, difRange, false);
} else {
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
}
// select from a to 2
SelectFrames(presContext, range, true);
} else if (*oldFocusNewFocusOrder <= 0 &&
*anchorNewFocusOrder >= 0) { // 1,2,a or 12,a or 1,2a or 12a
// deselect from 1 to 2
res = difRange->SetStartAndEnd(focusNode, focusOffset, &aContainer,
aOffset);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SetDirection(eDirPrevious);
range->SetStart(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SelectFrames(presContext, difRange, false);
difRange->SetStart(range->GetStartContainer(), range->StartOffset());
SelectFrames(presContext, difRange, true); // must reselect last node
} else if (*anchorNewFocusOrder >= 0 &&
*anchorOldFocusOrder <= 0) { // 2,a,1 or 2a,1 or 2,a1 or 2a1
if (GetDirection() == eDirNext) {
range->SetEnd(startNode, startOffset);
}
SetDirection(eDirPrevious);
range->SetStart(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
// deselect from a to 1
if (focusNode != anchorNode ||
focusOffset != anchorOffset) { // if collapsed diff dont do anything
res = difRange->SetStartAndEnd(anchorNode, anchorOffset, focusNode,
focusOffset);
nsresult tmp = SetAnchorFocusToRange(range);
if (NS_FAILED(tmp)) {
res = tmp;
}
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SelectFrames(presContext, difRange, false);
} else {
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
}
// select from 2 to a
SelectFrames(presContext, range, true);
} else if (*oldFocusNewFocusOrder >= 0 &&
*anchorOldFocusOrder >= 0) { // 2,1,a or 21,a or 2,1a or 21a
// select from 2 to 1
range->SetStart(aContainer, aOffset, aRv);
if (aRv.Failed()) {
return;
}
SetDirection(eDirPrevious);
res = difRange->SetStartAndEnd(range->GetStartContainer(),
range->StartOffset(), focusNode,
focusOffset);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
SelectFrames(presContext, difRange, true);
res = SetAnchorFocusToRange(range);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
}
}
if (mStyledRanges.Length() > 1) {
SelectFramesInAllRanges(presContext);
}
DEBUG_OUT_RANGE(range);
#ifdef DEBUG_SELECTION
if (GetDirection() != oldDirection) {
printf(" direction changed to %s\n",
GetDirection() == eDirNext ? "eDirNext" : "eDirPrevious");
}
nsCOMPtr<nsIContent> content = do_QueryInterface(&aContainer);
printf("Sel. Extend to %p %s %d\n", content.get(),
nsAtomCString(content->NodeInfo()->NameAtom()).get(), aOffset);
#endif
RefPtr<Selection> kungFuDeathGrip{this};
// Be aware, this instance may be destroyed after this call.
res = NotifySelectionListeners();
if (NS_FAILED(res)) {
aRv.Throw(res);
}
}
void Selection::SelectAllChildrenJS(nsINode& aNode, ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
SelectAllChildren(aNode, aRv);
}
void Selection::SelectAllChildren(nsINode& aNode, ErrorResult& aRv) {
if (aNode.NodeType() == nsINode::DOCUMENT_TYPE_NODE) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
if (!HasSameRootOrSameComposedDoc(aNode)) {
// Return with no error
return;
}
if (mFrameSelection) {
mFrameSelection->AddChangeReasons(nsISelectionListener::SELECTALL_REASON);
}
// Chrome moves focus when aNode is outside of active editing host.
// So, we don't need to respect the limiter with this method.
SetStartAndEndInternal(InLimiter::eNo, RawRangeBoundary(&aNode, 0u),
RawRangeBoundary(&aNode, aNode.GetChildCount()),
eDirNext, aRv);
}
bool Selection::ContainsNode(nsINode& aNode, bool aAllowPartial,
ErrorResult& aRv) {
nsresult rv;
if (mStyledRanges.Length() == 0) {
return false;
}
// XXXbz this duplicates the GetNodeLength code in nsRange.cpp
uint32_t nodeLength;
auto* nodeAsCharData = CharacterData::FromNode(aNode);
if (nodeAsCharData) {
nodeLength = nodeAsCharData->TextLength();
} else {
nodeLength = aNode.GetChildCount();
}
nsTArray<nsRange*> overlappingRanges;
rv = GetRangesForIntervalArray(&aNode, 0, &aNode, nodeLength, false,
&overlappingRanges);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return false;
}
if (overlappingRanges.Length() == 0) return false; // no ranges overlap
// if the caller said partial intersections are OK, we're done
if (aAllowPartial) {
return true;
}
// text nodes always count as inside
if (nodeAsCharData) {
return true;
}
// The caller wants to know if the node is entirely within the given range,
// so we have to check all intersecting ranges.
for (uint32_t i = 0; i < overlappingRanges.Length(); i++) {
bool nodeStartsBeforeRange, nodeEndsAfterRange;
if (NS_SUCCEEDED(RangeUtils::CompareNodeToRange(
&aNode, overlappingRanges[i], &nodeStartsBeforeRange,
&nodeEndsAfterRange))) {
if (!nodeStartsBeforeRange && !nodeEndsAfterRange) {
return true;
}
}
}
return false;
}
class PointInRectChecker : public mozilla::RectCallback {
public:
explicit PointInRectChecker(const nsPoint& aPoint)
: mPoint(aPoint), mMatchFound(false) {}
void AddRect(const nsRect& aRect) override {
mMatchFound = mMatchFound || aRect.Contains(mPoint);
}
bool MatchFound() { return mMatchFound; }
private:
nsPoint mPoint;
bool mMatchFound;
};
bool Selection::ContainsPoint(const nsPoint& aPoint) {
if (IsCollapsed()) {
return false;
}
PointInRectChecker checker(aPoint);
for (uint32_t i = 0; i < RangeCount(); i++) {
nsRange* range = GetRangeAt(i);
nsRange::CollectClientRectsAndText(
&checker, nullptr, range, range->GetStartContainer(),
range->StartOffset(), range->GetEndContainer(), range->EndOffset(),
true, false);
if (checker.MatchFound()) {
return true;
}
}
return false;
}
void Selection::MaybeNotifyAccessibleCaretEventHub(PresShell* aPresShell) {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
if (!mAccessibleCaretEventHub && aPresShell) {
mAccessibleCaretEventHub = aPresShell->GetAccessibleCaretEventHub();
}
}
void Selection::StopNotifyingAccessibleCaretEventHub() {
MOZ_ASSERT(mSelectionType == SelectionType::eNormal);
mAccessibleCaretEventHub = nullptr;
}
nsPresContext* Selection::GetPresContext() const {
PresShell* presShell = GetPresShell();
return presShell ? presShell->GetPresContext() : nullptr;
}
PresShell* Selection::GetPresShell() const {
if (!mFrameSelection) {
return nullptr; // nothing to do
}
return mFrameSelection->GetPresShell();
}
Document* Selection::GetDocument() const {
PresShell* presShell = GetPresShell();
return presShell ? presShell->GetDocument() : nullptr;
}
nsIFrame* Selection::GetSelectionAnchorGeometry(SelectionRegion aRegion,
nsRect* aRect) {
if (!mFrameSelection) return nullptr; // nothing to do
NS_ENSURE_TRUE(aRect, nullptr);
aRect->SetRect(0, 0, 0, 0);
switch (aRegion) {
case nsISelectionController::SELECTION_ANCHOR_REGION:
case nsISelectionController::SELECTION_FOCUS_REGION:
return GetSelectionEndPointGeometry(aRegion, aRect);
case nsISelectionController::SELECTION_WHOLE_SELECTION:
break;
default:
return nullptr;
}
NS_ASSERTION(aRegion == nsISelectionController::SELECTION_WHOLE_SELECTION,
"should only be SELECTION_WHOLE_SELECTION here");
nsRect anchorRect;
nsIFrame* anchorFrame = GetSelectionEndPointGeometry(
nsISelectionController::SELECTION_ANCHOR_REGION, &anchorRect);
if (!anchorFrame) return nullptr;
nsRect focusRect;
nsIFrame* focusFrame = GetSelectionEndPointGeometry(
nsISelectionController::SELECTION_FOCUS_REGION, &focusRect);
if (!focusFrame) return nullptr;
NS_ASSERTION(anchorFrame->PresContext() == focusFrame->PresContext(),
"points of selection in different documents?");
// make focusRect relative to anchorFrame
focusRect += focusFrame->GetOffsetTo(anchorFrame);
aRect->UnionRectEdges(anchorRect, focusRect);
return anchorFrame;
}
nsIFrame* Selection::GetSelectionEndPointGeometry(SelectionRegion aRegion,
nsRect* aRect) {
if (!mFrameSelection) return nullptr; // nothing to do
NS_ENSURE_TRUE(aRect, nullptr);
aRect->SetRect(0, 0, 0, 0);
nsINode* node = nullptr;
uint32_t nodeOffset = 0;
nsIFrame* frame = nullptr;
switch (aRegion) {
case nsISelectionController::SELECTION_ANCHOR_REGION:
node = GetAnchorNode();
nodeOffset = AnchorOffset();
break;
case nsISelectionController::SELECTION_FOCUS_REGION:
node = GetFocusNode();
nodeOffset = FocusOffset();
break;
default:
return nullptr;
}
if (!node) return nullptr;
nsCOMPtr<nsIContent> content = do_QueryInterface(node);
NS_ENSURE_TRUE(content.get(), nullptr);
int32_t frameOffset = 0;
frame = nsFrameSelection::GetFrameForNodeOffset(
content, nodeOffset, mFrameSelection->GetHint(), &frameOffset);
if (!frame) return nullptr;
// Figure out what node type we have, then get the
// appropriate rect for it's nodeOffset.
bool isText = node->IsText();
nsPoint pt(0, 0);
if (isText) {
nsIFrame* childFrame = nullptr;
frameOffset = 0;
nsresult rv = frame->GetChildFrameContainingOffset(
nodeOffset, mFrameSelection->GetHint(), &frameOffset, &childFrame);
if (NS_FAILED(rv)) return nullptr;
if (!childFrame) return nullptr;
frame = childFrame;
// Get the x coordinate of the offset into the text frame.
rv = GetCachedFrameOffset(frame, nodeOffset, pt);
if (NS_FAILED(rv)) return nullptr;
}
// Return the rect relative to the frame, with zero width.
if (isText) {
aRect->x = pt.x;
} else if (mFrameSelection->GetHint() == CARET_ASSOCIATE_BEFORE) {
// It's the frame's right edge we're interested in.
aRect->x = frame->GetRect().Width();
}
aRect->SetHeight(frame->GetRect().Height());
return frame;
}
NS_IMETHODIMP
Selection::ScrollSelectionIntoViewEvent::Run() {
if (!mSelection) return NS_OK; // event revoked
int32_t flags = Selection::SCROLL_DO_FLUSH | Selection::SCROLL_SYNCHRONOUS;
const RefPtr<Selection> selection{mSelection};
selection->mScrollEvent.Forget();
selection->ScrollIntoView(mRegion, mVerticalScroll, mHorizontalScroll,
mFlags | flags);
return NS_OK;
}
nsresult Selection::PostScrollSelectionIntoViewEvent(SelectionRegion aRegion,
int32_t aFlags,
ScrollAxis aVertical,
ScrollAxis aHorizontal) {
// If we've already posted an event, revoke it and place a new one at the
// end of the queue to make sure that any new pending reflow events are
// processed before we scroll. This will insure that we scroll to the
// correct place on screen.
mScrollEvent.Revoke();
nsPresContext* presContext = GetPresContext();
NS_ENSURE_STATE(presContext);
nsRefreshDriver* refreshDriver = presContext->RefreshDriver();
NS_ENSURE_STATE(refreshDriver);
mScrollEvent = new ScrollSelectionIntoViewEvent(this, aRegion, aVertical,
aHorizontal, aFlags);
refreshDriver->AddEarlyRunner(mScrollEvent.get());
return NS_OK;
}
void Selection::ScrollIntoView(int16_t aRegion, bool aIsSynchronous,
WhereToScroll aVPercent, WhereToScroll aHPercent,
ErrorResult& aRv) {
int32_t flags = aIsSynchronous ? Selection::SCROLL_SYNCHRONOUS : 0;
nsresult rv = ScrollIntoView(aRegion, ScrollAxis(aVPercent),
ScrollAxis(aHPercent), flags);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
}
}
nsresult Selection::ScrollIntoView(SelectionRegion aRegion,
ScrollAxis aVertical, ScrollAxis aHorizontal,
int32_t aFlags) {
if (!mFrameSelection) {
return NS_ERROR_NOT_INITIALIZED;
}
RefPtr<PresShell> presShell = mFrameSelection->GetPresShell();
if (!presShell || !presShell->GetDocument()) {
return NS_OK;
}
if (mFrameSelection->IsBatching()) {
return NS_OK;
}
if (!(aFlags & Selection::SCROLL_SYNCHRONOUS))
return PostScrollSelectionIntoViewEvent(aRegion, aFlags, aVertical,
aHorizontal);
// From this point on, the presShell may get destroyed by the calls below, so
// hold on to it using a strong reference to ensure the safety of the
// accesses to frame pointers in the callees.
RefPtr<PresShell> kungFuDeathGrip(presShell);
// Now that text frame character offsets are always valid (though not
// necessarily correct), the worst that will happen if we don't flush here
// is that some callers might scroll to the wrong place. Those should
// either manually flush if they're in a safe position for it or use the
// async version of this method.
if (aFlags & Selection::SCROLL_DO_FLUSH) {
presShell->GetDocument()->FlushPendingNotifications(FlushType::Layout);
// Reget the presshell, since it might have been Destroy'ed.
presShell = mFrameSelection ? mFrameSelection->GetPresShell() : nullptr;
if (!presShell) {
return NS_OK;
}
}
//
// Scroll the selection region into view.
//
nsRect rect;
nsIFrame* frame = GetSelectionAnchorGeometry(aRegion, &rect);
if (!frame) return NS_ERROR_FAILURE;
// Scroll vertically to get the caret into view, but only if the container
// is perceived to be scrollable in that direction (i.e. there is a visible
// vertical scrollbar or the scroll range is at least one device pixel)
aVertical.mOnlyIfPerceivedScrollableDirection = true;
ScrollFlags scrollFlags = ScrollFlags::IgnoreMarginAndPadding;
if (aFlags & Selection::SCROLL_FIRST_ANCESTOR_ONLY) {
scrollFlags |= ScrollFlags::ScrollFirstAncestorOnly;
}
if (aFlags & Selection::SCROLL_OVERFLOW_HIDDEN) {
scrollFlags |= ScrollFlags::ScrollOverflowHidden;
}
if (aFlags & Selection::SCROLL_FOR_CARET_MOVE) {
mozilla::Telemetry::Accumulate(
mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t)ScrollInputMethod::MainThreadScrollCaretIntoView);
}
presShell->ScrollFrameRectIntoView(frame, rect, aVertical, aHorizontal,
scrollFlags);
return NS_OK;
}
void Selection::AddSelectionListener(nsISelectionListener* aNewListener) {
MOZ_ASSERT(aNewListener);
mSelectionListeners.AppendElement(aNewListener); // AddRefs
}
void Selection::RemoveSelectionListener(
nsISelectionListener* aListenerToRemove) {
mSelectionListeners.RemoveElement(aListenerToRemove); // Releases
}
Element* Selection::StyledRanges::GetCommonEditingHost() const {
Element* editingHost = nullptr;
for (const StyledRange& rangeData : mRanges) {
const nsRange* range = rangeData.mRange;
MOZ_ASSERT(range);
nsINode* commonAncestorNode = range->GetClosestCommonInclusiveAncestor();
if (!commonAncestorNode || !commonAncestorNode->IsContent()) {
return nullptr;
}
nsIContent* commonAncestor = commonAncestorNode->AsContent();
Element* foundEditingHost = commonAncestor->GetEditingHost();
// Even when common ancestor is a non-editable element in a contenteditable
// element, we don't need to move focus to the contenteditable element
// because Chromium doesn't set focus to it.
if (!foundEditingHost) {
return nullptr;
}
if (!editingHost) {
editingHost = foundEditingHost;
continue;
}
if (editingHost == foundEditingHost) {
continue;
}
if (foundEditingHost->IsInclusiveDescendantOf(editingHost)) {
continue;
}
if (editingHost->IsInclusiveDescendantOf(foundEditingHost)) {
editingHost = foundEditingHost;
continue;
}
// editingHost and foundEditingHost are not a descendant of the other.
// So, there is no common editing host.
return nullptr;
}
return editingHost;
}
void Selection::StyledRanges::MaybeFocusCommonEditingHost(
PresShell* aPresShell) const {
if (!aPresShell) {
return;
}
nsPresContext* presContext = aPresShell->GetPresContext();
if (!presContext) {
return;
}
Document* document = aPresShell->GetDocument();
if (!document) {
return;
}
nsPIDOMWindowOuter* window = document->GetWindow();
// If the document is in design mode or doesn't have contenteditable
// element, we don't need to move focus.
if (window && !document->HasFlag(NODE_IS_EDITABLE) &&
nsContentUtils::GetHTMLEditor(presContext)) {
RefPtr<Element> newEditingHost = GetCommonEditingHost();
RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager();
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
nsIContent* focusedContent = nsFocusManager::GetFocusedDescendant(
window, nsFocusManager::eOnlyCurrentWindow,
getter_AddRefs(focusedWindow));
nsCOMPtr<Element> focusedElement = do_QueryInterface(focusedContent);
// When all selected ranges are in an editing host, it should take focus.
// But otherwise, we shouldn't move focus since Chromium doesn't move
// focus but only selection range is updated.
if (newEditingHost && newEditingHost != focusedElement) {
MOZ_ASSERT(!newEditingHost->IsInNativeAnonymousSubtree());
// Note that don't steal focus from focused window if the window doesn't
// have focus. Additionally, although when an element gets focus, we
// usually scroll to the element, but in this case, we shouldn't do it
// because Chrome does not do so.
fm->SetFocus(newEditingHost, nsIFocusManager::FLAG_NOSWITCHFRAME |
nsIFocusManager::FLAG_NOSCROLL);
}
}
}
nsresult Selection::NotifySelectionListeners(bool aCalledByJS) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = aCalledByJS;
return NotifySelectionListeners();
}
nsresult Selection::NotifySelectionListeners() {
if (!mFrameSelection) {
return NS_OK; // nothing to do
}
MOZ_LOG(sSelectionLog, LogLevel::Debug,
("%s: selection=%p", __FUNCTION__, this));
// Our internal code should not move focus with using this class while
// this moves focus nor from selection listeners.
AutoRestore<bool> calledByJSRestorer(mCalledByJS);
mCalledByJS = false;
// When normal selection is changed by Selection API, we need to move focus
// if common ancestor of all ranges are in an editing host. Note that we
// don't need to move focus *to* the other focusable node because other
// browsers don't do it either.
if (mSelectionType == SelectionType::eNormal &&
calledByJSRestorer.SavedValue()) {
mStyledRanges.MaybeFocusCommonEditingHost(GetPresShell());
}
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
if (frameSelection->IsBatching()) {
frameSelection->SetChangesDuringBatchingFlag();
return NS_OK;
}
if (mSelectionListeners.IsEmpty()) {
// If there are no selection listeners, we're done!
return NS_OK;
}
nsCOMPtr<Document> doc;
PresShell* presShell = GetPresShell();
if (presShell) {
doc = presShell->GetDocument();
}
// We've notified all selection listeners even when some of them are removed
// (and may be destroyed) during notifying one of them. Therefore, we should
// copy all listeners to the local variable first.
const CopyableAutoTArray<nsCOMPtr<nsISelectionListener>, 5>
selectionListeners = mSelectionListeners;
int16_t reason = frameSelection->PopChangeReasons();
if (calledByJSRestorer.SavedValue()) {
reason |= nsISelectionListener::JS_REASON;
}
if (mNotifyAutoCopy) {
AutoCopyListener::OnSelectionChange(doc, *this, reason);
}
if (mAccessibleCaretEventHub) {
RefPtr<AccessibleCaretEventHub> hub(mAccessibleCaretEventHub);
hub->OnSelectionChange(doc, this, reason);
}
if (mSelectionChangeEventDispatcher) {
RefPtr<SelectionChangeEventDispatcher> dispatcher(
mSelectionChangeEventDispatcher);
dispatcher->OnSelectionChange(doc, this, reason);
}
for (auto& listener : selectionListeners) {
// MOZ_KnownLive because 'selectionListeners' is guaranteed to
// keep it alive.
//
// This can go away once
// https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
MOZ_KnownLive(listener)->NotifySelectionChanged(doc, this, reason);
}
return NS_OK;
}
void Selection::StartBatchChanges() {
if (mFrameSelection) {
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->StartBatchChanges();
}
}
void Selection::EndBatchChanges(int16_t aReason) {
if (mFrameSelection) {
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
frameSelection->EndBatchChanges(aReason);
}
}
void Selection::AddSelectionChangeBlocker() { mSelectionChangeBlockerCount++; }
void Selection::RemoveSelectionChangeBlocker() {
MOZ_ASSERT(mSelectionChangeBlockerCount > 0,
"mSelectionChangeBlockerCount has an invalid value - "
"maybe you have a mismatched RemoveSelectionChangeBlocker?");
mSelectionChangeBlockerCount--;
}
bool Selection::IsBlockingSelectionChangeEvents() const {
return mSelectionChangeBlockerCount > 0;
}
void Selection::DeleteFromDocument(ErrorResult& aRv) {
if (mSelectionType != SelectionType::eNormal) {
return; // Nothing to do.
}
// If we're already collapsed, then we do nothing (bug 719503).
if (IsCollapsed()) {
return;
}
for (uint32_t rangeIdx = 0; rangeIdx < RangeCount(); ++rangeIdx) {
RefPtr<nsRange> range = GetRangeAt(rangeIdx);
range->DeleteContents(aRv);
if (aRv.Failed()) {
return;
}
}
// Collapse to the new location.
// If we deleted one character, then we move back one element.
// FIXME We don't know how to do this past frame boundaries yet.
if (AnchorOffset() > 0) {
RefPtr<nsINode> anchor = GetAnchorNode();
CollapseInLimiter(anchor, AnchorOffset());
}
#ifdef DEBUG
else {
printf("Don't know how to set selection back past frame boundary\n");
}
#endif
}
void Selection::Modify(const nsAString& aAlter, const nsAString& aDirection,
const nsAString& aGranularity, ErrorResult& aRv) {
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return;
}
if (!GetAnchorFocusRange() || !GetFocusNode()) {
return;
}
if (!aAlter.LowerCaseEqualsLiteral("move") &&
!aAlter.LowerCaseEqualsLiteral("extend")) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
if (!aDirection.LowerCaseEqualsLiteral("forward") &&
!aDirection.LowerCaseEqualsLiteral("backward") &&
!aDirection.LowerCaseEqualsLiteral("left") &&
!aDirection.LowerCaseEqualsLiteral("right")) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
// Make sure the layout is up to date as we access bidi information below.
if (RefPtr<Document> doc = GetDocument()) {
doc->FlushPendingNotifications(FlushType::Layout);
}
// Line moves are always visual.
bool visual = aDirection.LowerCaseEqualsLiteral("left") ||
aDirection.LowerCaseEqualsLiteral("right") ||
aGranularity.LowerCaseEqualsLiteral("line");
bool forward = aDirection.LowerCaseEqualsLiteral("forward") ||
aDirection.LowerCaseEqualsLiteral("right");
bool extend = aAlter.LowerCaseEqualsLiteral("extend");
nsSelectionAmount amount;
if (aGranularity.LowerCaseEqualsLiteral("character")) {
amount = eSelectCluster;
} else if (aGranularity.LowerCaseEqualsLiteral("word")) {
amount = eSelectWordNoSpace;
} else if (aGranularity.LowerCaseEqualsLiteral("line")) {
amount = eSelectLine;
} else if (aGranularity.LowerCaseEqualsLiteral("lineboundary")) {
amount = forward ? eSelectEndLine : eSelectBeginLine;
} else if (aGranularity.LowerCaseEqualsLiteral("sentence") ||
aGranularity.LowerCaseEqualsLiteral("sentenceboundary") ||
aGranularity.LowerCaseEqualsLiteral("paragraph") ||
aGranularity.LowerCaseEqualsLiteral("paragraphboundary") ||
aGranularity.LowerCaseEqualsLiteral("documentboundary")) {
aRv.Throw(NS_ERROR_NOT_IMPLEMENTED);
return;
} else {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
// If the anchor doesn't equal the focus and we try to move without first
// collapsing the selection, MoveCaret will collapse the selection and quit.
// To avoid this, we need to collapse the selection first.
nsresult rv = NS_OK;
if (!extend) {
RefPtr<nsINode> focusNode = GetFocusNode();
// We should have checked earlier that there was a focus node.
if (!focusNode) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
uint32_t focusOffset = FocusOffset();
CollapseInLimiter(focusNode, focusOffset);
}
// If the paragraph direction of the focused frame is right-to-left,
// we may have to swap the direction of movement.
if (nsIFrame* frame = GetPrimaryFrameForFocusNode(visual)) {
nsBidiDirection paraDir = nsBidiPresUtils::ParagraphDirection(frame);
if (paraDir == NSBIDI_RTL && visual) {
if (amount == eSelectBeginLine) {
amount = eSelectEndLine;
forward = !forward;
} else if (amount == eSelectEndLine) {
amount = eSelectBeginLine;
forward = !forward;
}
}
}
// MoveCaret will return an error if it can't move in the specified
// direction, but we just ignore this error unless it's a line move, in which
// case we call nsISelectionController::CompleteMove to move the cursor to
// the beginning/end of the line.
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
rv = frameSelection->MoveCaret(
forward ? eDirNext : eDirPrevious, extend, amount,
visual ? nsFrameSelection::eVisual : nsFrameSelection::eLogical);
if (aGranularity.LowerCaseEqualsLiteral("line") && NS_FAILED(rv)) {
RefPtr<PresShell> presShell = frameSelection->GetPresShell();
if (!presShell) {
return;
}
presShell->CompleteMove(forward, extend);
}
}
void Selection::SetBaseAndExtentJS(nsINode& aAnchorNode, uint32_t aAnchorOffset,
nsINode& aFocusNode, uint32_t aFocusOffset,
ErrorResult& aRv) {
AutoRestore<bool> calledFromJSRestorer(mCalledByJS);
mCalledByJS = true;
SetBaseAndExtent(aAnchorNode, aAnchorOffset, aFocusNode, aFocusOffset, aRv);
}
void Selection::SetBaseAndExtent(nsINode& aAnchorNode, uint32_t aAnchorOffset,
nsINode& aFocusNode, uint32_t aFocusOffset,
ErrorResult& aRv) {
if ((aAnchorOffset > aAnchorNode.Length()) ||
(aFocusOffset > aFocusNode.Length())) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
SetBaseAndExtent(RawRangeBoundary{&aAnchorNode, aAnchorOffset},
RawRangeBoundary{&aFocusNode, aFocusOffset}, aRv);
}
void Selection::SetBaseAndExtentInternal(InLimiter aInLimiter,
const RawRangeBoundary& aAnchorRef,
const RawRangeBoundary& aFocusRef,
ErrorResult& aRv) {
if (!mFrameSelection) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return;
}
if (NS_WARN_IF(!aAnchorRef.IsSet()) || NS_WARN_IF(!aFocusRef.IsSet())) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
if (!HasSameRootOrSameComposedDoc(*aAnchorRef.Container()) ||
!HasSameRootOrSameComposedDoc(*aFocusRef.Container())) {
// Return with no error
return;
}
// Prevent "selectionchange" event temporarily because it should be fired
// after we set the direction.
// XXX If they are disconnected, shouldn't we return error before allocating
// new nsRange instance?
SelectionBatcher batch(this);
const Maybe<int32_t> order =
nsContentUtils::ComparePoints(aAnchorRef, aFocusRef);
if (order && (*order <= 0)) {
SetStartAndEndInternal(aInLimiter, aAnchorRef, aFocusRef, eDirNext, aRv);
return;
}
// If there's no `order`, the range will be collapsed, unless another error is
// detected before.
SetStartAndEndInternal(aInLimiter, aFocusRef, aAnchorRef, eDirPrevious, aRv);
}
void Selection::SetStartAndEndInternal(InLimiter aInLimiter,
const RawRangeBoundary& aStartRef,
const RawRangeBoundary& aEndRef,
nsDirection aDirection,
ErrorResult& aRv) {
if (NS_WARN_IF(!aStartRef.IsSet()) || NS_WARN_IF(!aEndRef.IsSet())) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
// Don't fire "selectionchange" event until everything done.
SelectionBatcher batch(this);
if (aInLimiter == InLimiter::eYes) {
if (!mFrameSelection ||
!mFrameSelection->IsValidSelectionPoint(aStartRef.Container())) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
if (aStartRef.Container() != aEndRef.Container() &&
!mFrameSelection->IsValidSelectionPoint(aEndRef.Container())) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
}
RefPtr<nsRange> newRange = nsRange::Create(aStartRef, aEndRef, aRv);
if (aRv.Failed()) {
return;
}
RemoveAllRanges(aRv);
if (aRv.Failed()) {
return;
}
AddRangeAndSelectFramesAndNotifyListeners(*newRange, aRv);
if (aRv.Failed()) {
return;
}
// Adding a range may set 2 or more ranges if there are non-selectable
// contents only when this change is caused by a user operation. Therefore,
// we need to select frames with the result in such case.
if (mUserInitiated) {
RefPtr<nsPresContext> presContext = GetPresContext();
if (mStyledRanges.Length() > 1 && presContext) {
SelectFramesInAllRanges(presContext);
}
}
SetDirection(aDirection);
}
/** SelectionLanguageChange modifies the cursor Bidi level after a change in
* keyboard direction
* @param aLangRTL is true if the new language is right-to-left or false if the
* new language is left-to-right
*/
nsresult Selection::SelectionLanguageChange(bool aLangRTL) {
if (!mFrameSelection) {
return NS_ERROR_NOT_INITIALIZED;
}
RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
// if the direction of the language hasn't changed, nothing to do
nsBidiLevel kbdBidiLevel = aLangRTL ? NSBIDI_RTL : NSBIDI_LTR;
if (kbdBidiLevel == frameSelection->mKbdBidiLevel) {
return NS_OK;
}
frameSelection->mKbdBidiLevel = kbdBidiLevel;
nsIFrame* focusFrame = GetPrimaryFrameForFocusNode(false);
if (!focusFrame) {
return NS_ERROR_FAILURE;
}
int32_t frameStart, frameEnd;
focusFrame->GetOffsets(frameStart, frameEnd);
RefPtr<nsPresContext> context = GetPresContext();
nsBidiLevel levelBefore, levelAfter;
if (!context) {
return NS_ERROR_FAILURE;
}
nsBidiLevel level = focusFrame->GetEmbeddingLevel();
int32_t focusOffset = static_cast<int32_t>(FocusOffset());
if ((focusOffset != frameStart) && (focusOffset != frameEnd))
// the cursor is not at a frame boundary, so the level of both the
// characters (logically) before and after the cursor is equal to the frame
// level
levelBefore = levelAfter = level;
else {
// the cursor is at a frame boundary, so use GetPrevNextBidiLevels to find
// the level of the characters before and after the cursor
nsCOMPtr<nsIContent> focusContent = do_QueryInterface(GetFocusNode());
nsPrevNextBidiLevels levels =
frameSelection->GetPrevNextBidiLevels(focusContent, focusOffset, false);
levelBefore = levels.mLevelBefore;
levelAfter = levels.mLevelAfter;
}
if (IS_SAME_DIRECTION(levelBefore, levelAfter)) {
// if cursor is between two characters with the same orientation, changing
// the keyboard language must toggle the cursor level between the level of
// the character with the lowest level (if the new language corresponds to
// the orientation of that character) and this level plus 1 (if the new
// language corresponds to the opposite orientation)
if ((level != levelBefore) && (level != levelAfter))
level = std::min(levelBefore, levelAfter);
if (IS_SAME_DIRECTION(level, kbdBidiLevel))
frameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(level);
else
frameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(level + 1);
} else {
// if cursor is between characters with opposite orientations, changing the
// keyboard language must change the cursor level to that of the adjacent
// character with the orientation corresponding to the new language.
if (IS_SAME_DIRECTION(levelBefore, kbdBidiLevel))
frameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(levelBefore);
else
frameSelection->SetCaretBidiLevelAndMaybeSchedulePaint(levelAfter);
}
// The caret might have moved, so invalidate the desired position
// for future usages of up-arrow or down-arrow
frameSelection->InvalidateDesiredCaretPos();
return NS_OK;
}
void Selection::SetColors(const nsAString& aForegroundColor,
const nsAString& aBackgroundColor,
const nsAString& aAltForegroundColor,
const nsAString& aAltBackgroundColor,
ErrorResult& aRv) {
if (mSelectionType != SelectionType::eFind) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
mCustomColors.reset(new SelectionCustomColors);
constexpr auto currentColorStr = u"currentColor"_ns;
constexpr auto transparentStr = u"transparent"_ns;
if (!aForegroundColor.Equals(currentColorStr)) {
nscolor foregroundColor;
nsAttrValue aForegroundColorValue;
aForegroundColorValue.ParseColor(aForegroundColor);
if (!aForegroundColorValue.GetColorValue(foregroundColor)) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
mCustomColors->mForegroundColor = Some(foregroundColor);
} else {
mCustomColors->mForegroundColor = Nothing();
}
if (!aBackgroundColor.Equals(transparentStr)) {
nscolor backgroundColor;
nsAttrValue aBackgroundColorValue;
aBackgroundColorValue.ParseColor(aBackgroundColor);
if (!aBackgroundColorValue.GetColorValue(backgroundColor)) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
mCustomColors->mBackgroundColor = Some(backgroundColor);
} else {
mCustomColors->mBackgroundColor = Nothing();
}
if (!aAltForegroundColor.Equals(currentColorStr)) {
nscolor altForegroundColor;
nsAttrValue aAltForegroundColorValue;
aAltForegroundColorValue.ParseColor(aAltForegroundColor);
if (!aAltForegroundColorValue.GetColorValue(altForegroundColor)) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
mCustomColors->mAltForegroundColor = Some(altForegroundColor);
} else {
mCustomColors->mAltForegroundColor = Nothing();
}
if (!aAltBackgroundColor.Equals(transparentStr)) {
nscolor altBackgroundColor;
nsAttrValue aAltBackgroundColorValue;
aAltBackgroundColorValue.ParseColor(aAltBackgroundColor);
if (!aAltBackgroundColorValue.GetColorValue(altBackgroundColor)) {
aRv.Throw(NS_ERROR_INVALID_ARG);
return;
}
mCustomColors->mAltBackgroundColor = Some(altBackgroundColor);
} else {
mCustomColors->mAltBackgroundColor = Nothing();
}
}
void Selection::ResetColors(ErrorResult& aRv) { mCustomColors = nullptr; }
JSObject* Selection::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return mozilla::dom::Selection_Binding::Wrap(aCx, this, aGivenProto);
}
// AutoHideSelectionChanges
AutoHideSelectionChanges::AutoHideSelectionChanges(
const nsFrameSelection* aFrame)
: AutoHideSelectionChanges(
aFrame ? aFrame->GetSelection(SelectionType::eNormal) : nullptr) {}
bool Selection::HasSameRootOrSameComposedDoc(const nsINode& aNode) {
nsINode* root = aNode.SubtreeRoot();
Document* doc = GetDocument();
return doc == root || (root && doc == root->GetComposedDoc());
}
|