1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsHTMLDocument.h"
#include "nsIContentPolicy.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/dom/HTMLAllCollection.h"
#include "nsCOMPtr.h"
#include "nsGlobalWindow.h"
#include "nsXPIDLString.h"
#include "nsPrintfCString.h"
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
#include "nsIHTMLContentSink.h"
#include "nsIXMLContentSink.h"
#include "nsHTMLParts.h"
#include "nsHTMLStyleSheet.h"
#include "nsGkAtoms.h"
#include "nsIPresShell.h"
#include "nsPresContext.h"
#include "nsIDOMNode.h" // for Find
#include "nsIDOMNodeList.h"
#include "nsIDOMElement.h"
#include "nsPIDOMWindow.h"
#include "nsDOMString.h"
#include "nsIStreamListener.h"
#include "nsIURI.h"
#include "nsIIOService.h"
#include "nsNetUtil.h"
#include "nsIPrivateBrowsingChannel.h"
#include "nsIContentViewerContainer.h"
#include "nsIContentViewer.h"
#include "nsDocShell.h"
#include "nsDocShellLoadTypes.h"
#include "nsIWebNavigation.h"
#include "nsIBaseWindow.h"
#include "nsIWebShellServices.h"
#include "nsIScriptContext.h"
#include "nsIXPConnect.h"
#include "nsContentList.h"
#include "nsError.h"
#include "nsIPrincipal.h"
#include "nsJSPrincipals.h"
#include "nsIScriptSecurityManager.h"
#include "nsAttrName.h"
#include "nsNodeUtils.h"
#include "nsNetCID.h"
#include "nsICookieService.h"
#include "nsIServiceManager.h"
#include "nsIConsoleService.h"
#include "nsIComponentManager.h"
#include "nsParserCIID.h"
#include "nsIDOMHTMLElement.h"
#include "nsIDOMHTMLHeadElement.h"
#include "nsNameSpaceManager.h"
#include "nsGenericHTMLElement.h"
#include "mozilla/css/Loader.h"
#include "nsIHttpChannel.h"
#include "nsIFile.h"
#include "nsFrameSelection.h"
#include "nsISelectionPrivate.h"//for toStringwithformat code
#include "nsContentUtils.h"
#include "nsJSUtils.h"
#include "nsIDocumentInlines.h"
#include "nsIDocumentEncoder.h" //for outputting selection
#include "nsICachingChannel.h"
#include "nsIContentViewer.h"
#include "nsIWyciwygChannel.h"
#include "nsIScriptElement.h"
#include "nsIScriptError.h"
#include "nsIMutableArray.h"
#include "nsArrayUtils.h"
#include "nsIEffectiveTLDService.h"
//AHMED 12-2
#include "nsBidiUtils.h"
#include "mozilla/dom/EncodingUtils.h"
#include "mozilla/dom/FallbackEncoding.h"
#include "mozilla/LoadInfo.h"
#include "nsIEditingSession.h"
#include "nsIEditor.h"
#include "nsNodeInfoManager.h"
#include "nsIPlaintextEditor.h"
#include "nsIHTMLEditor.h"
#include "nsIEditorStyleSheets.h"
#include "nsIInlineSpellChecker.h"
#include "nsRange.h"
#include "mozAutoDocUpdate.h"
#include "nsCCUncollectableMarker.h"
#include "nsHtml5Module.h"
#include "prprf.h"
#include "mozilla/dom/Element.h"
#include "mozilla/Preferences.h"
#include "nsMimeTypes.h"
#include "nsIRequest.h"
#include "nsHtml5TreeOpExecutor.h"
#include "nsHtml5Parser.h"
#include "nsSandboxFlags.h"
#include "nsIImageDocument.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/HTMLDocumentBinding.h"
#include "nsCharsetSource.h"
#include "nsIStringBundle.h"
#include "nsDOMClassInfo.h"
#include "nsFocusManager.h"
#include "nsIFrame.h"
#include "nsIContent.h"
#include "nsLayoutStylesheetCache.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
using namespace mozilla;
using namespace mozilla::dom;
#define NS_MAX_DOCUMENT_WRITE_DEPTH 20
#include "prtime.h"
//#define DEBUG_charset
static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
uint32_t nsHTMLDocument::gWyciwygSessionCnt = 0;
// this function will return false if the command is not recognized
// inCommandID will be converted as necessary for internal operations
// inParam will be converted as necessary for internal operations
// outParam will be Empty if no parameter is needed or if returning a boolean
// outIsBoolean will determine whether to send param as a boolean or string
// outBooleanParam will not be set unless outIsBoolean
static bool ConvertToMidasInternalCommand(const nsAString & inCommandID,
const nsAString & inParam,
nsACString& outCommandID,
nsACString& outParam,
bool& isBoolean,
bool& boolValue);
static bool ConvertToMidasInternalCommand(const nsAString & inCommandID,
nsACString& outCommandID);
// ==================================================================
// =
// ==================================================================
nsresult
NS_NewHTMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData)
{
RefPtr<nsHTMLDocument> doc = new nsHTMLDocument();
nsresult rv = doc->Init();
if (NS_FAILED(rv)) {
*aInstancePtrResult = nullptr;
return rv;
}
doc->SetLoadedAsData(aLoadedAsData);
doc.forget(aInstancePtrResult);
return NS_OK;
}
// NOTE! nsDocument::operator new() zeroes out all members, so don't
// bother initializing members to 0.
nsHTMLDocument::nsHTMLDocument()
: nsDocument("text/html")
{
// NOTE! nsDocument::operator new() zeroes out all members, so don't
// bother initializing members to 0.
mType = eHTML;
mDefaultElementType = kNameSpaceID_XHTML;
mCompatMode = eCompatibility_NavQuirks;
}
nsHTMLDocument::~nsHTMLDocument()
{
}
NS_IMPL_CYCLE_COLLECTION_INHERITED(nsHTMLDocument, nsDocument,
mAll,
mImages,
mApplets,
mEmbeds,
mLinks,
mAnchors,
mScripts,
mForms,
mFormControls,
mWyciwygChannel,
mMidasCommandManager)
NS_IMPL_ADDREF_INHERITED(nsHTMLDocument, nsDocument)
NS_IMPL_RELEASE_INHERITED(nsHTMLDocument, nsDocument)
// QueryInterface implementation for nsHTMLDocument
NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(nsHTMLDocument)
NS_INTERFACE_TABLE_INHERITED(nsHTMLDocument, nsIHTMLDocument,
nsIDOMHTMLDocument)
NS_INTERFACE_TABLE_TAIL_INHERITING(nsDocument)
JSObject*
nsHTMLDocument::WrapNode(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return HTMLDocumentBinding::Wrap(aCx, this, aGivenProto);
}
nsresult
nsHTMLDocument::Init()
{
nsresult rv = nsDocument::Init();
NS_ENSURE_SUCCESS(rv, rv);
// Now reset the compatibility mode of the CSSLoader
// to match our compat mode.
CSSLoader()->SetCompatibilityMode(mCompatMode);
return NS_OK;
}
void
nsHTMLDocument::Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup)
{
nsDocument::Reset(aChannel, aLoadGroup);
if (aChannel) {
aChannel->GetLoadFlags(&mLoadFlags);
}
}
void
nsHTMLDocument::ResetToURI(nsIURI *aURI, nsILoadGroup *aLoadGroup,
nsIPrincipal* aPrincipal)
{
mLoadFlags = nsIRequest::LOAD_NORMAL;
nsDocument::ResetToURI(aURI, aLoadGroup, aPrincipal);
mImages = nullptr;
mApplets = nullptr;
mEmbeds = nullptr;
mLinks = nullptr;
mAnchors = nullptr;
mScripts = nullptr;
mForms = nullptr;
NS_ASSERTION(!mWyciwygChannel,
"nsHTMLDocument::Reset() - Wyciwyg Channel still exists!");
mWyciwygChannel = nullptr;
// Make the content type default to "text/html", we are a HTML
// document, after all. Once we start getting data, this may be
// changed.
SetContentTypeInternal(nsDependentCString("text/html"));
}
already_AddRefed<nsIPresShell>
nsHTMLDocument::CreateShell(nsPresContext* aContext,
nsViewManager* aViewManager,
StyleSetHandle aStyleSet)
{
return doCreateShell(aContext, aViewManager, aStyleSet);
}
void
nsHTMLDocument::TryHintCharset(nsIContentViewer* aCv,
int32_t& aCharsetSource, nsACString& aCharset)
{
if (aCv) {
int32_t requestCharsetSource;
nsresult rv = aCv->GetHintCharacterSetSource(&requestCharsetSource);
if(NS_SUCCEEDED(rv) && kCharsetUninitialized != requestCharsetSource) {
nsAutoCString requestCharset;
rv = aCv->GetHintCharacterSet(requestCharset);
aCv->SetHintCharacterSetSource((int32_t)(kCharsetUninitialized));
if(requestCharsetSource <= aCharsetSource)
return;
if(NS_SUCCEEDED(rv) && EncodingUtils::IsAsciiCompatible(requestCharset)) {
aCharsetSource = requestCharsetSource;
aCharset = requestCharset;
return;
}
}
}
return;
}
void
nsHTMLDocument::TryUserForcedCharset(nsIContentViewer* aCv,
nsIDocShell* aDocShell,
int32_t& aCharsetSource,
nsACString& aCharset)
{
nsresult rv = NS_OK;
if(kCharsetFromUserForced <= aCharsetSource)
return;
// mCharacterSet not updated yet for channel, so check aCharset, too.
if (WillIgnoreCharsetOverride() || !EncodingUtils::IsAsciiCompatible(aCharset)) {
return;
}
nsAutoCString forceCharsetFromDocShell;
if (aCv) {
// XXX mailnews-only
rv = aCv->GetForceCharacterSet(forceCharsetFromDocShell);
}
if(NS_SUCCEEDED(rv) &&
!forceCharsetFromDocShell.IsEmpty() &&
EncodingUtils::IsAsciiCompatible(forceCharsetFromDocShell)) {
aCharset = forceCharsetFromDocShell;
aCharsetSource = kCharsetFromUserForced;
return;
}
if (aDocShell) {
// This is the Character Encoding menu code path in Firefox
nsAutoCString charset;
rv = aDocShell->GetForcedCharset(charset);
if (NS_SUCCEEDED(rv) && !charset.IsEmpty()) {
if (!EncodingUtils::IsAsciiCompatible(charset)) {
return;
}
aCharset = charset;
aCharsetSource = kCharsetFromUserForced;
aDocShell->SetForcedCharset(NS_LITERAL_CSTRING(""));
}
}
}
void
nsHTMLDocument::TryCacheCharset(nsICachingChannel* aCachingChannel,
int32_t& aCharsetSource,
nsACString& aCharset)
{
nsresult rv;
if (kCharsetFromCache <= aCharsetSource) {
return;
}
nsCString cachedCharset;
rv = aCachingChannel->GetCacheTokenCachedCharset(cachedCharset);
// Check EncodingUtils::IsAsciiCompatible() even in the cache case, because the value
// might be stale and in the case of a stale charset that is not a rough
// ASCII superset, the parser has no way to recover.
if (NS_SUCCEEDED(rv) &&
!cachedCharset.IsEmpty() &&
EncodingUtils::IsAsciiCompatible(cachedCharset))
{
aCharset = cachedCharset;
aCharsetSource = kCharsetFromCache;
}
}
void
nsHTMLDocument::TryParentCharset(nsIDocShell* aDocShell,
int32_t& aCharsetSource,
nsACString& aCharset)
{
if (!aDocShell) {
return;
}
if (aCharsetSource >= kCharsetFromParentForced) {
return;
}
int32_t parentSource;
nsAutoCString parentCharset;
nsCOMPtr<nsIPrincipal> parentPrincipal;
aDocShell->GetParentCharset(parentCharset,
&parentSource,
getter_AddRefs(parentPrincipal));
if (parentCharset.IsEmpty()) {
return;
}
if (kCharsetFromParentForced == parentSource ||
kCharsetFromUserForced == parentSource) {
if (WillIgnoreCharsetOverride() ||
!EncodingUtils::IsAsciiCompatible(aCharset) || // if channel said UTF-16
!EncodingUtils::IsAsciiCompatible(parentCharset)) {
return;
}
aCharset.Assign(parentCharset);
aCharsetSource = kCharsetFromParentForced;
return;
}
if (aCharsetSource >= kCharsetFromParentFrame) {
return;
}
if (kCharsetFromCache <= parentSource) {
// Make sure that's OK
if (!NodePrincipal()->Equals(parentPrincipal) ||
!EncodingUtils::IsAsciiCompatible(parentCharset)) {
return;
}
aCharset.Assign(parentCharset);
aCharsetSource = kCharsetFromParentFrame;
}
}
void
nsHTMLDocument::TryTLD(int32_t& aCharsetSource, nsACString& aCharset)
{
if (aCharsetSource >= kCharsetFromTopLevelDomain) {
return;
}
if (!FallbackEncoding::sGuessFallbackFromTopLevelDomain) {
return;
}
if (!mDocumentURI) {
return;
}
nsAutoCString host;
mDocumentURI->GetAsciiHost(host);
if (host.IsEmpty()) {
return;
}
// First let's see if the host is DNS-absolute and ends with a dot and
// get rid of that one.
if (host.Last() == '.') {
host.SetLength(host.Length() - 1);
if (host.IsEmpty()) {
return;
}
}
// If we still have a dot, the host is weird, so let's continue only
// if we have something other than a dot now.
if (host.Last() == '.') {
return;
}
int32_t index = host.RFindChar('.');
if (index == kNotFound) {
// We have an intranet host, Gecko-internal URL or an IPv6 address.
return;
}
// Since the string didn't end with a dot and we found a dot,
// there is at least one character between the dot and the end of
// the string, so taking the substring below is safe.
nsAutoCString tld;
ToLowerCase(Substring(host, index + 1, host.Length() - (index + 1)), tld);
// Reject generic TLDs and country TLDs that need more research
if (!FallbackEncoding::IsParticipatingTopLevelDomain(tld)) {
return;
}
// Check if we have an IPv4 address
bool seenNonDigit = false;
for (size_t i = 0; i < tld.Length(); ++i) {
char c = tld.CharAt(i);
if (c < '0' || c > '9') {
seenNonDigit = true;
break;
}
}
if (!seenNonDigit) {
return;
}
aCharsetSource = kCharsetFromTopLevelDomain;
FallbackEncoding::FromTopLevelDomain(tld, aCharset);
}
void
nsHTMLDocument::TryFallback(int32_t& aCharsetSource, nsACString& aCharset)
{
if (kCharsetFromFallback <= aCharsetSource)
return;
aCharsetSource = kCharsetFromFallback;
FallbackEncoding::FromLocale(aCharset);
}
void
nsHTMLDocument::SetDocumentCharacterSet(const nsACString& aCharSetID)
{
nsDocument::SetDocumentCharacterSet(aCharSetID);
// Make sure to stash this charset on our channel as needed if it's a wyciwyg
// channel.
nsCOMPtr<nsIWyciwygChannel> wyciwygChannel = do_QueryInterface(mChannel);
if (wyciwygChannel) {
wyciwygChannel->SetCharsetAndSource(GetDocumentCharacterSetSource(),
aCharSetID);
}
}
nsresult
nsHTMLDocument::StartDocumentLoad(const char* aCommand,
nsIChannel* aChannel,
nsILoadGroup* aLoadGroup,
nsISupports* aContainer,
nsIStreamListener **aDocListener,
bool aReset,
nsIContentSink* aSink)
{
if (!aCommand) {
MOZ_ASSERT(false, "Command is mandatory");
return NS_ERROR_INVALID_POINTER;
}
if (aSink) {
MOZ_ASSERT(false, "Got a sink override. Should not happen for HTML doc.");
return NS_ERROR_INVALID_ARG;
}
if (mType != eHTML) {
MOZ_ASSERT(mType == eXHTML);
MOZ_ASSERT(false, "Must not set HTML doc to XHTML mode before load start.");
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
nsAutoCString contentType;
aChannel->GetContentType(contentType);
bool view = !strcmp(aCommand, "view") ||
!strcmp(aCommand, "external-resource");
bool viewSource = !strcmp(aCommand, "view-source");
bool asData = !strcmp(aCommand, kLoadAsData);
bool import = !strcmp(aCommand, "import");
if (!(view || viewSource || asData || import)) {
MOZ_ASSERT(false, "Bad parser command");
return NS_ERROR_INVALID_ARG;
}
bool html = contentType.EqualsLiteral(TEXT_HTML);
bool xhtml = !html && (contentType.EqualsLiteral(APPLICATION_XHTML_XML) || contentType.EqualsLiteral(APPLICATION_WAPXHTML_XML));
bool plainText = !html && !xhtml && nsContentUtils::IsPlainTextType(contentType);
if (!(html || xhtml || plainText || viewSource)) {
MOZ_ASSERT(false, "Channel with bad content type.");
return NS_ERROR_INVALID_ARG;
}
bool loadAsHtml5 = true;
if (!viewSource && xhtml) {
// We're parsing XHTML as XML, remember that.
mType = eXHTML;
mCompatMode = eCompatibility_FullStandards;
loadAsHtml5 = false;
}
// TODO: Proper about:blank treatment is bug 543435
if (loadAsHtml5 && view) {
// mDocumentURI hasn't been set, yet, so get the URI from the channel
nsCOMPtr<nsIURI> uri;
aChannel->GetOriginalURI(getter_AddRefs(uri));
// Adapted from nsDocShell:
// GetSpec can be expensive for some URIs, so check the scheme first.
bool isAbout = false;
if (uri && NS_SUCCEEDED(uri->SchemeIs("about", &isAbout)) && isAbout) {
if (uri->GetSpecOrDefault().EqualsLiteral("about:blank")) {
loadAsHtml5 = false;
}
}
}
CSSLoader()->SetCompatibilityMode(mCompatMode);
nsresult rv = nsDocument::StartDocumentLoad(aCommand,
aChannel, aLoadGroup,
aContainer,
aDocListener, aReset);
if (NS_FAILED(rv)) {
return rv;
}
// Store the security info for future use with wyciwyg channels.
aChannel->GetSecurityInfo(getter_AddRefs(mSecurityInfo));
nsCOMPtr<nsIURI> uri;
rv = aChannel->GetURI(getter_AddRefs(uri));
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsICachingChannel> cachingChan = do_QueryInterface(aChannel);
if (loadAsHtml5) {
mParser = nsHtml5Module::NewHtml5Parser();
if (plainText) {
if (viewSource) {
mParser->MarkAsNotScriptCreated("view-source-plain");
} else {
mParser->MarkAsNotScriptCreated("plain-text");
}
} else if (viewSource && !html) {
mParser->MarkAsNotScriptCreated("view-source-xml");
} else {
mParser->MarkAsNotScriptCreated(aCommand);
}
} else {
mParser = do_CreateInstance(kCParserCID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
// Look for the parent document. Note that at this point we don't have our
// content viewer set up yet, and therefore do not have a useful
// mParentDocument.
// in this block of code, if we get an error result, we return it
// but if we get a null pointer, that's perfectly legal for parent
// and parentContentViewer
nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(aContainer));
nsCOMPtr<nsIDocShellTreeItem> parentAsItem;
if (docShell) {
docShell->GetSameTypeParent(getter_AddRefs(parentAsItem));
}
nsCOMPtr<nsIDocShell> parent(do_QueryInterface(parentAsItem));
nsCOMPtr<nsIContentViewer> parentContentViewer;
if (parent) {
rv = parent->GetContentViewer(getter_AddRefs(parentContentViewer));
NS_ENSURE_SUCCESS(rv, rv);
}
nsCOMPtr<nsIContentViewer> cv;
if (docShell) {
docShell->GetContentViewer(getter_AddRefs(cv));
}
if (!cv) {
cv = parentContentViewer.forget();
}
nsAutoCString urlSpec;
uri->GetSpec(urlSpec);
#ifdef DEBUG_charset
printf("Determining charset for %s\n", urlSpec.get());
#endif
// These are the charset source and charset for our document
int32_t charsetSource;
nsAutoCString charset;
// These are the charset source and charset for the parser. This can differ
// from that for the document if the channel is a wyciwyg channel.
int32_t parserCharsetSource;
nsAutoCString parserCharset;
nsCOMPtr<nsIWyciwygChannel> wyciwygChannel;
// For error reporting and referrer policy setting
nsHtml5TreeOpExecutor* executor = nullptr;
if (loadAsHtml5) {
executor = static_cast<nsHtml5TreeOpExecutor*> (mParser->GetContentSink());
if (mReferrerPolicySet) {
// CSP may have set the referrer policy, so a speculative parser should
// start with the new referrer policy.
executor->SetSpeculationReferrerPolicy(static_cast<ReferrerPolicy>(mReferrerPolicy));
}
}
if (!IsHTMLDocument() || !docShell) { // no docshell for text/html XHR
charsetSource = IsHTMLDocument() ? kCharsetFromFallback
: kCharsetFromDocTypeDefault;
charset.AssignLiteral("UTF-8");
TryChannelCharset(aChannel, charsetSource, charset, executor);
parserCharsetSource = charsetSource;
parserCharset = charset;
} else {
NS_ASSERTION(docShell, "Unexpected null value");
charsetSource = kCharsetUninitialized;
wyciwygChannel = do_QueryInterface(aChannel);
// The following will try to get the character encoding from various
// sources. Each Try* function will return early if the source is already
// at least as large as any of the sources it might look at. Some of
// these functions (like TryHintCharset and TryParentCharset) can set
// charsetSource to various values depending on where the charset they
// end up finding originally comes from.
// Don't actually get the charset from the channel if this is a
// wyciwyg channel; it'll always be UTF-16
if (!wyciwygChannel) {
// Otherwise, try the channel's charset (e.g., charset from HTTP
// "Content-Type" header) first. This way, we get to reject overrides in
// TryParentCharset and TryUserForcedCharset if the channel said UTF-16.
// This is to avoid socially engineered XSS by adding user-supplied
// content to a UTF-16 site such that the byte have a dangerous
// interpretation as ASCII and the user can be lured to using the
// charset menu.
TryChannelCharset(aChannel, charsetSource, charset, executor);
}
TryUserForcedCharset(cv, docShell, charsetSource, charset);
TryHintCharset(cv, charsetSource, charset); // XXX mailnews-only
TryParentCharset(docShell, charsetSource, charset);
if (cachingChan && !urlSpec.IsEmpty()) {
TryCacheCharset(cachingChan, charsetSource, charset);
}
TryTLD(charsetSource, charset);
TryFallback(charsetSource, charset);
if (wyciwygChannel) {
// We know for sure that the parser needs to be using UTF16.
parserCharset = "UTF-16";
parserCharsetSource = charsetSource < kCharsetFromChannel ?
kCharsetFromChannel : charsetSource;
nsAutoCString cachedCharset;
int32_t cachedSource;
rv = wyciwygChannel->GetCharsetAndSource(&cachedSource, cachedCharset);
if (NS_SUCCEEDED(rv)) {
if (cachedSource > charsetSource) {
charsetSource = cachedSource;
charset = cachedCharset;
}
} else {
// Don't propagate this error.
rv = NS_OK;
}
} else {
parserCharset = charset;
parserCharsetSource = charsetSource;
}
}
SetDocumentCharacterSetSource(charsetSource);
SetDocumentCharacterSet(charset);
if (cachingChan) {
NS_ASSERTION(charset == parserCharset,
"How did those end up different here? wyciwyg channels are "
"not nsICachingChannel");
rv = cachingChan->SetCacheTokenCachedCharset(charset);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "cannot SetMetaDataElement");
rv = NS_OK; // don't propagate error
}
// Set the parser as the stream listener for the document loader...
rv = NS_OK;
nsCOMPtr<nsIStreamListener> listener = mParser->GetStreamListener();
listener.forget(aDocListener);
#ifdef DEBUG_charset
printf(" charset = %s source %d\n",
charset.get(), charsetSource);
#endif
mParser->SetDocumentCharset(parserCharset, parserCharsetSource);
mParser->SetCommand(aCommand);
if (!IsHTMLDocument()) {
MOZ_ASSERT(!loadAsHtml5);
nsCOMPtr<nsIXMLContentSink> xmlsink;
NS_NewXMLContentSink(getter_AddRefs(xmlsink), this, uri,
docShell, aChannel);
mParser->SetContentSink(xmlsink);
} else {
if (loadAsHtml5) {
nsHtml5Module::Initialize(mParser, this, uri, docShell, aChannel);
} else {
// about:blank *only*
nsCOMPtr<nsIHTMLContentSink> htmlsink;
NS_NewHTMLContentSink(getter_AddRefs(htmlsink), this, uri,
docShell, aChannel);
mParser->SetContentSink(htmlsink);
}
}
if (plainText && !nsContentUtils::IsChildOfSameType(this) &&
Preferences::GetBool("plain_text.wrap_long_lines")) {
nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv) && bundleService, "The bundle service could not be loaded");
nsCOMPtr<nsIStringBundle> bundle;
rv = bundleService->CreateBundle("chrome://global/locale/browser.properties",
getter_AddRefs(bundle));
NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/browser.properties could not be loaded");
nsXPIDLString title;
if (bundle) {
bundle->GetStringFromName(u"plainText.wordWrap", getter_Copies(title));
}
SetSelectedStyleSheetSet(title);
}
// parser the content of the URI
mParser->Parse(uri, nullptr, (void *)this);
return rv;
}
void
nsHTMLDocument::StopDocumentLoad()
{
BlockOnload();
// Remove the wyciwyg channel request from the document load group
// that we added in Open() if Open() was called on this doc.
RemoveWyciwygChannel();
NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::StopDocumentLoad(): "
"nsIWyciwygChannel could not be removed!");
nsDocument::StopDocumentLoad();
UnblockOnload(false);
return;
}
void
nsHTMLDocument::BeginLoad()
{
if (IsEditingOn()) {
// Reset() blows away all event listeners in the document, and our
// editor relies heavily on those. Midas is turned on, to make it
// work, re-initialize it to give it a chance to add its event
// listeners again.
TurnEditingOff();
EditingStateChanged();
}
nsDocument::BeginLoad();
}
void
nsHTMLDocument::EndLoad()
{
bool turnOnEditing =
mParser && (HasFlag(NODE_IS_EDITABLE) || mContentEditableCount > 0);
// Note: nsDocument::EndLoad nulls out mParser.
nsDocument::EndLoad();
if (turnOnEditing) {
EditingStateChanged();
}
}
void
nsHTMLDocument::SetCompatibilityMode(nsCompatibility aMode)
{
NS_ASSERTION(IsHTMLDocument() || aMode == eCompatibility_FullStandards,
"Bad compat mode for XHTML document!");
mCompatMode = aMode;
CSSLoader()->SetCompatibilityMode(mCompatMode);
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
nsPresContext *pc = shell->GetPresContext();
if (pc) {
pc->CompatibilityModeChanged();
}
}
}
//
// nsIDOMHTMLDocument interface implementation
//
already_AddRefed<nsIURI>
nsHTMLDocument::GetDomainURI()
{
nsIPrincipal* principal = NodePrincipal();
nsCOMPtr<nsIURI> uri;
principal->GetDomain(getter_AddRefs(uri));
if (uri) {
return uri.forget();
}
principal->GetURI(getter_AddRefs(uri));
return uri.forget();
}
NS_IMETHODIMP
nsHTMLDocument::GetDomain(nsAString& aDomain)
{
nsCOMPtr<nsIURI> uri = GetDomainURI();
if (!uri) {
SetDOMStringToNull(aDomain);
return NS_OK;
}
nsAutoCString hostName;
nsresult rv = nsContentUtils::GetHostOrIPv6WithBrackets(uri, hostName);
if (NS_SUCCEEDED(rv)) {
CopyUTF8toUTF16(hostName, aDomain);
} else {
// If we can't get the host from the URI (e.g. about:, javascript:,
// etc), just return an null string.
SetDOMStringToNull(aDomain);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetDomain(const nsAString& aDomain)
{
ErrorResult rv;
SetDomain(aDomain, rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::SetDomain(const nsAString& aDomain, ErrorResult& rv)
{
if (mSandboxFlags & SANDBOXED_DOMAIN) {
// We're sandboxed; disallow setting domain
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
if (aDomain.IsEmpty()) {
rv.Throw(NS_ERROR_DOM_BAD_DOCUMENT_DOMAIN);
return;
}
// Create new URI
nsCOMPtr<nsIURI> uri = GetDomainURI();
if (!uri) {
rv.Throw(NS_ERROR_FAILURE);
return;
}
nsCOMPtr<nsIURI> newURI;
nsresult rv2 = uri->Clone(getter_AddRefs(newURI));
if (NS_FAILED(rv2)) {
rv.Throw(rv2);
return;
}
rv2 = newURI->SetUserPass(EmptyCString());
if (NS_FAILED(rv2)) {
rv.Throw(rv2);
return;
}
// We use SetHostAndPort because we want to reset the port number if needed.
rv2 = newURI->SetHostAndPort(NS_ConvertUTF16toUTF8(aDomain));
if (NS_FAILED(rv2)) {
rv.Throw(rv2);
return;
}
// Check new domain - must be a superdomain of the current host
// For example, a page from foo.bar.com may set domain to bar.com,
// but not to ar.com, baz.com, or fi.foo.bar.com.
nsAutoCString current, domain;
if (NS_FAILED(uri->GetAsciiHost(current)))
current.Truncate();
if (NS_FAILED(newURI->GetAsciiHost(domain)))
domain.Truncate();
bool ok = current.Equals(domain);
if (current.Length() > domain.Length() &&
StringEndsWith(current, domain) &&
current.CharAt(current.Length() - domain.Length() - 1) == '.') {
// We're golden if the new domain is the current page's base domain or a
// subdomain of it.
nsCOMPtr<nsIEffectiveTLDService> tldService =
do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
if (!tldService) {
rv.Throw(NS_ERROR_NOT_AVAILABLE);
return;
}
nsAutoCString currentBaseDomain;
ok = NS_SUCCEEDED(tldService->GetBaseDomain(uri, 0, currentBaseDomain));
NS_ASSERTION(StringEndsWith(domain, currentBaseDomain) ==
(domain.Length() >= currentBaseDomain.Length()),
"uh-oh! slight optimization wasn't valid somehow!");
ok = ok && domain.Length() >= currentBaseDomain.Length();
}
if (!ok) {
// Error: illegal domain
rv.Throw(NS_ERROR_DOM_BAD_DOCUMENT_DOMAIN);
return;
}
NS_TryToSetImmutable(newURI);
rv = NodePrincipal()->SetDomain(newURI);
}
nsGenericHTMLElement*
nsHTMLDocument::GetBody()
{
Element* html = GetHtmlElement();
if (!html) {
return nullptr;
}
for (nsIContent* child = html->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->IsHTMLElement(nsGkAtoms::body) ||
child->IsHTMLElement(nsGkAtoms::frameset)) {
return static_cast<nsGenericHTMLElement*>(child);
}
}
return nullptr;
}
NS_IMETHODIMP
nsHTMLDocument::GetBody(nsIDOMHTMLElement** aBody)
{
*aBody = nullptr;
nsIContent *body = GetBody();
return body ? CallQueryInterface(body, aBody) : NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetBody(nsIDOMHTMLElement* aBody)
{
nsCOMPtr<nsIContent> newBody = do_QueryInterface(aBody);
MOZ_ASSERT(!newBody || newBody->IsHTMLElement(),
"How could we be an nsIContent but not actually HTML here?");
ErrorResult rv;
SetBody(static_cast<nsGenericHTMLElement*>(newBody.get()), rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::SetBody(nsGenericHTMLElement* newBody, ErrorResult& rv)
{
nsCOMPtr<Element> root = GetRootElement();
// The body element must be either a body tag or a frameset tag. And we must
// have a html root tag, otherwise GetBody will not return the newly set
// body.
if (!newBody ||
!newBody->IsAnyOfHTMLElements(nsGkAtoms::body, nsGkAtoms::frameset) ||
!root || !root->IsHTMLElement() ||
!root->IsHTMLElement(nsGkAtoms::html)) {
rv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
return;
}
// Use DOM methods so that we pass through the appropriate security checks.
nsCOMPtr<Element> currentBody = GetBodyElement();
if (currentBody) {
root->ReplaceChild(*newBody, *currentBody, rv);
} else {
root->AppendChild(*newBody, rv);
}
}
NS_IMETHODIMP
nsHTMLDocument::GetHead(nsIDOMHTMLHeadElement** aHead)
{
*aHead = nullptr;
Element* head = GetHeadElement();
return head ? CallQueryInterface(head, aHead) : NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetImages(nsIDOMHTMLCollection** aImages)
{
NS_ADDREF(*aImages = Images());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Images()
{
if (!mImages) {
mImages = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::img, nsGkAtoms::img);
}
return mImages;
}
NS_IMETHODIMP
nsHTMLDocument::GetApplets(nsIDOMHTMLCollection** aApplets)
{
NS_ADDREF(*aApplets = Applets());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Applets()
{
if (!mApplets) {
mApplets = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::applet, nsGkAtoms::applet);
}
return mApplets;
}
bool
nsHTMLDocument::MatchLinks(Element* aElement, int32_t aNamespaceID,
nsIAtom* aAtom, void* aData)
{
nsIDocument* doc = aElement->GetUncomposedDoc();
if (doc) {
NS_ASSERTION(aElement->IsInUncomposedDoc(),
"This method should never be called on content nodes that "
"are not in a document!");
#ifdef DEBUG
{
nsCOMPtr<nsIHTMLDocument> htmldoc =
do_QueryInterface(aElement->GetUncomposedDoc());
NS_ASSERTION(htmldoc,
"Huh, how did this happen? This should only be used with "
"HTML documents!");
}
#endif
mozilla::dom::NodeInfo *ni = aElement->NodeInfo();
nsIAtom *localName = ni->NameAtom();
if (ni->NamespaceID() == kNameSpaceID_XHTML &&
(localName == nsGkAtoms::a || localName == nsGkAtoms::area)) {
return aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::href);
}
}
return false;
}
NS_IMETHODIMP
nsHTMLDocument::GetLinks(nsIDOMHTMLCollection** aLinks)
{
NS_ADDREF(*aLinks = Links());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Links()
{
if (!mLinks) {
mLinks = new nsContentList(this, MatchLinks, nullptr, nullptr);
}
return mLinks;
}
bool
nsHTMLDocument::MatchAnchors(Element* aElement, int32_t aNamespaceID,
nsIAtom* aAtom, void* aData)
{
NS_ASSERTION(aElement->IsInUncomposedDoc(),
"This method should never be called on content nodes that "
"are not in a document!");
#ifdef DEBUG
{
nsCOMPtr<nsIHTMLDocument> htmldoc =
do_QueryInterface(aElement->GetUncomposedDoc());
NS_ASSERTION(htmldoc,
"Huh, how did this happen? This should only be used with "
"HTML documents!");
}
#endif
if (aElement->IsHTMLElement(nsGkAtoms::a)) {
return aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::name);
}
return false;
}
NS_IMETHODIMP
nsHTMLDocument::GetAnchors(nsIDOMHTMLCollection** aAnchors)
{
NS_ADDREF(*aAnchors = Anchors());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Anchors()
{
if (!mAnchors) {
mAnchors = new nsContentList(this, MatchAnchors, nullptr, nullptr);
}
return mAnchors;
}
NS_IMETHODIMP
nsHTMLDocument::GetScripts(nsIDOMHTMLCollection** aScripts)
{
NS_ADDREF(*aScripts = Scripts());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Scripts()
{
if (!mScripts) {
mScripts = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::script, nsGkAtoms::script);
}
return mScripts;
}
NS_IMETHODIMP
nsHTMLDocument::GetCookie(nsAString& aCookie)
{
ErrorResult rv;
GetCookie(aCookie, rv);
return rv.StealNSResult();
}
already_AddRefed<nsIChannel>
nsHTMLDocument::CreateDummyChannelForCookies(nsIURI* aCodebaseURI)
{
// The cookie service reads the privacy status of the channel we pass to it in
// order to determine which cookie database to query. In some cases we don't
// have a proper channel to hand it to the cookie service though. This
// function creates a dummy channel that is not used to load anything, for the
// sole purpose of handing it to the cookie service. DO NOT USE THIS CHANNEL
// FOR ANY OTHER PURPOSE.
MOZ_ASSERT(!mChannel);
// The following channel is never openend, so it does not matter what
// securityFlags we pass; let's follow the principle of least privilege.
nsCOMPtr<nsIChannel> channel;
NS_NewChannel(getter_AddRefs(channel), aCodebaseURI, this,
nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
nsIContentPolicy::TYPE_INVALID);
nsCOMPtr<nsIPrivateBrowsingChannel> pbChannel =
do_QueryInterface(channel);
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(docShell);
if (!pbChannel || !loadContext) {
return nullptr;
}
pbChannel->SetPrivate(loadContext->UsePrivateBrowsing());
return channel.forget();
}
void
nsHTMLDocument::GetCookie(nsAString& aCookie, ErrorResult& rv)
{
aCookie.Truncate(); // clear current cookie in case service fails;
// no cookie isn't an error condition.
if (mDisableCookieAccess) {
return;
}
// If the document's sandboxed origin flag is set, access to read cookies
// is prohibited.
if (mSandboxFlags & SANDBOXED_ORIGIN) {
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
// If the document is a cookie-averse document, return an empty string.
if (IsCookieAverse()) {
return;
}
// not having a cookie service isn't an error
nsCOMPtr<nsICookieService> service = do_GetService(NS_COOKIESERVICE_CONTRACTID);
if (service) {
// Get a URI from the document principal. We use the original
// codebase in case the codebase was changed by SetDomain
nsCOMPtr<nsIURI> codebaseURI;
NodePrincipal()->GetURI(getter_AddRefs(codebaseURI));
if (!codebaseURI) {
// Document's principal is not a codebase (may be system), so
// can't set cookies
return;
}
nsCOMPtr<nsIChannel> channel(mChannel);
if (!channel) {
channel = CreateDummyChannelForCookies(codebaseURI);
if (!channel) {
return;
}
}
nsXPIDLCString cookie;
service->GetCookieString(codebaseURI, channel, getter_Copies(cookie));
// CopyUTF8toUTF16 doesn't handle error
// because it assumes that the input is valid.
nsContentUtils::ConvertStringFromEncoding(NS_LITERAL_CSTRING("UTF-8"),
cookie, aCookie);
}
}
NS_IMETHODIMP
nsHTMLDocument::SetCookie(const nsAString& aCookie)
{
ErrorResult rv;
SetCookie(aCookie, rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::SetCookie(const nsAString& aCookie, ErrorResult& rv)
{
if (mDisableCookieAccess) {
return;
}
// If the document's sandboxed origin flag is set, access to write cookies
// is prohibited.
if (mSandboxFlags & SANDBOXED_ORIGIN) {
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
// If the document is a cookie-averse document, do nothing.
if (IsCookieAverse()) {
return;
}
// not having a cookie service isn't an error
nsCOMPtr<nsICookieService> service = do_GetService(NS_COOKIESERVICE_CONTRACTID);
if (service && mDocumentURI) {
// The for getting the URI matches nsNavigator::GetCookieEnabled
nsCOMPtr<nsIURI> codebaseURI;
NodePrincipal()->GetURI(getter_AddRefs(codebaseURI));
if (!codebaseURI) {
// Document's principal is not a codebase (may be system), so
// can't set cookies
return;
}
nsCOMPtr<nsIChannel> channel(mChannel);
if (!channel) {
channel = CreateDummyChannelForCookies(codebaseURI);
if (!channel) {
return;
}
}
NS_ConvertUTF16toUTF8 cookie(aCookie);
service->SetCookieString(codebaseURI, nullptr, cookie.get(), channel);
}
}
NS_IMETHODIMP
nsHTMLDocument::Open(const nsAString& aContentTypeOrUrl,
const nsAString& aReplaceOrName,
const nsAString& aFeatures,
JSContext* cx, uint8_t aOptionalArgCount,
nsISupports** aReturn)
{
// When called with 3 or more arguments, document.open() calls window.open().
if (aOptionalArgCount > 2) {
ErrorResult rv;
*aReturn = Open(cx, aContentTypeOrUrl, aReplaceOrName, aFeatures,
false, rv).take();
return rv.StealNSResult();
}
nsString type;
if (aOptionalArgCount > 0) {
type = aContentTypeOrUrl;
} else {
type.AssignLiteral("text/html");
}
nsString replace;
if (aOptionalArgCount > 1) {
replace = aReplaceOrName;
}
ErrorResult rv;
*aReturn = Open(cx, type, replace, rv).take();
return rv.StealNSResult();
}
already_AddRefed<nsPIDOMWindowOuter>
nsHTMLDocument::Open(JSContext* /* unused */,
const nsAString& aURL,
const nsAString& aName,
const nsAString& aFeatures,
bool aReplace,
ErrorResult& rv)
{
NS_ASSERTION(nsContentUtils::CanCallerAccess(static_cast<nsIDOMHTMLDocument*>(this)),
"XOW should have caught this!");
nsCOMPtr<nsPIDOMWindowInner> window = GetInnerWindow();
if (!window) {
rv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
return nullptr;
}
nsCOMPtr<nsPIDOMWindowOuter> outer =
nsPIDOMWindowOuter::GetFromCurrentInner(window);
if (!outer) {
rv.Throw(NS_ERROR_NOT_INITIALIZED);
return nullptr;
}
RefPtr<nsGlobalWindow> win = nsGlobalWindow::Cast(outer);
nsCOMPtr<nsPIDOMWindowOuter> newWindow;
// XXXbz We ignore aReplace for now.
rv = win->OpenJS(aURL, aName, aFeatures, getter_AddRefs(newWindow));
return newWindow.forget();
}
already_AddRefed<nsIDocument>
nsHTMLDocument::Open(JSContext* cx,
const nsAString& aType,
const nsAString& aReplace,
ErrorResult& rv)
{
// Implements the "When called with two arguments (or fewer)" steps here:
// https://html.spec.whatwg.org/multipage/webappapis.html#opening-the-input-stream
NS_ASSERTION(nsContentUtils::CanCallerAccess(static_cast<nsIDOMHTMLDocument*>(this)),
"XOW should have caught this!");
if (!IsHTMLDocument() || mDisableDocWrite || !IsMasterDocument()) {
// No calling document.open() on XHTML
rv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return nullptr;
}
nsAutoCString contentType;
contentType.AssignLiteral("text/html");
nsAutoString type;
nsContentUtils::ASCIIToLower(aType, type);
nsAutoCString actualType, dummy;
NS_ParseRequestContentType(NS_ConvertUTF16toUTF8(type), actualType, dummy);
if (!actualType.EqualsLiteral("text/html") &&
!type.EqualsLiteral("replace")) {
contentType.AssignLiteral("text/plain");
}
// If we already have a parser we ignore the document.open call.
if (mParser || mParserAborted) {
// The WHATWG spec says: "If the document has an active parser that isn't
// a script-created parser, and the insertion point associated with that
// parser's input stream is not undefined (that is, it does point to
// somewhere in the input stream), then the method does nothing. Abort
// these steps and return the Document object on which the method was
// invoked."
// Note that aborting a parser leaves the parser "active" with its
// insertion point "not undefined". We track this using mParserAborted,
// because aborting a parser nulls out mParser.
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
// No calling document.open() without a script global object
if (!mScriptGlobalObject) {
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
nsPIDOMWindowOuter* outer = GetWindow();
if (!outer || (GetInnerWindow() != outer->GetCurrentInnerWindow())) {
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
// check whether we're in the middle of unload. If so, ignore this call.
nsCOMPtr<nsIDocShell> shell(mDocumentContainer);
if (!shell) {
// We won't be able to create a parser anyway.
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
bool inUnload;
shell->GetIsInUnload(&inUnload);
if (inUnload) {
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
// Note: We want to use GetEntryDocument here because this document
// should inherit the security information of the document that's opening us,
// (since if it's secure, then it's presumably trusted).
nsCOMPtr<nsIDocument> callerDoc = GetEntryDocument();
if (!callerDoc) {
// If we're called from C++ or in some other way without an originating
// document we can't do a document.open w/o changing the principal of the
// document to something like about:blank (as that's the only sane thing to
// do when we don't know the origin of this call), and since we can't
// change the principals of a document for security reasons we'll have to
// refuse to go ahead with this call.
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
// Grab a reference to the calling documents security info (if any)
// and URIs as they may be lost in the call to Reset().
nsCOMPtr<nsISupports> securityInfo = callerDoc->GetSecurityInfo();
nsCOMPtr<nsIURI> uri = callerDoc->GetDocumentURI();
nsCOMPtr<nsIURI> baseURI = callerDoc->GetBaseURI();
nsCOMPtr<nsIPrincipal> callerPrincipal = callerDoc->NodePrincipal();
nsCOMPtr<nsIChannel> callerChannel = callerDoc->GetChannel();
// We're called from script. Make sure the script is from the same
// origin, not just that the caller can access the document. This is
// needed to keep document principals from ever changing, which is
// needed because of the way we use our XOW code, and is a sane
// thing to do anyways.
bool equals = false;
if (NS_FAILED(callerPrincipal->Equals(NodePrincipal(), &equals)) ||
!equals) {
#ifdef DEBUG
nsCOMPtr<nsIURI> callerDocURI = callerDoc->GetDocumentURI();
nsCOMPtr<nsIURI> thisURI = nsIDocument::GetDocumentURI();
printf("nsHTMLDocument::Open callerDoc %s this %s\n",
callerDocURI ? callerDocURI->GetSpecOrDefault().get() : "",
thisURI ? thisURI->GetSpecOrDefault().get() : "");
#endif
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
// Stop current loads targeted at the window this document is in.
if (mScriptGlobalObject) {
nsCOMPtr<nsIContentViewer> cv;
shell->GetContentViewer(getter_AddRefs(cv));
if (cv) {
bool okToUnload;
if (NS_SUCCEEDED(cv->PermitUnload(&okToUnload)) && !okToUnload) {
// We don't want to unload, so stop here, but don't throw an
// exception.
nsCOMPtr<nsIDocument> ret = this;
return ret.forget();
}
}
nsCOMPtr<nsIWebNavigation> webnav(do_QueryInterface(shell));
webnav->Stop(nsIWebNavigation::STOP_NETWORK);
// The Stop call may have cancelled the onload blocker request or prevented
// it from getting added, so we need to make sure it gets added to the
// document again otherwise the document could have a non-zero onload block
// count without the onload blocker request being in the loadgroup.
EnsureOnloadBlocker();
}
// The open occurred after the document finished loading.
// So we reset the document and then reinitialize it.
nsCOMPtr<nsIChannel> channel;
nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
rv = NS_NewChannel(getter_AddRefs(channel),
uri,
callerDoc,
nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL,
nsIContentPolicy::TYPE_OTHER,
group);
if (rv.Failed()) {
return nullptr;
}
if (callerChannel) {
nsLoadFlags callerLoadFlags;
rv = callerChannel->GetLoadFlags(&callerLoadFlags);
if (rv.Failed()) {
return nullptr;
}
nsLoadFlags loadFlags;
rv = channel->GetLoadFlags(&loadFlags);
if (rv.Failed()) {
return nullptr;
}
loadFlags |= callerLoadFlags & nsIRequest::INHIBIT_PERSISTENT_CACHING;
rv = channel->SetLoadFlags(loadFlags);
if (rv.Failed()) {
return nullptr;
}
// If the user has allowed mixed content on the rootDoc, then we should propogate it
// down to the new document channel.
bool rootHasSecureConnection = false;
bool allowMixedContent = false;
bool isDocShellRoot = false;
nsresult rvalue = shell->GetAllowMixedContentAndConnectionData(&rootHasSecureConnection, &allowMixedContent, &isDocShellRoot);
if (NS_SUCCEEDED(rvalue) && allowMixedContent && isDocShellRoot) {
shell->SetMixedContentChannel(channel);
}
}
// Before we reset the doc notify the globalwindow of the change,
// but only if we still have a window (i.e. our window object the
// current inner window in our outer window).
// Hold onto ourselves on the offchance that we're down to one ref
nsCOMPtr<nsIDocument> kungFuDeathGrip = this;
if (nsPIDOMWindowInner *window = GetInnerWindow()) {
// Remember the old scope in case the call to SetNewDocument changes it.
nsCOMPtr<nsIScriptGlobalObject> oldScope(do_QueryReferent(mScopeObject));
#ifdef DEBUG
bool willReparent = mWillReparent;
mWillReparent = true;
nsDocument* templateContentsOwner =
static_cast<nsDocument*>(mTemplateContentsOwner.get());
if (templateContentsOwner) {
templateContentsOwner->mWillReparent = true;
}
#endif
// Per spec, we pass false here so that a new Window is created.
rv = window->SetNewDocument(this, nullptr,
/* aForceReuseInnerWindow */ false);
if (rv.Failed()) {
return nullptr;
}
#ifdef DEBUG
if (templateContentsOwner) {
templateContentsOwner->mWillReparent = willReparent;
}
mWillReparent = willReparent;
#endif
// Now make sure we're not flagged as the initial document anymore, now
// that we've had stuff done to us. From now on, if anyone tries to
// document.open() us, they get a new inner window.
SetIsInitialDocument(false);
nsCOMPtr<nsIScriptGlobalObject> newScope(do_QueryReferent(mScopeObject));
JS::Rooted<JSObject*> wrapper(cx, GetWrapper());
if (oldScope && newScope != oldScope && wrapper) {
JSAutoCompartment ac(cx, wrapper);
rv = mozilla::dom::ReparentWrapper(cx, wrapper);
if (rv.Failed()) {
return nullptr;
}
// Also reparent the template contents owner document
// because its global is set to the same as this document.
if (mTemplateContentsOwner) {
JS::Rooted<JSObject*> contentsOwnerWrapper(cx,
mTemplateContentsOwner->GetWrapper());
if (contentsOwnerWrapper) {
rv = mozilla::dom::ReparentWrapper(cx, contentsOwnerWrapper);
if (rv.Failed()) {
return nullptr;
}
}
}
}
}
mDidDocumentOpen = true;
// Call Reset(), this will now do the full reset
Reset(channel, group);
if (baseURI) {
mDocumentBaseURI = baseURI;
}
// Store the security info of the caller now that we're done
// resetting the document.
mSecurityInfo = securityInfo;
mParserAborted = false;
mParser = nsHtml5Module::NewHtml5Parser();
nsHtml5Module::Initialize(mParser, this, uri, shell, channel);
if (mReferrerPolicySet) {
// CSP may have set the referrer policy, so a speculative parser should
// start with the new referrer policy.
nsHtml5TreeOpExecutor* executor = nullptr;
executor = static_cast<nsHtml5TreeOpExecutor*> (mParser->GetContentSink());
if (executor && mReferrerPolicySet) {
executor->SetSpeculationReferrerPolicy(static_cast<ReferrerPolicy>(mReferrerPolicy));
}
}
// This will be propagated to the parser when someone actually calls write()
SetContentTypeInternal(contentType);
// Prepare the docshell and the document viewer for the impending
// out of band document.write()
shell->PrepareForNewContentModel();
// Now check whether we were opened with a "replace" argument. If
// so, we need to tell the docshell to not create a new history
// entry for this load. Otherwise, make sure that we're doing a normal load,
// not whatever type of load was previously done on this docshell.
shell->SetLoadType(aReplace.LowerCaseEqualsLiteral("replace") ?
LOAD_NORMAL_REPLACE : LOAD_NORMAL);
nsCOMPtr<nsIContentViewer> cv;
shell->GetContentViewer(getter_AddRefs(cv));
if (cv) {
cv->LoadStart(this);
}
// Add a wyciwyg channel request into the document load group
NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::Open(): wyciwyg "
"channel already exists!");
// In case the editor is listening and will see the new channel
// being added, make sure mWriteLevel is non-zero so that the editor
// knows that document.open/write/close() is being called on this
// document.
++mWriteLevel;
CreateAndAddWyciwygChannel();
--mWriteLevel;
SetReadyStateInternal(nsIDocument::READYSTATE_LOADING);
// After changing everything around, make sure that the principal on the
// document's compartment exactly matches NodePrincipal().
DebugOnly<JSObject*> wrapper = GetWrapperPreserveColor();
MOZ_ASSERT_IF(wrapper,
JS_GetCompartmentPrincipals(js::GetObjectCompartment(wrapper)) ==
nsJSPrincipals::get(NodePrincipal()));
return kungFuDeathGrip.forget();
}
NS_IMETHODIMP
nsHTMLDocument::Clear()
{
// This method has been deprecated
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::Close()
{
ErrorResult rv;
Close(rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::Close(ErrorResult& rv)
{
if (!IsHTMLDocument()) {
// No calling document.close() on XHTML!
rv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (!mParser || !mParser->IsScriptCreated()) {
return;
}
++mWriteLevel;
rv = (static_cast<nsHtml5Parser*>(mParser.get()))->Parse(
EmptyString(), nullptr, GetContentTypeInternal(), true);
--mWriteLevel;
// Even if that Parse() call failed, do the rest of this method
// XXX Make sure that all the document.written content is
// reflowed. We should remove this call once we change
// nsHTMLDocument::OpenCommon() so that it completely destroys the
// earlier document's content and frame hierarchy. Right now, it
// re-uses the earlier document's root content object and
// corresponding frame objects. These re-used frame objects think
// that they have already been reflowed, so they drop initial
// reflows. For certain cases of document.written content, like a
// frameset document, the dropping of the initial reflow means
// that we end up in document.close() without appended any reflow
// commands to the reflow queue and, consequently, without adding
// the dummy layout request to the load group. Since the dummy
// layout request is not added to the load group, the onload
// handler of the frameset fires before the frames get reflowed
// and loaded. That is the long explanation for why we need this
// one line of code here!
// XXXbz as far as I can tell this may not be needed anymore; all
// the testcases in bug 57636 pass without this line... Leaving
// it be for now, though. In any case, there's no reason to do
// this if we have no presshell, since in that case none of the
// above about reusing frames applies.
//
// XXXhsivonen keeping this around for bug 577508 / 253951 still :-(
if (GetShell()) {
FlushPendingNotifications(Flush_Layout);
}
// Removing the wyciwygChannel here is wrong when document.close() is
// called from within the document itself. However, legacy requires the
// channel to be removed here. Otherwise, the load event never fires.
NS_ASSERTION(mWyciwygChannel, "nsHTMLDocument::Close(): Trying to remove "
"nonexistent wyciwyg channel!");
RemoveWyciwygChannel();
NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::Close(): "
"nsIWyciwygChannel could not be removed!");
}
void
nsHTMLDocument::WriteCommon(JSContext *cx,
const Sequence<nsString>& aText,
bool aNewlineTerminate,
mozilla::ErrorResult& rv)
{
// Fast path the common case
if (aText.Length() == 1) {
rv = WriteCommon(cx, aText[0], aNewlineTerminate);
} else {
// XXXbz it would be nice if we could pass all the strings to the parser
// without having to do all this copying and then ask it to start
// parsing....
nsString text;
for (uint32_t i = 0; i < aText.Length(); ++i) {
text.Append(aText[i]);
}
rv = WriteCommon(cx, text, aNewlineTerminate);
}
}
nsresult
nsHTMLDocument::WriteCommon(JSContext *cx,
const nsAString& aText,
bool aNewlineTerminate)
{
mTooDeepWriteRecursion =
(mWriteLevel > NS_MAX_DOCUMENT_WRITE_DEPTH || mTooDeepWriteRecursion);
NS_ENSURE_STATE(!mTooDeepWriteRecursion);
if (!IsHTMLDocument() || mDisableDocWrite || !IsMasterDocument()) {
// No calling document.write*() on XHTML!
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
if (mParserAborted) {
// Hixie says aborting the parser doesn't undefine the insertion point.
// However, since we null out mParser in that case, we track the
// theoretically defined insertion point using mParserAborted.
return NS_OK;
}
nsresult rv = NS_OK;
void *key = GenerateParserKey();
if (mParser && !mParser->IsInsertionPointDefined()) {
if (mExternalScriptsBeingEvaluated) {
// Instead of implying a call to document.open(), ignore the call.
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM Events"), this,
nsContentUtils::eDOM_PROPERTIES,
"DocumentWriteIgnored",
nullptr, 0,
mDocumentURI);
return NS_OK;
}
mParser->Terminate();
NS_ASSERTION(!mParser, "mParser should have been null'd out");
}
if (!mParser) {
if (mExternalScriptsBeingEvaluated) {
// Instead of implying a call to document.open(), ignore the call.
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM Events"), this,
nsContentUtils::eDOM_PROPERTIES,
"DocumentWriteIgnored",
nullptr, 0,
mDocumentURI);
return NS_OK;
}
nsCOMPtr<nsISupports> ignored;
rv = Open(NS_LITERAL_STRING("text/html"), EmptyString(), EmptyString(), cx,
1, getter_AddRefs(ignored));
// If Open() fails, or if it didn't create a parser (as it won't
// if the user chose to not discard the current document through
// onbeforeunload), don't write anything.
if (NS_FAILED(rv) || !mParser) {
return rv;
}
MOZ_ASSERT(!JS_IsExceptionPending(cx),
"Open() succeeded but JS exception is pending");
}
static NS_NAMED_LITERAL_STRING(new_line, "\n");
// Save the data in cache if the write isn't from within the doc
if (mWyciwygChannel && !key) {
if (!aText.IsEmpty()) {
mWyciwygChannel->WriteToCacheEntry(aText);
}
if (aNewlineTerminate) {
mWyciwygChannel->WriteToCacheEntry(new_line);
}
}
++mWriteLevel;
// This could be done with less code, but for performance reasons it
// makes sense to have the code for two separate Parse() calls here
// since the concatenation of strings costs more than we like. And
// why pay that price when we don't need to?
if (aNewlineTerminate) {
rv = (static_cast<nsHtml5Parser*>(mParser.get()))->Parse(
aText + new_line, key, GetContentTypeInternal(), false);
} else {
rv = (static_cast<nsHtml5Parser*>(mParser.get()))->Parse(
aText, key, GetContentTypeInternal(), false);
}
--mWriteLevel;
mTooDeepWriteRecursion = (mWriteLevel != 0 && mTooDeepWriteRecursion);
return rv;
}
NS_IMETHODIMP
nsHTMLDocument::Write(const nsAString& aText, JSContext *cx)
{
return WriteCommon(cx, aText, false);
}
void
nsHTMLDocument::Write(JSContext* cx, const Sequence<nsString>& aText,
ErrorResult& rv)
{
WriteCommon(cx, aText, false, rv);
}
NS_IMETHODIMP
nsHTMLDocument::Writeln(const nsAString& aText, JSContext *cx)
{
return WriteCommon(cx, aText, true);
}
void
nsHTMLDocument::Writeln(JSContext* cx, const Sequence<nsString>& aText,
ErrorResult& rv)
{
WriteCommon(cx, aText, true, rv);
}
bool
nsHTMLDocument::MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
nsIAtom* aAtom, void* aData)
{
NS_PRECONDITION(aElement, "Must have element to work with!");
nsString* elementName = static_cast<nsString*>(aData);
return
aElement->GetNameSpaceID() == kNameSpaceID_XHTML &&
aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name,
*elementName, eCaseMatters);
}
/* static */
void*
nsHTMLDocument::UseExistingNameString(nsINode* aRootNode, const nsString* aName)
{
return const_cast<nsString*>(aName);
}
NS_IMETHODIMP
nsHTMLDocument::GetElementsByName(const nsAString& aElementName,
nsIDOMNodeList** aReturn)
{
*aReturn = GetElementsByName(aElementName).take();
return NS_OK;
}
void
nsHTMLDocument::AddedForm()
{
++mNumForms;
}
void
nsHTMLDocument::RemovedForm()
{
--mNumForms;
}
int32_t
nsHTMLDocument::GetNumFormsSynchronous()
{
return mNumForms;
}
NS_IMETHODIMP
nsHTMLDocument::GetAlinkColor(nsAString& aAlinkColor)
{
aAlinkColor.Truncate();
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->GetALink(aAlinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetAlinkColor(const nsAString& aAlinkColor)
{
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->SetALink(aAlinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetLinkColor(nsAString& aLinkColor)
{
aLinkColor.Truncate();
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->GetLink(aLinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetLinkColor(const nsAString& aLinkColor)
{
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->SetLink(aLinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetVlinkColor(nsAString& aVlinkColor)
{
aVlinkColor.Truncate();
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->GetVLink(aVlinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetVlinkColor(const nsAString& aVlinkColor)
{
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->SetVLink(aVlinkColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetBgColor(nsAString& aBgColor)
{
aBgColor.Truncate();
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->GetBgColor(aBgColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetBgColor(const nsAString& aBgColor)
{
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->SetBgColor(aBgColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetFgColor(nsAString& aFgColor)
{
aFgColor.Truncate();
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->GetText(aFgColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetFgColor(const nsAString& aFgColor)
{
HTMLBodyElement* body = GetBodyElement();
if (body) {
body->SetText(aFgColor);
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::GetEmbeds(nsIDOMHTMLCollection** aEmbeds)
{
NS_ADDREF(*aEmbeds = Embeds());
return NS_OK;
}
nsIHTMLCollection*
nsHTMLDocument::Embeds()
{
if (!mEmbeds) {
mEmbeds = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::embed, nsGkAtoms::embed);
}
return mEmbeds;
}
NS_IMETHODIMP
nsHTMLDocument::GetSelection(nsISelection** aReturn)
{
ErrorResult rv;
NS_IF_ADDREF(*aReturn = GetSelection(rv));
return rv.StealNSResult();
}
Selection*
nsHTMLDocument::GetSelection(ErrorResult& aRv)
{
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(GetScopeObject());
if (!window) {
return nullptr;
}
NS_ASSERTION(window->IsInnerWindow(), "Should have inner window here!");
if (!window->IsCurrentInnerWindow()) {
return nullptr;
}
return nsGlobalWindow::Cast(window)->GetSelection(aRv);
}
NS_IMETHODIMP
nsHTMLDocument::CaptureEvents()
{
WarnOnceAbout(nsIDocument::eUseOfCaptureEvents);
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::ReleaseEvents()
{
WarnOnceAbout(nsIDocument::eUseOfReleaseEvents);
return NS_OK;
}
// Mapped to document.embeds for NS4 compatibility
NS_IMETHODIMP
nsHTMLDocument::GetPlugins(nsIDOMHTMLCollection** aPlugins)
{
*aPlugins = nullptr;
return GetEmbeds(aPlugins);
}
nsIHTMLCollection*
nsHTMLDocument::Plugins()
{
return Embeds();
}
nsISupports*
nsHTMLDocument::ResolveName(const nsAString& aName, nsWrapperCache **aCache)
{
nsIdentifierMapEntry *entry = mIdentifierMap.GetEntry(aName);
if (!entry) {
*aCache = nullptr;
return nullptr;
}
nsBaseContentList *list = entry->GetNameContentList();
uint32_t length = list ? list->Length() : 0;
if (length > 0) {
if (length == 1) {
// Only one element in the list, return the element instead of returning
// the list.
nsIContent *node = list->Item(0);
*aCache = node;
return node;
}
// The list contains more than one element, return the whole list.
*aCache = list;
return list;
}
// No named items were found, see if there's one registerd by id for aName.
Element *e = entry->GetIdElement();
if (e && nsGenericHTMLElement::ShouldExposeIdAsHTMLDocumentProperty(e)) {
*aCache = e;
return e;
}
*aCache = nullptr;
return nullptr;
}
void
nsHTMLDocument::NamedGetter(JSContext* cx, const nsAString& aName, bool& aFound,
JS::MutableHandle<JSObject*> aRetval,
ErrorResult& rv)
{
nsWrapperCache* cache;
nsISupports* supp = ResolveName(aName, &cache);
if (!supp) {
aFound = false;
aRetval.set(nullptr);
return;
}
JS::Rooted<JS::Value> val(cx);
if (!dom::WrapObject(cx, supp, cache, nullptr, &val)) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
aFound = true;
aRetval.set(&val.toObject());
}
void
nsHTMLDocument::GetSupportedNames(nsTArray<nsString>& aNames)
{
for (auto iter = mIdentifierMap.Iter(); !iter.Done(); iter.Next()) {
nsIdentifierMapEntry* entry = iter.Get();
if (entry->HasNameElement() ||
entry->HasIdElementExposedAsHTMLDocumentProperty()) {
aNames.AppendElement(entry->GetKey());
}
}
}
//----------------------------
// forms related stuff
NS_IMETHODIMP
nsHTMLDocument::GetForms(nsIDOMHTMLCollection** aForms)
{
NS_ADDREF(*aForms = nsHTMLDocument::GetForms());
return NS_OK;
}
nsContentList*
nsHTMLDocument::GetForms()
{
if (!mForms) {
mForms = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::form, nsGkAtoms::form);
}
return mForms;
}
static bool MatchFormControls(Element* aElement, int32_t aNamespaceID,
nsIAtom* aAtom, void* aData)
{
return aElement->IsNodeOfType(nsIContent::eHTML_FORM_CONTROL);
}
nsContentList*
nsHTMLDocument::GetFormControls()
{
if (!mFormControls) {
mFormControls = new nsContentList(this, MatchFormControls, nullptr, nullptr);
}
return mFormControls;
}
nsresult
nsHTMLDocument::CreateAndAddWyciwygChannel(void)
{
nsresult rv = NS_OK;
nsAutoCString url, originalSpec;
mDocumentURI->GetSpec(originalSpec);
// Generate the wyciwyg url
url = NS_LITERAL_CSTRING("wyciwyg://")
+ nsPrintfCString("%d", gWyciwygSessionCnt++)
+ NS_LITERAL_CSTRING("/")
+ originalSpec;
nsCOMPtr<nsIURI> wcwgURI;
NS_NewURI(getter_AddRefs(wcwgURI), url);
// Create the nsIWyciwygChannel to store out-of-band
// document.write() script to cache
nsCOMPtr<nsIChannel> channel;
// Create a wyciwyg Channel
rv = NS_NewChannel(getter_AddRefs(channel),
wcwgURI,
NodePrincipal(),
nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL,
nsIContentPolicy::TYPE_OTHER);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsILoadInfo> loadInfo = channel->GetLoadInfo();
loadInfo->SetPrincipalToInherit(NodePrincipal());
mWyciwygChannel = do_QueryInterface(channel);
mWyciwygChannel->SetSecurityInfo(mSecurityInfo);
// Note: we want to treat this like a "previous document" hint so that,
// e.g. a <meta> tag in the document.write content can override it.
SetDocumentCharacterSetSource(kCharsetFromHintPrevDoc);
mWyciwygChannel->SetCharsetAndSource(kCharsetFromHintPrevDoc,
GetDocumentCharacterSet());
// Inherit load flags from the original document's channel
channel->SetLoadFlags(mLoadFlags);
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
// Use the Parent document's loadgroup to trigger load notifications
if (loadGroup && channel) {
rv = channel->SetLoadGroup(loadGroup);
NS_ENSURE_SUCCESS(rv, rv);
nsLoadFlags loadFlags = 0;
channel->GetLoadFlags(&loadFlags);
loadFlags |= nsIChannel::LOAD_DOCUMENT_URI;
channel->SetLoadFlags(loadFlags);
channel->SetOriginalURI(wcwgURI);
rv = loadGroup->AddRequest(mWyciwygChannel, nullptr);
NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to add request to load group.");
}
return rv;
}
nsresult
nsHTMLDocument::RemoveWyciwygChannel(void)
{
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
// note there can be a write request without a load group if
// this is a synchronously constructed about:blank document
if (loadGroup && mWyciwygChannel) {
mWyciwygChannel->CloseCacheEntry(NS_OK);
loadGroup->RemoveRequest(mWyciwygChannel, nullptr, NS_OK);
}
mWyciwygChannel = nullptr;
return NS_OK;
}
void *
nsHTMLDocument::GenerateParserKey(void)
{
if (!mScriptLoader) {
// If we don't have a script loader, then the parser probably isn't parsing
// anything anyway, so just return null.
return nullptr;
}
// The script loader provides us with the currently executing script element,
// which is guaranteed to be unique per script.
nsIScriptElement* script = mScriptLoader->GetCurrentParserInsertedScript();
if (script && mParser && mParser->IsScriptCreated()) {
nsCOMPtr<nsIParser> creatorParser = script->GetCreatorParser();
if (creatorParser != mParser) {
// Make scripts that aren't inserted by the active parser of this document
// participate in the context of the script that document.open()ed
// this document.
return nullptr;
}
}
return script;
}
NS_IMETHODIMP
nsHTMLDocument::GetDesignMode(nsAString& aDesignMode)
{
if (HasFlag(NODE_IS_EDITABLE)) {
aDesignMode.AssignLiteral("on");
}
else {
aDesignMode.AssignLiteral("off");
}
return NS_OK;
}
void
nsHTMLDocument::MaybeEditingStateChanged()
{
if (!mPendingMaybeEditingStateChanged &&
mUpdateNestLevel == 0 && (mContentEditableCount > 0) != IsEditingOn()) {
if (nsContentUtils::IsSafeToRunScript()) {
EditingStateChanged();
} else if (!mInDestructor) {
nsContentUtils::AddScriptRunner(
NewRunnableMethod(this, &nsHTMLDocument::MaybeEditingStateChanged));
}
}
}
void
nsHTMLDocument::EndUpdate(nsUpdateType aUpdateType)
{
const bool reset = !mPendingMaybeEditingStateChanged;
mPendingMaybeEditingStateChanged = true;
nsDocument::EndUpdate(aUpdateType);
if (reset) {
mPendingMaybeEditingStateChanged = false;
}
MaybeEditingStateChanged();
}
// Helper class, used below in ChangeContentEditableCount().
class DeferredContentEditableCountChangeEvent : public Runnable
{
public:
DeferredContentEditableCountChangeEvent(nsHTMLDocument *aDoc,
nsIContent *aElement)
: mDoc(aDoc)
, mElement(aElement)
{
}
NS_IMETHOD Run() override {
if (mElement && mElement->OwnerDoc() == mDoc) {
mDoc->DeferredContentEditableCountChange(mElement);
}
return NS_OK;
}
private:
RefPtr<nsHTMLDocument> mDoc;
nsCOMPtr<nsIContent> mElement;
};
nsresult
nsHTMLDocument::ChangeContentEditableCount(nsIContent *aElement,
int32_t aChange)
{
NS_ASSERTION(int32_t(mContentEditableCount) + aChange >= 0,
"Trying to decrement too much.");
mContentEditableCount += aChange;
nsContentUtils::AddScriptRunner(
new DeferredContentEditableCountChangeEvent(this, aElement));
return NS_OK;
}
void
nsHTMLDocument::DeferredContentEditableCountChange(nsIContent *aElement)
{
if (mParser ||
(mUpdateNestLevel > 0 && (mContentEditableCount > 0) != IsEditingOn())) {
return;
}
EditingState oldState = mEditingState;
nsresult rv = EditingStateChanged();
NS_ENSURE_SUCCESS_VOID(rv);
if (oldState == mEditingState && mEditingState == eContentEditable) {
// We just changed the contentEditable state of a node, we need to reset
// the spellchecking state of that node.
nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aElement);
if (node) {
nsPIDOMWindowOuter *window = GetWindow();
if (!window)
return;
nsIDocShell *docshell = window->GetDocShell();
if (!docshell)
return;
nsCOMPtr<nsIEditor> editor;
docshell->GetEditor(getter_AddRefs(editor));
if (editor) {
RefPtr<nsRange> range = new nsRange(aElement);
rv = range->SelectNode(node);
if (NS_FAILED(rv)) {
// The node might be detached from the document at this point,
// which would cause this call to fail. In this case, we can
// safely ignore the contenteditable count change.
return;
}
nsCOMPtr<nsIInlineSpellChecker> spellChecker;
rv = editor->GetInlineSpellChecker(false,
getter_AddRefs(spellChecker));
NS_ENSURE_SUCCESS_VOID(rv);
if (spellChecker) {
rv = spellChecker->SpellCheckRange(range);
}
}
}
}
}
HTMLAllCollection*
nsHTMLDocument::All()
{
if (!mAll) {
mAll = new HTMLAllCollection(this);
}
return mAll;
}
static void
NotifyEditableStateChange(nsINode *aNode, nsIDocument *aDocument)
{
for (nsIContent* child = aNode->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->IsElement()) {
child->AsElement()->UpdateState(true);
}
NotifyEditableStateChange(child, aDocument);
}
}
void
nsHTMLDocument::TearingDownEditor(nsIEditor *aEditor)
{
if (IsEditingOn()) {
EditingState oldState = mEditingState;
mEditingState = eTearingDown;
nsCOMPtr<nsIPresShell> presShell = GetShell();
if (!presShell)
return;
nsTArray<RefPtr<StyleSheet>> agentSheets;
presShell->GetAgentStyleSheets(agentSheets);
auto cache = nsLayoutStylesheetCache::For(GetStyleBackendType());
agentSheets.RemoveElement(cache->ContentEditableSheet());
if (oldState == eDesignMode)
agentSheets.RemoveElement(cache->DesignModeSheet());
presShell->SetAgentStyleSheets(agentSheets);
presShell->RestyleForCSSRuleChanges();
}
}
nsresult
nsHTMLDocument::TurnEditingOff()
{
NS_ASSERTION(mEditingState != eOff, "Editing is already off.");
nsPIDOMWindowOuter *window = GetWindow();
if (!window)
return NS_ERROR_FAILURE;
nsIDocShell *docshell = window->GetDocShell();
if (!docshell)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIEditingSession> editSession;
nsresult rv = docshell->GetEditingSession(getter_AddRefs(editSession));
NS_ENSURE_SUCCESS(rv, rv);
// turn editing off
rv = editSession->TearDownEditorOnWindow(window);
NS_ENSURE_SUCCESS(rv, rv);
mEditingState = eOff;
return NS_OK;
}
static bool HasPresShell(nsPIDOMWindowOuter *aWindow)
{
nsIDocShell *docShell = aWindow->GetDocShell();
if (!docShell)
return false;
return docShell->GetPresShell() != nullptr;
}
nsresult
nsHTMLDocument::SetEditingState(EditingState aState)
{
mEditingState = aState;
return NS_OK;
}
nsresult
nsHTMLDocument::EditingStateChanged()
{
if (mRemovedFromDocShell) {
return NS_OK;
}
if (mEditingState == eSettingUp || mEditingState == eTearingDown) {
// XXX We shouldn't recurse
return NS_OK;
}
bool designMode = HasFlag(NODE_IS_EDITABLE);
EditingState newState = designMode ? eDesignMode :
(mContentEditableCount > 0 ? eContentEditable : eOff);
if (mEditingState == newState) {
// No changes in editing mode.
return NS_OK;
}
if (newState == eOff) {
// Editing is being turned off.
nsAutoScriptBlocker scriptBlocker;
NotifyEditableStateChange(this, this);
return TurnEditingOff();
}
// Flush out style changes on our _parent_ document, if any, so that
// our check for a presshell won't get stale information.
if (mParentDocument) {
mParentDocument->FlushPendingNotifications(Flush_Style);
}
// get editing session, make sure this is a strong reference so the
// window can't get deleted during the rest of this call.
nsCOMPtr<nsPIDOMWindowOuter> window = GetWindow();
if (!window)
return NS_ERROR_FAILURE;
nsIDocShell *docshell = window->GetDocShell();
if (!docshell)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIEditingSession> editSession;
nsresult rv = docshell->GetEditingSession(getter_AddRefs(editSession));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIEditor> existingEditor;
editSession->GetEditorForWindow(window, getter_AddRefs(existingEditor));
if (existingEditor) {
// We might already have an editor if it was set up for mail, let's see
// if this is actually the case.
#ifdef DEBUG
nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(existingEditor);
MOZ_ASSERT(htmlEditor, "If we have an editor, it must be an HTML editor");
#endif
uint32_t flags = 0;
existingEditor->GetFlags(&flags);
if (flags & nsIPlaintextEditor::eEditorMailMask) {
// We already have a mail editor, then we should not attempt to create
// another one.
return NS_OK;
}
}
if (!HasPresShell(window)) {
// We should not make the window editable or setup its editor.
// It's probably style=display:none.
return NS_OK;
}
bool makeWindowEditable = mEditingState == eOff;
bool updateState = false;
bool spellRecheckAll = false;
bool putOffToRemoveScriptBlockerUntilModifyingEditingState = false;
nsCOMPtr<nsIEditor> editor;
{
EditingState oldState = mEditingState;
nsAutoEditingState push(this, eSettingUp);
nsCOMPtr<nsIPresShell> presShell = GetShell();
NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
// Before making this window editable, we need to modify UA style sheet
// because new style may change whether focused element will be focusable
// or not.
nsTArray<RefPtr<StyleSheet>> agentSheets;
rv = presShell->GetAgentStyleSheets(agentSheets);
NS_ENSURE_SUCCESS(rv, rv);
auto cache = nsLayoutStylesheetCache::For(GetStyleBackendType());
StyleSheet* contentEditableSheet = cache->ContentEditableSheet();
if (!agentSheets.Contains(contentEditableSheet)) {
agentSheets.AppendElement(contentEditableSheet);
}
// Should we update the editable state of all the nodes in the document? We
// need to do this when the designMode value changes, as that overrides
// specific states on the elements.
if (designMode) {
// designMode is being turned on (overrides contentEditable).
StyleSheet* designModeSheet = cache->DesignModeSheet();
if (!agentSheets.Contains(designModeSheet)) {
agentSheets.AppendElement(designModeSheet);
}
updateState = true;
spellRecheckAll = oldState == eContentEditable;
}
else if (oldState == eDesignMode) {
// designMode is being turned off (contentEditable is still on).
agentSheets.RemoveElement(cache->DesignModeSheet());
updateState = true;
}
rv = presShell->SetAgentStyleSheets(agentSheets);
NS_ENSURE_SUCCESS(rv, rv);
presShell->RestyleForCSSRuleChanges();
// Adjust focused element with new style but blur event shouldn't be fired
// until mEditingState is modified with newState.
nsAutoScriptBlocker scriptBlocker;
if (designMode) {
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
nsIContent* focusedContent =
nsFocusManager::GetFocusedDescendant(window, false,
getter_AddRefs(focusedWindow));
if (focusedContent) {
nsIFrame* focusedFrame = focusedContent->GetPrimaryFrame();
bool clearFocus = focusedFrame ? !focusedFrame->IsFocusable() :
!focusedContent->IsFocusable();
if (clearFocus) {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (fm) {
fm->ClearFocus(window);
// If we need to dispatch blur event, we should put off after
// modifying mEditingState since blur event handler may change
// designMode state again.
putOffToRemoveScriptBlockerUntilModifyingEditingState = true;
}
}
}
}
if (makeWindowEditable) {
// Editing is being turned on (through designMode or contentEditable)
// Turn on editor.
// XXX This can cause flushing which can change the editing state, so make
// sure to avoid recursing.
rv = editSession->MakeWindowEditable(window, "html", false, false,
true);
NS_ENSURE_SUCCESS(rv, rv);
}
// XXX Need to call TearDownEditorOnWindow for all failures.
docshell->GetEditor(getter_AddRefs(editor));
if (!editor)
return NS_ERROR_FAILURE;
// If we're entering the design mode, put the selection at the beginning of
// the document for compatibility reasons.
if (designMode && oldState == eOff) {
editor->BeginningOfDocument();
}
if (putOffToRemoveScriptBlockerUntilModifyingEditingState) {
nsContentUtils::AddScriptBlocker();
}
}
mEditingState = newState;
if (putOffToRemoveScriptBlockerUntilModifyingEditingState) {
nsContentUtils::RemoveScriptBlocker();
// If mEditingState is overwritten by another call and already disabled
// the editing, we shouldn't keep making window editable.
if (mEditingState == eOff) {
return NS_OK;
}
}
if (makeWindowEditable) {
// Set the editor to not insert br's on return when in p
// elements by default.
// XXX Do we only want to do this for designMode?
bool unused;
rv = ExecCommand(NS_LITERAL_STRING("insertBrOnReturn"), false,
NS_LITERAL_STRING("false"), &unused);
if (NS_FAILED(rv)) {
// Editor setup failed. Editing is not on after all.
// XXX Should we reset the editable flag on nodes?
editSession->TearDownEditorOnWindow(window);
mEditingState = eOff;
return rv;
}
}
if (updateState) {
nsAutoScriptBlocker scriptBlocker;
NotifyEditableStateChange(this, this);
}
// Resync the editor's spellcheck state.
if (spellRecheckAll) {
nsCOMPtr<nsISelectionController> selcon;
nsresult rv = editor->GetSelectionController(getter_AddRefs(selcon));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISelection> spellCheckSelection;
rv = selcon->GetSelection(nsISelectionController::SELECTION_SPELLCHECK,
getter_AddRefs(spellCheckSelection));
if (NS_SUCCEEDED(rv)) {
spellCheckSelection->RemoveAllRanges();
}
}
editor->SyncRealTimeSpell();
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDocument::SetDesignMode(const nsAString& aDesignMode)
{
ErrorResult rv;
SetDesignMode(aDesignMode, nsContentUtils::GetCurrentJSContext()
? Some(nsContentUtils::SubjectPrincipal())
: Nothing(), rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::SetDesignMode(const nsAString& aDesignMode,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& rv)
{
SetDesignMode(aDesignMode, Some(&aSubjectPrincipal), rv);
}
void
nsHTMLDocument::SetDesignMode(const nsAString& aDesignMode,
const Maybe<nsIPrincipal*>& aSubjectPrincipal,
ErrorResult& rv)
{
if (aSubjectPrincipal.isSome() &&
!aSubjectPrincipal.value()->Subsumes(NodePrincipal())) {
rv.Throw(NS_ERROR_DOM_PROP_ACCESS_DENIED);
return;
}
bool editableMode = HasFlag(NODE_IS_EDITABLE);
if (aDesignMode.LowerCaseEqualsASCII(editableMode ? "off" : "on")) {
SetEditableFlag(!editableMode);
rv = EditingStateChanged();
}
}
nsresult
nsHTMLDocument::GetMidasCommandManager(nsICommandManager** aCmdMgr)
{
// initialize return value
NS_ENSURE_ARG_POINTER(aCmdMgr);
// check if we have it cached
if (mMidasCommandManager) {
NS_ADDREF(*aCmdMgr = mMidasCommandManager);
return NS_OK;
}
*aCmdMgr = nullptr;
nsPIDOMWindowOuter *window = GetWindow();
if (!window)
return NS_ERROR_FAILURE;
nsIDocShell *docshell = window->GetDocShell();
if (!docshell)
return NS_ERROR_FAILURE;
mMidasCommandManager = docshell->GetCommandManager();
if (!mMidasCommandManager)
return NS_ERROR_FAILURE;
NS_ADDREF(*aCmdMgr = mMidasCommandManager);
return NS_OK;
}
struct MidasCommand {
const char* incomingCommandString;
const char* internalCommandString;
const char* internalParamString;
bool useNewParam;
bool convertToBoolean;
};
static const struct MidasCommand gMidasCommandTable[] = {
{ "bold", "cmd_bold", "", true, false },
{ "italic", "cmd_italic", "", true, false },
{ "underline", "cmd_underline", "", true, false },
{ "strikethrough", "cmd_strikethrough", "", true, false },
{ "subscript", "cmd_subscript", "", true, false },
{ "superscript", "cmd_superscript", "", true, false },
{ "cut", "cmd_cut", "", true, false },
{ "copy", "cmd_copy", "", true, false },
{ "paste", "cmd_paste", "", true, false },
{ "delete", "cmd_deleteCharBackward", "", true, false },
{ "forwarddelete", "cmd_deleteCharForward", "", true, false },
{ "selectall", "cmd_selectAll", "", true, false },
{ "undo", "cmd_undo", "", true, false },
{ "redo", "cmd_redo", "", true, false },
{ "indent", "cmd_indent", "", true, false },
{ "outdent", "cmd_outdent", "", true, false },
{ "backcolor", "cmd_highlight", "", false, false },
{ "forecolor", "cmd_fontColor", "", false, false },
{ "hilitecolor", "cmd_highlight", "", false, false },
{ "fontname", "cmd_fontFace", "", false, false },
{ "fontsize", "cmd_fontSize", "", false, false },
{ "increasefontsize", "cmd_increaseFont", "", false, false },
{ "decreasefontsize", "cmd_decreaseFont", "", false, false },
{ "inserthorizontalrule", "cmd_insertHR", "", true, false },
{ "createlink", "cmd_insertLinkNoUI", "", false, false },
{ "insertimage", "cmd_insertImageNoUI", "", false, false },
{ "inserthtml", "cmd_insertHTML", "", false, false },
{ "inserttext", "cmd_insertText", "", false, false },
{ "gethtml", "cmd_getContents", "", false, false },
{ "justifyleft", "cmd_align", "left", true, false },
{ "justifyright", "cmd_align", "right", true, false },
{ "justifycenter", "cmd_align", "center", true, false },
{ "justifyfull", "cmd_align", "justify", true, false },
{ "removeformat", "cmd_removeStyles", "", true, false },
{ "unlink", "cmd_removeLinks", "", true, false },
{ "insertorderedlist", "cmd_ol", "", true, false },
{ "insertunorderedlist", "cmd_ul", "", true, false },
{ "insertparagraph", "cmd_insertParagraph", "", true, false },
{ "insertlinebreak", "cmd_insertLineBreak", "", true, false },
{ "formatblock", "cmd_paragraphState", "", false, false },
{ "heading", "cmd_paragraphState", "", false, false },
{ "styleWithCSS", "cmd_setDocumentUseCSS", "", false, true },
{ "contentReadOnly", "cmd_setDocumentReadOnly", "", false, true },
{ "insertBrOnReturn", "cmd_insertBrOnReturn", "", false, true },
{ "enableObjectResizing", "cmd_enableObjectResizing", "", false, true },
{ "enableInlineTableEditing", "cmd_enableInlineTableEditing", "", false, true },
#if 0
// no editor support to remove alignments right now
{ "justifynone", "cmd_align", "", true, false },
// the following will need special review before being turned on
{ "saveas", "cmd_saveAs", "", true, false },
{ "print", "cmd_print", "", true, false },
#endif
{ nullptr, nullptr, nullptr, false, false }
};
#define MidasCommandCount ((sizeof(gMidasCommandTable) / sizeof(struct MidasCommand)) - 1)
static const char* const gBlocks[] = {
"ADDRESS",
"BLOCKQUOTE",
"DD",
"DIV",
"DL",
"DT",
"H1",
"H2",
"H3",
"H4",
"H5",
"H6",
"P",
"PRE"
};
static bool
ConvertToMidasInternalCommandInner(const nsAString& inCommandID,
const nsAString& inParam,
nsACString& outCommandID,
nsACString& outParam,
bool& outIsBoolean,
bool& outBooleanValue,
bool aIgnoreParams)
{
NS_ConvertUTF16toUTF8 convertedCommandID(inCommandID);
// Hack to support old boolean commands that were backwards (see bug 301490).
bool invertBool = false;
if (convertedCommandID.LowerCaseEqualsLiteral("usecss")) {
convertedCommandID.AssignLiteral("styleWithCSS");
invertBool = true;
} else if (convertedCommandID.LowerCaseEqualsLiteral("readonly")) {
convertedCommandID.AssignLiteral("contentReadOnly");
invertBool = true;
}
uint32_t i;
bool found = false;
for (i = 0; i < MidasCommandCount; ++i) {
if (convertedCommandID.Equals(gMidasCommandTable[i].incomingCommandString,
nsCaseInsensitiveCStringComparator())) {
found = true;
break;
}
}
if (!found) {
// reset results if the command is not found in our table
outCommandID.SetLength(0);
outParam.SetLength(0);
outIsBoolean = false;
return false;
}
// set outCommandID (what we use internally)
outCommandID.Assign(gMidasCommandTable[i].internalCommandString);
// set outParam & outIsBoolean based on flags from the table
outIsBoolean = gMidasCommandTable[i].convertToBoolean;
if (aIgnoreParams) {
// No further work to do
return true;
}
if (gMidasCommandTable[i].useNewParam) {
// Just have to copy it, no checking
outParam.Assign(gMidasCommandTable[i].internalParamString);
return true;
}
// handle checking of param passed in
if (outIsBoolean) {
// If this is a boolean value and it's not explicitly false (e.g. no value)
// we default to "true". For old backwards commands we invert the check (see
// bug 301490).
if (invertBool) {
outBooleanValue = inParam.LowerCaseEqualsLiteral("false");
} else {
outBooleanValue = !inParam.LowerCaseEqualsLiteral("false");
}
outParam.Truncate();
return true;
}
// String parameter -- see if we need to convert it (necessary for
// cmd_paragraphState and cmd_fontSize)
if (outCommandID.EqualsLiteral("cmd_paragraphState")) {
const char16_t* start = inParam.BeginReading();
const char16_t* end = inParam.EndReading();
if (start != end && *start == '<' && *(end - 1) == '>') {
++start;
--end;
}
NS_ConvertUTF16toUTF8 convertedParam(Substring(start, end));
uint32_t j;
for (j = 0; j < ArrayLength(gBlocks); ++j) {
if (convertedParam.Equals(gBlocks[j],
nsCaseInsensitiveCStringComparator())) {
outParam.Assign(gBlocks[j]);
break;
}
}
if (j == ArrayLength(gBlocks)) {
outParam.Truncate();
}
} else if (outCommandID.EqualsLiteral("cmd_fontSize")) {
// Per editing spec as of April 23, 2012, we need to reject the value if
// it's not a valid floating-point number surrounded by optional whitespace.
// Otherwise, we parse it as a legacy font size. For now, we just parse as
// a legacy font size regardless (matching WebKit) -- bug 747879.
outParam.Truncate();
int32_t size = nsContentUtils::ParseLegacyFontSize(inParam);
if (size) {
outParam.AppendInt(size);
}
} else {
CopyUTF16toUTF8(inParam, outParam);
}
return true;
}
static bool
ConvertToMidasInternalCommand(const nsAString & inCommandID,
const nsAString & inParam,
nsACString& outCommandID,
nsACString& outParam,
bool& outIsBoolean,
bool& outBooleanValue)
{
return ConvertToMidasInternalCommandInner(inCommandID, inParam, outCommandID,
outParam, outIsBoolean,
outBooleanValue, false);
}
static bool
ConvertToMidasInternalCommand(const nsAString & inCommandID,
nsACString& outCommandID)
{
nsAutoCString dummyCString;
nsAutoString dummyString;
bool dummyBool;
return ConvertToMidasInternalCommandInner(inCommandID, dummyString,
outCommandID, dummyCString,
dummyBool, dummyBool, true);
}
/* TODO: don't let this call do anything if the page is not done loading */
NS_IMETHODIMP
nsHTMLDocument::ExecCommand(const nsAString& commandID,
bool doShowUI,
const nsAString& value,
bool* _retval)
{
ErrorResult rv;
*_retval = ExecCommand(commandID, doShowUI, value, rv);
return rv.StealNSResult();
}
bool
nsHTMLDocument::ExecCommand(const nsAString& commandID,
bool doShowUI,
const nsAString& value,
ErrorResult& rv)
{
// for optional parameters see dom/src/base/nsHistory.cpp: HistoryImpl::Go()
// this might add some ugly JS dependencies?
nsAutoCString cmdToDispatch, paramStr;
bool isBool, boolVal;
if (!ConvertToMidasInternalCommand(commandID, value,
cmdToDispatch, paramStr,
isBool, boolVal)) {
return false;
}
bool isCutCopy = (commandID.LowerCaseEqualsLiteral("cut") ||
commandID.LowerCaseEqualsLiteral("copy"));
// if editing is not on, bail
if (!isCutCopy && !IsEditingOnAfterFlush()) {
return false;
}
// if they are requesting UI from us, let's fail since we have no UI
if (doShowUI) {
return false;
}
// special case for cut & copy
// cut & copy are allowed in non editable documents
if (isCutCopy) {
if (!nsContentUtils::IsCutCopyAllowed()) {
// We have rejected the event due to it not being performed in an
// input-driven context therefore, we report the error to the console.
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM"), this,
nsContentUtils::eDOM_PROPERTIES,
"ExecCommandCutCopyDeniedNotInputDriven");
return false;
}
// For cut & copy commands, we need the behaviour from nsWindowRoot::GetControllers
// which is to look at the focused element, and defer to a focused textbox's controller
// The code past taken by other commands in ExecCommand always uses the window directly,
// rather than deferring to the textbox, which is desireable for most editor commands,
// but not 'cut' and 'copy' (as those should allow copying out of embedded editors).
// This behaviour is invoked if we call DoCommand directly on the docShell.
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell) {
nsresult res = docShell->DoCommand(cmdToDispatch.get());
return NS_SUCCEEDED(res);
}
return false;
}
if (commandID.LowerCaseEqualsLiteral("gethtml")) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
bool restricted = commandID.LowerCaseEqualsLiteral("paste");
if (restricted && !nsContentUtils::IsCallerChrome()) {
return false;
}
// get command manager and dispatch command to our window if it's acceptable
nsCOMPtr<nsICommandManager> cmdMgr;
GetMidasCommandManager(getter_AddRefs(cmdMgr));
if (!cmdMgr) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
nsPIDOMWindowOuter* window = GetWindow();
if (!window) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
if ((cmdToDispatch.EqualsLiteral("cmd_fontSize") ||
cmdToDispatch.EqualsLiteral("cmd_insertImageNoUI") ||
cmdToDispatch.EqualsLiteral("cmd_insertLinkNoUI") ||
cmdToDispatch.EqualsLiteral("cmd_paragraphState")) &&
paramStr.IsEmpty()) {
// Invalid value, return false
return false;
}
// Return false for disabled commands (bug 760052)
bool enabled = false;
cmdMgr->IsCommandEnabled(cmdToDispatch.get(), window, &enabled);
if (!enabled) {
return false;
}
if (!isBool && paramStr.IsEmpty()) {
rv = cmdMgr->DoCommand(cmdToDispatch.get(), nullptr, window);
} else {
// we have a command that requires a parameter, create params
nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
NS_COMMAND_PARAMS_CONTRACTID);
if (!cmdParams) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
if (isBool) {
rv = cmdParams->SetBooleanValue("state_attribute", boolVal);
} else if (cmdToDispatch.EqualsLiteral("cmd_fontFace")) {
rv = cmdParams->SetStringValue("state_attribute", value);
} else if (cmdToDispatch.EqualsLiteral("cmd_insertHTML") ||
cmdToDispatch.EqualsLiteral("cmd_insertText")) {
rv = cmdParams->SetStringValue("state_data", value);
} else {
rv = cmdParams->SetCStringValue("state_attribute", paramStr.get());
}
if (rv.Failed()) {
return false;
}
rv = cmdMgr->DoCommand(cmdToDispatch.get(), cmdParams, window);
}
return !rv.Failed();
}
NS_IMETHODIMP
nsHTMLDocument::QueryCommandEnabled(const nsAString& commandID,
bool* _retval)
{
ErrorResult rv;
*_retval = QueryCommandEnabled(commandID, rv);
return rv.StealNSResult();
}
bool
nsHTMLDocument::QueryCommandEnabled(const nsAString& commandID, ErrorResult& rv)
{
nsAutoCString cmdToDispatch;
if (!ConvertToMidasInternalCommand(commandID, cmdToDispatch)) {
return false;
}
// cut & copy are always allowed
bool isCutCopy = commandID.LowerCaseEqualsLiteral("cut") ||
commandID.LowerCaseEqualsLiteral("copy");
if (isCutCopy) {
return nsContentUtils::IsCutCopyAllowed();
}
// Report false for restricted commands
bool restricted = commandID.LowerCaseEqualsLiteral("paste");
if (restricted && !nsContentUtils::IsCallerChrome()) {
return false;
}
// if editing is not on, bail
if (!IsEditingOnAfterFlush()) {
return false;
}
// get command manager and dispatch command to our window if it's acceptable
nsCOMPtr<nsICommandManager> cmdMgr;
GetMidasCommandManager(getter_AddRefs(cmdMgr));
if (!cmdMgr) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
nsPIDOMWindowOuter* window = GetWindow();
if (!window) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
bool retval;
rv = cmdMgr->IsCommandEnabled(cmdToDispatch.get(), window, &retval);
return retval;
}
NS_IMETHODIMP
nsHTMLDocument::QueryCommandIndeterm(const nsAString & commandID,
bool *_retval)
{
ErrorResult rv;
*_retval = QueryCommandIndeterm(commandID, rv);
return rv.StealNSResult();
}
bool
nsHTMLDocument::QueryCommandIndeterm(const nsAString& commandID, ErrorResult& rv)
{
nsAutoCString cmdToDispatch;
if (!ConvertToMidasInternalCommand(commandID, cmdToDispatch)) {
return false;
}
// if editing is not on, bail
if (!IsEditingOnAfterFlush()) {
return false;
}
// get command manager and dispatch command to our window if it's acceptable
nsCOMPtr<nsICommandManager> cmdMgr;
GetMidasCommandManager(getter_AddRefs(cmdMgr));
if (!cmdMgr) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
nsPIDOMWindowOuter* window = GetWindow();
if (!window) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
nsresult res;
nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
NS_COMMAND_PARAMS_CONTRACTID, &res);
if (NS_FAILED(res)) {
rv.Throw(res);
return false;
}
rv = cmdMgr->GetCommandState(cmdToDispatch.get(), window, cmdParams);
if (rv.Failed()) {
return false;
}
// If command does not have a state_mixed value, this call fails and sets
// retval to false. This is fine -- we want to return false in that case
// anyway (bug 738385), so we just don't throw regardless.
bool retval = false;
cmdParams->GetBooleanValue("state_mixed", &retval);
return retval;
}
NS_IMETHODIMP
nsHTMLDocument::QueryCommandState(const nsAString & commandID, bool *_retval)
{
ErrorResult rv;
*_retval = QueryCommandState(commandID, rv);
return rv.StealNSResult();
}
bool
nsHTMLDocument::QueryCommandState(const nsAString& commandID, ErrorResult& rv)
{
nsAutoCString cmdToDispatch, paramToCheck;
bool dummy, dummy2;
if (!ConvertToMidasInternalCommand(commandID, commandID,
cmdToDispatch, paramToCheck,
dummy, dummy2)) {
return false;
}
// if editing is not on, bail
if (!IsEditingOnAfterFlush()) {
return false;
}
// get command manager and dispatch command to our window if it's acceptable
nsCOMPtr<nsICommandManager> cmdMgr;
GetMidasCommandManager(getter_AddRefs(cmdMgr));
if (!cmdMgr) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
nsPIDOMWindowOuter* window = GetWindow();
if (!window) {
rv.Throw(NS_ERROR_FAILURE);
return false;
}
if (commandID.LowerCaseEqualsLiteral("usecss")) {
// Per spec, state is supported for styleWithCSS but not useCSS, so we just
// return false always.
return false;
}
nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
NS_COMMAND_PARAMS_CONTRACTID);
if (!cmdParams) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
rv = cmdMgr->GetCommandState(cmdToDispatch.get(), window, cmdParams);
if (rv.Failed()) {
return false;
}
// handle alignment as a special case (possibly other commands too?)
// Alignment is special because the external api is individual
// commands but internally we use cmd_align with different
// parameters. When getting the state of this command, we need to
// return the boolean for this particular alignment rather than the
// string of 'which alignment is this?'
if (cmdToDispatch.EqualsLiteral("cmd_align")) {
char * actualAlignmentType = nullptr;
rv = cmdParams->GetCStringValue("state_attribute", &actualAlignmentType);
bool retval = false;
if (!rv.Failed() && actualAlignmentType && actualAlignmentType[0]) {
retval = paramToCheck.Equals(actualAlignmentType);
}
if (actualAlignmentType) {
free(actualAlignmentType);
}
return retval;
}
// If command does not have a state_all value, this call fails and sets
// retval to false. This is fine -- we want to return false in that case
// anyway (bug 738385), so we just succeed and return false regardless.
bool retval = false;
cmdParams->GetBooleanValue("state_all", &retval);
return retval;
}
NS_IMETHODIMP
nsHTMLDocument::QueryCommandSupported(const nsAString & commandID,
bool *_retval)
{
*_retval = QueryCommandSupported(commandID);
return NS_OK;
}
bool
nsHTMLDocument::QueryCommandSupported(const nsAString& commandID)
{
// Gecko technically supports all the clipboard commands including
// cut/copy/paste, but non-privileged content will be unable to call
// paste, and depending on the pref "dom.allow_cut_copy", cut and copy
// may also be disallowed to be called from non-privileged content.
// For that reason, we report the support status of corresponding
// command accordingly.
if (!nsContentUtils::IsCallerChrome()) {
if (commandID.LowerCaseEqualsLiteral("paste")) {
return false;
}
if (nsContentUtils::IsCutCopyRestricted()) {
if (commandID.LowerCaseEqualsLiteral("cut") ||
commandID.LowerCaseEqualsLiteral("copy")) {
return false;
}
}
}
// commandID is supported if it can be converted to a Midas command
nsAutoCString cmdToDispatch;
return ConvertToMidasInternalCommand(commandID, cmdToDispatch);
}
NS_IMETHODIMP
nsHTMLDocument::QueryCommandValue(const nsAString & commandID,
nsAString &_retval)
{
ErrorResult rv;
QueryCommandValue(commandID, _retval, rv);
return rv.StealNSResult();
}
void
nsHTMLDocument::QueryCommandValue(const nsAString& commandID,
nsAString& aValue,
ErrorResult& rv)
{
aValue.Truncate();
nsAutoCString cmdToDispatch, paramStr;
if (!ConvertToMidasInternalCommand(commandID, cmdToDispatch)) {
// Return empty string
return;
}
// if editing is not on, bail
if (!IsEditingOnAfterFlush()) {
return;
}
// get command manager and dispatch command to our window if it's acceptable
nsCOMPtr<nsICommandManager> cmdMgr;
GetMidasCommandManager(getter_AddRefs(cmdMgr));
if (!cmdMgr) {
rv.Throw(NS_ERROR_FAILURE);
return;
}
nsPIDOMWindowOuter* window = GetWindow();
if (!window) {
rv.Throw(NS_ERROR_FAILURE);
return;
}
// create params
nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
NS_COMMAND_PARAMS_CONTRACTID);
if (!cmdParams) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
// this is a special command since we are calling DoCommand rather than
// GetCommandState like the other commands
if (cmdToDispatch.EqualsLiteral("cmd_getContents")) {
rv = cmdParams->SetBooleanValue("selection_only", true);
if (rv.Failed()) {
return;
}
rv = cmdParams->SetCStringValue("format", "text/html");
if (rv.Failed()) {
return;
}
rv = cmdMgr->DoCommand(cmdToDispatch.get(), cmdParams, window);
if (rv.Failed()) {
return;
}
rv = cmdParams->GetStringValue("result", aValue);
return;
}
rv = cmdParams->SetCStringValue("state_attribute", paramStr.get());
if (rv.Failed()) {
return;
}
rv = cmdMgr->GetCommandState(cmdToDispatch.get(), window, cmdParams);
if (rv.Failed()) {
return;
}
// If command does not have a state_attribute value, this call fails, and
// aValue will wind up being the empty string. This is fine -- we want to
// return "" in that case anyway (bug 738385), so we just return NS_OK
// regardless.
nsXPIDLCString cStringResult;
cmdParams->GetCStringValue("state_attribute",
getter_Copies(cStringResult));
CopyUTF8toUTF16(cStringResult, aValue);
}
nsresult
nsHTMLDocument::Clone(mozilla::dom::NodeInfo *aNodeInfo, nsINode **aResult) const
{
NS_ASSERTION(aNodeInfo->NodeInfoManager() == mNodeInfoManager,
"Can't import this document into another document!");
RefPtr<nsHTMLDocument> clone = new nsHTMLDocument();
nsresult rv = CloneDocHelper(clone.get());
NS_ENSURE_SUCCESS(rv, rv);
// State from nsHTMLDocument
clone->mLoadFlags = mLoadFlags;
return CallQueryInterface(clone.get(), aResult);
}
bool
nsHTMLDocument::IsEditingOnAfterFlush()
{
nsIDocument* doc = GetParentDocument();
if (doc) {
// Make sure frames are up to date, since that can affect whether
// we're editable.
doc->FlushPendingNotifications(Flush_Frames);
}
return IsEditingOn();
}
void
nsHTMLDocument::RemovedFromDocShell()
{
mEditingState = eOff;
nsDocument::RemovedFromDocShell();
}
/* virtual */ void
nsHTMLDocument::DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const
{
nsDocument::DocAddSizeOfExcludingThis(aWindowSizes);
// Measurement of the following members may be added later if DMD finds it is
// worthwhile:
// - mImages
// - mApplets
// - mEmbeds
// - mLinks
// - mAnchors
// - mScripts
// - mForms
// - mFormControls
// - mWyciwygChannel
// - mMidasCommandManager
}
bool
nsHTMLDocument::WillIgnoreCharsetOverride()
{
if (mType != eHTML) {
MOZ_ASSERT(mType == eXHTML);
return true;
}
if (mCharacterSetSource == kCharsetFromByteOrderMark) {
return true;
}
if (!EncodingUtils::IsAsciiCompatible(mCharacterSet)) {
return true;
}
nsCOMPtr<nsIWyciwygChannel> wyciwyg = do_QueryInterface(mChannel);
if (wyciwyg) {
return true;
}
nsIURI* uri = GetOriginalURI();
if (uri) {
bool schemeIs = false;
uri->SchemeIs("about", &schemeIs);
if (schemeIs) {
return true;
}
bool isResource;
nsresult rv = NS_URIChainHasFlags(uri,
nsIProtocolHandler::URI_IS_UI_RESOURCE,
&isResource);
if (NS_FAILED(rv) || isResource) {
return true;
}
}
return false;
}
|