1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
|
/* -*- 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/. */
/*
* Base class for all our document implementations.
*/
#include "nsDocument.h"
#include "nsIDocumentInlines.h"
#include "mozilla/AnimationComparator.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EffectSet.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Likely.h"
#include <algorithm>
#include "mozilla/Logging.h"
#include "plstr.h"
#include "mozilla/Sprintf.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsITextControlFrame.h"
#include "nsNumberControlFrame.h"
#include "nsUnicharUtils.h"
#include "nsContentList.h"
#include "nsCSSPseudoElements.h"
#include "nsIObserver.h"
#include "nsIBaseWindow.h"
#include "mozilla/css/Loader.h"
#include "mozilla/css/ImageLoader.h"
#include "nsDocShell.h"
#include "nsDocShellLoadTypes.h"
#include "nsIDocShellTreeItem.h"
#include "nsCOMArray.h"
#include "nsQueryObject.h"
#include "nsDOMClassInfo.h"
#include "mozilla/Services.h"
#include "nsScreen.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventStateManager.h"
#include "nsIDOMNodeFilter.h"
#include "nsIDOMStyleSheet.h"
#include "mozilla/dom/Attr.h"
#include "nsIDOMDOMImplementation.h"
#include "nsIDOMDocumentXBL.h"
#include "mozilla/dom/Element.h"
#include "nsGenericHTMLElement.h"
#include "mozilla/dom/CDATASection.h"
#include "mozilla/dom/ProcessingInstruction.h"
#include "nsDSURIContentListener.h"
#include "nsDOMString.h"
#include "nsNodeUtils.h"
#include "nsLayoutUtils.h" // for GetFrameForPoint
#include "nsIFrame.h"
#include "nsITabChild.h"
#include "nsRange.h"
#include "nsIDOMText.h"
#include "nsIDOMComment.h"
#include "mozilla/dom/DocumentType.h"
#include "mozilla/dom/NodeIterator.h"
#include "mozilla/dom/TreeWalker.h"
#include "nsIServiceManager.h"
#include "mozilla/dom/workers/ServiceWorkerManager.h"
#include "imgLoader.h"
#include "nsCanvasFrame.h"
#include "nsContentCID.h"
#include "nsError.h"
#include "nsPresShell.h"
#include "nsPresContext.h"
#include "nsIJSON.h"
#include "nsThreadUtils.h"
#include "nsNodeInfoManager.h"
#include "nsIFileChannel.h"
#include "nsIMultiPartChannel.h"
#include "nsIRefreshURI.h"
#include "nsIWebNavigation.h"
#include "nsIScriptError.h"
#include "nsISimpleEnumerator.h"
#include "nsStyleSheetService.h"
#include "nsNetUtil.h" // for NS_NewURI
#include "nsIInputStreamChannel.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPrompt2.h"
#include "nsIScriptSecurityManager.h"
#include "nsIPermissionManager.h"
#include "nsIPrincipal.h"
#include "nsNullPrincipal.h"
#include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsIDOMElement.h"
#include "nsFocusManager.h"
// for radio group stuff
#include "nsIDOMHTMLInputElement.h"
#include "nsIRadioVisitor.h"
#include "nsIFormControl.h"
#include "nsBidiUtils.h"
#include "nsIParserService.h"
#include "nsContentCreatorFunctions.h"
#include "nsIScriptContext.h"
#include "nsBindingManager.h"
#include "nsIDOMHTMLDocument.h"
#include "nsHTMLDocument.h"
#include "nsIDOMHTMLFormElement.h"
#include "nsIRequest.h"
#include "nsHostObjectProtocolHandler.h"
#include "nsCharsetSource.h"
#include "nsIParser.h"
#include "nsIContentSink.h"
#include "nsDateTimeFormatCID.h"
#include "nsIDateTimeFormat.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventStates.h"
#include "mozilla/InternalMutationEvent.h"
#include "nsDOMCID.h"
#include "jsapi.h"
#include "nsIXPConnect.h"
#include "xpcpublic.h"
#include "nsCCUncollectableMarker.h"
#include "nsIContentPolicy.h"
#include "nsContentPolicyUtils.h"
#include "nsICategoryManager.h"
#include "nsIDocumentLoaderFactory.h"
#include "nsIDocumentLoader.h"
#include "nsIContentViewer.h"
#include "nsIXMLContentSink.h"
#include "nsIXULDocument.h"
#include "nsIPrompt.h"
#include "nsIPropertyBag2.h"
#include "mozilla/dom/PageTransitionEvent.h"
#include "mozilla/dom/StyleRuleChangeEvent.h"
#include "mozilla/dom/StyleSheetChangeEvent.h"
#include "mozilla/dom/StyleSheetApplicableStateChangeEvent.h"
#include "nsJSUtils.h"
#include "nsFrameLoader.h"
#include "nsEscape.h"
#include "nsObjectLoadingContent.h"
#include "nsHtml5TreeOpExecutor.h"
#include "mozilla/dom/HTMLLinkElement.h"
#include "mozilla/dom/HTMLMediaElement.h"
#include "mozilla/dom/HTMLIFrameElement.h"
#include "mozilla/dom/HTMLImageElement.h"
#include "mozilla/dom/MediaSource.h"
#include "mozAutoDocUpdate.h"
#include "nsGlobalWindow.h"
#include "mozilla/dom/EncodingUtils.h"
#include "nsDOMNavigationTiming.h"
#include "nsSMILAnimationController.h"
#include "imgIContainer.h"
#include "nsSVGUtils.h"
#include "nsRefreshDriver.h"
// FOR CSP (autogenerated by xpidl)
#include "nsIContentSecurityPolicy.h"
#include "mozilla/dom/nsCSPContext.h"
#include "mozilla/dom/nsCSPService.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "nsHTMLStyleSheet.h"
#include "nsHTMLCSSStyleSheet.h"
#include "SVGAttrAnimationRuleProcessor.h"
#include "mozilla/dom/DOMImplementation.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/Comment.h"
#include "nsTextNode.h"
#include "mozilla/dom/Link.h"
#include "mozilla/dom/HTMLElementBinding.h"
#include "nsXULAppAPI.h"
#include "mozilla/dom/Touch.h"
#include "mozilla/dom/TouchEvent.h"
#include "mozilla/Preferences.h"
#include "imgILoader.h"
#include "imgRequestProxy.h"
#include "nsWrapperCacheInlines.h"
#include "nsSandboxFlags.h"
#include "nsIAddonPolicyService.h"
#include "mozilla/dom/AnimatableBinding.h"
#include "mozilla/dom/AnonymousContent.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/ImageTracker.h"
#include "mozilla/dom/MediaQueryList.h"
#include "mozilla/dom/NodeFilterBinding.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/dom/TabChild.h"
#include "mozilla/dom/WebComponentsBinding.h"
#include "mozilla/dom/CustomElementRegistryBinding.h"
#include "mozilla/dom/CustomElementRegistry.h"
#include "nsFrame.h"
#include "nsDOMCaretPosition.h"
#include "nsIDOMHTMLTextAreaElement.h"
#include "nsViewportInfo.h"
#include "mozilla/StaticPtr.h"
#include "nsITextControlElement.h"
#include "nsIDOMNSEditableElement.h"
#include "nsIEditor.h"
#include "nsIDOMCSSStyleRule.h"
#include "mozilla/css/Rule.h"
#include "nsIDOMLocation.h"
#include "nsIHttpChannelInternal.h"
#include "nsISecurityConsoleMessage.h"
#include "nsCharSeparatedTokenizer.h"
#include "mozilla/dom/XPathEvaluator.h"
#include "mozilla/dom/XPathNSResolverBinding.h"
#include "mozilla/dom/XPathResult.h"
#include "nsIDocumentEncoder.h"
#include "nsIDocumentActivity.h"
#include "nsIStructuredCloneContainer.h"
#include "nsIMutableArray.h"
#include "mozilla/dom/DOMStringList.h"
#include "nsWindowMemoryReporter.h"
#include "mozilla/dom/Location.h"
#include "mozilla/dom/FontFaceSet.h"
#include "mozilla/dom/BoxObject.h"
#include "gfxPrefs.h"
#include "nsISupportsPrimitives.h"
#include "mozilla/StyleSetHandle.h"
#include "mozilla/StyleSetHandleInlines.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/dom/SVGSVGElement.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/TabGroup.h"
#include "mozilla/DocLoadingTimelineMarker.h"
#include "nsISpeculativeConnect.h"
#include "mozilla/MediaManager.h"
#ifdef MOZ_WEBRTC
#include "IPeerConnection.h"
#endif // MOZ_WEBRTC
using namespace mozilla;
using namespace mozilla::dom;
typedef nsTArray<Link*> LinkArray;
static LazyLogModule gDocumentLeakPRLog("DocumentLeak");
static LazyLogModule gCspPRLog("CSP");
static nsresult
GetHttpChannelHelper(nsIChannel* aChannel, nsIHttpChannel** aHttpChannel)
{
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
if (httpChannel) {
httpChannel.forget(aHttpChannel);
return NS_OK;
}
nsCOMPtr<nsIMultiPartChannel> multipart = do_QueryInterface(aChannel);
if (!multipart) {
*aHttpChannel = nullptr;
return NS_OK;
}
nsCOMPtr<nsIChannel> baseChannel;
nsresult rv = multipart->GetBaseChannel(getter_AddRefs(baseChannel));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
httpChannel = do_QueryInterface(baseChannel);
httpChannel.forget(aHttpChannel);
return NS_OK;
}
#define NAME_NOT_VALID ((nsSimpleContentList*)1)
nsIdentifierMapEntry::~nsIdentifierMapEntry()
{
}
void
nsIdentifierMapEntry::Traverse(nsCycleCollectionTraversalCallback* aCallback)
{
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mIdentifierMap mNameContentList");
aCallback->NoteXPCOMChild(static_cast<nsIDOMNodeList*>(mNameContentList));
if (mImageElement) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mIdentifierMap mImageElement element");
nsIContent* imageElement = mImageElement;
aCallback->NoteXPCOMChild(imageElement);
}
}
bool
nsIdentifierMapEntry::IsEmpty()
{
return mIdContentList.IsEmpty() && !mNameContentList &&
!mChangeCallbacks && !mImageElement;
}
Element*
nsIdentifierMapEntry::GetIdElement()
{
return mIdContentList.SafeElementAt(0);
}
Element*
nsIdentifierMapEntry::GetImageIdElement()
{
return mImageElement ? mImageElement.get() : GetIdElement();
}
void
nsIdentifierMapEntry::AppendAllIdContent(nsCOMArray<nsIContent>* aElements)
{
for (size_t i = 0; i < mIdContentList.Length(); ++i) {
aElements->AppendObject(mIdContentList[i]);
}
}
void
nsIdentifierMapEntry::AddContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
void* aData, bool aForImage)
{
if (!mChangeCallbacks) {
mChangeCallbacks = new nsTHashtable<ChangeCallbackEntry>;
}
ChangeCallback cc = { aCallback, aData, aForImage };
mChangeCallbacks->PutEntry(cc);
}
void
nsIdentifierMapEntry::RemoveContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
void* aData, bool aForImage)
{
if (!mChangeCallbacks)
return;
ChangeCallback cc = { aCallback, aData, aForImage };
mChangeCallbacks->RemoveEntry(cc);
if (mChangeCallbacks->Count() == 0) {
mChangeCallbacks = nullptr;
}
}
void
nsIdentifierMapEntry::FireChangeCallbacks(Element* aOldElement,
Element* aNewElement,
bool aImageOnly)
{
if (!mChangeCallbacks)
return;
for (auto iter = mChangeCallbacks->ConstIter(); !iter.Done(); iter.Next()) {
nsIdentifierMapEntry::ChangeCallbackEntry* entry = iter.Get();
// Don't fire image changes for non-image observers, and don't fire element
// changes for image observers when an image override is active.
if (entry->mKey.mForImage ? (mImageElement && !aImageOnly) : aImageOnly) {
continue;
}
if (!entry->mKey.mCallback(aOldElement, aNewElement, entry->mKey.mData)) {
iter.Remove();
}
}
}
void
nsIdentifierMapEntry::ClearAndNotify()
{
Element* currentElement = mIdContentList.SafeElementAt(0);
mIdContentList.Clear();
if (currentElement) {
FireChangeCallbacks(currentElement, nullptr);
}
mNameContentList = nullptr;
if (mImageElement) {
SetImageElement(nullptr);
}
mChangeCallbacks = nullptr;
}
namespace {
struct PositionComparator
{
Element* const mElement;
explicit PositionComparator(Element* const aElement) : mElement(aElement) {}
int operator()(void* aElement) const {
Element* curElement = static_cast<Element*>(aElement);
if (mElement == curElement) {
return 0;
}
if (nsContentUtils::PositionIsBefore(mElement, curElement)) {
return -1;
}
return 1;
}
};
} // namespace
bool
nsIdentifierMapEntry::AddIdElement(Element* aElement)
{
NS_PRECONDITION(aElement, "Must have element");
NS_PRECONDITION(!mIdContentList.Contains(nullptr),
"Why is null in our list?");
#ifdef DEBUG
Element* currentElement = mIdContentList.SafeElementAt(0);
#endif
// Common case
if (mIdContentList.IsEmpty()) {
if (!mIdContentList.AppendElement(aElement))
return false;
NS_ASSERTION(currentElement == nullptr, "How did that happen?");
FireChangeCallbacks(nullptr, aElement);
return true;
}
// We seem to have multiple content nodes for the same id, or XUL is messing
// with us. Search for the right place to insert the content.
size_t idx;
if (BinarySearchIf(mIdContentList, 0, mIdContentList.Length(),
PositionComparator(aElement), &idx)) {
// Already in the list, so already in the right spot. Get out of here.
// XXXbz this only happens because XUL does all sorts of random
// UpdateIdTableEntry calls. Hate, hate, hate!
return true;
}
if (!mIdContentList.InsertElementAt(idx, aElement)) {
return false;
}
if (idx == 0) {
Element* oldElement = mIdContentList.SafeElementAt(1);
NS_ASSERTION(currentElement == oldElement, "How did that happen?");
FireChangeCallbacks(oldElement, aElement);
}
return true;
}
void
nsIdentifierMapEntry::RemoveIdElement(Element* aElement)
{
NS_PRECONDITION(aElement, "Missing element");
// This should only be called while the document is in an update.
// Assertions near the call to this method guarantee this.
// This could fire in OOM situations
// Only assert this in HTML documents for now as XUL does all sorts of weird
// crap.
NS_ASSERTION(!aElement->OwnerDoc()->IsHTMLDocument() ||
mIdContentList.Contains(aElement),
"Removing id entry that doesn't exist");
// XXXbz should this ever Compact() I guess when all the content is gone
// we'll just get cleaned up in the natural order of things...
Element* currentElement = mIdContentList.SafeElementAt(0);
mIdContentList.RemoveElement(aElement);
if (currentElement == aElement) {
FireChangeCallbacks(currentElement, mIdContentList.SafeElementAt(0));
}
}
void
nsIdentifierMapEntry::SetImageElement(Element* aElement)
{
Element* oldElement = GetImageIdElement();
mImageElement = aElement;
Element* newElement = GetImageIdElement();
if (oldElement != newElement) {
FireChangeCallbacks(oldElement, newElement, true);
}
}
void
nsIdentifierMapEntry::AddNameElement(nsINode* aNode, Element* aElement)
{
if (!mNameContentList) {
mNameContentList = new nsSimpleContentList(aNode);
}
mNameContentList->AppendElement(aElement);
}
void
nsIdentifierMapEntry::RemoveNameElement(Element* aElement)
{
if (mNameContentList) {
mNameContentList->RemoveElement(aElement);
}
}
bool
nsIdentifierMapEntry::HasIdElementExposedAsHTMLDocumentProperty()
{
Element* idElement = GetIdElement();
return idElement &&
nsGenericHTMLElement::ShouldExposeIdAsHTMLDocumentProperty(idElement);
}
size_t
nsIdentifierMapEntry::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
return nsStringHashKey::SizeOfExcludingThis(aMallocSizeOf);
}
// Helper structs for the content->subdoc map
class SubDocMapEntry : public PLDHashEntryHdr
{
public:
// Both of these are strong references
Element *mKey; // must be first, to look like PLDHashEntryStub
nsIDocument *mSubDocument;
};
/**
* A struct that holds all the information about a radio group.
*/
struct nsRadioGroupStruct
{
nsRadioGroupStruct()
: mRequiredRadioCount(0)
, mGroupSuffersFromValueMissing(false)
{}
/**
* A strong pointer to the currently selected radio button.
*/
RefPtr<HTMLInputElement> mSelectedRadioButton;
nsCOMArray<nsIFormControl> mRadioButtons;
uint32_t mRequiredRadioCount;
bool mGroupSuffersFromValueMissing;
};
nsDOMStyleSheetList::nsDOMStyleSheetList(nsIDocument *aDocument)
{
mLength = -1;
// Not reference counted to avoid circular references.
// The document will tell us when its going away.
mDocument = aDocument;
mDocument->AddObserver(this);
}
nsDOMStyleSheetList::~nsDOMStyleSheetList()
{
if (mDocument) {
mDocument->RemoveObserver(this);
}
}
NS_IMPL_ISUPPORTS_INHERITED(nsDOMStyleSheetList, StyleSheetList,
nsIDocumentObserver,
nsIMutationObserver)
uint32_t
nsDOMStyleSheetList::Length()
{
if (!mDocument) {
return 0;
}
// XXX Find the number and then cache it. We'll use the
// observer notification to figure out if new ones have
// been added or removed.
if (-1 == mLength) {
mLength = mDocument->GetNumberOfStyleSheets();
}
return mLength;
}
StyleSheet*
nsDOMStyleSheetList::IndexedGetter(uint32_t aIndex, bool& aFound)
{
if (!mDocument || aIndex >= (uint32_t)mDocument->GetNumberOfStyleSheets()) {
aFound = false;
return nullptr;
}
aFound = true;
return mDocument->GetStyleSheetAt(aIndex);
}
void
nsDOMStyleSheetList::NodeWillBeDestroyed(const nsINode *aNode)
{
mDocument = nullptr;
}
void
nsDOMStyleSheetList::StyleSheetAdded(StyleSheet* aStyleSheet,
bool aDocumentSheet)
{
if (aDocumentSheet && -1 != mLength) {
mLength++;
}
}
void
nsDOMStyleSheetList::StyleSheetRemoved(StyleSheet* aStyleSheet,
bool aDocumentSheet)
{
if (aDocumentSheet && -1 != mLength) {
mLength--;
}
}
// nsOnloadBlocker implementation
NS_IMPL_ISUPPORTS(nsOnloadBlocker, nsIRequest)
NS_IMETHODIMP
nsOnloadBlocker::GetName(nsACString &aResult)
{
aResult.AssignLiteral("about:document-onload-blocker");
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::IsPending(bool *_retval)
{
*_retval = true;
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::GetStatus(nsresult *status)
{
*status = NS_OK;
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::Cancel(nsresult status)
{
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::Suspend(void)
{
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::Resume(void)
{
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::GetLoadGroup(nsILoadGroup * *aLoadGroup)
{
*aLoadGroup = nullptr;
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::SetLoadGroup(nsILoadGroup * aLoadGroup)
{
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::GetLoadFlags(nsLoadFlags *aLoadFlags)
{
*aLoadFlags = nsIRequest::LOAD_NORMAL;
return NS_OK;
}
NS_IMETHODIMP
nsOnloadBlocker::SetLoadFlags(nsLoadFlags aLoadFlags)
{
return NS_OK;
}
// ==================================================================
nsExternalResourceMap::nsExternalResourceMap()
: mHaveShutDown(false)
{
}
nsIDocument*
nsExternalResourceMap::RequestResource(nsIURI* aURI,
nsINode* aRequestingNode,
nsDocument* aDisplayDocument,
ExternalResourceLoad** aPendingLoad)
{
// If we ever start allowing non-same-origin loads here, we might need to do
// something interesting with aRequestingPrincipal even for the hashtable
// gets.
NS_PRECONDITION(aURI, "Must have a URI");
NS_PRECONDITION(aRequestingNode, "Must have a node");
*aPendingLoad = nullptr;
if (mHaveShutDown) {
return nullptr;
}
// First, make sure we strip the ref from aURI.
nsCOMPtr<nsIURI> clone;
nsresult rv = aURI->CloneIgnoringRef(getter_AddRefs(clone));
if (NS_FAILED(rv) || !clone) {
return nullptr;
}
ExternalResource* resource;
mMap.Get(clone, &resource);
if (resource) {
return resource->mDocument;
}
RefPtr<PendingLoad> load;
mPendingLoads.Get(clone, getter_AddRefs(load));
if (load) {
load.forget(aPendingLoad);
return nullptr;
}
load = new PendingLoad(aDisplayDocument);
mPendingLoads.Put(clone, load);
if (NS_FAILED(load->StartLoad(clone, aRequestingNode))) {
// Make sure we don't thrash things by trying this load again, since
// chances are it failed for good reasons (security check, etc).
AddExternalResource(clone, nullptr, nullptr, aDisplayDocument);
} else {
load.forget(aPendingLoad);
}
return nullptr;
}
void
nsExternalResourceMap::EnumerateResources(nsIDocument::nsSubDocEnumFunc aCallback,
void* aData)
{
for (auto iter = mMap.Iter(); !iter.Done(); iter.Next()) {
nsExternalResourceMap::ExternalResource* resource = iter.UserData();
if (resource->mDocument && !aCallback(resource->mDocument, aData)) {
break;
}
}
}
void
nsExternalResourceMap::Traverse(nsCycleCollectionTraversalCallback* aCallback) const
{
// mPendingLoads will get cleared out as the requests complete, so
// no need to worry about those here.
for (auto iter = mMap.ConstIter(); !iter.Done(); iter.Next()) {
nsExternalResourceMap::ExternalResource* resource = iter.UserData();
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mDocument");
aCallback->NoteXPCOMChild(resource->mDocument);
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mViewer");
aCallback->NoteXPCOMChild(resource->mViewer);
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mLoadGroup");
aCallback->NoteXPCOMChild(resource->mLoadGroup);
}
}
void
nsExternalResourceMap::HideViewers()
{
for (auto iter = mMap.Iter(); !iter.Done(); iter.Next()) {
nsCOMPtr<nsIContentViewer> viewer = iter.UserData()->mViewer;
if (viewer) {
viewer->Hide();
}
}
}
void
nsExternalResourceMap::ShowViewers()
{
for (auto iter = mMap.Iter(); !iter.Done(); iter.Next()) {
nsCOMPtr<nsIContentViewer> viewer = iter.UserData()->mViewer;
if (viewer) {
viewer->Show();
}
}
}
void
TransferZoomLevels(nsIDocument* aFromDoc,
nsIDocument* aToDoc)
{
MOZ_ASSERT(aFromDoc && aToDoc,
"transferring zoom levels from/to null doc");
nsIPresShell* fromShell = aFromDoc->GetShell();
if (!fromShell)
return;
nsPresContext* fromCtxt = fromShell->GetPresContext();
if (!fromCtxt)
return;
nsIPresShell* toShell = aToDoc->GetShell();
if (!toShell)
return;
nsPresContext* toCtxt = toShell->GetPresContext();
if (!toCtxt)
return;
toCtxt->SetFullZoom(fromCtxt->GetFullZoom());
toCtxt->SetBaseMinFontSize(fromCtxt->BaseMinFontSize());
toCtxt->SetTextZoom(fromCtxt->TextZoom());
toCtxt->SetOverrideDPPX(fromCtxt->GetOverrideDPPX());
}
void
TransferShowingState(nsIDocument* aFromDoc, nsIDocument* aToDoc)
{
MOZ_ASSERT(aFromDoc && aToDoc,
"transferring showing state from/to null doc");
if (aFromDoc->IsShowing()) {
aToDoc->OnPageShow(true, nullptr);
}
}
nsresult
nsExternalResourceMap::AddExternalResource(nsIURI* aURI,
nsIContentViewer* aViewer,
nsILoadGroup* aLoadGroup,
nsIDocument* aDisplayDocument)
{
NS_PRECONDITION(aURI, "Unexpected call");
NS_PRECONDITION((aViewer && aLoadGroup) || (!aViewer && !aLoadGroup),
"Must have both or neither");
RefPtr<PendingLoad> load;
mPendingLoads.Get(aURI, getter_AddRefs(load));
mPendingLoads.Remove(aURI);
nsresult rv = NS_OK;
nsCOMPtr<nsIDocument> doc;
if (aViewer) {
doc = aViewer->GetDocument();
NS_ASSERTION(doc, "Must have a document");
nsCOMPtr<nsIXULDocument> xulDoc = do_QueryInterface(doc);
if (xulDoc) {
// We don't handle XUL stuff here yet.
rv = NS_ERROR_NOT_AVAILABLE;
} else {
doc->SetDisplayDocument(aDisplayDocument);
// Make sure that hiding our viewer will tear down its presentation.
aViewer->SetSticky(false);
rv = aViewer->Init(nullptr, nsIntRect(0, 0, 0, 0));
if (NS_SUCCEEDED(rv)) {
rv = aViewer->Open(nullptr, nullptr);
}
}
if (NS_FAILED(rv)) {
doc = nullptr;
aViewer = nullptr;
aLoadGroup = nullptr;
}
}
ExternalResource* newResource = new ExternalResource();
mMap.Put(aURI, newResource);
newResource->mDocument = doc;
newResource->mViewer = aViewer;
newResource->mLoadGroup = aLoadGroup;
if (doc) {
TransferZoomLevels(aDisplayDocument, doc);
TransferShowingState(aDisplayDocument, doc);
}
const nsTArray< nsCOMPtr<nsIObserver> > & obs = load->Observers();
for (uint32_t i = 0; i < obs.Length(); ++i) {
obs[i]->Observe(doc, "external-resource-document-created", nullptr);
}
return rv;
}
NS_IMPL_ISUPPORTS(nsExternalResourceMap::PendingLoad,
nsIStreamListener,
nsIRequestObserver)
NS_IMETHODIMP
nsExternalResourceMap::PendingLoad::OnStartRequest(nsIRequest *aRequest,
nsISupports *aContext)
{
nsExternalResourceMap& map = mDisplayDocument->ExternalResourceMap();
if (map.HaveShutDown()) {
return NS_BINDING_ABORTED;
}
nsCOMPtr<nsIContentViewer> viewer;
nsCOMPtr<nsILoadGroup> loadGroup;
nsresult rv = SetupViewer(aRequest, getter_AddRefs(viewer),
getter_AddRefs(loadGroup));
// Make sure to do this no matter what
nsresult rv2 = map.AddExternalResource(mURI, viewer, loadGroup,
mDisplayDocument);
if (NS_FAILED(rv)) {
return rv;
}
if (NS_FAILED(rv2)) {
mTargetListener = nullptr;
return rv2;
}
return mTargetListener->OnStartRequest(aRequest, aContext);
}
nsresult
nsExternalResourceMap::PendingLoad::SetupViewer(nsIRequest* aRequest,
nsIContentViewer** aViewer,
nsILoadGroup** aLoadGroup)
{
NS_PRECONDITION(!mTargetListener, "Unexpected call to OnStartRequest");
*aViewer = nullptr;
*aLoadGroup = nullptr;
nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
if (httpChannel) {
bool requestSucceeded;
if (NS_FAILED(httpChannel->GetRequestSucceeded(&requestSucceeded)) ||
!requestSucceeded) {
// Bail out on this load, since it looks like we have an HTTP error page
return NS_BINDING_ABORTED;
}
}
nsAutoCString type;
chan->GetContentType(type);
nsCOMPtr<nsILoadGroup> loadGroup;
chan->GetLoadGroup(getter_AddRefs(loadGroup));
// Give this document its own loadgroup
nsCOMPtr<nsILoadGroup> newLoadGroup =
do_CreateInstance(NS_LOADGROUP_CONTRACTID);
NS_ENSURE_TRUE(newLoadGroup, NS_ERROR_OUT_OF_MEMORY);
newLoadGroup->SetLoadGroup(loadGroup);
nsCOMPtr<nsIInterfaceRequestor> callbacks;
loadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
nsCOMPtr<nsIInterfaceRequestor> newCallbacks =
new LoadgroupCallbacks(callbacks);
newLoadGroup->SetNotificationCallbacks(newCallbacks);
// This is some serious hackery cribbed from docshell
nsCOMPtr<nsICategoryManager> catMan =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
NS_ENSURE_TRUE(catMan, NS_ERROR_NOT_AVAILABLE);
nsXPIDLCString contractId;
nsresult rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", type.get(),
getter_Copies(contractId));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDocumentLoaderFactory> docLoaderFactory =
do_GetService(contractId);
NS_ENSURE_TRUE(docLoaderFactory, NS_ERROR_NOT_AVAILABLE);
nsCOMPtr<nsIContentViewer> viewer;
nsCOMPtr<nsIStreamListener> listener;
rv = docLoaderFactory->CreateInstance("external-resource", chan, newLoadGroup,
type, nullptr, nullptr,
getter_AddRefs(listener),
getter_AddRefs(viewer));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
if (!parser) {
/// We don't want to deal with the various fake documents yet
return NS_ERROR_NOT_IMPLEMENTED;
}
// We can't handle HTML and other weird things here yet.
nsIContentSink* sink = parser->GetContentSink();
nsCOMPtr<nsIXMLContentSink> xmlSink = do_QueryInterface(sink);
if (!xmlSink) {
return NS_ERROR_NOT_IMPLEMENTED;
}
listener.swap(mTargetListener);
viewer.forget(aViewer);
newLoadGroup.forget(aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsExternalResourceMap::PendingLoad::OnDataAvailable(nsIRequest* aRequest,
nsISupports* aContext,
nsIInputStream* aStream,
uint64_t aOffset,
uint32_t aCount)
{
NS_PRECONDITION(mTargetListener, "Shouldn't be getting called!");
if (mDisplayDocument->ExternalResourceMap().HaveShutDown()) {
return NS_BINDING_ABORTED;
}
return mTargetListener->OnDataAvailable(aRequest, aContext, aStream, aOffset,
aCount);
}
NS_IMETHODIMP
nsExternalResourceMap::PendingLoad::OnStopRequest(nsIRequest* aRequest,
nsISupports* aContext,
nsresult aStatus)
{
// mTargetListener might be null if SetupViewer or AddExternalResource failed
if (mTargetListener) {
nsCOMPtr<nsIStreamListener> listener;
mTargetListener.swap(listener);
return listener->OnStopRequest(aRequest, aContext, aStatus);
}
return NS_OK;
}
nsresult
nsExternalResourceMap::PendingLoad::StartLoad(nsIURI* aURI,
nsINode* aRequestingNode)
{
NS_PRECONDITION(aURI, "Must have a URI");
NS_PRECONDITION(aRequestingNode, "Must have a node");
nsCOMPtr<nsILoadGroup> loadGroup =
aRequestingNode->OwnerDoc()->GetDocumentLoadGroup();
nsresult rv = NS_OK;
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel),
aURI,
aRequestingNode,
nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS,
nsIContentPolicy::TYPE_OTHER,
loadGroup);
NS_ENSURE_SUCCESS(rv, rv);
mURI = aURI;
return channel->AsyncOpen2(this);
}
NS_IMPL_ISUPPORTS(nsExternalResourceMap::LoadgroupCallbacks,
nsIInterfaceRequestor)
#define IMPL_SHIM(_i) \
NS_IMPL_ISUPPORTS(nsExternalResourceMap::LoadgroupCallbacks::_i##Shim, _i)
IMPL_SHIM(nsILoadContext)
IMPL_SHIM(nsIProgressEventSink)
IMPL_SHIM(nsIChannelEventSink)
IMPL_SHIM(nsISecurityEventSink)
IMPL_SHIM(nsIApplicationCacheContainer)
#undef IMPL_SHIM
#define IID_IS(_i) aIID.Equals(NS_GET_IID(_i))
#define TRY_SHIM(_i) \
PR_BEGIN_MACRO \
if (IID_IS(_i)) { \
nsCOMPtr<_i> real = do_GetInterface(mCallbacks); \
if (!real) { \
return NS_NOINTERFACE; \
} \
nsCOMPtr<_i> shim = new _i##Shim(this, real); \
shim.forget(aSink); \
return NS_OK; \
} \
PR_END_MACRO
NS_IMETHODIMP
nsExternalResourceMap::LoadgroupCallbacks::GetInterface(const nsIID & aIID,
void **aSink)
{
if (mCallbacks &&
(IID_IS(nsIPrompt) || IID_IS(nsIAuthPrompt) || IID_IS(nsIAuthPrompt2) ||
IID_IS(nsITabChild))) {
return mCallbacks->GetInterface(aIID, aSink);
}
*aSink = nullptr;
TRY_SHIM(nsILoadContext);
TRY_SHIM(nsIProgressEventSink);
TRY_SHIM(nsIChannelEventSink);
TRY_SHIM(nsISecurityEventSink);
TRY_SHIM(nsIApplicationCacheContainer);
return NS_NOINTERFACE;
}
#undef TRY_SHIM
#undef IID_IS
nsExternalResourceMap::ExternalResource::~ExternalResource()
{
if (mViewer) {
mViewer->Close(nullptr);
mViewer->Destroy();
}
}
// ==================================================================
// =
// ==================================================================
// If we ever have an nsIDocumentObserver notification for stylesheet title
// changes we should update the list from that instead of overriding
// EnsureFresh.
class nsDOMStyleSheetSetList final : public DOMStringList
{
public:
explicit nsDOMStyleSheetSetList(nsIDocument* aDocument);
void Disconnect()
{
mDocument = nullptr;
}
virtual void EnsureFresh() override;
protected:
nsIDocument* mDocument; // Our document; weak ref. It'll let us know if it
// dies.
};
nsDOMStyleSheetSetList::nsDOMStyleSheetSetList(nsIDocument* aDocument)
: mDocument(aDocument)
{
NS_ASSERTION(mDocument, "Must have document!");
}
void
nsDOMStyleSheetSetList::EnsureFresh()
{
MOZ_ASSERT(NS_IsMainThread());
mNames.Clear();
if (!mDocument) {
return; // Spec says "no exceptions", and we have no style sets if we have
// no document, for sure
}
int32_t count = mDocument->GetNumberOfStyleSheets();
nsAutoString title;
for (int32_t index = 0; index < count; index++) {
StyleSheet* sheet = mDocument->GetStyleSheetAt(index);
NS_ASSERTION(sheet, "Null sheet in sheet list!");
// XXXheycam ServoStyleSheets don't expose their title yet.
if (sheet->IsServo()) {
NS_ERROR("stylo: ServoStyleSets don't expose their title yet");
continue;
}
sheet->AsGecko()->GetTitle(title);
if (!title.IsEmpty() && !mNames.Contains(title) && !Add(title)) {
return;
}
}
}
// ==================================================================
nsIDocument::SelectorCache::SelectorCache()
: nsExpirationTracker<SelectorCacheKey, 4>(1000, "nsIDocument::SelectorCache")
{ }
// CacheList takes ownership of aSelectorList.
void nsIDocument::SelectorCache::CacheList(const nsAString& aSelector,
nsCSSSelectorList* aSelectorList)
{
SelectorCacheKey* key = new SelectorCacheKey(aSelector);
mTable.Put(key->mKey, aSelectorList);
AddObject(key);
}
class nsIDocument::SelectorCacheKeyDeleter final : public Runnable
{
public:
explicit SelectorCacheKeyDeleter(SelectorCacheKey* aToDelete)
: mSelector(aToDelete)
{
MOZ_COUNT_CTOR(SelectorCacheKeyDeleter);
}
protected:
~SelectorCacheKeyDeleter()
{
MOZ_COUNT_DTOR(SelectorCacheKeyDeleter);
}
public:
NS_IMETHOD Run() override
{
return NS_OK;
}
private:
nsAutoPtr<SelectorCacheKey> mSelector;
};
void nsIDocument::SelectorCache::NotifyExpired(SelectorCacheKey* aSelector)
{
RemoveObject(aSelector);
mTable.Remove(aSelector->mKey);
nsCOMPtr<nsIRunnable> runnable = new SelectorCacheKeyDeleter(aSelector);
NS_DispatchToCurrentThread(runnable);
}
struct nsIDocument::FrameRequest
{
FrameRequest(FrameRequestCallback& aCallback,
int32_t aHandle) :
mCallback(&aCallback),
mHandle(aHandle)
{}
// Conversion operator so that we can append these to a
// FrameRequestCallbackList
operator const RefPtr<FrameRequestCallback>& () const {
return mCallback;
}
// Comparator operators to allow RemoveElementSorted with an
// integer argument on arrays of FrameRequest
bool operator==(int32_t aHandle) const {
return mHandle == aHandle;
}
bool operator<(int32_t aHandle) const {
return mHandle < aHandle;
}
RefPtr<FrameRequestCallback> mCallback;
int32_t mHandle;
};
static already_AddRefed<mozilla::dom::NodeInfo> nullNodeInfo;
// ==================================================================
// =
// ==================================================================
nsIDocument::nsIDocument()
: nsINode(nullNodeInfo),
mReferrerPolicySet(false),
mReferrerPolicy(mozilla::net::RP_Default),
mBlockAllMixedContent(false),
mBlockAllMixedContentPreloads(false),
mUpgradeInsecureRequests(false),
mUpgradeInsecurePreloads(false),
mCharacterSet(NS_LITERAL_CSTRING("ISO-8859-1")),
mNodeInfoManager(nullptr),
mCompatMode(eCompatibility_FullStandards),
mVisibilityState(dom::VisibilityState::Hidden),
mIsInitialDocumentInWindow(false),
mMayStartLayout(true),
mVisible(true),
mRemovedFromDocShell(false),
// mAllowDNSPrefetch starts true, so that we can always reliably && it
// with various values that might disable it. Since we never prefetch
// unless we get a window, and in that case the docshell value will get
// &&-ed in, this is safe.
mAllowDNSPrefetch(true),
mIsBeingUsedAsImage(false),
mHasLinksToUpdate(false),
mFontFaceSetDirty(true),
mGetUserFontSetCalled(false),
mPostedFlushUserFontSet(false),
mDidFireDOMContentLoaded(true),
mHasScrollLinkedEffect(false),
mFrameRequestCallbacksScheduled(false),
mBidiOptions(IBMBIDI_DEFAULT_BIDI_OPTIONS),
mPartID(0),
mUserHasInteracted(false)
{
SetIsInDocument();
PR_INIT_CLIST(&mDOMMediaQueryLists);
}
// NOTE! nsDocument::operator new() zeroes out all members, so don't
// bother initializing members to 0.
nsDocument::nsDocument(const char* aContentType)
: nsIDocument()
, mViewportType(Unknown)
{
SetContentTypeInternal(nsDependentCString(aContentType));
if (gDocumentLeakPRLog)
MOZ_LOG(gDocumentLeakPRLog, LogLevel::Debug,
("DOCUMENT %p created", this));
// Start out mLastStyleSheetSet as null, per spec
SetDOMStringToNull(mLastStyleSheetSet);
// void state used to differentiate an empty source from an unselected source
mPreloadPictureFoundSource.SetIsVoid(true);
mEverInForeground = false;
}
void
nsDocument::ClearAllBoxObjects()
{
if (mBoxObjectTable) {
for (auto iter = mBoxObjectTable->Iter(); !iter.Done(); iter.Next()) {
nsPIBoxObject* boxObject = iter.UserData();
if (boxObject) {
boxObject->Clear();
}
}
delete mBoxObjectTable;
mBoxObjectTable = nullptr;
}
}
nsIDocument::~nsIDocument()
{
MOZ_ASSERT(PR_CLIST_IS_EMPTY(&mDOMMediaQueryLists),
"must not have media query lists left");
if (mNodeInfoManager) {
mNodeInfoManager->DropDocumentReference();
}
if (mDocGroup) {
mDocGroup->RemoveDocument(this);
}
UnlinkOriginalDocumentIfStatic();
}
bool
nsDocument::IsAboutPage()
{
nsCOMPtr<nsIPrincipal> principal = GetPrincipal();
nsCOMPtr<nsIURI> uri;
principal->GetURI(getter_AddRefs(uri));
bool isAboutScheme = true;
if (uri) {
uri->SchemeIs("about", &isAboutScheme);
}
return isAboutScheme;
}
nsDocument::~nsDocument()
{
if (gDocumentLeakPRLog)
MOZ_LOG(gDocumentLeakPRLog, LogLevel::Debug,
("DOCUMENT %p destroyed", this));
NS_ASSERTION(!mIsShowing, "Destroying a currently-showing document");
mInDestructor = true;
mInUnlinkOrDeletion = true;
mozilla::DropJSObjects(this);
// Clear mObservers to keep it in sync with the mutationobserver list
mObservers.Clear();
mIntersectionObservers.Clear();
if (mStyleSheetSetList) {
mStyleSheetSetList->Disconnect();
}
if (mAnimationController) {
mAnimationController->Disconnect();
}
MOZ_ASSERT(mTimelines.isEmpty());
mParentDocument = nullptr;
// Kill the subdocument map, doing this will release its strong
// references, if any.
delete mSubDocuments;
mSubDocuments = nullptr;
nsAutoScriptBlocker scriptBlocker;
// Destroy link map now so we don't waste time removing
// links one by one
DestroyElementMaps();
for (uint32_t indx = mChildren.ChildCount(); indx-- != 0; ) {
mChildren.ChildAt(indx)->UnbindFromTree();
mChildren.RemoveChildAt(indx);
}
mFirstChild = nullptr;
mCachedRootElement = nullptr;
// Let the stylesheets know we're going away
for (StyleSheet* sheet : mStyleSheets) {
sheet->SetOwningDocument(nullptr);
}
for (auto& sheets : mAdditionalSheets) {
for (StyleSheet* sheet : sheets) {
sheet->SetOwningDocument(nullptr);
}
}
if (mAttrStyleSheet) {
mAttrStyleSheet->SetOwningDocument(nullptr);
}
// We don't own the mOnDemandBuiltInUASheets, so we don't need to reset them.
if (mListenerManager) {
mListenerManager->Disconnect();
UnsetFlags(NODE_HAS_LISTENERMANAGER);
}
if (mScriptLoader) {
mScriptLoader->DropDocumentReference();
}
if (mCSSLoader) {
// Could be null here if Init() failed or if we have been unlinked.
mCSSLoader->DropDocumentReference();
}
if (mStyleImageLoader) {
mStyleImageLoader->DropDocumentReference();
}
delete mHeaderData;
ClearAllBoxObjects();
mPendingTitleChangeEvent.Revoke();
mPlugins.Clear();
}
NS_INTERFACE_TABLE_HEAD(nsDocument)
NS_WRAPPERCACHE_INTERFACE_TABLE_ENTRY
NS_INTERFACE_TABLE_BEGIN
NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(nsDocument, nsISupports, nsINode)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsINode)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDocument)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMDocument)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMNode)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMDocumentXBL)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIScriptObjectPrincipal)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMEventTarget)
NS_INTERFACE_TABLE_ENTRY(nsDocument, mozilla::dom::EventTarget)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsISupportsWeakReference)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIRadioGroupContainer)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIMutationObserver)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIApplicationCacheContainer)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIObserver)
NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMXPathEvaluator)
NS_INTERFACE_TABLE_END
NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(nsDocument)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDocument)
NS_IMETHODIMP_(MozExternalRefCountType)
nsDocument::Release()
{
NS_PRECONDITION(0 != mRefCnt, "dup release");
NS_ASSERT_OWNINGTHREAD(nsDocument);
nsISupports* base = NS_CYCLE_COLLECTION_CLASSNAME(nsDocument)::Upcast(this);
bool shouldDelete = false;
nsrefcnt count = mRefCnt.decr(base, &shouldDelete);
NS_LOG_RELEASE(this, count, "nsDocument");
if (count == 0) {
if (mStackRefCnt && !mNeedsReleaseAfterStackRefCntRelease) {
mNeedsReleaseAfterStackRefCntRelease = true;
NS_ADDREF_THIS();
return mRefCnt.get();
}
mRefCnt.incr(base);
nsNodeUtils::LastRelease(this);
mRefCnt.decr(base);
if (shouldDelete) {
mRefCnt.stabilizeForDeletion();
DeleteCycleCollectable();
}
}
return count;
}
NS_IMETHODIMP_(void)
nsDocument::DeleteCycleCollectable()
{
delete this;
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsDocument)
if (Element::CanSkip(tmp, aRemovingAllowed)) {
EventListenerManager* elm = tmp->GetExistingListenerManager();
if (elm) {
elm->MarkForCC();
}
return true;
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsDocument)
return Element::CanSkipInCC(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsDocument)
return Element::CanSkipThis(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
static const char* kNSURIs[] = {
"([none])",
"(xmlns)",
"(xml)",
"(xhtml)",
"(XLink)",
"(XSLT)",
"(XBL)",
"(MathML)",
"(RDF)",
"(XUL)"
};
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsDocument)
if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
char name[512];
nsAutoCString loadedAsData;
if (tmp->IsLoadedAsData()) {
loadedAsData.AssignLiteral("data");
} else {
loadedAsData.AssignLiteral("normal");
}
uint32_t nsid = tmp->GetDefaultNamespaceID();
nsAutoCString uri;
if (tmp->mDocumentURI)
uri = tmp->mDocumentURI->GetSpecOrDefault();
if (nsid < ArrayLength(kNSURIs)) {
SprintfLiteral(name, "nsDocument %s %s %s",
loadedAsData.get(), kNSURIs[nsid], uri.get());
}
else {
SprintfLiteral(name, "nsDocument %s %s",
loadedAsData.get(), uri.get());
}
cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
}
else {
NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsDocument, tmp->mRefCnt.get())
}
if (!nsINode::Traverse(tmp, cb)) {
return NS_SUCCESS_INTERRUPTED_TRAVERSE;
}
if (tmp->mMaybeEndOutermostXBLUpdateRunner) {
// The cached runnable keeps a reference to the document object..
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb,
"mMaybeEndOutermostXBLUpdateRunner.mObj");
cb.NoteXPCOMChild(ToSupports(tmp));
}
for (auto iter = tmp->mIdentifierMap.ConstIter(); !iter.Done();
iter.Next()) {
iter.Get()->Traverse(&cb);
}
tmp->mExternalResourceMap.Traverse(&cb);
// Traverse the mChildren nsAttrAndChildArray.
for (int32_t indx = int32_t(tmp->mChildren.ChildCount()); indx > 0; --indx) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mChildren[i]");
cb.NoteXPCOMChild(tmp->mChildren.ChildAt(indx - 1));
}
// Traverse all nsIDocument pointer members.
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSecurityInfo)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDisplayDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFontFaceSet)
// Traverse all nsDocument nsCOMPtrs.
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParser)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mScriptGlobalObject)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mListenerManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDOMStyleSheets)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheetSetList)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mScriptLoader)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMasterDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mImportManager)
for (auto iter = tmp->mRadioGroups.Iter(); !iter.Done(); iter.Next()) {
nsRadioGroupStruct* radioGroup = iter.UserData();
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(
cb, "mRadioGroups entry->mSelectedRadioButton");
cb.NoteXPCOMChild(ToSupports(radioGroup->mSelectedRadioButton));
uint32_t i, count = radioGroup->mRadioButtons.Count();
for (i = 0; i < count; ++i) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(
cb, "mRadioGroups entry->mRadioButtons[i]");
cb.NoteXPCOMChild(radioGroup->mRadioButtons[i]);
}
}
// The boxobject for an element will only exist as long as it's in the
// document, so we'll traverse the table here instead of from the element.
if (tmp->mBoxObjectTable) {
for (auto iter = tmp->mBoxObjectTable->Iter(); !iter.Done(); iter.Next()) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mBoxObjectTable entry");
cb.NoteXPCOMChild(iter.UserData());
}
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChannel)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleAttrStyleSheet)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mXPathEvaluator)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLayoutHistoryState)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnloadBlocker)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFirstBaseNodeWithHref)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDOMImplementation)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mImageMaps)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOrientationPendingPromise)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOriginalDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCachedEncoder)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStateObjectCached)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentTimeline)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPendingAnimationTracker)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTemplateContentsOwner)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChildrenCollection)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAnonymousContents)
// Traverse all our nsCOMArrays.
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheets)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnDemandBuiltInUASheets)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPreloadingImages)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSubImportLinks)
for (uint32_t i = 0; i < tmp->mFrameRequestCallbacks.Length(); ++i) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mFrameRequestCallbacks[i]");
cb.NoteXPCOMChild(tmp->mFrameRequestCallbacks[i].mCallback);
}
// Traverse animation components
if (tmp->mAnimationController) {
tmp->mAnimationController->Traverse(&cb);
}
if (tmp->mSubDocuments) {
for (auto iter = tmp->mSubDocuments->Iter(); !iter.Done(); iter.Next()) {
auto entry = static_cast<SubDocMapEntry*>(iter.Get());
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb,
"mSubDocuments entry->mKey");
cb.NoteXPCOMChild(entry->mKey);
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb,
"mSubDocuments entry->mSubDocument");
cb.NoteXPCOMChild(entry->mSubDocument);
}
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCSSLoader)
// We own only the items in mDOMMediaQueryLists that have listeners;
// this reference is managed by their AddListener and RemoveListener
// methods.
for (PRCList *l = PR_LIST_HEAD(&tmp->mDOMMediaQueryLists);
l != &tmp->mDOMMediaQueryLists; l = PR_NEXT_LINK(l)) {
MediaQueryList *mql = static_cast<MediaQueryList*>(l);
if (mql->HasListeners()) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mDOMMediaQueryLists item");
cb.NoteXPCOMChild(mql);
}
}
if (tmp->mResizeObserverController) {
tmp->mResizeObserverController->Traverse(cb);
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_CLASS(nsDocument)
NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(nsDocument)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDocument)
tmp->mInUnlinkOrDeletion = true;
// Clear out our external resources
tmp->mExternalResourceMap.Shutdown();
nsAutoScriptBlocker scriptBlocker;
nsINode::Unlink(tmp);
// Unlink the mChildren nsAttrAndChildArray.
for (int32_t indx = int32_t(tmp->mChildren.ChildCount()) - 1;
indx >= 0; --indx) {
tmp->mChildren.ChildAt(indx)->UnbindFromTree();
tmp->mChildren.RemoveChildAt(indx);
}
tmp->mFirstChild = nullptr;
tmp->UnlinkOriginalDocumentIfStatic();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mXPathEvaluator)
tmp->mCachedRootElement = nullptr; // Avoid a dangling pointer
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDisplayDocument)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mFirstBaseNodeWithHref)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMaybeEndOutermostXBLUpdateRunner)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDOMImplementation)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mImageMaps)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCachedEncoder)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentTimeline)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingAnimationTracker)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTemplateContentsOwner)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mChildrenCollection)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMasterDocument)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mOrientationPendingPromise)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mImportManager)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSubImportLinks)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mFontFaceSet)
tmp->mParentDocument = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPreloadingImages)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mIntersectionObservers)
tmp->ClearAllBoxObjects();
if (tmp->mListenerManager) {
tmp->mListenerManager->Disconnect();
tmp->UnsetFlags(NODE_HAS_LISTENERMANAGER);
tmp->mListenerManager = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDOMStyleSheets)
if (tmp->mStyleSheetSetList) {
tmp->mStyleSheetSetList->Disconnect();
tmp->mStyleSheetSetList = nullptr;
}
delete tmp->mSubDocuments;
tmp->mSubDocuments = nullptr;
tmp->mFrameRequestCallbacks.Clear();
MOZ_RELEASE_ASSERT(!tmp->mFrameRequestCallbacksScheduled,
"How did we get here without our presshell going away "
"first?");
tmp->mRadioGroups.Clear();
// nsDocument has a pretty complex destructor, so we're going to
// assume that *most* cycles you actually want to break somewhere
// else, and not unlink an awful lot here.
tmp->mIdentifierMap.Clear();
tmp->mExpandoAndGeneration.OwnerUnlinked();
if (tmp->mAnimationController) {
tmp->mAnimationController->Unlink();
}
tmp->mPendingTitleChangeEvent.Revoke();
if (tmp->mCSSLoader) {
tmp->mCSSLoader->DropDocumentReference();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCSSLoader)
}
// We own only the items in mDOMMediaQueryLists that have listeners;
// this reference is managed by their AddListener and RemoveListener
// methods.
for (PRCList *l = PR_LIST_HEAD(&tmp->mDOMMediaQueryLists);
l != &tmp->mDOMMediaQueryLists; ) {
PRCList *next = PR_NEXT_LINK(l);
MediaQueryList *mql = static_cast<MediaQueryList*>(l);
mql->Disconnect();
l = next;
}
tmp->mInUnlinkOrDeletion = false;
if (tmp->mResizeObserverController) {
tmp->mResizeObserverController->Unlink();
}
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
nsresult
nsDocument::Init()
{
if (mCSSLoader || mStyleImageLoader || mNodeInfoManager || mScriptLoader) {
return NS_ERROR_ALREADY_INITIALIZED;
}
// Force initialization.
nsINode::nsSlots* slots = Slots();
// Prepend self as mutation-observer whether we need it or not (some
// subclasses currently do, other don't). This is because the code in
// nsNodeUtils always notifies the first observer first, expecting the
// first observer to be the document.
NS_ENSURE_TRUE(slots->mMutationObservers.PrependElementUnlessExists(static_cast<nsIMutationObserver*>(this)),
NS_ERROR_OUT_OF_MEMORY);
mOnloadBlocker = new nsOnloadBlocker();
mCSSLoader = new mozilla::css::Loader(this);
// Assume we're not quirky, until we know otherwise
mCSSLoader->SetCompatibilityMode(eCompatibility_FullStandards);
mStyleImageLoader = new mozilla::css::ImageLoader(this);
mNodeInfoManager = new nsNodeInfoManager();
nsresult rv = mNodeInfoManager->Init(this);
NS_ENSURE_SUCCESS(rv, rv);
// mNodeInfo keeps NodeInfoManager alive!
mNodeInfo = mNodeInfoManager->GetDocumentNodeInfo();
NS_ENSURE_TRUE(mNodeInfo, NS_ERROR_OUT_OF_MEMORY);
MOZ_ASSERT(mNodeInfo->NodeType() == nsIDOMNode::DOCUMENT_NODE,
"Bad NodeType in aNodeInfo");
NS_ASSERTION(OwnerDoc() == this, "Our nodeinfo is busted!");
// If after creation the owner js global is not set for a document
// we use the default compartment for this document, instead of creating
// wrapper in some random compartment when the document is exposed to js
// via some events.
nsCOMPtr<nsIGlobalObject> global = xpc::NativeGlobal(xpc::PrivilegedJunkScope());
NS_ENSURE_TRUE(global, NS_ERROR_FAILURE);
mScopeObject = do_GetWeakReference(global);
MOZ_ASSERT(mScopeObject);
mScriptLoader = new dom::ScriptLoader(this);
mozilla::HoldJSObjects(this);
return NS_OK;
}
void
nsIDocument::DeleteAllProperties()
{
for (uint32_t i = 0; i < GetPropertyTableCount(); ++i) {
PropertyTable(i)->DeleteAllProperties();
}
}
void
nsIDocument::DeleteAllPropertiesFor(nsINode* aNode)
{
for (uint32_t i = 0; i < GetPropertyTableCount(); ++i) {
PropertyTable(i)->DeleteAllPropertiesFor(aNode);
}
}
nsPropertyTable*
nsIDocument::GetExtraPropertyTable(uint16_t aCategory)
{
NS_ASSERTION(aCategory > 0, "Category 0 should have already been handled");
while (aCategory >= mExtraPropertyTables.Length() + 1) {
mExtraPropertyTables.AppendElement(new nsPropertyTable());
}
return mExtraPropertyTables[aCategory - 1];
}
bool
nsIDocument::IsVisibleConsideringAncestors() const
{
const nsIDocument *parent = this;
do {
if (!parent->IsVisible()) {
return false;
}
} while ((parent = parent->GetParentDocument()));
return true;
}
void
nsDocument::Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup)
{
nsCOMPtr<nsIURI> uri;
nsCOMPtr<nsIPrincipal> principal;
if (aChannel) {
// Note: this code is duplicated in XULDocument::StartDocumentLoad and
// nsScriptSecurityManager::GetChannelResultPrincipal.
// Note: this should match nsDocShell::OnLoadingSite
NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
nsIScriptSecurityManager *securityManager =
nsContentUtils::GetSecurityManager();
if (securityManager) {
securityManager->GetChannelResultPrincipal(aChannel,
getter_AddRefs(principal));
}
}
ResetToURI(uri, aLoadGroup, principal);
// Note that, since mTiming does not change during a reset, the
// navigationStart time remains unchanged and therefore any future new
// timeline will have the same global clock time as the old one.
mDocumentTimeline = nullptr;
nsCOMPtr<nsIPropertyBag2> bag = do_QueryInterface(aChannel);
if (bag) {
nsCOMPtr<nsIURI> baseURI;
bag->GetPropertyAsInterface(NS_LITERAL_STRING("baseURI"),
NS_GET_IID(nsIURI), getter_AddRefs(baseURI));
if (baseURI) {
mDocumentBaseURI = baseURI;
mChromeXHRDocBaseURI = nullptr;
}
}
mChannel = aChannel;
}
void
nsDocument::DisconnectNodeTree() {
// Delete references to sub-documents and kill the subdocument map,
// if any. This is not strictly needed, but makes the node tree
// teardown a bit faster.
delete mSubDocuments;
mSubDocuments = nullptr;
bool oldVal = mInUnlinkOrDeletion;
mInUnlinkOrDeletion = true;
uint32_t count = mChildren.ChildCount();
{ // Scope for update
MOZ_AUTO_DOC_UPDATE(this, UPDATE_CONTENT_MODEL, true);
// Destroy link map now so we don't waste time removing
// links one by one
DestroyElementMaps();
for (int32_t i = int32_t(count) - 1; i >= 0; i--) {
nsCOMPtr<nsIContent> content = mChildren.ChildAt(i);
nsIContent* previousSibling = content->GetPreviousSibling();
if (nsINode::GetFirstChild() == content) {
mFirstChild = content->GetNextSibling();
}
mChildren.RemoveChildAt(i);
if (content == mCachedRootElement) {
// Immediately clear mCachedRootElement, now that it's been removed
// from mChildren, so that GetRootElement() will stop returning this
// now-stale value.
mCachedRootElement = nullptr;
}
nsNodeUtils::ContentRemoved(this, content, i, previousSibling);
content->UnbindFromTree();
}
MOZ_ASSERT(!mCachedRootElement,
"After removing all children, there should be no root elem");
}
mInUnlinkOrDeletion = oldVal;
}
void
nsDocument::ResetToURI(nsIURI *aURI, nsILoadGroup *aLoadGroup,
nsIPrincipal* aPrincipal)
{
NS_PRECONDITION(aURI, "Null URI passed to ResetToURI");
if (gDocumentLeakPRLog && MOZ_LOG_TEST(gDocumentLeakPRLog, LogLevel::Debug)) {
PR_LogPrint("DOCUMENT %p ResetToURI %s", this,
aURI->GetSpecOrDefault().get());
}
mSecurityInfo = nullptr;
mDocumentLoadGroup = nullptr;
// Reset our stylesheets
ResetStylesheetsToURI(aURI);
// Release the listener manager
if (mListenerManager) {
mListenerManager->Disconnect();
mListenerManager = nullptr;
}
DisconnectNodeTree();
// Release the stylesheets list.
mDOMStyleSheets = nullptr;
// Release our principal after tearing down the document, rather than before.
// This ensures that, during teardown, the document and the dying window (which
// already nulled out its document pointer and cached the principal) have
// matching principals.
SetPrincipal(nullptr);
// Clear the original URI so SetDocumentURI sets it.
mOriginalURI = nullptr;
SetDocumentURI(aURI);
mChromeXHRDocURI = nullptr;
// If mDocumentBaseURI is null, nsIDocument::GetBaseURI() returns
// mDocumentURI.
mDocumentBaseURI = nullptr;
mChromeXHRDocBaseURI = nullptr;
if (aLoadGroup) {
mDocumentLoadGroup = do_GetWeakReference(aLoadGroup);
// there was an assertion here that aLoadGroup was not null. This
// is no longer valid: nsDocShell::SetDocument does not create a
// load group, and it works just fine
// XXXbz what does "just fine" mean exactly? And given that there
// is no nsDocShell::SetDocument, what is this talking about?
}
mLastModified.Truncate();
// XXXbz I guess we're assuming that the caller will either pass in
// a channel with a useful type or call SetContentType?
SetContentTypeInternal(EmptyCString());
mContentLanguage.Truncate();
mBaseTarget.Truncate();
mReferrer.Truncate();
mXMLDeclarationBits = 0;
// Now get our new principal
if (aPrincipal) {
SetPrincipal(aPrincipal);
} else {
nsIScriptSecurityManager *securityManager =
nsContentUtils::GetSecurityManager();
if (securityManager) {
nsCOMPtr<nsILoadContext> loadContext(mDocumentContainer);
if (!loadContext && aLoadGroup) {
nsCOMPtr<nsIInterfaceRequestor> cbs;
aLoadGroup->GetNotificationCallbacks(getter_AddRefs(cbs));
loadContext = do_GetInterface(cbs);
}
MOZ_ASSERT(loadContext,
"must have a load context or pass in an explicit principal");
nsCOMPtr<nsIPrincipal> principal;
nsresult rv = securityManager->
GetLoadContextCodebasePrincipal(mDocumentURI, loadContext,
getter_AddRefs(principal));
if (NS_SUCCEEDED(rv)) {
SetPrincipal(principal);
}
}
}
// Refresh the principal on the compartment.
if (nsPIDOMWindowInner* win = GetInnerWindow()) {
nsGlobalWindow::Cast(win)->RefreshCompartmentPrincipal();
}
}
void
nsDocument::RemoveDocStyleSheetsFromStyleSets()
{
// The stylesheets should forget us
for (StyleSheet* sheet : Reversed(mStyleSheets)) {
sheet->SetOwningDocument(nullptr);
if (sheet->IsApplicable()) {
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
shell->StyleSet()->RemoveDocStyleSheet(sheet);
}
}
// XXX Tell observers?
}
}
void
nsDocument::RemoveStyleSheetsFromStyleSets(
const nsTArray<RefPtr<StyleSheet>>& aSheets,
SheetType aType)
{
// The stylesheets should forget us
for (StyleSheet* sheet : Reversed(aSheets)) {
sheet->SetOwningDocument(nullptr);
if (sheet->IsApplicable()) {
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
shell->StyleSet()->RemoveStyleSheet(aType, sheet);
}
}
// XXX Tell observers?
}
}
void
nsDocument::ResetStylesheetsToURI(nsIURI* aURI)
{
MOZ_ASSERT(aURI);
mozAutoDocUpdate upd(this, UPDATE_STYLE, true);
if (mStyleSetFilled) {
// Skip removing style sheets from the style set if we know we haven't
// filled the style set. (This allows us to avoid calling
// GetStyleBackendType() too early.)
RemoveDocStyleSheetsFromStyleSets();
RemoveStyleSheetsFromStyleSets(mOnDemandBuiltInUASheets, SheetType::Agent);
RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eAgentSheet], SheetType::Agent);
RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eUserSheet], SheetType::User);
RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eAuthorSheet], SheetType::Doc);
if (GetStyleBackendType() == StyleBackendType::Gecko) {
nsStyleSheetService *sheetService = nsStyleSheetService::GetInstance();
if (sheetService) {
RemoveStyleSheetsFromStyleSets(*sheetService->AuthorStyleSheets(), SheetType::Doc);
}
} else {
NS_ERROR("stylo: nsStyleSheetService doesn't handle ServoStyleSheets yet");
}
mStyleSetFilled = false;
}
// Release all the sheets
mStyleSheets.Clear();
mOnDemandBuiltInUASheets.Clear();
for (auto& sheets : mAdditionalSheets) {
sheets.Clear();
}
// NOTE: We don't release the catalog sheets. It doesn't really matter
// now, but it could in the future -- in which case not releasing them
// is probably the right thing to do.
// Now reset our inline style and attribute sheets.
if (mAttrStyleSheet) {
mAttrStyleSheet->Reset();
mAttrStyleSheet->SetOwningDocument(this);
} else {
mAttrStyleSheet = new nsHTMLStyleSheet(this);
}
if (!mStyleAttrStyleSheet) {
mStyleAttrStyleSheet = new nsHTMLCSSStyleSheet();
}
if (!mSVGAttrAnimationRuleProcessor) {
mSVGAttrAnimationRuleProcessor =
new mozilla::SVGAttrAnimationRuleProcessor();
}
// Now set up our style sets
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
FillStyleSet(shell->StyleSet());
}
}
static void
AppendSheetsToStyleSet(StyleSetHandle aStyleSet,
const nsTArray<RefPtr<StyleSheet>>& aSheets,
SheetType aType)
{
for (StyleSheet* sheet : Reversed(aSheets)) {
aStyleSet->AppendStyleSheet(aType, sheet);
}
}
void
nsDocument::FillStyleSet(StyleSetHandle aStyleSet)
{
NS_PRECONDITION(aStyleSet, "Must have a style set");
NS_PRECONDITION(aStyleSet->SheetCount(SheetType::Doc) == 0,
"Style set already has document sheets?");
MOZ_ASSERT(!mStyleSetFilled);
for (StyleSheet* sheet : Reversed(mStyleSheets)) {
if (sheet->IsApplicable()) {
aStyleSet->AddDocStyleSheet(sheet, this);
}
}
if (aStyleSet->IsGecko()) {
nsStyleSheetService *sheetService = nsStyleSheetService::GetInstance();
if (sheetService) {
for (StyleSheet* sheet : *sheetService->AuthorStyleSheets()) {
aStyleSet->AppendStyleSheet(SheetType::Doc, sheet);
}
}
// Iterate backwards to maintain order
for (StyleSheet* sheet : Reversed(mOnDemandBuiltInUASheets)) {
if (sheet->IsApplicable()) {
aStyleSet->PrependStyleSheet(SheetType::Agent, sheet);
}
}
} else {
NS_WARNING("stylo: Not yet checking nsStyleSheetService for Servo-backed "
"documents. See bug 1290224");
}
AppendSheetsToStyleSet(aStyleSet, mAdditionalSheets[eAgentSheet],
SheetType::Agent);
AppendSheetsToStyleSet(aStyleSet, mAdditionalSheets[eUserSheet],
SheetType::User);
AppendSheetsToStyleSet(aStyleSet, mAdditionalSheets[eAuthorSheet],
SheetType::Doc);
mStyleSetFilled = true;
}
static void
WarnIfSandboxIneffective(nsIDocShell* aDocShell,
uint32_t aSandboxFlags,
nsIChannel* aChannel)
{
// If the document is sandboxed (via the HTML5 iframe sandbox
// attribute) and both the allow-scripts and allow-same-origin
// keywords are supplied, the sandboxed document can call into its
// parent document and remove its sandboxing entirely - we print a
// warning to the web console in this case.
if (aSandboxFlags & SANDBOXED_NAVIGATION &&
!(aSandboxFlags & SANDBOXED_SCRIPTS) &&
!(aSandboxFlags & SANDBOXED_ORIGIN)) {
nsCOMPtr<nsIDocShellTreeItem> parentAsItem;
aDocShell->GetSameTypeParent(getter_AddRefs(parentAsItem));
nsCOMPtr<nsIDocShell> parentDocShell = do_QueryInterface(parentAsItem);
if (!parentDocShell) {
return;
}
// Don't warn if our parent is not the top-level document.
nsCOMPtr<nsIDocShellTreeItem> grandParentAsItem;
parentDocShell->GetSameTypeParent(getter_AddRefs(grandParentAsItem));
if (grandParentAsItem) {
return;
}
nsCOMPtr<nsIChannel> parentChannel;
parentDocShell->GetCurrentDocumentChannel(getter_AddRefs(parentChannel));
if (!parentChannel) {
return;
}
nsresult rv = nsContentUtils::CheckSameOrigin(aChannel, parentChannel);
if (NS_FAILED(rv)) {
return;
}
nsCOMPtr<nsIDocument> parentDocument = parentDocShell->GetDocument();
nsCOMPtr<nsIURI> iframeUri;
parentChannel->GetURI(getter_AddRefs(iframeUri));
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("Iframe Sandbox"),
parentDocument,
nsContentUtils::eSECURITY_PROPERTIES,
"BothAllowScriptsAndSameOriginPresent",
nullptr, 0, iframeUri);
}
}
nsresult
nsDocument::StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
nsILoadGroup* aLoadGroup,
nsISupports* aContainer,
nsIStreamListener **aDocListener,
bool aReset, nsIContentSink* aSink)
{
if (gDocumentLeakPRLog && MOZ_LOG_TEST(gDocumentLeakPRLog, LogLevel::Debug)) {
nsCOMPtr<nsIURI> uri;
aChannel->GetURI(getter_AddRefs(uri));
PR_LogPrint("DOCUMENT %p StartDocumentLoad %s",
this, uri ? uri->GetSpecOrDefault().get() : "");
}
MOZ_ASSERT(NodePrincipal()->GetAppId() != nsIScriptSecurityManager::UNKNOWN_APP_ID,
"Document should never have UNKNOWN_APP_ID");
MOZ_ASSERT(GetReadyStateEnum() == nsIDocument::READYSTATE_UNINITIALIZED,
"Bad readyState");
SetReadyStateInternal(READYSTATE_LOADING);
if (nsCRT::strcmp(kLoadAsData, aCommand) == 0) {
mLoadedAsData = true;
// We need to disable script & style loading in this case.
// We leave them disabled even in EndLoad(), and let anyone
// who puts the document on display to worry about enabling.
// Do not load/process scripts when loading as data
ScriptLoader()->SetEnabled(false);
// styles
CSSLoader()->SetEnabled(false); // Do not load/process styles when loading as data
} else if (nsCRT::strcmp("external-resource", aCommand) == 0) {
// Allow CSS, but not scripts
ScriptLoader()->SetEnabled(false);
}
mMayStartLayout = false;
if (aReset) {
Reset(aChannel, aLoadGroup);
}
nsAutoCString contentType;
nsCOMPtr<nsIPropertyBag2> bag = do_QueryInterface(aChannel);
if ((bag && NS_SUCCEEDED(bag->GetPropertyAsACString(
NS_LITERAL_STRING("contentType"), contentType))) ||
NS_SUCCEEDED(aChannel->GetContentType(contentType))) {
// XXX this is only necessary for viewsource:
nsACString::const_iterator start, end, semicolon;
contentType.BeginReading(start);
contentType.EndReading(end);
semicolon = start;
FindCharInReadable(';', semicolon, end);
SetContentTypeInternal(Substring(start, semicolon));
}
RetrieveRelevantHeaders(aChannel);
mChannel = aChannel;
nsCOMPtr<nsIInputStreamChannel> inStrmChan = do_QueryInterface(mChannel);
if (inStrmChan) {
bool isSrcdocChannel;
inStrmChan->GetIsSrcdocChannel(&isSrcdocChannel);
if (isSrcdocChannel) {
mIsSrcdocDocument = true;
}
}
// If this document is being loaded by a docshell, copy its sandbox flags
// to the document, and store the fullscreen enabled flag. These are
// immutable after being set here.
nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(aContainer);
// If this is an error page, don't inherit sandbox flags from docshell
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
if (docShell && !(loadInfo && loadInfo->GetLoadErrorPage())) {
nsresult rv = docShell->GetSandboxFlags(&mSandboxFlags);
NS_ENSURE_SUCCESS(rv, rv);
WarnIfSandboxIneffective(docShell, mSandboxFlags, GetChannel());
}
// The CSP directive upgrade-insecure-requests not only applies to the
// toplevel document, but also to nested documents. Let's propagate that
// flag from the parent to the nested document.
nsCOMPtr<nsIDocShellTreeItem> treeItem = this->GetDocShell();
if (treeItem) {
nsCOMPtr<nsIDocShellTreeItem> sameTypeParent;
treeItem->GetSameTypeParent(getter_AddRefs(sameTypeParent));
if (sameTypeParent) {
nsIDocument* doc = sameTypeParent->GetDocument();
mBlockAllMixedContent = doc->GetBlockAllMixedContent(false);
// if the parent document makes use of block-all-mixed-content
// then subdocument preloads should always be blocked.
mBlockAllMixedContentPreloads =
mBlockAllMixedContent || doc->GetBlockAllMixedContent(true);
mUpgradeInsecureRequests = doc->GetUpgradeInsecureRequests(false);
// if the parent document makes use of upgrade-insecure-requests
// then subdocument preloads should always be upgraded.
mUpgradeInsecurePreloads =
mUpgradeInsecureRequests || doc->GetUpgradeInsecureRequests(true);
}
}
// If this is not a data document, set CSP.
if (!mLoadedAsData) {
nsresult rv = InitCSP(aChannel);
NS_ENSURE_SUCCESS(rv, rv);
}
// XFO needs to be checked after CSP because it is ignored if
// the CSP defines frame-ancestors.
if (!nsDSURIContentListener::CheckFrameOptions(aChannel, docShell, NodePrincipal())) {
MOZ_LOG(gCspPRLog, LogLevel::Debug,
("XFO doesn't like frame's ancestry, not loading."));
// stop! ERROR page!
aChannel->Cancel(NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION);
}
return NS_OK;
}
void
nsDocument::SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages)
{
for (uint32_t i = 0; i < aMessages.Length(); ++i) {
nsAutoString messageTag;
aMessages[i]->GetTag(messageTag);
nsAutoString category;
aMessages[i]->GetCategory(category);
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_ConvertUTF16toUTF8(category),
this, nsContentUtils::eSECURITY_PROPERTIES,
NS_ConvertUTF16toUTF8(messageTag).get());
}
}
void
nsDocument::ApplySettingsFromCSP(bool aSpeculative)
{
nsresult rv = NS_OK;
if (!aSpeculative) {
// 1) apply settings from regular CSP
nsCOMPtr<nsIContentSecurityPolicy> csp;
rv = NodePrincipal()->GetCsp(getter_AddRefs(csp));
NS_ENSURE_SUCCESS_VOID(rv);
if (csp) {
// Set up any Referrer Policy specified by CSP
bool hasReferrerPolicy = false;
uint32_t referrerPolicy = mozilla::net::RP_Default;
rv = csp->GetReferrerPolicy(&referrerPolicy, &hasReferrerPolicy);
NS_ENSURE_SUCCESS_VOID(rv);
if (hasReferrerPolicy) {
mReferrerPolicy = static_cast<ReferrerPolicy>(referrerPolicy);
mReferrerPolicySet = true;
}
// Set up 'block-all-mixed-content' if not already inherited
// from the parent context or set by any other CSP.
if (!mBlockAllMixedContent) {
rv = csp->GetBlockAllMixedContent(&mBlockAllMixedContent);
NS_ENSURE_SUCCESS_VOID(rv);
}
if (!mBlockAllMixedContentPreloads) {
mBlockAllMixedContentPreloads = mBlockAllMixedContent;
}
// Set up 'upgrade-insecure-requests' if not already inherited
// from the parent context or set by any other CSP.
if (!mUpgradeInsecureRequests) {
rv = csp->GetUpgradeInsecureRequests(&mUpgradeInsecureRequests);
NS_ENSURE_SUCCESS_VOID(rv);
}
if (!mUpgradeInsecurePreloads) {
mUpgradeInsecurePreloads = mUpgradeInsecureRequests;
}
}
return;
}
// 2) apply settings from speculative csp
nsCOMPtr<nsIContentSecurityPolicy> preloadCsp;
rv = NodePrincipal()->GetPreloadCsp(getter_AddRefs(preloadCsp));
NS_ENSURE_SUCCESS_VOID(rv);
if (preloadCsp) {
if (!mBlockAllMixedContentPreloads) {
rv = preloadCsp->GetBlockAllMixedContent(&mBlockAllMixedContentPreloads);
NS_ENSURE_SUCCESS_VOID(rv);
}
if (!mUpgradeInsecurePreloads) {
rv = preloadCsp->GetUpgradeInsecureRequests(&mUpgradeInsecurePreloads);
NS_ENSURE_SUCCESS_VOID(rv);
}
}
}
nsresult
nsDocument::InitCSP(nsIChannel* aChannel)
{
MOZ_ASSERT(!mScriptGlobalObject,
"CSP must be initialized before mScriptGlobalObject is set!");
if (!CSPService::sCSPEnabled) {
MOZ_LOG(gCspPRLog, LogLevel::Debug,
("CSP is disabled, skipping CSP init for document %p", this));
return NS_OK;
}
nsAutoCString tCspHeaderValue, tCspROHeaderValue;
nsCOMPtr<nsIHttpChannel> httpChannel;
nsresult rv = GetHttpChannelHelper(aChannel, getter_AddRefs(httpChannel));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (httpChannel) {
httpChannel->GetResponseHeader(
NS_LITERAL_CSTRING("content-security-policy"),
tCspHeaderValue);
httpChannel->GetResponseHeader(
NS_LITERAL_CSTRING("content-security-policy-report-only"),
tCspROHeaderValue);
}
NS_ConvertASCIItoUTF16 cspHeaderValue(tCspHeaderValue);
NS_ConvertASCIItoUTF16 cspROHeaderValue(tCspROHeaderValue);
// Check if this is a document from a WebExtension.
nsString addonId;
nsCOMPtr<nsIPrincipal> principal = NodePrincipal();
principal->GetAddonId(addonId);
bool applyAddonCSP = !addonId.IsEmpty();
// Check if this is a signed content to apply default CSP.
bool applySignedContentCSP = false;
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
if (loadInfo && loadInfo->GetVerifySignedContent()) {
applySignedContentCSP = true;
}
// If there's no CSP to apply, go ahead and return early
if (!applyAddonCSP &&
!applySignedContentCSP &&
cspHeaderValue.IsEmpty() &&
cspROHeaderValue.IsEmpty()) {
if (MOZ_LOG_TEST(gCspPRLog, LogLevel::Debug)) {
nsCOMPtr<nsIURI> chanURI;
aChannel->GetURI(getter_AddRefs(chanURI));
nsAutoCString aspec;
chanURI->GetAsciiSpec(aspec);
MOZ_LOG(gCspPRLog, LogLevel::Debug,
("no CSP for document, %s",
aspec.get()));
}
return NS_OK;
}
MOZ_LOG(gCspPRLog, LogLevel::Debug, ("Document is an add-on or CSP header specified %p", this));
nsCOMPtr<nsIContentSecurityPolicy> csp;
rv = principal->EnsureCSP(this, getter_AddRefs(csp));
NS_ENSURE_SUCCESS(rv, rv);
// ----- if the doc is an addon, apply its CSP.
if (applyAddonCSP) {
nsCOMPtr<nsIAddonPolicyService> aps = do_GetService("@mozilla.org/addons/policy-service;1");
nsAutoString addonCSP;
rv = aps->GetBaseCSP(addonCSP);
if (NS_SUCCEEDED(rv)) {
csp->AppendPolicy(addonCSP, false, false);
}
rv = aps->GetAddonCSP(addonId, addonCSP);
if (NS_SUCCEEDED(rv)) {
csp->AppendPolicy(addonCSP, false, false);
}
}
// ----- if the doc is a signed content, apply the default CSP.
// Note that when the content signing becomes a standard, we might have
// to restrict this enforcement to "remote content" only.
if (applySignedContentCSP) {
nsAdoptingString signedContentCSP =
Preferences::GetString("security.signed_content.CSP.default");
csp->AppendPolicy(signedContentCSP, false, false);
}
// ----- if there's a full-strength CSP header, apply it.
if (!cspHeaderValue.IsEmpty()) {
rv = CSP_AppendCSPFromHeader(csp, cspHeaderValue, false);
NS_ENSURE_SUCCESS(rv, rv);
}
// ----- if there's a report-only CSP header, apply it.
if (!cspROHeaderValue.IsEmpty()) {
rv = CSP_AppendCSPFromHeader(csp, cspROHeaderValue, true);
NS_ENSURE_SUCCESS(rv, rv);
}
// ----- Enforce sandbox policy if supplied in CSP header
// The document may already have some sandbox flags set (e.g. if the document
// is an iframe with the sandbox attribute set). If we have a CSP sandbox
// directive, intersect the CSP sandbox flags with the existing flags. This
// corresponds to the _least_ permissive policy.
uint32_t cspSandboxFlags = SANDBOXED_NONE;
rv = csp->GetCSPSandboxFlags(&cspSandboxFlags);
NS_ENSURE_SUCCESS(rv, rv);
// Probably the iframe sandbox attribute already caused the creation of a
// new NullPrincipal. Only create a new NullPrincipal if CSP requires so
// and no one has been created yet.
bool needNewNullPrincipal =
(cspSandboxFlags & SANDBOXED_ORIGIN) && !(mSandboxFlags & SANDBOXED_ORIGIN);
mSandboxFlags |= cspSandboxFlags;
if (needNewNullPrincipal) {
principal = nsNullPrincipal::CreateWithInheritedAttributes(principal);
principal->SetCsp(csp);
SetPrincipal(principal);
}
// ----- Enforce frame-ancestor policy on any applied policies
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell) {
bool safeAncestry = false;
// PermitsAncestry sends violation reports when necessary
rv = csp->PermitsAncestry(docShell, &safeAncestry);
if (NS_FAILED(rv) || !safeAncestry) {
MOZ_LOG(gCspPRLog, LogLevel::Debug,
("CSP doesn't like frame's ancestry, not loading."));
// stop! ERROR page!
aChannel->Cancel(NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION);
}
}
ApplySettingsFromCSP(false);
return NS_OK;
}
void
nsDocument::StopDocumentLoad()
{
if (mParser) {
mParserAborted = true;
mParser->Terminate();
}
}
void
nsDocument::SetDocumentURI(nsIURI* aURI)
{
nsCOMPtr<nsIURI> oldBase = GetDocBaseURI();
mDocumentURI = NS_TryToMakeImmutable(aURI);
nsIURI* newBase = GetDocBaseURI();
bool equalBases = false;
// Changing just the ref of a URI does not change how relative URIs would
// resolve wrt to it, so we can treat the bases as equal as long as they're
// equal ignoring the ref.
if (oldBase && newBase) {
oldBase->EqualsExceptRef(newBase, &equalBases);
}
else {
equalBases = !oldBase && !newBase;
}
// If this is the first time we're setting the document's URI, set the
// document's original URI.
if (!mOriginalURI)
mOriginalURI = mDocumentURI;
// If changing the document's URI changed the base URI of the document, we
// need to refresh the hrefs of all the links on the page.
if (!equalBases) {
RefreshLinkHrefs();
}
}
void
nsDocument::SetChromeXHRDocURI(nsIURI* aURI)
{
mChromeXHRDocURI = aURI;
}
void
nsDocument::SetChromeXHRDocBaseURI(nsIURI* aURI)
{
mChromeXHRDocBaseURI = aURI;
}
NS_IMETHODIMP
nsDocument::GetLastModified(nsAString& aLastModified)
{
nsIDocument::GetLastModified(aLastModified);
return NS_OK;
}
static void
GetFormattedTimeString(PRTime aTime, nsAString& aFormattedTimeString)
{
PRExplodedTime prtime;
PR_ExplodeTime(aTime, PR_LocalTimeParameters, &prtime);
// "MM/DD/YYYY hh:mm:ss"
char formatedTime[24];
if (SprintfLiteral(formatedTime, "%02d/%02d/%04d %02d:%02d:%02d",
prtime.tm_month + 1, prtime.tm_mday, int(prtime.tm_year),
prtime.tm_hour , prtime.tm_min, prtime.tm_sec)) {
CopyASCIItoUTF16(nsDependentCString(formatedTime), aFormattedTimeString);
} else {
// If we for whatever reason failed to find the last modified time
// (or even the current time), fall back to what NS4.x returned.
aFormattedTimeString.AssignLiteral(u"01/01/1970 00:00:00");
}
}
void
nsIDocument::GetLastModified(nsAString& aLastModified) const
{
if (!mLastModified.IsEmpty()) {
aLastModified.Assign(mLastModified);
} else {
GetFormattedTimeString(PR_Now(), aLastModified);
}
}
void
nsDocument::AddToNameTable(Element *aElement, nsIAtom* aName)
{
MOZ_ASSERT(nsGenericHTMLElement::ShouldExposeNameAsHTMLDocumentProperty(aElement),
"Only put elements that need to be exposed as document['name'] in "
"the named table.");
nsIdentifierMapEntry *entry =
mIdentifierMap.PutEntry(nsDependentAtomString(aName));
// Null for out-of-memory
if (entry) {
if (!entry->HasNameElement() &&
!entry->HasIdElementExposedAsHTMLDocumentProperty()) {
++mExpandoAndGeneration.generation;
}
entry->AddNameElement(this, aElement);
}
}
void
nsDocument::RemoveFromNameTable(Element *aElement, nsIAtom* aName)
{
// Speed up document teardown
if (mIdentifierMap.Count() == 0)
return;
nsIdentifierMapEntry *entry =
mIdentifierMap.GetEntry(nsDependentAtomString(aName));
if (!entry) // Could be false if the element was anonymous, hence never added
return;
entry->RemoveNameElement(aElement);
if (!entry->HasNameElement() &&
!entry->HasIdElementExposedAsHTMLDocumentProperty()) {
++mExpandoAndGeneration.generation;
}
}
void
nsDocument::AddToIdTable(Element *aElement, nsIAtom* aId)
{
nsIdentifierMapEntry *entry =
mIdentifierMap.PutEntry(nsDependentAtomString(aId));
if (entry) { /* True except on OOM */
if (nsGenericHTMLElement::ShouldExposeIdAsHTMLDocumentProperty(aElement) &&
!entry->HasNameElement() &&
!entry->HasIdElementExposedAsHTMLDocumentProperty()) {
++mExpandoAndGeneration.generation;
}
entry->AddIdElement(aElement);
}
}
void
nsDocument::RemoveFromIdTable(Element *aElement, nsIAtom* aId)
{
NS_ASSERTION(aId, "huhwhatnow?");
// Speed up document teardown
if (mIdentifierMap.Count() == 0) {
return;
}
nsIdentifierMapEntry *entry =
mIdentifierMap.GetEntry(nsDependentAtomString(aId));
if (!entry) // Can be null for XML elements with changing ids.
return;
entry->RemoveIdElement(aElement);
if (nsGenericHTMLElement::ShouldExposeIdAsHTMLDocumentProperty(aElement) &&
!entry->HasNameElement() &&
!entry->HasIdElementExposedAsHTMLDocumentProperty()) {
++mExpandoAndGeneration.generation;
}
if (entry->IsEmpty()) {
mIdentifierMap.RemoveEntry(entry);
}
}
nsIPrincipal*
nsDocument::GetPrincipal()
{
return NodePrincipal();
}
extern bool sDisablePrefetchHTTPSPref;
void
nsDocument::SetPrincipal(nsIPrincipal *aNewPrincipal)
{
if (aNewPrincipal && mAllowDNSPrefetch && sDisablePrefetchHTTPSPref) {
nsCOMPtr<nsIURI> uri;
aNewPrincipal->GetURI(getter_AddRefs(uri));
bool isHTTPS;
if (!uri || NS_FAILED(uri->SchemeIs("https", &isHTTPS)) ||
isHTTPS) {
mAllowDNSPrefetch = false;
}
}
mNodeInfoManager->SetDocumentPrincipal(aNewPrincipal);
#ifdef DEBUG
// Validate that the docgroup is set correctly by calling its getter and
// triggering its sanity check.
//
// If we're setting the principal to null, we don't want to perform the check,
// as the document is entering an intermediate state where it does not have a
// principal. It will be given another real principal shortly which we will
// check. It's not unsafe to have a document which has a null principal in the
// same docgroup as another document, so this should not be a problem.
if (aNewPrincipal) {
GetDocGroup();
}
#endif
}
mozilla::dom::DocGroup*
nsIDocument::GetDocGroup()
{
#ifdef DEBUG
// Sanity check that we have an up-to-date and accurate docgroup
if (mDocGroup) {
nsAutoCString docGroupKey;
mozilla::dom::DocGroup::GetKey(NodePrincipal(), docGroupKey);
MOZ_ASSERT(mDocGroup->MatchesKey(docGroupKey));
// XXX: Check that the TabGroup is correct as well!
}
#endif
return mDocGroup;
}
NS_IMETHODIMP
nsDocument::GetApplicationCache(nsIApplicationCache **aApplicationCache)
{
NS_IF_ADDREF(*aApplicationCache = mApplicationCache);
return NS_OK;
}
NS_IMETHODIMP
nsDocument::SetApplicationCache(nsIApplicationCache *aApplicationCache)
{
mApplicationCache = aApplicationCache;
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetContentType(nsAString& aContentType)
{
CopyUTF8toUTF16(GetContentTypeInternal(), aContentType);
return NS_OK;
}
void
nsDocument::SetContentType(const nsAString& aContentType)
{
SetContentTypeInternal(NS_ConvertUTF16toUTF8(aContentType));
}
nsresult
nsDocument::GetAllowPlugins(bool * aAllowPlugins)
{
// First, we ask our docshell if it allows plugins.
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell) {
docShell->GetAllowPlugins(aAllowPlugins);
// If the docshell allows plugins, we check whether
// we are sandboxed and plugins should not be allowed.
if (*aAllowPlugins)
*aAllowPlugins = !(mSandboxFlags & SANDBOXED_PLUGINS);
}
return NS_OK;
}
bool
nsDocument::IsElementAnimateEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
Preferences::GetBool("dom.animations-api.core.enabled") ||
Preferences::GetBool("dom.animations-api.element-animate.enabled");
}
bool
nsDocument::IsWebAnimationsEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
Preferences::GetBool("dom.animations-api.core.enabled");
}
DocumentTimeline*
nsDocument::Timeline()
{
if (!mDocumentTimeline) {
mDocumentTimeline = new DocumentTimeline(this, TimeDuration(0));
}
return mDocumentTimeline;
}
void
nsDocument::GetAnimations(nsTArray<RefPtr<Animation>>& aAnimations)
{
// Hold a strong ref for the root element since Element::GetAnimations() calls
// FlushPendingNotifications() which may destroy the element.
RefPtr<Element> root = GetRootElement();
if (!root) {
return;
}
AnimationFilter filter;
filter.mSubtree = true;
root->GetAnimations(filter, aAnimations);
}
SVGSVGElement*
nsIDocument::GetSVGRootElement() const
{
Element* root = GetRootElement();
if (!root || !root->IsSVGElement(nsGkAtoms::svg)) {
return nullptr;
}
return static_cast<SVGSVGElement*>(root);
}
/* Return true if the document is in the focused top-level window, and is an
* ancestor of the focused DOMWindow. */
NS_IMETHODIMP
nsDocument::HasFocus(bool* aResult)
{
ErrorResult rv;
*aResult = nsIDocument::HasFocus(rv);
return rv.StealNSResult();
}
bool
nsIDocument::HasFocus(ErrorResult& rv) const
{
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
rv.Throw(NS_ERROR_NOT_AVAILABLE);
return false;
}
// Is there a focused DOMWindow?
nsCOMPtr<mozIDOMWindowProxy> focusedWindow;
fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
if (!focusedWindow) {
return false;
}
nsPIDOMWindowOuter* piWindow = nsPIDOMWindowOuter::From(focusedWindow);
// Are we an ancestor of the focused DOMWindow?
for (nsIDocument* currentDoc = piWindow->GetDoc(); currentDoc;
currentDoc = currentDoc->GetParentDocument()) {
if (currentDoc == this) {
// Yes, we are an ancestor
return true;
}
}
return false;
}
NS_IMETHODIMP
nsDocument::GetReferrer(nsAString& aReferrer)
{
nsIDocument::GetReferrer(aReferrer);
return NS_OK;
}
void
nsIDocument::GetReferrer(nsAString& aReferrer) const
{
if (mIsSrcdocDocument && mParentDocument)
mParentDocument->GetReferrer(aReferrer);
else
CopyUTF8toUTF16(mReferrer, aReferrer);
}
nsresult
nsIDocument::GetSrcdocData(nsAString &aSrcdocData)
{
if (mIsSrcdocDocument) {
nsCOMPtr<nsIInputStreamChannel> inStrmChan = do_QueryInterface(mChannel);
if (inStrmChan) {
return inStrmChan->GetSrcdocData(aSrcdocData);
}
}
aSrcdocData = NullString();
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetActiveElement(nsIDOMElement **aElement)
{
nsCOMPtr<nsIDOMElement> el(do_QueryInterface(nsIDocument::GetActiveElement()));
el.forget(aElement);
return NS_OK;
}
Element*
nsIDocument::GetActiveElement()
{
// Get the focused element.
if (nsCOMPtr<nsPIDOMWindowOuter> window = GetWindow()) {
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
nsIContent* focusedContent =
nsFocusManager::GetFocusedDescendant(window, false,
getter_AddRefs(focusedWindow));
// be safe and make sure the element is from this document
if (focusedContent && focusedContent->OwnerDoc() == this) {
if (focusedContent->ChromeOnlyAccess()) {
focusedContent = focusedContent->FindFirstNonChromeOnlyAccessContent();
}
if (focusedContent) {
return focusedContent->AsElement();
}
}
}
// No focused element anywhere in this document. Try to get the BODY.
RefPtr<nsHTMLDocument> htmlDoc = AsHTMLDocument();
if (htmlDoc) {
// Because of IE compatibility, return null when html document doesn't have
// a body.
return htmlDoc->GetBody();
}
// If we couldn't get a BODY, return the root element.
return GetDocumentElement();
}
NS_IMETHODIMP
nsDocument::GetCurrentScript(nsIDOMElement **aElement)
{
nsCOMPtr<nsIDOMElement> el(do_QueryInterface(nsIDocument::GetCurrentScript()));
el.forget(aElement);
return NS_OK;
}
Element*
nsIDocument::GetCurrentScript()
{
nsCOMPtr<Element> el(do_QueryInterface(ScriptLoader()->GetCurrentScript()));
return el;
}
NS_IMETHODIMP
nsDocument::ElementFromPoint(float aX, float aY, nsIDOMElement** aReturn)
{
Element* el = nsIDocument::ElementFromPoint(aX, aY);
nsCOMPtr<nsIDOMElement> retval = do_QueryInterface(el);
retval.forget(aReturn);
return NS_OK;
}
Element*
nsIDocument::ElementFromPoint(float aX, float aY)
{
return ElementFromPointHelper(aX, aY, false, true);
}
void
nsIDocument::ElementsFromPoint(float aX, float aY,
nsTArray<RefPtr<Element>>& aElements)
{
ElementsFromPointHelper(aX, aY, nsIDocument::FLUSH_LAYOUT, aElements);
}
Element*
nsDocument::ElementFromPointHelper(float aX, float aY,
bool aIgnoreRootScrollFrame,
bool aFlushLayout)
{
AutoTArray<RefPtr<Element>, 1> elementArray;
ElementsFromPointHelper(aX, aY,
((aIgnoreRootScrollFrame ? nsIDocument::IGNORE_ROOT_SCROLL_FRAME : 0) |
(aFlushLayout ? nsIDocument::FLUSH_LAYOUT : 0) |
nsIDocument::IS_ELEMENT_FROM_POINT),
elementArray);
if (elementArray.IsEmpty()) {
return nullptr;
}
return elementArray[0];
}
void
nsDocument::ElementsFromPointHelper(float aX, float aY,
uint32_t aFlags,
nsTArray<RefPtr<mozilla::dom::Element>>& aElements)
{
// As per the the spec, we return null if either coord is negative
if (!(aFlags & nsIDocument::IGNORE_ROOT_SCROLL_FRAME) && (aX < 0 || aY < 0)) {
return;
}
nscoord x = nsPresContext::CSSPixelsToAppUnits(aX);
nscoord y = nsPresContext::CSSPixelsToAppUnits(aY);
nsPoint pt(x, y);
// Make sure the layout information we get is up-to-date, and
// ensure we get a root frame (for everything but XUL)
if (aFlags & nsIDocument::FLUSH_LAYOUT) {
FlushPendingNotifications(Flush_Layout);
}
nsIPresShell *ps = GetShell();
if (!ps) {
return;
}
nsIFrame *rootFrame = ps->GetRootFrame();
// XUL docs, unlike HTML, have no frame tree until everything's done loading
if (!rootFrame) {
return; // return null to premature XUL callers as a reminder to wait
}
nsTArray<nsIFrame*> outFrames;
// Emulate what GetFrameAtPoint does, since we want all the frames under our
// point.
nsLayoutUtils::GetFramesForArea(rootFrame, nsRect(pt, nsSize(1, 1)), outFrames,
nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC |
((aFlags & nsIDocument::IGNORE_ROOT_SCROLL_FRAME) ? nsLayoutUtils::IGNORE_ROOT_SCROLL_FRAME : 0));
// Dunno when this would ever happen, as we should at least have a root frame under us?
if (outFrames.IsEmpty()) {
return;
}
// Used to filter out repeated elements in sequence.
nsIContent* lastAdded = nullptr;
for (uint32_t i = 0; i < outFrames.Length(); i++) {
nsIContent* node = GetContentInThisDocument(outFrames[i]);
if (!node || !node->IsElement()) {
// If this helper is called via ElementsFromPoint, we need to make sure
// our frame is an element. Otherwise return whatever the top frame is
// even if it isn't the top-painted element.
if (!(aFlags & nsIDocument::IS_ELEMENT_FROM_POINT)) {
continue;
}
node = node->GetParent();
}
if (node && node != lastAdded) {
aElements.AppendElement(node->AsElement());
lastAdded = node;
// If this helper is called via ElementFromPoint, just return the first
// element we find.
if (aFlags & nsIDocument::IS_ELEMENT_FROM_POINT) {
return;
}
}
}
}
nsresult
nsDocument::NodesFromRectHelper(float aX, float aY,
float aTopSize, float aRightSize,
float aBottomSize, float aLeftSize,
bool aIgnoreRootScrollFrame,
bool aFlushLayout,
nsIDOMNodeList** aReturn)
{
NS_ENSURE_ARG_POINTER(aReturn);
nsSimpleContentList* elements = new nsSimpleContentList(this);
NS_ADDREF(elements);
*aReturn = elements;
// Following the same behavior of elementFromPoint,
// we don't return anything if either coord is negative
if (!aIgnoreRootScrollFrame && (aX < 0 || aY < 0))
return NS_OK;
nscoord x = nsPresContext::CSSPixelsToAppUnits(aX - aLeftSize);
nscoord y = nsPresContext::CSSPixelsToAppUnits(aY - aTopSize);
nscoord w = nsPresContext::CSSPixelsToAppUnits(aLeftSize + aRightSize) + 1;
nscoord h = nsPresContext::CSSPixelsToAppUnits(aTopSize + aBottomSize) + 1;
nsRect rect(x, y, w, h);
// Make sure the layout information we get is up-to-date, and
// ensure we get a root frame (for everything but XUL)
if (aFlushLayout) {
FlushPendingNotifications(Flush_Layout);
}
nsIPresShell *ps = GetShell();
NS_ENSURE_STATE(ps);
nsIFrame *rootFrame = ps->GetRootFrame();
// XUL docs, unlike HTML, have no frame tree until everything's done loading
if (!rootFrame)
return NS_OK; // return nothing to premature XUL callers as a reminder to wait
AutoTArray<nsIFrame*,8> outFrames;
nsLayoutUtils::GetFramesForArea(rootFrame, rect, outFrames,
nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC |
(aIgnoreRootScrollFrame ? nsLayoutUtils::IGNORE_ROOT_SCROLL_FRAME : 0));
// Used to filter out repeated elements in sequence.
nsIContent* lastAdded = nullptr;
for (uint32_t i = 0; i < outFrames.Length(); i++) {
nsIContent* node = GetContentInThisDocument(outFrames[i]);
if (node && !node->IsElement() && !node->IsNodeOfType(nsINode::eTEXT)) {
// We have a node that isn't an element or a text node,
// use its parent content instead.
node = node->GetParent();
}
if (node && node != lastAdded) {
elements->AppendElement(node);
lastAdded = node;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetElementsByClassName(const nsAString& aClasses,
nsIDOMNodeList** aReturn)
{
*aReturn = nsIDocument::GetElementsByClassName(aClasses).take();
return NS_OK;
}
already_AddRefed<nsContentList>
nsIDocument::GetElementsByClassName(const nsAString& aClasses)
{
return nsContentUtils::GetElementsByClassName(this, aClasses);
}
NS_IMETHODIMP
nsDocument::ReleaseCapture()
{
nsIDocument::ReleaseCapture();
return NS_OK;
}
void
nsIDocument::ReleaseCapture() const
{
// only release the capture if the caller can access it. This prevents a
// page from stopping a scrollbar grab for example.
nsCOMPtr<nsINode> node = nsIPresShell::GetCapturingContent();
if (node && nsContentUtils::CanCallerAccess(node)) {
nsIPresShell::SetCapturingContent(nullptr, 0);
}
}
already_AddRefed<nsIURI>
nsIDocument::GetBaseURI(bool aTryUseXHRDocBaseURI) const
{
nsCOMPtr<nsIURI> uri;
if (aTryUseXHRDocBaseURI && mChromeXHRDocBaseURI) {
uri = mChromeXHRDocBaseURI;
} else {
uri = GetDocBaseURI();
}
return uri.forget();
}
void
nsDocument::SetBaseURI(nsIURI* aURI)
{
if (!aURI && !mDocumentBaseURI) {
return;
}
// Don't do anything if the URI wasn't actually changed.
if (aURI && mDocumentBaseURI) {
bool equalBases = false;
mDocumentBaseURI->Equals(aURI, &equalBases);
if (equalBases) {
return;
}
}
if (aURI) {
mDocumentBaseURI = NS_TryToMakeImmutable(aURI);
} else {
mDocumentBaseURI = nullptr;
}
RefreshLinkHrefs();
}
void
nsDocument::GetBaseTarget(nsAString &aBaseTarget)
{
aBaseTarget = mBaseTarget;
}
void
nsDocument::SetDocumentCharacterSet(const nsACString& aCharSetID)
{
// XXX it would be a good idea to assert the sanity of the argument,
// but before we figure out what to do about non-Encoding Standard
// encodings in the charset menu and in mailnews, assertions are futile.
if (!mCharacterSet.Equals(aCharSetID)) {
if (mMasterDocument && !aCharSetID.EqualsLiteral("UTF-8")) {
// Imports are always UTF-8
return;
}
mCharacterSet = aCharSetID;
int32_t n = mCharSetObservers.Length();
for (int32_t i = 0; i < n; i++) {
nsIObserver* observer = mCharSetObservers.ElementAt(i);
observer->Observe(static_cast<nsIDocument *>(this), "charset",
NS_ConvertASCIItoUTF16(aCharSetID).get());
}
}
}
nsresult
nsDocument::AddCharSetObserver(nsIObserver* aObserver)
{
NS_ENSURE_ARG_POINTER(aObserver);
NS_ENSURE_TRUE(mCharSetObservers.AppendElement(aObserver), NS_ERROR_FAILURE);
return NS_OK;
}
void
nsDocument::RemoveCharSetObserver(nsIObserver* aObserver)
{
mCharSetObservers.RemoveElement(aObserver);
}
void
nsIDocument::GetSandboxFlagsAsString(nsAString& aFlags)
{
nsContentUtils::SandboxFlagsToString(mSandboxFlags, aFlags);
}
void
nsDocument::GetHeaderData(nsIAtom* aHeaderField, nsAString& aData) const
{
aData.Truncate();
const nsDocHeaderData* data = mHeaderData;
while (data) {
if (data->mField == aHeaderField) {
aData = data->mData;
break;
}
data = data->mNext;
}
}
void
nsDocument::SetHeaderData(nsIAtom* aHeaderField, const nsAString& aData)
{
if (!aHeaderField) {
NS_ERROR("null headerField");
return;
}
if (!mHeaderData) {
if (!aData.IsEmpty()) { // don't bother storing empty string
mHeaderData = new nsDocHeaderData(aHeaderField, aData);
}
}
else {
nsDocHeaderData* data = mHeaderData;
nsDocHeaderData** lastPtr = &mHeaderData;
bool found = false;
do { // look for existing and replace
if (data->mField == aHeaderField) {
if (!aData.IsEmpty()) {
data->mData.Assign(aData);
}
else { // don't store empty string
*lastPtr = data->mNext;
data->mNext = nullptr;
delete data;
}
found = true;
break;
}
lastPtr = &(data->mNext);
data = *lastPtr;
} while (data);
if (!aData.IsEmpty() && !found) {
// didn't find, append
*lastPtr = new nsDocHeaderData(aHeaderField, aData);
}
}
if (aHeaderField == nsGkAtoms::headerContentLanguage) {
CopyUTF16toUTF8(aData, mContentLanguage);
}
if (aHeaderField == nsGkAtoms::headerDefaultStyle) {
// Only mess with our stylesheets if we don't have a lastStyleSheetSet, per
// spec.
if (DOMStringIsNull(mLastStyleSheetSet)) {
// Calling EnableStyleSheetsForSetInternal, not SetSelectedStyleSheetSet,
// per spec. The idea here is that we're changing our preferred set and
// that shouldn't change the value of lastStyleSheetSet. Also, we're
// using the Internal version so we can update the CSSLoader and not have
// to worry about null strings.
EnableStyleSheetsForSetInternal(aData, true);
}
}
if (aHeaderField == nsGkAtoms::refresh) {
// We get into this code before we have a script global yet, so get to
// our container via mDocumentContainer.
nsCOMPtr<nsIRefreshURI> refresher(mDocumentContainer);
if (refresher) {
// Note: using mDocumentURI instead of mBaseURI here, for consistency
// (used to just use the current URI of our webnavigation, but that
// should really be the same thing). Note that this code can run
// before the current URI of the webnavigation has been updated, so we
// can't assert equality here.
refresher->SetupRefreshURIFromHeader(mDocumentURI, NodePrincipal(),
NS_ConvertUTF16toUTF8(aData));
}
}
if (aHeaderField == nsGkAtoms::headerDNSPrefetchControl &&
mAllowDNSPrefetch) {
// Chromium treats any value other than 'on' (case insensitive) as 'off'.
mAllowDNSPrefetch = aData.IsEmpty() || aData.LowerCaseEqualsLiteral("on");
}
if (aHeaderField == nsGkAtoms::viewport ||
aHeaderField == nsGkAtoms::handheldFriendly ||
aHeaderField == nsGkAtoms::viewport_minimum_scale ||
aHeaderField == nsGkAtoms::viewport_maximum_scale ||
aHeaderField == nsGkAtoms::viewport_initial_scale ||
aHeaderField == nsGkAtoms::viewport_height ||
aHeaderField == nsGkAtoms::viewport_width ||
aHeaderField == nsGkAtoms::viewport_user_scalable) {
mViewportType = Unknown;
}
// Referrer policy spec says to ignore any empty referrer policies.
if (aHeaderField == nsGkAtoms::referrer && !aData.IsEmpty()) {
ReferrerPolicy policy = mozilla::net::ReferrerPolicyFromString(aData);
// If policy is not the empty string, then set element's node document's
// referrer policy to policy
if (policy != mozilla::net::RP_Unset) {
// Referrer policy spec (section 6.1) says that we always use the newest
// referrer policy we find
mReferrerPolicy = policy;
mReferrerPolicySet = true;
}
}
if (aHeaderField == nsGkAtoms::headerReferrerPolicy && !aData.IsEmpty()) {
ReferrerPolicy policy = nsContentUtils::GetReferrerPolicyFromHeader(aData);
if (policy != mozilla::net::RP_Unset) {
mReferrerPolicy = policy;
mReferrerPolicySet = true;
}
}
}
void
nsDocument::TryChannelCharset(nsIChannel *aChannel,
int32_t& aCharsetSource,
nsACString& aCharset,
nsHtml5TreeOpExecutor* aExecutor)
{
if (aChannel) {
nsAutoCString charsetVal;
nsresult rv = aChannel->GetContentCharset(charsetVal);
if (NS_SUCCEEDED(rv)) {
nsAutoCString preferred;
if(EncodingUtils::FindEncodingForLabel(charsetVal, preferred)) {
aCharset = preferred;
aCharsetSource = kCharsetFromChannel;
return;
} else if (aExecutor && !charsetVal.IsEmpty()) {
aExecutor->ComplainAboutBogusProtocolCharset(this);
}
}
}
}
already_AddRefed<nsIPresShell>
nsDocument::CreateShell(nsPresContext* aContext, nsViewManager* aViewManager,
StyleSetHandle aStyleSet)
{
// Don't add anything here. Add it to |doCreateShell| instead.
// This exists so that subclasses can pass other values for the 4th
// parameter some of the time.
return doCreateShell(aContext, aViewManager, aStyleSet);
}
already_AddRefed<nsIPresShell>
nsDocument::doCreateShell(nsPresContext* aContext,
nsViewManager* aViewManager, StyleSetHandle aStyleSet)
{
NS_ASSERTION(!mPresShell, "We have a presshell already!");
NS_ENSURE_FALSE(GetBFCacheEntry(), nullptr);
FillStyleSet(aStyleSet);
RefPtr<PresShell> shell = new PresShell;
shell->Init(this, aContext, aViewManager, aStyleSet);
// Note: we don't hold a ref to the shell (it holds a ref to us)
mPresShell = shell;
// Make sure to never paint if we belong to an invisible DocShell.
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell && docShell->IsInvisible())
shell->SetNeverPainting(true);
mExternalResourceMap.ShowViewers();
UpdateFrameRequestCallbackSchedulingState();
// Now that we have a shell, we might have @font-face rules.
RebuildUserFontSet();
return shell.forget();
}
void
nsIDocument::UpdateFrameRequestCallbackSchedulingState(nsIPresShell* aOldShell)
{
// If the condition for shouldBeScheduled changes to depend on some other
// variable, add UpdateFrameRequestCallbackSchedulingState() calls to the
// places where that variable can change.
bool shouldBeScheduled =
mPresShell && IsEventHandlingEnabled() && !AnimationsPaused() &&
!mFrameRequestCallbacks.IsEmpty();
if (shouldBeScheduled == mFrameRequestCallbacksScheduled) {
// nothing to do
return;
}
nsIPresShell* presShell = aOldShell ? aOldShell : mPresShell;
MOZ_RELEASE_ASSERT(presShell);
nsRefreshDriver* rd = presShell->GetPresContext()->RefreshDriver();
if (shouldBeScheduled) {
rd->ScheduleFrameRequestCallbacks(this);
} else {
rd->RevokeFrameRequestCallbacks(this);
}
mFrameRequestCallbacksScheduled = shouldBeScheduled;
}
void
nsIDocument::TakeFrameRequestCallbacks(FrameRequestCallbackList& aCallbacks)
{
aCallbacks.AppendElements(mFrameRequestCallbacks);
mFrameRequestCallbacks.Clear();
// No need to manually remove ourselves from the refresh driver; it will
// handle that part. But we do have to update our state.
mFrameRequestCallbacksScheduled = false;
}
bool
nsIDocument::ShouldThrottleFrameRequests()
{
if (mStaticCloneCount > 0) {
// Even if we're not visible, a static clone may be, so run at full speed.
return false;
}
if (Hidden()) {
// We're not visible (probably in a background tab or the bf cache).
return true;
}
if (!mPresShell) {
return false; // Can't do anything smarter.
}
nsIFrame* frame = mPresShell->GetRootFrame();
if (!frame) {
return false; // Can't do anything smarter.
}
nsIFrame* displayRootFrame = nsLayoutUtils::GetDisplayRootFrame(frame);
if (!displayRootFrame) {
return false; // Can't do anything smarter.
}
if (!displayRootFrame->DidPaintPresShell(mPresShell)) {
// We didn't get painted during the last paint, so we're not visible.
// Throttle. Note that because we have to paint this document at least
// once to unthrottle it, we will drop one requestAnimationFrame frame
// when a document that previously wasn't visible scrolls into view. This
// is acceptable since it would happen outside the viewport on APZ
// platforms and is unlikely to be human-perceivable on non-APZ platforms.
return true;
}
// We got painted during the last paint, so run at full speed.
return false;
}
void
nsDocument::DeleteShell()
{
mExternalResourceMap.HideViewers();
if (nsPresContext* presContext = mPresShell->GetPresContext()) {
presContext->RefreshDriver()->CancelPendingEvents(this);
}
// When our shell goes away, request that all our images be immediately
// discarded, so we don't carry around decoded image data for a document we
// no longer intend to paint.
ImageTracker()->RequestDiscardAll();
// Now that we no longer have a shell, we need to forget about any FontFace
// objects for @font-face rules that came from the style set.
RebuildUserFontSet();
if (mResizeObserverController) {
// If the shell is going away, we need to remove any links to this document
// from the observer.
mResizeObserverController->DetachFromDocument();
}
nsIPresShell* oldShell = mPresShell;
mPresShell = nullptr;
UpdateFrameRequestCallbackSchedulingState(oldShell);
mStyleSetFilled = false;
}
static void
SubDocClearEntry(PLDHashTable *table, PLDHashEntryHdr *entry)
{
SubDocMapEntry *e = static_cast<SubDocMapEntry *>(entry);
NS_RELEASE(e->mKey);
if (e->mSubDocument) {
e->mSubDocument->SetParentDocument(nullptr);
NS_RELEASE(e->mSubDocument);
}
}
static void
SubDocInitEntry(PLDHashEntryHdr *entry, const void *key)
{
SubDocMapEntry *e =
const_cast<SubDocMapEntry *>
(static_cast<const SubDocMapEntry *>(entry));
e->mKey = const_cast<Element*>(static_cast<const Element*>(key));
NS_ADDREF(e->mKey);
e->mSubDocument = nullptr;
}
nsresult
nsDocument::SetSubDocumentFor(Element* aElement, nsIDocument* aSubDoc)
{
NS_ENSURE_TRUE(aElement, NS_ERROR_UNEXPECTED);
if (!aSubDoc) {
// aSubDoc is nullptr, remove the mapping
if (mSubDocuments) {
mSubDocuments->Remove(aElement);
}
} else {
if (!mSubDocuments) {
// Create a new hashtable
static const PLDHashTableOps hash_table_ops =
{
PLDHashTable::HashVoidPtrKeyStub,
PLDHashTable::MatchEntryStub,
PLDHashTable::MoveEntryStub,
SubDocClearEntry,
SubDocInitEntry
};
mSubDocuments = new PLDHashTable(&hash_table_ops, sizeof(SubDocMapEntry));
}
// Add a mapping to the hash table
auto entry =
static_cast<SubDocMapEntry*>(mSubDocuments->Add(aElement, fallible));
if (!entry) {
return NS_ERROR_OUT_OF_MEMORY;
}
if (entry->mSubDocument) {
entry->mSubDocument->SetParentDocument(nullptr);
// Release the old sub document
NS_RELEASE(entry->mSubDocument);
}
entry->mSubDocument = aSubDoc;
NS_ADDREF(entry->mSubDocument);
aSubDoc->SetParentDocument(this);
}
return NS_OK;
}
nsIDocument*
nsDocument::GetSubDocumentFor(nsIContent *aContent) const
{
if (mSubDocuments && aContent->IsElement()) {
auto entry = static_cast<SubDocMapEntry*>
(mSubDocuments->Search(aContent->AsElement()));
if (entry) {
return entry->mSubDocument;
}
}
return nullptr;
}
Element*
nsDocument::FindContentForSubDocument(nsIDocument *aDocument) const
{
NS_ENSURE_TRUE(aDocument, nullptr);
if (!mSubDocuments) {
return nullptr;
}
for (auto iter = mSubDocuments->Iter(); !iter.Done(); iter.Next()) {
auto entry = static_cast<SubDocMapEntry*>(iter.Get());
if (entry->mSubDocument == aDocument) {
return entry->mKey;
}
}
return nullptr;
}
bool
nsDocument::IsNodeOfType(uint32_t aFlags) const
{
return !(aFlags & ~eDOCUMENT);
}
Element*
nsIDocument::GetRootElement() const
{
return (mCachedRootElement && mCachedRootElement->GetParentNode() == this) ?
mCachedRootElement : GetRootElementInternal();
}
Element*
nsDocument::GetRootElementInternal() const
{
// Loop backwards because any non-elements, such as doctypes and PIs
// are likely to appear before the root element.
uint32_t i;
for (i = mChildren.ChildCount(); i > 0; --i) {
nsIContent* child = mChildren.ChildAt(i - 1);
if (child->IsElement()) {
const_cast<nsDocument*>(this)->mCachedRootElement = child->AsElement();
return child->AsElement();
}
}
const_cast<nsDocument*>(this)->mCachedRootElement = nullptr;
return nullptr;
}
nsIContent *
nsDocument::GetChildAt(uint32_t aIndex) const
{
return mChildren.GetSafeChildAt(aIndex);
}
int32_t
nsDocument::IndexOf(const nsINode* aPossibleChild) const
{
return mChildren.IndexOfChild(aPossibleChild);
}
uint32_t
nsDocument::GetChildCount() const
{
return mChildren.ChildCount();
}
nsIContent * const *
nsDocument::GetChildArray(uint32_t* aChildCount) const
{
return mChildren.GetChildArray(aChildCount);
}
nsresult
nsDocument::InsertChildAt(nsIContent* aKid, uint32_t aIndex,
bool aNotify)
{
if (aKid->IsElement() && GetRootElement()) {
NS_WARNING("Inserting root element when we already have one");
return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
}
return doInsertChildAt(aKid, aIndex, aNotify, mChildren);
}
void
nsDocument::RemoveChildAt(uint32_t aIndex, bool aNotify)
{
nsCOMPtr<nsIContent> oldKid = GetChildAt(aIndex);
if (!oldKid) {
return;
}
if (oldKid->IsElement()) {
// Destroy the link map up front before we mess with the child list.
DestroyElementMaps();
}
// Preemptively clear mCachedRootElement, since we may be about to remove it
// from our child list, and we don't want to return this maybe-obsolete value
// from any GetRootElement() calls that happen inside of doRemoveChildAt().
// (NOTE: for this to be useful, doRemoveChildAt() must NOT trigger any
// GetRootElement() calls until after it's removed the child from mChildren.
// Any call before that point would restore this soon-to-be-obsolete cached
// answer, and our clearing here would be fruitless.)
mCachedRootElement = nullptr;
doRemoveChildAt(aIndex, aNotify, oldKid, mChildren);
MOZ_ASSERT(mCachedRootElement != oldKid,
"Stale pointer in mCachedRootElement, after we tried to clear it "
"(maybe somebody called GetRootElement() too early?)");
}
void
nsDocument::EnsureOnDemandBuiltInUASheet(StyleSheet* aSheet)
{
if (mOnDemandBuiltInUASheets.Contains(aSheet)) {
return;
}
BeginUpdate(UPDATE_STYLE);
AddOnDemandBuiltInUASheet(aSheet);
EndUpdate(UPDATE_STYLE);
}
void
nsDocument::AddOnDemandBuiltInUASheet(StyleSheet* aSheet)
{
MOZ_ASSERT(!mOnDemandBuiltInUASheets.Contains(aSheet));
// Prepend here so that we store the sheets in mOnDemandBuiltInUASheets in
// the same order that they should end up in the style set.
mOnDemandBuiltInUASheets.InsertElementAt(0, aSheet);
if (aSheet->IsApplicable()) {
// This is like |AddStyleSheetToStyleSets|, but for an agent sheet.
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
// Note that prepending here is necessary to make sure that html.css etc.
// do not override Firefox OS/Mobile's content.css sheet. Maybe we should
// have an insertion point to match the order of
// nsDocumentViewer::CreateStyleSet though?
shell->StyleSet()->PrependStyleSheet(SheetType::Agent, aSheet);
}
}
NotifyStyleSheetAdded(aSheet, false);
}
int32_t
nsDocument::GetNumberOfStyleSheets() const
{
return mStyleSheets.Length();
}
StyleSheet*
nsDocument::GetStyleSheetAt(int32_t aIndex) const
{
return mStyleSheets.SafeElementAt(aIndex, nullptr);
}
int32_t
nsDocument::GetIndexOfStyleSheet(const StyleSheet* aSheet) const
{
return mStyleSheets.IndexOf(aSheet);
}
void
nsDocument::AddStyleSheetToStyleSets(StyleSheet* aSheet)
{
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
shell->StyleSet()->AddDocStyleSheet(aSheet, this);
}
}
#define DO_STYLESHEET_NOTIFICATION(className, type, memberName, argName) \
do { \
className##Init init; \
init.mBubbles = true; \
init.mCancelable = true; \
/* XXXheycam ServoStyleSheet doesn't implement DOM interfaces yet */ \
if (aSheet->IsServo()) { \
NS_ERROR("stylo: can't dispatch events for ServoStyleSheets yet"); \
} \
init.mStylesheet = aSheet->IsGecko() ? aSheet->AsGecko() : nullptr; \
init.memberName = argName; \
\
RefPtr<className> event = \
className::Constructor(this, NS_LITERAL_STRING(type), init); \
event->SetTrusted(true); \
event->SetTarget(this); \
RefPtr<AsyncEventDispatcher> asyncDispatcher = \
new AsyncEventDispatcher(this, event); \
asyncDispatcher->mOnlyChromeDispatch = true; \
asyncDispatcher->PostDOMEvent(); \
} while (0);
void
nsDocument::NotifyStyleSheetAdded(StyleSheet* aSheet, bool aDocumentSheet)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetAdded, (aSheet, aDocumentSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
"StyleSheetAdded",
mDocumentSheet,
aDocumentSheet);
}
}
void
nsDocument::NotifyStyleSheetRemoved(StyleSheet* aSheet, bool aDocumentSheet)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetRemoved, (aSheet, aDocumentSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
"StyleSheetRemoved",
mDocumentSheet,
aDocumentSheet);
}
}
void
nsDocument::AddStyleSheet(StyleSheet* aSheet)
{
NS_PRECONDITION(aSheet, "null arg");
mStyleSheets.AppendElement(aSheet);
aSheet->SetOwningDocument(this);
if (aSheet->IsApplicable()) {
AddStyleSheetToStyleSets(aSheet);
}
NotifyStyleSheetAdded(aSheet, true);
}
void
nsDocument::RemoveStyleSheetFromStyleSets(StyleSheet* aSheet)
{
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
shell->StyleSet()->RemoveDocStyleSheet(aSheet);
}
}
void
nsDocument::RemoveStyleSheet(StyleSheet* aSheet)
{
NS_PRECONDITION(aSheet, "null arg");
RefPtr<StyleSheet> sheet = aSheet; // hold ref so it won't die too soon
if (!mStyleSheets.RemoveElement(aSheet)) {
NS_ASSERTION(mInUnlinkOrDeletion, "stylesheet not found");
return;
}
if (!mIsGoingAway) {
if (aSheet->IsApplicable()) {
RemoveStyleSheetFromStyleSets(aSheet);
}
NotifyStyleSheetRemoved(aSheet, true);
}
aSheet->SetOwningDocument(nullptr);
}
void
nsDocument::UpdateStyleSheets(nsTArray<RefPtr<StyleSheet>>& aOldSheets,
nsTArray<RefPtr<StyleSheet>>& aNewSheets)
{
BeginUpdate(UPDATE_STYLE);
// XXX Need to set the sheet on the ownernode, if any
NS_PRECONDITION(aOldSheets.Length() == aNewSheets.Length(),
"The lists must be the same length!");
int32_t count = aOldSheets.Length();
RefPtr<StyleSheet> oldSheet;
int32_t i;
for (i = 0; i < count; ++i) {
oldSheet = aOldSheets[i];
// First remove the old sheet.
NS_ASSERTION(oldSheet, "None of the old sheets should be null");
int32_t oldIndex = mStyleSheets.IndexOf(oldSheet);
RemoveStyleSheet(oldSheet); // This does the right notifications
// Now put the new one in its place. If it's null, just ignore it.
StyleSheet* newSheet = aNewSheets[i];
if (newSheet) {
mStyleSheets.InsertElementAt(oldIndex, newSheet);
newSheet->SetOwningDocument(this);
if (newSheet->IsApplicable()) {
AddStyleSheetToStyleSets(newSheet);
}
NotifyStyleSheetAdded(newSheet, true);
}
}
EndUpdate(UPDATE_STYLE);
}
void
nsDocument::InsertStyleSheetAt(StyleSheet* aSheet, int32_t aIndex)
{
NS_PRECONDITION(aSheet, "null ptr");
mStyleSheets.InsertElementAt(aIndex, aSheet);
aSheet->SetOwningDocument(this);
if (aSheet->IsApplicable()) {
AddStyleSheetToStyleSets(aSheet);
}
NotifyStyleSheetAdded(aSheet, true);
}
void
nsDocument::SetStyleSheetApplicableState(StyleSheet* aSheet,
bool aApplicable)
{
NS_PRECONDITION(aSheet, "null arg");
// If we're actually in the document style sheet list
if (mStyleSheets.IndexOf(aSheet) != mStyleSheets.NoIndex) {
if (aApplicable) {
AddStyleSheetToStyleSets(aSheet);
} else {
RemoveStyleSheetFromStyleSets(aSheet);
}
}
// We have to always notify, since this will be called for sheets
// that are children of sheets in our style set, as well as some
// sheets for HTMLEditor.
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetApplicableStateChanged, (aSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleSheetApplicableStateChangeEvent,
"StyleSheetApplicableStateChanged",
mApplicable,
aApplicable);
}
if (!mSSApplicableStateNotificationPending) {
nsCOMPtr<nsIRunnable> notification = NewRunnableMethod(this,
&nsDocument::NotifyStyleSheetApplicableStateChanged);
mSSApplicableStateNotificationPending =
NS_SUCCEEDED(NS_DispatchToCurrentThread(notification));
}
}
void
nsDocument::NotifyStyleSheetApplicableStateChanged()
{
mSSApplicableStateNotificationPending = false;
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->NotifyObservers(static_cast<nsIDocument*>(this),
"style-sheet-applicable-state-changed",
nullptr);
}
}
static SheetType
ConvertAdditionalSheetType(nsIDocument::additionalSheetType aType)
{
switch(aType) {
case nsIDocument::eAgentSheet:
return SheetType::Agent;
case nsIDocument::eUserSheet:
return SheetType::User;
case nsIDocument::eAuthorSheet:
return SheetType::Doc;
default:
MOZ_ASSERT(false, "wrong type");
// we must return something although this should never happen
return SheetType::Count;
}
}
static int32_t
FindSheet(const nsTArray<RefPtr<StyleSheet>>& aSheets, nsIURI* aSheetURI)
{
for (int32_t i = aSheets.Length() - 1; i >= 0; i-- ) {
bool bEqual;
nsIURI* uri = aSheets[i]->GetSheetURI();
if (uri && NS_SUCCEEDED(uri->Equals(aSheetURI, &bEqual)) && bEqual)
return i;
}
return -1;
}
nsresult
nsDocument::LoadAdditionalStyleSheet(additionalSheetType aType,
nsIURI* aSheetURI)
{
NS_PRECONDITION(aSheetURI, "null arg");
// Checking if we have loaded this one already.
if (FindSheet(mAdditionalSheets[aType], aSheetURI) >= 0)
return NS_ERROR_INVALID_ARG;
// Loading the sheet sync.
RefPtr<css::Loader> loader = new css::Loader(GetStyleBackendType());
css::SheetParsingMode parsingMode;
switch (aType) {
case nsIDocument::eAgentSheet:
parsingMode = css::eAgentSheetFeatures;
break;
case nsIDocument::eUserSheet:
parsingMode = css::eUserSheetFeatures;
break;
case nsIDocument::eAuthorSheet:
parsingMode = css::eAuthorSheetFeatures;
break;
default:
MOZ_CRASH("impossible value for aType");
}
RefPtr<StyleSheet> sheet;
nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true, &sheet);
NS_ENSURE_SUCCESS(rv, rv);
sheet->SetOwningDocument(this);
MOZ_ASSERT(sheet->IsApplicable());
return AddAdditionalStyleSheet(aType, sheet);
}
nsresult
nsDocument::AddAdditionalStyleSheet(additionalSheetType aType, StyleSheet* aSheet)
{
if (mAdditionalSheets[aType].Contains(aSheet))
return NS_ERROR_INVALID_ARG;
if (!aSheet->IsApplicable())
return NS_ERROR_INVALID_ARG;
mAdditionalSheets[aType].AppendElement(aSheet);
BeginUpdate(UPDATE_STYLE);
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
SheetType type = ConvertAdditionalSheetType(aType);
shell->StyleSet()->AppendStyleSheet(type, aSheet);
}
// Passing false, so documet.styleSheets.length will not be affected by
// these additional sheets.
NotifyStyleSheetAdded(aSheet, false);
EndUpdate(UPDATE_STYLE);
return NS_OK;
}
void
nsDocument::RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* aSheetURI)
{
MOZ_ASSERT(aSheetURI);
nsTArray<RefPtr<StyleSheet>>& sheets = mAdditionalSheets[aType];
int32_t i = FindSheet(mAdditionalSheets[aType], aSheetURI);
if (i >= 0) {
RefPtr<StyleSheet> sheetRef = sheets[i];
sheets.RemoveElementAt(i);
BeginUpdate(UPDATE_STYLE);
if (!mIsGoingAway) {
MOZ_ASSERT(sheetRef->IsApplicable());
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
SheetType type = ConvertAdditionalSheetType(aType);
shell->StyleSet()->RemoveStyleSheet(type, sheetRef);
}
}
// Passing false, so documet.styleSheets.length will not be affected by
// these additional sheets.
NotifyStyleSheetRemoved(sheetRef, false);
EndUpdate(UPDATE_STYLE);
sheetRef->SetOwningDocument(nullptr);
}
}
StyleSheet*
nsDocument::GetFirstAdditionalAuthorSheet()
{
return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
}
nsIGlobalObject*
nsDocument::GetScopeObject() const
{
nsCOMPtr<nsIGlobalObject> scope(do_QueryReferent(mScopeObject));
return scope;
}
void
nsDocument::SetScopeObject(nsIGlobalObject* aGlobal)
{
mScopeObject = do_GetWeakReference(aGlobal);
if (aGlobal) {
mHasHadScriptHandlingObject = true;
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
if (window) {
// We want to get the tabgroup unconditionally, such that we can make
// certain that it is cached in the inner window early enough.
mozilla::dom::TabGroup* tabgroup = window->TabGroup();
// We should already have the principal, and now that we have been added to a
// window, we should be able to join a DocGroup!
nsAutoCString docGroupKey;
mozilla::dom::DocGroup::GetKey(NodePrincipal(), docGroupKey);
if (!mDocGroup) {
mDocGroup = tabgroup->AddDocument(docGroupKey, this);
MOZ_ASSERT(mDocGroup);
}
}
}
}
#ifdef MOZ_EME
static void
CheckIfContainsEMEContent(nsISupports* aSupports, void* aContainsEME)
{
nsCOMPtr<nsIDOMHTMLMediaElement> domMediaElem(do_QueryInterface(aSupports));
if (domMediaElem) {
nsCOMPtr<nsIContent> content(do_QueryInterface(domMediaElem));
MOZ_ASSERT(content, "aSupports is not a content");
HTMLMediaElement* mediaElem = static_cast<HTMLMediaElement*>(content.get());
bool* contains = static_cast<bool*>(aContainsEME);
if (mediaElem->GetMediaKeys()) {
*contains = true;
}
}
}
bool
nsDocument::ContainsEMEContent()
{
bool containsEME = false;
EnumerateActivityObservers(CheckIfContainsEMEContent,
static_cast<void*>(&containsEME));
return containsEME;
}
#endif // MOZ_EME
static void
CheckIfContainsMSEContent(nsISupports* aSupports, void* aContainsMSE)
{
nsCOMPtr<nsIDOMHTMLMediaElement> domMediaElem(do_QueryInterface(aSupports));
if (domMediaElem) {
nsCOMPtr<nsIContent> content(do_QueryInterface(domMediaElem));
MOZ_ASSERT(content, "aSupports is not a content");
HTMLMediaElement* mediaElem = static_cast<HTMLMediaElement*>(content.get());
bool* contains = static_cast<bool*>(aContainsMSE);
RefPtr<MediaSource> ms = mediaElem->GetMozMediaSourceObject();
if (ms) {
*contains = true;
}
}
}
bool
nsDocument::ContainsMSEContent()
{
bool containsMSE = false;
EnumerateActivityObservers(CheckIfContainsMSEContent,
static_cast<void*>(&containsMSE));
return containsMSE;
}
static void
NotifyActivityChanged(nsISupports *aSupports, void *aUnused)
{
nsCOMPtr<nsIDOMHTMLMediaElement> domMediaElem(do_QueryInterface(aSupports));
if (domMediaElem) {
nsCOMPtr<nsIContent> content(do_QueryInterface(domMediaElem));
MOZ_ASSERT(content, "aSupports is not a content");
HTMLMediaElement* mediaElem = static_cast<HTMLMediaElement*>(content.get());
mediaElem->NotifyOwnerDocumentActivityChanged();
}
nsCOMPtr<nsIObjectLoadingContent> objectLoadingContent(do_QueryInterface(aSupports));
if (objectLoadingContent) {
nsObjectLoadingContent* olc = static_cast<nsObjectLoadingContent*>(objectLoadingContent.get());
olc->NotifyOwnerDocumentActivityChanged();
}
nsCOMPtr<nsIDocumentActivity> objectDocumentActivity(do_QueryInterface(aSupports));
if (objectDocumentActivity) {
objectDocumentActivity->NotifyOwnerDocumentActivityChanged();
}
}
void
nsIDocument::SetContainer(nsDocShell* aContainer)
{
if (aContainer) {
mDocumentContainer = aContainer;
} else {
mDocumentContainer = WeakPtr<nsDocShell>();
}
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
if (!aContainer) {
return;
}
// Get the Docshell
if (aContainer->ItemType() == nsIDocShellTreeItem::typeContent) {
// check if same type root
nsCOMPtr<nsIDocShellTreeItem> sameTypeRoot;
aContainer->GetSameTypeRootTreeItem(getter_AddRefs(sameTypeRoot));
NS_ASSERTION(sameTypeRoot, "No document shell root tree item from document shell tree item!");
if (sameTypeRoot == aContainer) {
static_cast<nsDocument*>(this)->SetIsTopLevelContentDocument(true);
}
static_cast<nsDocument*>(this)->SetIsContentDocument(true);
}
}
nsISupports*
nsIDocument::GetContainer() const
{
return static_cast<nsIDocShell*>(mDocumentContainer);
}
void
nsDocument::SetScriptGlobalObject(nsIScriptGlobalObject *aScriptGlobalObject)
{
#ifdef DEBUG
{
nsCOMPtr<nsPIDOMWindowInner> win(do_QueryInterface(aScriptGlobalObject));
NS_ASSERTION(!win || win->IsInnerWindow(),
"Script global object must be an inner window!");
}
#endif
MOZ_ASSERT(aScriptGlobalObject || !mAnimationController ||
mAnimationController->IsPausedByType(
nsSMILTimeContainer::PAUSE_PAGEHIDE |
nsSMILTimeContainer::PAUSE_BEGIN),
"Clearing window pointer while animations are unpaused");
if (mScriptGlobalObject && !aScriptGlobalObject) {
// We're detaching from the window. We need to grab a pointer to
// our layout history state now.
mLayoutHistoryState = GetLayoutHistoryState();
// Also make sure to remove our onload blocker now if we haven't done it yet
if (mOnloadBlockCount != 0) {
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
if (loadGroup) {
loadGroup->RemoveRequest(mOnloadBlocker, nullptr, NS_OK);
}
}
using mozilla::dom::workers::ServiceWorkerManager;
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (swm) {
ErrorResult error;
if (swm->IsControlled(this, error)) {
imgLoader* loader = nsContentUtils::GetImgLoaderForDocument(this);
if (loader) {
loader->ClearCacheForControlledDocument(this);
}
// We may become controlled again if this document comes back out
// of bfcache. Clear our state to allow that to happen. Only
// clear this flag if we are actually controlled, though, so pages
// that were force reloaded don't become controlled when they
// come out of bfcache.
mMaybeServiceWorkerControlled = false;
}
swm->MaybeStopControlling(this);
}
// Remove ourself from the list of clients. We only register
// content principal documents in this list.
if (!nsContentUtils::IsSystemPrincipal(GetPrincipal()) &&
!GetPrincipal()->GetIsNullPrincipal()) {
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
os->RemoveObserver(this, "service-worker-get-client");
}
}
} else if (!mScriptGlobalObject && aScriptGlobalObject &&
mDocumentContainer && GetChannel() &&
!nsContentUtils::IsSystemPrincipal(GetPrincipal()) &&
!GetPrincipal()->GetIsNullPrincipal()) {
// This document is being activated. Register it in the list of
// clients. We only do this for content principal documents
// since we can never observe system or null principals.
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
os->AddObserver(this, "service-worker-get-client", /* ownsWeak */ false);
}
}
// BlockOnload() might be called before mScriptGlobalObject is set.
// We may need to add the blocker once mScriptGlobalObject is set.
bool needOnloadBlocker = !mScriptGlobalObject && aScriptGlobalObject;
mScriptGlobalObject = aScriptGlobalObject;
if (needOnloadBlocker) {
EnsureOnloadBlocker();
}
UpdateFrameRequestCallbackSchedulingState();
if (aScriptGlobalObject) {
// Go back to using the docshell for the layout history state
mLayoutHistoryState = nullptr;
SetScopeObject(aScriptGlobalObject);
mHasHadDefaultView = true;
if (mAllowDNSPrefetch) {
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell) {
#ifdef DEBUG
nsCOMPtr<nsIWebNavigation> webNav =
do_GetInterface(aScriptGlobalObject);
NS_ASSERTION(SameCOMIdentity(webNav, docShell),
"Unexpected container or script global?");
#endif
bool allowDNSPrefetch;
docShell->GetAllowDNSPrefetch(&allowDNSPrefetch);
mAllowDNSPrefetch = allowDNSPrefetch;
}
}
}
// Remember the pointer to our window (or lack there of), to avoid
// having to QI every time it's asked for.
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(mScriptGlobalObject);
mWindow = window;
// Now that we know what our window is, we can flush the CSP errors to the
// Web Console. We are flushing all messages that occured and were stored
// in the queue prior to this point.
nsCOMPtr<nsIContentSecurityPolicy> csp;
NodePrincipal()->GetCsp(getter_AddRefs(csp));
if (csp) {
static_cast<nsCSPContext*>(csp.get())->flushConsoleMessages();
}
nsCOMPtr<nsIHttpChannelInternal> internalChannel =
do_QueryInterface(GetChannel());
if (internalChannel) {
nsCOMArray<nsISecurityConsoleMessage> messages;
internalChannel->TakeAllSecurityMessages(messages);
SendToConsole(messages);
}
// Set our visibility state, but do not fire the event. This is correct
// because either we're coming out of bfcache (in which case IsVisible() will
// still test false at this point and no state change will happen) or we're
// doing the initial document load and don't want to fire the event for this
// change.
dom::VisibilityState oldState = mVisibilityState;
mVisibilityState = GetVisibilityState();
// When the visibility is changed, notify it to observers.
// Some observers need the notification, for example HTMLMediaElement uses
// it to update internal media resource allocation.
// When video is loaded via VideoDocument, HTMLMediaElement and MediaDecoder
// creation are already done before nsDocument::SetScriptGlobalObject() call.
// MediaDecoder decides whether starting decoding is decided based on
// document's visibility. When the MediaDecoder is created,
// nsDocument::SetScriptGlobalObject() is not yet called and document is
// hidden state. Therefore the MediaDecoder decides that decoding is
// not yet necessary. But soon after nsDocument::SetScriptGlobalObject()
// call, the document becomes not hidden. At the time, MediaDecoder needs
// to know it and needs to start updating decoding.
if (oldState != mVisibilityState) {
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
}
// The global in the template contents owner document should be the same.
if (mTemplateContentsOwner && mTemplateContentsOwner != this) {
mTemplateContentsOwner->SetScriptGlobalObject(aScriptGlobalObject);
}
if (!mMaybeServiceWorkerControlled && mDocumentContainer && mScriptGlobalObject && GetChannel()) {
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
uint32_t loadType;
docShell->GetLoadType(&loadType);
// If we are shift-reloaded, don't associate with a ServiceWorker.
if (IsForceReloadType(loadType)) {
NS_WARNING("Page was shift reloaded, skipping ServiceWorker control");
return;
}
nsCOMPtr<nsIServiceWorkerManager> swm = mozilla::services::GetServiceWorkerManager();
if (swm) {
// If this document is being resurrected from the bfcache, then we may
// already have a document ID. In that case reuse the same ID. Otherwise
// get our document ID from the docshell.
nsString documentId(GetId());
if (documentId.IsEmpty()) {
static_cast<nsDocShell*>(docShell.get())->GetInterceptedDocumentId(documentId);
}
swm->MaybeStartControlling(this, documentId);
mMaybeServiceWorkerControlled = true;
}
}
}
nsIScriptGlobalObject*
nsDocument::GetScriptHandlingObjectInternal() const
{
MOZ_ASSERT(!mScriptGlobalObject,
"Do not call this when mScriptGlobalObject is set!");
if (mHasHadDefaultView) {
return nullptr;
}
nsCOMPtr<nsIScriptGlobalObject> scriptHandlingObject =
do_QueryReferent(mScopeObject);
nsCOMPtr<nsPIDOMWindowInner> win = do_QueryInterface(scriptHandlingObject);
if (win) {
nsPIDOMWindowOuter* outer = win->GetOuterWindow();
if (!outer || outer->GetCurrentInnerWindow() != win) {
NS_WARNING("Wrong inner/outer window combination!");
return nullptr;
}
}
return scriptHandlingObject;
}
void
nsDocument::SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject)
{
NS_ASSERTION(!mScriptGlobalObject ||
mScriptGlobalObject == aScriptObject,
"Wrong script object!");
if (aScriptObject) {
SetScopeObject(aScriptObject);
mHasHadDefaultView = false;
}
}
bool
nsDocument::IsTopLevelContentDocument()
{
return mIsTopLevelContentDocument;
}
void
nsDocument::SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument)
{
mIsTopLevelContentDocument = aIsTopLevelContentDocument;
}
bool
nsDocument::IsContentDocument() const
{
return mIsContentDocument;
}
void
nsDocument::SetIsContentDocument(bool aIsContentDocument)
{
mIsContentDocument = aIsContentDocument;
}
nsPIDOMWindowOuter*
nsDocument::GetWindowInternal() const
{
MOZ_ASSERT(!mWindow, "This should not be called when mWindow is not null!");
// Let's use mScriptGlobalObject. Even if the document is already removed from
// the docshell, the outer window might be still obtainable from the it.
nsCOMPtr<nsPIDOMWindowOuter> win;
if (mRemovedFromDocShell) {
// The docshell returns the outer window we are done.
nsCOMPtr<nsIDocShell> kungFuDeathGrip(mDocumentContainer);
if (kungFuDeathGrip) {
win = kungFuDeathGrip->GetWindow();
}
} else {
if (nsCOMPtr<nsPIDOMWindowInner> inner = do_QueryInterface(mScriptGlobalObject)) {
// mScriptGlobalObject is always the inner window, let's get the outer.
win = inner->GetOuterWindow();
}
}
return win;
}
ScriptLoader*
nsDocument::ScriptLoader()
{
return mScriptLoader;
}
bool
nsDocument::InternalAllowXULXBL()
{
if (nsContentUtils::AllowXULXBLForPrincipal(NodePrincipal())) {
mAllowXULXBL = eTriTrue;
return true;
}
mAllowXULXBL = eTriFalse;
return false;
}
// Note: We don't hold a reference to the document observer; we assume
// that it has a live reference to the document.
void
nsDocument::AddObserver(nsIDocumentObserver* aObserver)
{
NS_ASSERTION(mObservers.IndexOf(aObserver) == nsTArray<int>::NoIndex,
"Observer already in the list");
mObservers.AppendElement(aObserver);
AddMutationObserver(aObserver);
}
bool
nsDocument::RemoveObserver(nsIDocumentObserver* aObserver)
{
// If we're in the process of destroying the document (and we're
// informing the observers of the destruction), don't remove the
// observers from the list. This is not a big deal, since we
// don't hold a live reference to the observers.
if (!mInDestructor) {
RemoveMutationObserver(aObserver);
return mObservers.RemoveElement(aObserver);
}
return mObservers.Contains(aObserver);
}
void
nsDocument::MaybeEndOutermostXBLUpdate()
{
// Only call BindingManager()->EndOutermostUpdate() when
// we're not in an update and it is safe to run scripts.
if (mUpdateNestLevel == 0 && mInXBLUpdate) {
if (nsContentUtils::IsSafeToRunScript()) {
mInXBLUpdate = false;
BindingManager()->EndOutermostUpdate();
} else if (!mInDestructor) {
if (!mMaybeEndOutermostXBLUpdateRunner) {
mMaybeEndOutermostXBLUpdateRunner =
NewRunnableMethod(this, &nsDocument::MaybeEndOutermostXBLUpdate);
}
nsContentUtils::AddScriptRunner(mMaybeEndOutermostXBLUpdateRunner);
}
}
}
void
nsDocument::BeginUpdate(nsUpdateType aUpdateType)
{
if (mUpdateNestLevel == 0 && !mInXBLUpdate) {
mInXBLUpdate = true;
BindingManager()->BeginOutermostUpdate();
}
++mUpdateNestLevel;
nsContentUtils::AddScriptBlocker();
NS_DOCUMENT_NOTIFY_OBSERVERS(BeginUpdate, (this, aUpdateType));
}
void
nsDocument::EndUpdate(nsUpdateType aUpdateType)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(EndUpdate, (this, aUpdateType));
nsContentUtils::RemoveScriptBlocker();
--mUpdateNestLevel;
// This set of updates may have created XBL bindings. Let the
// binding manager know we're done.
MaybeEndOutermostXBLUpdate();
MaybeInitializeFinalizeFrameLoaders();
}
void
nsDocument::BeginLoad()
{
// Block onload here to prevent having to deal with blocking and
// unblocking it while we know the document is loading.
BlockOnload();
mDidFireDOMContentLoaded = false;
BlockDOMContentLoaded();
if (mScriptLoader) {
mScriptLoader->BeginDeferringScripts();
}
NS_DOCUMENT_NOTIFY_OBSERVERS(BeginLoad, (this));
}
void
nsDocument::ReportEmptyGetElementByIdArg()
{
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM"), this,
nsContentUtils::eDOM_PROPERTIES,
"EmptyGetElementByIdParam");
}
Element*
nsDocument::GetElementById(const nsAString& aElementId)
{
if (!CheckGetElementByIdArg(aElementId)) {
return nullptr;
}
nsIdentifierMapEntry *entry = mIdentifierMap.GetEntry(aElementId);
return entry ? entry->GetIdElement() : nullptr;
}
const nsTArray<Element*>*
nsDocument::GetAllElementsForId(const nsAString& aElementId) const
{
if (aElementId.IsEmpty()) {
return nullptr;
}
nsIdentifierMapEntry *entry = mIdentifierMap.GetEntry(aElementId);
return entry ? &entry->GetIdElements() : nullptr;
}
NS_IMETHODIMP
nsDocument::GetElementById(const nsAString& aId, nsIDOMElement** aReturn)
{
Element *content = GetElementById(aId);
if (content) {
return CallQueryInterface(content, aReturn);
}
*aReturn = nullptr;
return NS_OK;
}
Element*
nsDocument::AddIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
void* aData, bool aForImage)
{
nsDependentAtomString id(aID);
if (!CheckGetElementByIdArg(id))
return nullptr;
nsIdentifierMapEntry *entry = mIdentifierMap.PutEntry(id);
NS_ENSURE_TRUE(entry, nullptr);
entry->AddContentChangeCallback(aObserver, aData, aForImage);
return aForImage ? entry->GetImageIdElement() : entry->GetIdElement();
}
void
nsDocument::RemoveIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
void* aData, bool aForImage)
{
nsDependentAtomString id(aID);
if (!CheckGetElementByIdArg(id))
return;
nsIdentifierMapEntry *entry = mIdentifierMap.GetEntry(id);
if (!entry) {
return;
}
entry->RemoveContentChangeCallback(aObserver, aData, aForImage);
}
NS_IMETHODIMP
nsDocument::MozSetImageElement(const nsAString& aImageElementId,
nsIDOMElement* aImageElement)
{
nsCOMPtr<Element> el = do_QueryInterface(aImageElement);
MozSetImageElement(aImageElementId, el);
return NS_OK;
}
void
nsDocument::MozSetImageElement(const nsAString& aImageElementId,
Element* aElement)
{
if (aImageElementId.IsEmpty())
return;
// Hold a script blocker while calling SetImageElement since that can call
// out to id-observers
nsAutoScriptBlocker scriptBlocker;
nsIdentifierMapEntry *entry = mIdentifierMap.PutEntry(aImageElementId);
if (entry) {
entry->SetImageElement(aElement);
if (entry->IsEmpty()) {
mIdentifierMap.RemoveEntry(entry);
}
}
}
Element*
nsDocument::LookupImageElement(const nsAString& aId)
{
if (aId.IsEmpty())
return nullptr;
nsIdentifierMapEntry *entry = mIdentifierMap.GetEntry(aId);
return entry ? entry->GetImageIdElement() : nullptr;
}
void
nsDocument::DispatchContentLoadedEvents()
{
// If you add early returns from this method, make sure you're
// calling UnblockOnload properly.
// Unpin references to preloaded images
mPreloadingImages.Clear();
// DOM manipulation after content loaded should not care if the element
// came from the preloader.
mPreloadedPreconnects.Clear();
if (mTiming) {
mTiming->NotifyDOMContentLoadedStart(nsIDocument::GetDocumentURI());
}
// Dispatch observer notification to notify observers document is interactive.
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
nsIPrincipal *principal = GetPrincipal();
os->NotifyObservers(static_cast<nsIDocument*>(this),
nsContentUtils::IsSystemPrincipal(principal) ?
"chrome-document-interactive" :
"content-document-interactive",
nullptr);
}
// Fire a DOM event notifying listeners that this document has been
// loaded (excluding images and other loads initiated by this
// document).
nsContentUtils::DispatchTrustedEvent(this, static_cast<nsIDocument*>(this),
NS_LITERAL_STRING("DOMContentLoaded"),
true, false);
RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
nsIDocShell* docShell = this->GetDocShell();
if (timelines && timelines->HasConsumer(docShell)) {
timelines->AddMarkerForDocShell(docShell,
MakeUnique<DocLoadingTimelineMarker>("document::DOMContentLoaded"));
}
if (mTiming) {
mTiming->NotifyDOMContentLoadedEnd(nsIDocument::GetDocumentURI());
}
// If this document is a [i]frame, fire a DOMFrameContentLoaded
// event on all parent documents notifying that the HTML (excluding
// other external files such as images and stylesheets) in a frame
// has finished loading.
// target_frame is the [i]frame element that will be used as the
// target for the event. It's the [i]frame whose content is done
// loading.
nsCOMPtr<EventTarget> target_frame;
if (mParentDocument) {
target_frame = mParentDocument->FindContentForSubDocument(this);
}
if (target_frame) {
nsCOMPtr<nsIDocument> parent = mParentDocument;
do {
nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(parent);
nsCOMPtr<nsIDOMEvent> event;
if (domDoc) {
domDoc->CreateEvent(NS_LITERAL_STRING("Events"),
getter_AddRefs(event));
}
if (event) {
event->InitEvent(NS_LITERAL_STRING("DOMFrameContentLoaded"), true,
true);
event->SetTarget(target_frame);
event->SetTrusted(true);
// To dispatch this event we must manually call
// EventDispatcher::Dispatch() on the ancestor document since the
// target is not in the same document, so the event would never reach
// the ancestor document if we used the normal event
// dispatching code.
WidgetEvent* innerEvent = event->WidgetEventPtr();
if (innerEvent) {
nsEventStatus status = nsEventStatus_eIgnore;
nsIPresShell *shell = parent->GetShell();
if (shell) {
RefPtr<nsPresContext> context = shell->GetPresContext();
if (context) {
EventDispatcher::Dispatch(parent, context, innerEvent, event,
&status);
}
}
}
}
parent = parent->GetParentDocument();
} while (parent);
}
// If the document has a manifest attribute, fire a MozApplicationManifest
// event.
Element* root = GetRootElement();
if (root && root->HasAttr(kNameSpaceID_None, nsGkAtoms::manifest)) {
nsContentUtils::DispatchChromeEvent(this, static_cast<nsIDocument*>(this),
NS_LITERAL_STRING("MozApplicationManifest"),
true, true);
}
if (mMaybeServiceWorkerControlled) {
using mozilla::dom::workers::ServiceWorkerManager;
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (swm) {
swm->MaybeCheckNavigationUpdate(this);
}
}
UnblockOnload(true);
}
void
nsDocument::EndLoad()
{
// Drop the ref to our parser, if any, but keep hold of the sink so that we
// can flush it from FlushPendingNotifications as needed. We might have to
// do that to get a StartLayout() to happen.
if (mParser) {
mWeakSink = do_GetWeakReference(mParser->GetContentSink());
mParser = nullptr;
}
NS_DOCUMENT_NOTIFY_OBSERVERS(EndLoad, (this));
UnblockDOMContentLoaded();
}
void
nsDocument::UnblockDOMContentLoaded()
{
MOZ_ASSERT(mBlockDOMContentLoaded);
if (--mBlockDOMContentLoaded != 0 || mDidFireDOMContentLoaded) {
return;
}
mDidFireDOMContentLoaded = true;
MOZ_ASSERT(mReadyState == READYSTATE_INTERACTIVE);
if (!mSynchronousDOMContentLoaded) {
nsCOMPtr<nsIRunnable> ev =
NewRunnableMethod(this, &nsDocument::DispatchContentLoadedEvents);
NS_DispatchToCurrentThread(ev);
} else {
DispatchContentLoadedEvents();
}
}
void
nsDocument::ContentStateChanged(nsIContent* aContent, EventStates aStateMask)
{
NS_PRECONDITION(!nsContentUtils::IsSafeToRunScript(),
"Someone forgot a scriptblocker");
NS_DOCUMENT_NOTIFY_OBSERVERS(ContentStateChanged,
(this, aContent, aStateMask));
}
void
nsDocument::DocumentStatesChanged(EventStates aStateMask)
{
// Invalidate our cached state.
mGotDocumentState &= ~aStateMask;
mDocumentState &= ~aStateMask;
NS_DOCUMENT_NOTIFY_OBSERVERS(DocumentStatesChanged, (this, aStateMask));
}
void
nsDocument::StyleRuleChanged(StyleSheet* aSheet,
css::Rule* aStyleRule)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleChanged, (aSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
"StyleRuleChanged",
mRule,
aStyleRule ? aStyleRule->GetDOMRule() : nullptr);
}
}
void
nsDocument::StyleRuleAdded(StyleSheet* aSheet,
css::Rule* aStyleRule)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleAdded, (aSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
"StyleRuleAdded",
mRule,
aStyleRule ? aStyleRule->GetDOMRule()
: nullptr);
}
}
void
nsDocument::StyleRuleRemoved(StyleSheet* aSheet,
css::Rule* aStyleRule)
{
NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleRemoved, (aSheet));
if (StyleSheetChangeEventsEnabled()) {
DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
"StyleRuleRemoved",
mRule,
aStyleRule ? aStyleRule->GetDOMRule()
: nullptr);
}
}
#undef DO_STYLESHEET_NOTIFICATION
already_AddRefed<AnonymousContent>
nsIDocument::InsertAnonymousContent(Element& aElement, ErrorResult& aRv)
{
nsIPresShell* shell = GetShell();
if (!shell || !shell->GetCanvasFrame()) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsAutoScriptBlocker scriptBlocker;
nsCOMPtr<Element> container = shell->GetCanvasFrame()
->GetCustomContentContainer();
if (!container) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
// Clone the node to avoid returning a direct reference
nsCOMPtr<nsINode> clonedElement = aElement.CloneNode(true, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Insert the element into the container
nsresult rv;
rv = container->AppendChildTo(clonedElement->AsContent(), true);
if (NS_FAILED(rv)) {
return nullptr;
}
RefPtr<AnonymousContent> anonymousContent =
new AnonymousContent(clonedElement->AsElement());
mAnonymousContents.AppendElement(anonymousContent);
shell->GetCanvasFrame()->ShowCustomContentContainer();
return anonymousContent.forget();
}
void
nsIDocument::RemoveAnonymousContent(AnonymousContent& aContent,
ErrorResult& aRv)
{
nsIPresShell* shell = GetShell();
if (!shell || !shell->GetCanvasFrame()) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
nsAutoScriptBlocker scriptBlocker;
nsCOMPtr<Element> container = shell->GetCanvasFrame()
->GetCustomContentContainer();
if (!container) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
// Iterate over mAnonymousContents to find and remove the given node.
for (size_t i = 0, len = mAnonymousContents.Length(); i < len; ++i) {
if (mAnonymousContents[i] == &aContent) {
// Get the node from the customContent
nsCOMPtr<Element> node = aContent.GetContentNode();
// Remove the entry in mAnonymousContents
mAnonymousContents.RemoveElementAt(i);
// Remove the node from its container
container->RemoveChild(*node, aRv);
if (aRv.Failed()) {
return;
}
break;
}
}
if (mAnonymousContents.IsEmpty()) {
shell->GetCanvasFrame()->HideCustomContentContainer();
}
}
Element*
nsIDocument::GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const
{
if (!aNode->IsInNativeAnonymousSubtree()) {
return nullptr;
}
nsIPresShell* shell = GetShell();
if (!shell || !shell->GetCanvasFrame()) {
return nullptr;
}
nsAutoScriptBlocker scriptBlocker;
nsCOMPtr<Element> customContainer = shell->GetCanvasFrame()
->GetCustomContentContainer();
if (!customContainer) {
return nullptr;
}
// An arbitrary number of elements can be inserted as children of the custom
// container frame. We want the one that was added that contains aNode, so
// we need to keep track of the last child separately using |child| here.
nsINode* child = aNode;
nsINode* parent = aNode->GetParentNode();
while (parent && parent->IsInNativeAnonymousSubtree()) {
if (parent == customContainer) {
return child->IsElement() ? child->AsElement() : nullptr;
}
child = parent;
parent = child->GetParentNode();
}
return nullptr;
}
//
// nsIDOMDocument interface
//
DocumentType*
nsIDocument::GetDoctype() const
{
for (nsIContent* child = GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->NodeType() == nsIDOMNode::DOCUMENT_TYPE_NODE) {
return static_cast<DocumentType*>(child);
}
}
return nullptr;
}
NS_IMETHODIMP
nsDocument::GetDoctype(nsIDOMDocumentType** aDoctype)
{
MOZ_ASSERT(aDoctype);
nsCOMPtr<nsIDOMDocumentType> doctype = nsIDocument::GetDoctype();
doctype.forget(aDoctype);
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetImplementation(nsIDOMDOMImplementation** aImplementation)
{
ErrorResult rv;
*aImplementation = GetImplementation(rv);
if (rv.Failed()) {
MOZ_ASSERT(!*aImplementation);
return rv.StealNSResult();
}
NS_ADDREF(*aImplementation);
return NS_OK;
}
DOMImplementation*
nsDocument::GetImplementation(ErrorResult& rv)
{
if (!mDOMImplementation) {
nsCOMPtr<nsIURI> uri;
NS_NewURI(getter_AddRefs(uri), "about:blank");
if (!uri) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return nullptr;
}
bool hasHadScriptObject = true;
nsIScriptGlobalObject* scriptObject =
GetScriptHandlingObject(hasHadScriptObject);
if (!scriptObject && hasHadScriptObject) {
rv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
mDOMImplementation = new DOMImplementation(this,
scriptObject ? scriptObject : GetScopeObject(), uri, uri);
}
return mDOMImplementation;
}
NS_IMETHODIMP
nsDocument::GetDocumentElement(nsIDOMElement** aDocumentElement)
{
NS_ENSURE_ARG_POINTER(aDocumentElement);
Element* root = GetRootElement();
if (root) {
return CallQueryInterface(root, aDocumentElement);
}
*aDocumentElement = nullptr;
return NS_OK;
}
NS_IMETHODIMP
nsDocument::CreateElement(const nsAString& aTagName,
nsIDOMElement** aReturn)
{
*aReturn = nullptr;
ErrorResult rv;
ElementCreationOptionsOrString options;
options.SetAsString();
nsCOMPtr<Element> element = CreateElement(aTagName, options, rv);
NS_ENSURE_FALSE(rv.Failed(), rv.StealNSResult());
return CallQueryInterface(element, aReturn);
}
bool IsLowercaseASCII(const nsAString& aValue)
{
int32_t len = aValue.Length();
for (int32_t i = 0; i < len; ++i) {
char16_t c = aValue[i];
if (!(0x0061 <= (c) && ((c) <= 0x007a))) {
return false;
}
}
return true;
}
already_AddRefed<mozilla::dom::CustomElementRegistry>
nsDocument::GetCustomElementRegistry()
{
nsAutoString contentType;
GetContentType(contentType);
if (!IsHTMLDocument() &&
!contentType.EqualsLiteral("application/xhtml+xml")) {
return nullptr;
}
nsCOMPtr<nsPIDOMWindowInner> window(
do_QueryInterface(mScriptGlobalObject ? mScriptGlobalObject
: GetScopeObject()));
if (!window) {
return nullptr;
}
RefPtr<CustomElementRegistry> registry = window->CustomElements();
if (!registry) {
return nullptr;
}
return registry.forget();
}
already_AddRefed<Element>
nsDocument::CreateElement(const nsAString& aTagName,
const ElementCreationOptionsOrString& aOptions,
ErrorResult& rv)
{
rv = nsContentUtils::CheckQName(aTagName, false);
if (rv.Failed()) {
return nullptr;
}
bool needsLowercase = IsHTMLDocument() && !IsLowercaseASCII(aTagName);
nsAutoString lcTagName;
if (needsLowercase) {
nsContentUtils::ASCIIToLower(aTagName, lcTagName);
}
const nsString* is = nullptr;
if (aOptions.IsElementCreationOptions()) {
// Throw NotFoundError if 'is' is not-null and definition is null
is = CheckCustomElementName(aOptions.GetAsElementCreationOptions(),
needsLowercase ? lcTagName : aTagName, mDefaultElementType, rv);
if (rv.Failed()) {
return nullptr;
}
}
RefPtr<Element> elem = CreateElem(
needsLowercase ? lcTagName : aTagName, nullptr, mDefaultElementType, is);
return elem.forget();
}
NS_IMETHODIMP
nsDocument::CreateElementNS(const nsAString& aNamespaceURI,
const nsAString& aQualifiedName,
nsIDOMElement** aReturn)
{
*aReturn = nullptr;
ElementCreationOptionsOrString options;
options.SetAsString();
ErrorResult rv;
nsCOMPtr<Element> element =
CreateElementNS(aNamespaceURI, aQualifiedName, options, rv);
NS_ENSURE_FALSE(rv.Failed(), rv.StealNSResult());
return CallQueryInterface(element, aReturn);
}
already_AddRefed<Element>
nsDocument::CreateElementNS(const nsAString& aNamespaceURI,
const nsAString& aQualifiedName,
const ElementCreationOptionsOrString& aOptions,
ErrorResult& rv)
{
RefPtr<mozilla::dom::NodeInfo> nodeInfo;
rv = nsContentUtils::GetNodeInfoFromQName(aNamespaceURI,
aQualifiedName,
mNodeInfoManager,
nsIDOMNode::ELEMENT_NODE,
getter_AddRefs(nodeInfo));
if (rv.Failed()) {
return nullptr;
}
const nsString* is = nullptr;
if (aOptions.IsElementCreationOptions()) {
// Throw NotFoundError if 'is' is not-null and definition is null
is = CheckCustomElementName(aOptions.GetAsElementCreationOptions(),
aQualifiedName, nodeInfo->NamespaceID(), rv);
if (rv.Failed()) {
return nullptr;
}
}
nsCOMPtr<Element> element;
rv = NS_NewElement(getter_AddRefs(element), nodeInfo.forget(),
NOT_FROM_PARSER, is);
if (rv.Failed()) {
return nullptr;
}
return element.forget();
}
NS_IMETHODIMP
nsDocument::CreateTextNode(const nsAString& aData, nsIDOMText** aReturn)
{
*aReturn = nsIDocument::CreateTextNode(aData).take();
return NS_OK;
}
already_AddRefed<nsTextNode>
nsIDocument::CreateTextNode(const nsAString& aData) const
{
RefPtr<nsTextNode> text = new nsTextNode(mNodeInfoManager);
// Don't notify; this node is still being created.
text->SetText(aData, false);
return text.forget();
}
NS_IMETHODIMP
nsDocument::CreateDocumentFragment(nsIDOMDocumentFragment** aReturn)
{
*aReturn = nsIDocument::CreateDocumentFragment().take();
return NS_OK;
}
already_AddRefed<DocumentFragment>
nsIDocument::CreateDocumentFragment() const
{
RefPtr<DocumentFragment> frag = new DocumentFragment(mNodeInfoManager);
return frag.forget();
}
NS_IMETHODIMP
nsDocument::CreateComment(const nsAString& aData, nsIDOMComment** aReturn)
{
*aReturn = nsIDocument::CreateComment(aData).take();
return NS_OK;
}
// Unfortunately, bareword "Comment" is ambiguous with some Mac system headers.
already_AddRefed<dom::Comment>
nsIDocument::CreateComment(const nsAString& aData) const
{
RefPtr<dom::Comment> comment = new dom::Comment(mNodeInfoManager);
// Don't notify; this node is still being created.
comment->SetText(aData, false);
return comment.forget();
}
NS_IMETHODIMP
nsDocument::CreateCDATASection(const nsAString& aData,
nsIDOMCDATASection** aReturn)
{
NS_ENSURE_ARG_POINTER(aReturn);
ErrorResult rv;
*aReturn = nsIDocument::CreateCDATASection(aData, rv).take();
return rv.StealNSResult();
}
already_AddRefed<CDATASection>
nsIDocument::CreateCDATASection(const nsAString& aData,
ErrorResult& rv)
{
if (IsHTMLDocument()) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
if (FindInReadable(NS_LITERAL_STRING("]]>"), aData)) {
rv.Throw(NS_ERROR_DOM_INVALID_CHARACTER_ERR);
return nullptr;
}
RefPtr<CDATASection> cdata = new CDATASection(mNodeInfoManager);
// Don't notify; this node is still being created.
cdata->SetText(aData, false);
return cdata.forget();
}
NS_IMETHODIMP
nsDocument::CreateProcessingInstruction(const nsAString& aTarget,
const nsAString& aData,
nsIDOMProcessingInstruction** aReturn)
{
ErrorResult rv;
*aReturn =
nsIDocument::CreateProcessingInstruction(aTarget, aData, rv).take();
return rv.StealNSResult();
}
already_AddRefed<ProcessingInstruction>
nsIDocument::CreateProcessingInstruction(const nsAString& aTarget,
const nsAString& aData,
ErrorResult& rv) const
{
nsresult res = nsContentUtils::CheckQName(aTarget, false);
if (NS_FAILED(res)) {
rv.Throw(res);
return nullptr;
}
if (FindInReadable(NS_LITERAL_STRING("?>"), aData)) {
rv.Throw(NS_ERROR_DOM_INVALID_CHARACTER_ERR);
return nullptr;
}
RefPtr<ProcessingInstruction> pi =
NS_NewXMLProcessingInstruction(mNodeInfoManager, aTarget, aData);
return pi.forget();
}
NS_IMETHODIMP
nsDocument::CreateAttribute(const nsAString& aName,
nsIDOMAttr** aReturn)
{
ErrorResult rv;
*aReturn = nsIDocument::CreateAttribute(aName, rv).take();
return rv.StealNSResult();
}
already_AddRefed<Attr>
nsIDocument::CreateAttribute(const nsAString& aName, ErrorResult& rv)
{
WarnOnceAbout(eCreateAttribute);
if (!mNodeInfoManager) {
rv.Throw(NS_ERROR_NOT_INITIALIZED);
return nullptr;
}
nsresult res = nsContentUtils::CheckQName(aName, false);
if (NS_FAILED(res)) {
rv.Throw(res);
return nullptr;
}
nsAutoString name;
if (IsHTMLDocument()) {
nsContentUtils::ASCIIToLower(aName, name);
} else {
name = aName;
}
RefPtr<mozilla::dom::NodeInfo> nodeInfo;
res = mNodeInfoManager->GetNodeInfo(name, nullptr, kNameSpaceID_None,
nsIDOMNode::ATTRIBUTE_NODE,
getter_AddRefs(nodeInfo));
if (NS_FAILED(res)) {
rv.Throw(res);
return nullptr;
}
RefPtr<Attr> attribute = new Attr(nullptr, nodeInfo.forget(),
EmptyString());
return attribute.forget();
}
NS_IMETHODIMP
nsDocument::CreateAttributeNS(const nsAString & aNamespaceURI,
const nsAString & aQualifiedName,
nsIDOMAttr **aResult)
{
ErrorResult rv;
*aResult =
nsIDocument::CreateAttributeNS(aNamespaceURI, aQualifiedName, rv).take();
return rv.StealNSResult();
}
already_AddRefed<Attr>
nsIDocument::CreateAttributeNS(const nsAString& aNamespaceURI,
const nsAString& aQualifiedName,
ErrorResult& rv)
{
WarnOnceAbout(eCreateAttributeNS);
RefPtr<mozilla::dom::NodeInfo> nodeInfo;
rv = nsContentUtils::GetNodeInfoFromQName(aNamespaceURI,
aQualifiedName,
mNodeInfoManager,
nsIDOMNode::ATTRIBUTE_NODE,
getter_AddRefs(nodeInfo));
if (rv.Failed()) {
return nullptr;
}
RefPtr<Attr> attribute = new Attr(nullptr, nodeInfo.forget(),
EmptyString());
return attribute.forget();
}
bool
nsDocument::CustomElementConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
JS::CallArgs args = JS::CallArgsFromVp(aArgc, aVp);
JS::Rooted<JSObject*> global(aCx,
JS_GetGlobalForObject(aCx, &args.callee()));
RefPtr<nsGlobalWindow> window;
UNWRAP_OBJECT(Window, global, window);
MOZ_ASSERT(window, "Should have a non-null window");
nsDocument* document = static_cast<nsDocument*>(window->GetDoc());
// Function name is the type of the custom element.
JSString* jsFunName =
JS_GetFunctionId(JS_ValueToFunction(aCx, args.calleev()));
nsAutoJSString elemName;
if (!elemName.init(aCx, jsFunName)) {
return true;
}
RefPtr<mozilla::dom::CustomElementRegistry> registry = window->CustomElements();
if (!registry) {
return true;
}
nsCOMPtr<nsIAtom> typeAtom(NS_Atomize(elemName));
CustomElementDefinition* definition = registry->mCustomDefinitions.Get(typeAtom);
if (!definition) {
return true;
}
nsDependentAtomString localName(definition->mLocalName);
nsCOMPtr<Element> element =
document->CreateElem(localName, nullptr, kNameSpaceID_XHTML);
NS_ENSURE_TRUE(element, true);
if (definition->mLocalName != typeAtom) {
// This element is a custom element by extension, thus we need to
// do some special setup. For non-extended custom elements, this happens
// when the element is created.
nsContentUtils::SetupCustomElement(element, &elemName);
}
nsresult rv = nsContentUtils::WrapNative(aCx, element, element, args.rval());
NS_ENSURE_SUCCESS(rv, true);
return true;
}
bool
nsDocument::IsWebComponentsEnabled(JSContext* aCx, JSObject* aObject)
{
JS::Rooted<JSObject*> obj(aCx, aObject);
//if (Preferences::GetBool("dom.webcomponents.enabled")) {
// return true;
//}
// Check for the webcomponents permission. See Bug 1181555.
JSAutoCompartment ac(aCx, obj);
JS::Rooted<JSObject*> global(aCx, JS_GetGlobalForObject(aCx, obj));
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(nsJSUtils::GetStaticScriptGlobal(global));
return IsWebComponentsEnabled(window);
}
bool
nsDocument::IsWebComponentsEnabled(dom::NodeInfo* aNodeInfo)
{
//if (Preferences::GetBool("dom.webcomponents.enabled")) {
// return true;
//}
nsIDocument* doc = aNodeInfo->GetDocument();
// Use GetScopeObject() here so that data documents work the same way as the
// main document they're associated with.
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(doc->GetScopeObject());
return IsWebComponentsEnabled(window);
}
bool
nsDocument::IsWebComponentsEnabled(nsPIDOMWindowInner* aWindow)
{
/*
if (aWindow) {
nsresult rv;
nsCOMPtr<nsIPermissionManager> permMgr =
do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, false);
uint32_t perm;
rv = permMgr->TestPermissionFromWindow(
aWindow, "moz-extremely-unstable-and-will-change-webcomponents", &perm);
NS_ENSURE_SUCCESS(rv, false);
return perm == nsIPermissionManager::ALLOW_ACTION;
}
*/
return false;
}
void
nsDocument::RegisterElement(JSContext* aCx, const nsAString& aType,
const ElementRegistrationOptions& aOptions,
JS::MutableHandle<JSObject*> aRetval,
ErrorResult& rv)
{
RefPtr<CustomElementRegistry> registry(GetCustomElementRegistry());
if (!registry) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
// Unconditionally convert TYPE to lowercase.
nsAutoString lcType;
nsContentUtils::ASCIIToLower(aType, lcType);
nsIGlobalObject* sgo = GetScopeObject();
if (!sgo) {
rv.Throw(NS_ERROR_UNEXPECTED);
return;
}
JS::Rooted<JSObject*> global(aCx, sgo->GetGlobalJSObject());
JS::Rooted<JSObject*> protoObject(aCx);
if (!aOptions.mPrototype) {
JS::Rooted<JSObject*> htmlProto(aCx);
htmlProto = HTMLElementBinding::GetProtoObjectHandle(aCx);
if (!htmlProto) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
protoObject = JS_NewObjectWithGivenProto(aCx, nullptr, htmlProto);
if (!protoObject) {
rv.Throw(NS_ERROR_UNEXPECTED);
return;
}
} else {
protoObject = aOptions.mPrototype;
// Get the unwrapped prototype to do some checks.
JS::Rooted<JSObject*> protoObjectUnwrapped(aCx, js::CheckedUnwrap(protoObject));
if (!protoObjectUnwrapped) {
// If the caller's compartment does not have permission to access the
// unwrapped prototype then throw.
rv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
// If PROTOTYPE is already an interface prototype object for any interface
// object or PROTOTYPE has a non-configurable property named constructor,
// throw a NotSupportedError and stop.
const js::Class* clasp = js::GetObjectClass(protoObjectUnwrapped);
if (IsDOMIfaceAndProtoClass(clasp)) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
JS::Rooted<JS::PropertyDescriptor> descRoot(aCx);
JS::MutableHandle<JS::PropertyDescriptor> desc(&descRoot);
// This check may go through a wrapper, but as we checked above
// it should be transparent or an xray. This should be fine for now,
// until the spec is sorted out.
if (!JS_GetPropertyDescriptor(aCx, protoObject, "constructor", desc)) {
rv.Throw(NS_ERROR_UNEXPECTED);
return;
}
if (!desc.configurable()) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
}
JS::Rooted<JSFunction*> constructor(aCx);
{
// Go into the document's global compartment when creating the constructor
// function because we want to get the correct document (where the
// definition is registered) when it is called.
JSAutoCompartment ac(aCx, global);
// Create constructor to return. Store the name of the custom element as the
// name of the function.
constructor = JS_NewFunction(aCx, nsDocument::CustomElementConstructor, 0,
JSFUN_CONSTRUCTOR,
NS_ConvertUTF16toUTF8(lcType).get());
if (!constructor) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
}
JS::Rooted<JSObject*> wrappedConstructor(aCx);
wrappedConstructor = JS_GetFunctionObject(constructor);
if (!JS_WrapObject(aCx, &wrappedConstructor)) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
if (!JS_LinkConstructorAndPrototype(aCx, wrappedConstructor, protoObject)) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
ElementDefinitionOptions options;
if (!aOptions.mExtends.IsVoid()) {
// Only convert NAME to lowercase in HTML documents.
nsAutoString lcName;
IsHTMLDocument() ? nsContentUtils::ASCIIToLower(aOptions.mExtends, lcName)
: lcName.Assign(aOptions.mExtends);
options.mExtends.Construct(lcName);
}
RootedCallback<OwningNonNull<binding_detail::FastFunction>> functionConstructor(aCx);
functionConstructor = new binding_detail::FastFunction(aCx, wrappedConstructor, sgo);
registry->Define(lcType, functionConstructor, options, rv);
aRetval.set(wrappedConstructor);
}
NS_IMETHODIMP
nsDocument::GetElementsByTagName(const nsAString& aTagname,
nsIDOMNodeList** aReturn)
{
RefPtr<nsContentList> list = GetElementsByTagName(aTagname);
NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
// transfer ref to aReturn
list.forget(aReturn);
return NS_OK;
}
long
nsDocument::BlockedTrackingNodeCount() const
{
return mBlockedTrackingNodes.Length();
}
already_AddRefed<nsSimpleContentList>
nsDocument::BlockedTrackingNodes() const
{
RefPtr<nsSimpleContentList> list = new nsSimpleContentList(nullptr);
nsTArray<nsWeakPtr> blockedTrackingNodes;
blockedTrackingNodes = mBlockedTrackingNodes;
for (unsigned long i = 0; i < blockedTrackingNodes.Length(); i++) {
nsWeakPtr weakNode = blockedTrackingNodes[i];
nsCOMPtr<nsIContent> node = do_QueryReferent(weakNode);
// Consider only nodes to which we have managed to get strong references.
// Coping with nullptrs since it's expected for nodes to disappear when
// nobody else is referring to them.
if (node) {
list->AppendElement(node);
}
}
return list.forget();
}
already_AddRefed<nsContentList>
nsIDocument::GetElementsByTagNameNS(const nsAString& aNamespaceURI,
const nsAString& aLocalName,
ErrorResult& aResult)
{
int32_t nameSpaceId = kNameSpaceID_Wildcard;
if (!aNamespaceURI.EqualsLiteral("*")) {
aResult =
nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI,
nameSpaceId);
if (aResult.Failed()) {
return nullptr;
}
}
NS_ASSERTION(nameSpaceId != kNameSpaceID_Unknown, "Unexpected namespace ID!");
return NS_GetContentList(this, nameSpaceId, aLocalName);
}
NS_IMETHODIMP
nsDocument::GetElementsByTagNameNS(const nsAString& aNamespaceURI,
const nsAString& aLocalName,
nsIDOMNodeList** aReturn)
{
ErrorResult rv;
RefPtr<nsContentList> list =
nsIDocument::GetElementsByTagNameNS(aNamespaceURI, aLocalName, rv);
if (rv.Failed()) {
return rv.StealNSResult();
}
// transfer ref to aReturn
list.forget(aReturn);
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetStyleSheets(nsIDOMStyleSheetList** aStyleSheets)
{
NS_ADDREF(*aStyleSheets = StyleSheets());
return NS_OK;
}
StyleSheetList*
nsDocument::StyleSheets()
{
if (!mDOMStyleSheets) {
mDOMStyleSheets = new nsDOMStyleSheetList(this);
}
return mDOMStyleSheets;
}
NS_IMETHODIMP
nsDocument::GetMozSelectedStyleSheetSet(nsAString& aSheetSet)
{
nsIDocument::GetSelectedStyleSheetSet(aSheetSet);
return NS_OK;
}
void
nsIDocument::GetSelectedStyleSheetSet(nsAString& aSheetSet)
{
aSheetSet.Truncate();
// Look through our sheets, find the selected set title
int32_t count = GetNumberOfStyleSheets();
nsAutoString title;
for (int32_t index = 0; index < count; index++) {
StyleSheet* sheet = GetStyleSheetAt(index);
NS_ASSERTION(sheet, "Null sheet in sheet list!");
// XXXheycam Make this work with ServoStyleSheets.
if (sheet->IsServo()) {
NS_ERROR("stylo: can't handle alternate ServoStyleSheets yet");
continue;
}
bool disabled;
sheet->AsGecko()->GetDisabled(&disabled);
if (disabled) {
// Disabled sheets don't affect the currently selected set
continue;
}
sheet->AsGecko()->GetTitle(title);
if (aSheetSet.IsEmpty()) {
aSheetSet = title;
} else if (!title.IsEmpty() && !aSheetSet.Equals(title)) {
// Sheets from multiple sets enabled; return null string, per spec.
SetDOMStringToNull(aSheetSet);
return;
}
}
}
NS_IMETHODIMP
nsDocument::SetMozSelectedStyleSheetSet(const nsAString& aSheetSet)
{
SetSelectedStyleSheetSet(aSheetSet);
return NS_OK;
}
void
nsDocument::SetSelectedStyleSheetSet(const nsAString& aSheetSet)
{
if (DOMStringIsNull(aSheetSet)) {
return;
}
// Must update mLastStyleSheetSet before doing anything else with stylesheets
// or CSSLoaders.
mLastStyleSheetSet = aSheetSet;
EnableStyleSheetsForSetInternal(aSheetSet, true);
}
NS_IMETHODIMP
nsDocument::GetLastStyleSheetSet(nsAString& aSheetSet)
{
nsString sheetSet;
GetLastStyleSheetSet(sheetSet);
aSheetSet = sheetSet;
return NS_OK;
}
void
nsDocument::GetLastStyleSheetSet(nsString& aSheetSet)
{
aSheetSet = mLastStyleSheetSet;
}
NS_IMETHODIMP
nsDocument::GetPreferredStyleSheetSet(nsAString& aSheetSet)
{
nsIDocument::GetPreferredStyleSheetSet(aSheetSet);
return NS_OK;
}
void
nsIDocument::GetPreferredStyleSheetSet(nsAString& aSheetSet)
{
GetHeaderData(nsGkAtoms::headerDefaultStyle, aSheetSet);
}
NS_IMETHODIMP
nsDocument::GetStyleSheetSets(nsISupports** aList)
{
NS_ADDREF(*aList = StyleSheetSets());
return NS_OK;
}
DOMStringList*
nsDocument::StyleSheetSets()
{
if (!mStyleSheetSetList) {
mStyleSheetSetList = new nsDOMStyleSheetSetList(this);
}
return mStyleSheetSetList;
}
NS_IMETHODIMP
nsDocument::MozEnableStyleSheetsForSet(const nsAString& aSheetSet)
{
EnableStyleSheetsForSet(aSheetSet);
return NS_OK;
}
void
nsDocument::EnableStyleSheetsForSet(const nsAString& aSheetSet)
{
// Per spec, passing in null is a no-op.
if (!DOMStringIsNull(aSheetSet)) {
// Note: must make sure to not change the CSSLoader's preferred sheet --
// that value should be equal to either our lastStyleSheetSet (if that's
// non-null) or to our preferredStyleSheetSet. And this method doesn't
// change either of those.
EnableStyleSheetsForSetInternal(aSheetSet, false);
}
}
void
nsDocument::EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
bool aUpdateCSSLoader)
{
BeginUpdate(UPDATE_STYLE);
int32_t count = GetNumberOfStyleSheets();
nsAutoString title;
for (int32_t index = 0; index < count; index++) {
StyleSheet* sheet = GetStyleSheetAt(index);
NS_ASSERTION(sheet, "Null sheet in sheet list!");
// XXXheycam Make this work with ServoStyleSheets.
if (sheet->IsServo()) {
NS_ERROR("stylo: can't handle alternate ServoStyleSheets yet");
continue;
}
sheet->AsGecko()->GetTitle(title);
if (!title.IsEmpty()) {
sheet->AsGecko()->SetEnabled(title.Equals(aSheetSet));
}
}
if (aUpdateCSSLoader) {
CSSLoader()->SetPreferredSheet(aSheetSet);
}
EndUpdate(UPDATE_STYLE);
}
NS_IMETHODIMP
nsDocument::GetCharacterSet(nsAString& aCharacterSet)
{
nsIDocument::GetCharacterSet(aCharacterSet);
return NS_OK;
}
void
nsIDocument::GetCharacterSet(nsAString& aCharacterSet) const
{
CopyASCIItoUTF16(GetDocumentCharacterSet(), aCharacterSet);
}
NS_IMETHODIMP
nsDocument::ImportNode(nsIDOMNode* aImportedNode,
bool aDeep,
uint8_t aArgc,
nsIDOMNode** aResult)
{
if (aArgc == 0) {
aDeep = true;
}
*aResult = nullptr;
nsCOMPtr<nsINode> imported = do_QueryInterface(aImportedNode);
NS_ENSURE_TRUE(imported, NS_ERROR_UNEXPECTED);
ErrorResult rv;
nsCOMPtr<nsINode> result = nsIDocument::ImportNode(*imported, aDeep, rv);
if (rv.Failed()) {
return rv.StealNSResult();
}
NS_ADDREF(*aResult = result->AsDOMNode());
return NS_OK;
}
already_AddRefed<nsINode>
nsIDocument::ImportNode(nsINode& aNode, bool aDeep, ErrorResult& rv) const
{
nsINode* imported = &aNode;
switch (imported->NodeType()) {
case nsIDOMNode::DOCUMENT_NODE:
{
break;
}
case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
{
if (ShadowRoot::FromNode(imported)) {
break;
}
MOZ_FALLTHROUGH;
}
case nsIDOMNode::ATTRIBUTE_NODE:
case nsIDOMNode::ELEMENT_NODE:
case nsIDOMNode::PROCESSING_INSTRUCTION_NODE:
case nsIDOMNode::TEXT_NODE:
case nsIDOMNode::CDATA_SECTION_NODE:
case nsIDOMNode::COMMENT_NODE:
case nsIDOMNode::DOCUMENT_TYPE_NODE:
{
nsCOMPtr<nsINode> newNode;
nsCOMArray<nsINode> nodesWithProperties;
rv = nsNodeUtils::Clone(imported, aDeep, mNodeInfoManager,
nodesWithProperties, getter_AddRefs(newNode));
if (rv.Failed()) {
return nullptr;
}
return newNode.forget();
}
default:
{
NS_WARNING("Don't know how to clone this nodetype for importNode.");
}
}
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
NS_IMETHODIMP
nsDocument::LoadBindingDocument(const nsAString& aURI)
{
ErrorResult rv;
nsIDocument::LoadBindingDocument(aURI,
nsContentUtils::GetCurrentJSContext()
? Some(nsContentUtils::SubjectPrincipal())
: Nothing(),
rv);
return rv.StealNSResult();
}
void
nsIDocument::LoadBindingDocument(const nsAString& aURI,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& rv)
{
LoadBindingDocument(aURI, Some(&aSubjectPrincipal), rv);
}
void
nsIDocument::LoadBindingDocument(const nsAString& aURI,
const Maybe<nsIPrincipal*>& aSubjectPrincipal,
ErrorResult& rv)
{
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), aURI,
mCharacterSet.get(),
GetDocBaseURI());
if (rv.Failed()) {
return;
}
// Note - This computation of subjectPrincipal isn't necessarily sensical.
// It's just designed to preserve the old semantics during a mass-conversion
// patch.
nsCOMPtr<nsIPrincipal> subjectPrincipal =
aSubjectPrincipal.isSome() ? aSubjectPrincipal.value() : NodePrincipal();
BindingManager()->LoadBindingDocument(this, uri, subjectPrincipal);
}
NS_IMETHODIMP
nsDocument::GetBindingParent(nsIDOMNode* aNode, nsIDOMElement** aResult)
{
nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
NS_ENSURE_ARG_POINTER(node);
Element* bindingParent = nsIDocument::GetBindingParent(*node);
nsCOMPtr<nsIDOMElement> retval = do_QueryInterface(bindingParent);
retval.forget(aResult);
return NS_OK;
}
Element*
nsIDocument::GetBindingParent(nsINode& aNode)
{
nsCOMPtr<nsIContent> content(do_QueryInterface(&aNode));
if (!content)
return nullptr;
nsIContent* bindingParent = content->GetBindingParent();
return bindingParent ? bindingParent->AsElement() : nullptr;
}
static Element*
GetElementByAttribute(nsIContent* aContent, nsIAtom* aAttrName,
const nsAString& aAttrValue, bool aUniversalMatch)
{
if (aUniversalMatch ? aContent->HasAttr(kNameSpaceID_None, aAttrName) :
aContent->AttrValueIs(kNameSpaceID_None, aAttrName,
aAttrValue, eCaseMatters)) {
return aContent->AsElement();
}
for (nsIContent* child = aContent->GetFirstChild();
child;
child = child->GetNextSibling()) {
Element* matchedElement =
GetElementByAttribute(child, aAttrName, aAttrValue, aUniversalMatch);
if (matchedElement)
return matchedElement;
}
return nullptr;
}
Element*
nsDocument::GetAnonymousElementByAttribute(nsIContent* aElement,
nsIAtom* aAttrName,
const nsAString& aAttrValue) const
{
nsINodeList* nodeList = BindingManager()->GetAnonymousNodesFor(aElement);
if (!nodeList)
return nullptr;
uint32_t length = 0;
nodeList->GetLength(&length);
bool universalMatch = aAttrValue.EqualsLiteral("*");
for (uint32_t i = 0; i < length; ++i) {
nsIContent* current = nodeList->Item(i);
Element* matchedElm =
GetElementByAttribute(current, aAttrName, aAttrValue, universalMatch);
if (matchedElm)
return matchedElm;
}
return nullptr;
}
NS_IMETHODIMP
nsDocument::GetAnonymousElementByAttribute(nsIDOMElement* aElement,
const nsAString& aAttrName,
const nsAString& aAttrValue,
nsIDOMElement** aResult)
{
nsCOMPtr<Element> element = do_QueryInterface(aElement);
NS_ENSURE_ARG_POINTER(element);
Element* anonEl =
nsIDocument::GetAnonymousElementByAttribute(*element, aAttrName,
aAttrValue);
nsCOMPtr<nsIDOMElement> retval = do_QueryInterface(anonEl);
retval.forget(aResult);
return NS_OK;
}
Element*
nsIDocument::GetAnonymousElementByAttribute(Element& aElement,
const nsAString& aAttrName,
const nsAString& aAttrValue)
{
nsCOMPtr<nsIAtom> attribute = NS_Atomize(aAttrName);
return GetAnonymousElementByAttribute(&aElement, attribute, aAttrValue);
}
NS_IMETHODIMP
nsDocument::GetAnonymousNodes(nsIDOMElement* aElement,
nsIDOMNodeList** aResult)
{
*aResult = nullptr;
nsCOMPtr<nsIContent> content(do_QueryInterface(aElement));
return BindingManager()->GetAnonymousNodesFor(content, aResult);
}
nsINodeList*
nsIDocument::GetAnonymousNodes(Element& aElement)
{
return BindingManager()->GetAnonymousNodesFor(&aElement);
}
NS_IMETHODIMP
nsDocument::CreateRange(nsIDOMRange** aReturn)
{
ErrorResult rv;
*aReturn = nsIDocument::CreateRange(rv).take();
return rv.StealNSResult();
}
already_AddRefed<nsRange>
nsIDocument::CreateRange(ErrorResult& rv)
{
RefPtr<nsRange> range = new nsRange(this);
nsresult res = range->Set(this, 0, this, 0);
if (NS_FAILED(res)) {
rv.Throw(res);
return nullptr;
}
return range.forget();
}
NS_IMETHODIMP
nsDocument::CreateNodeIterator(nsIDOMNode *aRoot,
uint32_t aWhatToShow,
nsIDOMNodeFilter *aFilter,
uint8_t aOptionalArgc,
nsIDOMNodeIterator **_retval)
{
*_retval = nullptr;
if (!aOptionalArgc) {
aWhatToShow = nsIDOMNodeFilter::SHOW_ALL;
}
if (!aRoot) {
return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
}
nsCOMPtr<nsINode> root = do_QueryInterface(aRoot);
NS_ENSURE_TRUE(root, NS_ERROR_UNEXPECTED);
ErrorResult rv;
*_retval = nsIDocument::CreateNodeIterator(*root, aWhatToShow,
NodeFilterHolder(aFilter),
rv).take();
return rv.StealNSResult();
}
already_AddRefed<NodeIterator>
nsIDocument::CreateNodeIterator(nsINode& aRoot, uint32_t aWhatToShow,
NodeFilter* aFilter,
ErrorResult& rv) const
{
return CreateNodeIterator(aRoot, aWhatToShow, NodeFilterHolder(aFilter), rv);
}
already_AddRefed<NodeIterator>
nsIDocument::CreateNodeIterator(nsINode& aRoot, uint32_t aWhatToShow,
NodeFilterHolder aFilter,
ErrorResult& rv) const
{
nsINode* root = &aRoot;
RefPtr<NodeIterator> iterator = new NodeIterator(root, aWhatToShow,
Move(aFilter));
return iterator.forget();
}
NS_IMETHODIMP
nsDocument::CreateTreeWalker(nsIDOMNode *aRoot,
uint32_t aWhatToShow,
nsIDOMNodeFilter *aFilter,
uint8_t aOptionalArgc,
nsIDOMTreeWalker **_retval)
{
*_retval = nullptr;
if (!aOptionalArgc) {
aWhatToShow = nsIDOMNodeFilter::SHOW_ALL;
}
nsCOMPtr<nsINode> root = do_QueryInterface(aRoot);
NS_ENSURE_TRUE(root, NS_ERROR_DOM_NOT_SUPPORTED_ERR);
ErrorResult rv;
*_retval = nsIDocument::CreateTreeWalker(*root, aWhatToShow,
NodeFilterHolder(aFilter),
rv).take();
return rv.StealNSResult();
}
already_AddRefed<TreeWalker>
nsIDocument::CreateTreeWalker(nsINode& aRoot, uint32_t aWhatToShow,
NodeFilter* aFilter,
ErrorResult& rv) const
{
return CreateTreeWalker(aRoot, aWhatToShow, NodeFilterHolder(aFilter), rv);
}
already_AddRefed<TreeWalker>
nsIDocument::CreateTreeWalker(nsINode& aRoot, uint32_t aWhatToShow,
NodeFilterHolder aFilter, ErrorResult& rv) const
{
nsINode* root = &aRoot;
RefPtr<TreeWalker> walker = new TreeWalker(root, aWhatToShow, Move(aFilter));
return walker.forget();
}
NS_IMETHODIMP
nsDocument::GetDefaultView(mozIDOMWindowProxy** aDefaultView)
{
*aDefaultView = nullptr;
nsCOMPtr<nsPIDOMWindowOuter> win = GetWindow();
win.forget(aDefaultView);
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetLocation(nsIDOMLocation **_retval)
{
*_retval = nsIDocument::GetLocation().take();
return NS_OK;
}
already_AddRefed<Location>
nsIDocument::GetLocation() const
{
nsCOMPtr<nsPIDOMWindowInner> w = do_QueryInterface(mScriptGlobalObject);
if (!w) {
return nullptr;
}
nsGlobalWindow* window = nsGlobalWindow::Cast(w);
ErrorResult dummy;
RefPtr<Location> loc = window->GetLocation(dummy);
dummy.SuppressException();
return loc.forget();
}
Element*
nsIDocument::GetHtmlElement() const
{
Element* rootElement = GetRootElement();
if (rootElement && rootElement->IsHTMLElement(nsGkAtoms::html))
return rootElement;
return nullptr;
}
Element*
nsIDocument::GetHtmlChildElement(nsIAtom* aTag)
{
Element* html = GetHtmlElement();
if (!html)
return nullptr;
// Look for the element with aTag inside html. This needs to run
// forwards to find the first such element.
for (nsIContent* child = html->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->IsHTMLElement(aTag))
return child->AsElement();
}
return nullptr;
}
Element*
nsDocument::GetTitleElement()
{
// mMayHaveTitleElement will have been set to true if any HTML or SVG
// <title> element has been bound to this document. So if it's false,
// we know there is nothing to do here. This avoids us having to search
// the whole DOM if someone calls document.title on a large document
// without a title.
if (!mMayHaveTitleElement)
return nullptr;
Element* root = GetRootElement();
if (root && root->IsSVGElement(nsGkAtoms::svg)) {
// In SVG, the document's title must be a child
for (nsIContent* child = root->GetFirstChild();
child; child = child->GetNextSibling()) {
if (child->IsSVGElement(nsGkAtoms::title)) {
return child->AsElement();
}
}
return nullptr;
}
// We check the HTML namespace even for non-HTML documents, except SVG. This
// matches the spec and the behavior of all tested browsers.
RefPtr<nsContentList> list =
NS_GetContentList(this, kNameSpaceID_XHTML, NS_LITERAL_STRING("title"));
nsIContent* first = list->Item(0, false);
return first ? first->AsElement() : nullptr;
}
NS_IMETHODIMP
nsDocument::GetTitle(nsAString& aTitle)
{
nsString title;
GetTitle(title);
aTitle = title;
return NS_OK;
}
void
nsDocument::GetTitle(nsString& aTitle)
{
aTitle.Truncate();
Element* rootElement = GetRootElement();
if (!rootElement) {
return;
}
nsAutoString tmp;
#ifdef MOZ_XUL
if (rootElement->IsXULElement()) {
rootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::title, tmp);
} else
#endif
{
Element* title = GetTitleElement();
if (!title) {
return;
}
nsContentUtils::GetNodeTextContent(title, false, tmp);
}
tmp.CompressWhitespace();
aTitle = tmp;
}
NS_IMETHODIMP
nsDocument::SetTitle(const nsAString& aTitle)
{
Element* rootElement = GetRootElement();
if (!rootElement) {
return NS_OK;
}
#ifdef MOZ_XUL
if (rootElement->IsXULElement()) {
return rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::title,
aTitle, true);
}
#endif
// Batch updates so that mutation events don't change "the title
// element" under us
mozAutoDocUpdate updateBatch(this, UPDATE_CONTENT_MODEL, true);
nsCOMPtr<Element> title = GetTitleElement();
if (rootElement->IsSVGElement(nsGkAtoms::svg)) {
if (!title) {
RefPtr<mozilla::dom::NodeInfo> titleInfo =
mNodeInfoManager->GetNodeInfo(nsGkAtoms::title, nullptr,
kNameSpaceID_SVG,
nsIDOMNode::ELEMENT_NODE);
NS_NewSVGElement(getter_AddRefs(title), titleInfo.forget(),
NOT_FROM_PARSER);
if (!title) {
return NS_OK;
}
rootElement->InsertChildAt(title, 0, true);
}
} else if (rootElement->IsHTMLElement()) {
if (!title) {
Element* head = GetHeadElement();
if (!head) {
return NS_OK;
}
RefPtr<mozilla::dom::NodeInfo> titleInfo;
titleInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::title, nullptr,
kNameSpaceID_XHTML,
nsIDOMNode::ELEMENT_NODE);
title = NS_NewHTMLTitleElement(titleInfo.forget());
if (!title) {
return NS_OK;
}
head->AppendChildTo(title, true);
}
} else {
return NS_OK;
}
return nsContentUtils::SetNodeTextContent(title, aTitle, false);
}
void
nsDocument::SetTitle(const nsAString& aTitle, ErrorResult& rv)
{
rv = SetTitle(aTitle);
}
void
nsDocument::NotifyPossibleTitleChange(bool aBoundTitleElement)
{
NS_ASSERTION(!mInUnlinkOrDeletion || !aBoundTitleElement,
"Setting a title while unlinking or destroying the element?");
if (mInUnlinkOrDeletion) {
return;
}
if (aBoundTitleElement) {
mMayHaveTitleElement = true;
}
if (mPendingTitleChangeEvent.IsPending())
return;
RefPtr<nsRunnableMethod<nsDocument, void, false> > event =
NewNonOwningRunnableMethod(this,
&nsDocument::DoNotifyPossibleTitleChange);
nsresult rv = NS_DispatchToCurrentThread(event);
if (NS_SUCCEEDED(rv)) {
mPendingTitleChangeEvent = event;
}
}
void
nsDocument::DoNotifyPossibleTitleChange()
{
mPendingTitleChangeEvent.Forget();
mHaveFiredTitleChange = true;
nsAutoString title;
GetTitle(title);
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
nsCOMPtr<nsISupports> container =
shell->GetPresContext()->GetContainerWeak();
if (container) {
nsCOMPtr<nsIBaseWindow> docShellWin = do_QueryInterface(container);
if (docShellWin) {
docShellWin->SetTitle(title.get());
}
}
}
// Fire a DOM event for the title change.
nsContentUtils::DispatchChromeEvent(this, static_cast<nsIDocument*>(this),
NS_LITERAL_STRING("DOMTitleChanged"),
true, true);
}
already_AddRefed<BoxObject>
nsDocument::GetBoxObjectFor(Element* aElement, ErrorResult& aRv)
{
if (!aElement) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsIDocument* doc = aElement->OwnerDoc();
if (doc != this) {
aRv.Throw(NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
return nullptr;
}
if (!mHasWarnedAboutBoxObjects && !aElement->IsXULElement()) {
mHasWarnedAboutBoxObjects = true;
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("BoxObjects"), this,
nsContentUtils::eDOM_PROPERTIES,
"UseOfGetBoxObjectForWarning");
}
if (!mBoxObjectTable) {
mBoxObjectTable = new nsInterfaceHashtable<nsPtrHashKey<nsIContent>, nsPIBoxObject>(6);
} else {
nsCOMPtr<nsPIBoxObject> boxObject = mBoxObjectTable->Get(aElement);
if (boxObject) {
return boxObject.forget().downcast<BoxObject>();
}
}
int32_t namespaceID;
nsCOMPtr<nsIAtom> tag = BindingManager()->ResolveTag(aElement, &namespaceID);
nsAutoCString contractID("@mozilla.org/layout/xul-boxobject");
if (namespaceID == kNameSpaceID_XUL) {
if (tag == nsGkAtoms::browser ||
tag == nsGkAtoms::editor ||
tag == nsGkAtoms::iframe)
contractID += "-container";
else if (tag == nsGkAtoms::menu)
contractID += "-menu";
else if (tag == nsGkAtoms::popup ||
tag == nsGkAtoms::menupopup ||
tag == nsGkAtoms::panel ||
tag == nsGkAtoms::tooltip)
contractID += "-popup";
else if (tag == nsGkAtoms::tree)
contractID += "-tree";
else if (tag == nsGkAtoms::listbox)
contractID += "-listbox";
else if (tag == nsGkAtoms::scrollbox)
contractID += "-scrollbox";
}
contractID += ";1";
nsCOMPtr<nsPIBoxObject> boxObject(do_CreateInstance(contractID.get()));
if (!boxObject) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
boxObject->Init(aElement);
if (mBoxObjectTable) {
mBoxObjectTable->Put(aElement, boxObject.get());
}
return boxObject.forget().downcast<BoxObject>();
}
void
nsDocument::ClearBoxObjectFor(nsIContent* aContent)
{
if (mBoxObjectTable) {
nsPIBoxObject *boxObject = mBoxObjectTable->GetWeak(aContent);
if (boxObject) {
boxObject->Clear();
mBoxObjectTable->Remove(aContent);
}
}
}
already_AddRefed<MediaQueryList>
nsIDocument::MatchMedia(const nsAString& aMediaQueryList)
{
RefPtr<MediaQueryList> result = new MediaQueryList(this, aMediaQueryList);
// Insert the new item at the end of the linked list.
PR_INSERT_BEFORE(result, &mDOMMediaQueryLists);
return result.forget();
}
void
nsDocument::FlushSkinBindings()
{
BindingManager()->FlushSkinBindings();
}
nsresult
nsDocument::InitializeFrameLoader(nsFrameLoader* aLoader)
{
mInitializableFrameLoaders.RemoveElement(aLoader);
// Don't even try to initialize.
if (mInDestructor) {
NS_WARNING("Trying to initialize a frame loader while"
"document is being deleted");
return NS_ERROR_FAILURE;
}
mInitializableFrameLoaders.AppendElement(aLoader);
if (!mFrameLoaderRunner) {
mFrameLoaderRunner =
NewRunnableMethod(this, &nsDocument::MaybeInitializeFinalizeFrameLoaders);
NS_ENSURE_TRUE(mFrameLoaderRunner, NS_ERROR_OUT_OF_MEMORY);
nsContentUtils::AddScriptRunner(mFrameLoaderRunner);
}
return NS_OK;
}
nsresult
nsDocument::FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer)
{
mInitializableFrameLoaders.RemoveElement(aLoader);
if (mInDestructor) {
return NS_ERROR_FAILURE;
}
mFrameLoaderFinalizers.AppendElement(aFinalizer);
if (!mFrameLoaderRunner) {
mFrameLoaderRunner =
NewRunnableMethod(this, &nsDocument::MaybeInitializeFinalizeFrameLoaders);
NS_ENSURE_TRUE(mFrameLoaderRunner, NS_ERROR_OUT_OF_MEMORY);
nsContentUtils::AddScriptRunner(mFrameLoaderRunner);
}
return NS_OK;
}
void
nsDocument::MaybeInitializeFinalizeFrameLoaders()
{
if (mDelayFrameLoaderInitialization || mUpdateNestLevel != 0) {
// This method will be recalled when mUpdateNestLevel drops to 0,
// or when !mDelayFrameLoaderInitialization.
mFrameLoaderRunner = nullptr;
return;
}
// We're not in an update, but it is not safe to run scripts, so
// postpone frameloader initialization and finalization.
if (!nsContentUtils::IsSafeToRunScript()) {
if (!mInDestructor && !mFrameLoaderRunner &&
(mInitializableFrameLoaders.Length() ||
mFrameLoaderFinalizers.Length())) {
mFrameLoaderRunner =
NewRunnableMethod(this, &nsDocument::MaybeInitializeFinalizeFrameLoaders);
nsContentUtils::AddScriptRunner(mFrameLoaderRunner);
}
return;
}
mFrameLoaderRunner = nullptr;
// Don't use a temporary array for mInitializableFrameLoaders, because
// loading a frame may cause some other frameloader to be removed from the
// array. But be careful to keep the loader alive when starting the load!
while (mInitializableFrameLoaders.Length()) {
RefPtr<nsFrameLoader> loader = mInitializableFrameLoaders[0];
mInitializableFrameLoaders.RemoveElementAt(0);
NS_ASSERTION(loader, "null frameloader in the array?");
loader->ReallyStartLoading();
}
uint32_t length = mFrameLoaderFinalizers.Length();
if (length > 0) {
nsTArray<nsCOMPtr<nsIRunnable> > finalizers;
mFrameLoaderFinalizers.SwapElements(finalizers);
for (uint32_t i = 0; i < length; ++i) {
finalizers[i]->Run();
}
}
}
void
nsDocument::TryCancelFrameLoaderInitialization(nsIDocShell* aShell)
{
uint32_t length = mInitializableFrameLoaders.Length();
for (uint32_t i = 0; i < length; ++i) {
if (mInitializableFrameLoaders[i]->GetExistingDocShell() == aShell) {
mInitializableFrameLoaders.RemoveElementAt(i);
return;
}
}
}
nsIDocument*
nsDocument::RequestExternalResource(nsIURI* aURI,
nsINode* aRequestingNode,
ExternalResourceLoad** aPendingLoad)
{
NS_PRECONDITION(aURI, "Must have a URI");
NS_PRECONDITION(aRequestingNode, "Must have a node");
if (mDisplayDocument) {
return mDisplayDocument->RequestExternalResource(aURI,
aRequestingNode,
aPendingLoad);
}
return mExternalResourceMap.RequestResource(aURI, aRequestingNode,
this, aPendingLoad);
}
void
nsDocument::EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData)
{
mExternalResourceMap.EnumerateResources(aCallback, aData);
}
nsSMILAnimationController*
nsDocument::GetAnimationController()
{
// We create the animation controller lazily because most documents won't want
// one and only SVG documents and the like will call this
if (mAnimationController)
return mAnimationController;
// Refuse to create an Animation Controller for data documents.
if (mLoadedAsData || mLoadedAsInteractiveData)
return nullptr;
mAnimationController = new nsSMILAnimationController(this);
// If there's a presContext then check the animation mode and pause if
// necessary.
nsIPresShell *shell = GetShell();
if (mAnimationController && shell) {
nsPresContext *context = shell->GetPresContext();
if (context &&
context->ImageAnimationMode() == imgIContainer::kDontAnimMode) {
mAnimationController->Pause(nsSMILTimeContainer::PAUSE_USERPREF);
}
}
// If we're hidden (or being hidden), notify the newly-created animation
// controller. (Skip this check for SVG-as-an-image documents, though,
// because they don't get OnPageShow / OnPageHide calls).
if (!mIsShowing && !mIsBeingUsedAsImage) {
mAnimationController->OnPageHide();
}
return mAnimationController;
}
PendingAnimationTracker*
nsDocument::GetOrCreatePendingAnimationTracker()
{
if (!mPendingAnimationTracker) {
mPendingAnimationTracker = new PendingAnimationTracker(this);
}
return mPendingAnimationTracker;
}
/**
* Retrieve the "direction" property of the document.
*
* @lina 01/09/2001
*/
NS_IMETHODIMP
nsDocument::GetDir(nsAString& aDirection)
{
nsIDocument::GetDir(aDirection);
return NS_OK;
}
void
nsIDocument::GetDir(nsAString& aDirection) const
{
aDirection.Truncate();
Element* rootElement = GetHtmlElement();
if (rootElement) {
static_cast<nsGenericHTMLElement*>(rootElement)->GetDir(aDirection);
}
}
/**
* Set the "direction" property of the document.
*
* @lina 01/09/2001
*/
NS_IMETHODIMP
nsDocument::SetDir(const nsAString& aDirection)
{
nsIDocument::SetDir(aDirection);
return NS_OK;
}
void
nsIDocument::SetDir(const nsAString& aDirection)
{
Element* rootElement = GetHtmlElement();
if (rootElement) {
rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir,
aDirection, true);
}
}
NS_IMETHODIMP
nsDocument::GetInputEncoding(nsAString& aInputEncoding)
{
nsIDocument::GetCharacterSet(aInputEncoding);
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetMozSyntheticDocument(bool *aSyntheticDocument)
{
*aSyntheticDocument = mIsSyntheticDocument;
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetDocumentURI(nsAString& aDocumentURI)
{
nsString temp;
nsresult rv = nsIDocument::GetDocumentURI(temp);
aDocumentURI = temp;
return rv;
}
nsresult
nsIDocument::GetDocumentURI(nsString& aDocumentURI) const
{
if (mDocumentURI) {
nsAutoCString uri;
nsresult rv = mDocumentURI->GetSpec(uri);
NS_ENSURE_SUCCESS(rv, rv);
CopyUTF8toUTF16(uri, aDocumentURI);
} else {
aDocumentURI.Truncate();
}
return NS_OK;
}
// Alias of above
NS_IMETHODIMP
nsDocument::GetURL(nsAString& aURL)
{
return GetDocumentURI(aURL);
}
nsresult
nsIDocument::GetURL(nsString& aURL) const
{
return GetDocumentURI(aURL);
}
void
nsIDocument::GetDocumentURIFromJS(nsString& aDocumentURI, ErrorResult& aRv) const
{
if (!mChromeXHRDocURI || !nsContentUtils::IsCallerChrome()) {
aRv = GetDocumentURI(aDocumentURI);
return;
}
nsAutoCString uri;
nsresult res = mChromeXHRDocURI->GetSpec(uri);
if (NS_FAILED(res)) {
aRv.Throw(res);
return;
}
CopyUTF8toUTF16(uri, aDocumentURI);
}
nsIURI*
nsIDocument::GetDocumentURIObject() const
{
if (!mChromeXHRDocURI) {
return GetDocumentURI();
}
return mChromeXHRDocURI;
}
// Returns "BackCompat" if we are in quirks mode, "CSS1Compat" if we are
// in almost standards or full standards mode. See bug 105640. This was
// implemented to match MSIE's compatMode property.
NS_IMETHODIMP
nsDocument::GetCompatMode(nsAString& aCompatMode)
{
nsString temp;
nsIDocument::GetCompatMode(temp);
aCompatMode = temp;
return NS_OK;
}
void
nsIDocument::GetCompatMode(nsString& aCompatMode) const
{
NS_ASSERTION(mCompatMode == eCompatibility_NavQuirks ||
mCompatMode == eCompatibility_AlmostStandards ||
mCompatMode == eCompatibility_FullStandards,
"mCompatMode is neither quirks nor strict for this document");
if (mCompatMode == eCompatibility_NavQuirks) {
aCompatMode.AssignLiteral("BackCompat");
} else {
aCompatMode.AssignLiteral("CSS1Compat");
}
}
void
nsDOMAttributeMap::BlastSubtreeToPieces(nsINode *aNode)
{
if (aNode->IsElement()) {
Element *element = aNode->AsElement();
const nsDOMAttributeMap *map = element->GetAttributeMap();
if (map) {
// This non-standard style of iteration is presumably used because some
// of the code in the loop body can trigger element removal, which
// invalidates the iterator.
while (true) {
auto iter = map->mAttributeCache.ConstIter();
if (iter.Done()) {
break;
}
nsCOMPtr<nsIAttribute> attr = iter.UserData();
NS_ASSERTION(attr.get(),
"non-nsIAttribute somehow made it into the hashmap?!");
BlastSubtreeToPieces(attr);
DebugOnly<nsresult> rv =
element->UnsetAttr(attr->NodeInfo()->NamespaceID(),
attr->NodeInfo()->NameAtom(),
false);
// XXX Should we abort here?
NS_ASSERTION(NS_SUCCEEDED(rv), "Uh-oh, UnsetAttr shouldn't fail!");
}
}
}
uint32_t count = aNode->GetChildCount();
for (uint32_t i = 0; i < count; ++i) {
BlastSubtreeToPieces(aNode->GetFirstChild());
aNode->RemoveChildAt(0, false);
}
}
NS_IMETHODIMP
nsDocument::AdoptNode(nsIDOMNode *aAdoptedNode, nsIDOMNode **aResult)
{
*aResult = nullptr;
nsCOMPtr<nsINode> adoptedNode = do_QueryInterface(aAdoptedNode);
NS_ENSURE_TRUE(adoptedNode, NS_ERROR_UNEXPECTED);
ErrorResult rv;
nsINode* result = nsIDocument::AdoptNode(*adoptedNode, rv);
if (rv.Failed()) {
return rv.StealNSResult();
}
NS_ADDREF(*aResult = result->AsDOMNode());
return NS_OK;
}
nsINode*
nsIDocument::AdoptNode(nsINode& aAdoptedNode, ErrorResult& rv)
{
nsINode* adoptedNode = &aAdoptedNode;
// Scope firing mutation events so that we don't carry any state that
// might be stale
{
nsINode* parent = adoptedNode->GetParentNode();
if (parent) {
nsContentUtils::MaybeFireNodeRemoved(adoptedNode, parent,
adoptedNode->OwnerDoc());
}
}
nsAutoScriptBlocker scriptBlocker;
switch (adoptedNode->NodeType()) {
case nsIDOMNode::ATTRIBUTE_NODE:
{
// Remove from ownerElement.
RefPtr<Attr> adoptedAttr = static_cast<Attr*>(adoptedNode);
nsCOMPtr<Element> ownerElement = adoptedAttr->GetOwnerElement(rv);
if (rv.Failed()) {
return nullptr;
}
if (ownerElement) {
RefPtr<Attr> newAttr =
ownerElement->RemoveAttributeNode(*adoptedAttr, rv);
if (rv.Failed()) {
return nullptr;
}
newAttr.swap(adoptedAttr);
}
break;
}
case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
{
if (ShadowRoot::FromNode(adoptedNode)) {
rv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
return nullptr;
}
MOZ_FALLTHROUGH;
}
case nsIDOMNode::ELEMENT_NODE:
case nsIDOMNode::PROCESSING_INSTRUCTION_NODE:
case nsIDOMNode::TEXT_NODE:
case nsIDOMNode::CDATA_SECTION_NODE:
case nsIDOMNode::COMMENT_NODE:
case nsIDOMNode::DOCUMENT_TYPE_NODE:
{
// Don't allow adopting a node's anonymous subtree out from under it.
if (adoptedNode->AsContent()->IsRootOfAnonymousSubtree()) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
// We don't want to adopt an element into its own contentDocument or into
// a descendant contentDocument, so we check if the frameElement of this
// document or any of its parents is the adopted node or one of its
// descendants.
nsIDocument *doc = this;
do {
if (nsPIDOMWindowOuter *win = doc->GetWindow()) {
nsCOMPtr<nsINode> node = win->GetFrameElementInternal();
if (node &&
nsContentUtils::ContentIsDescendantOf(node, adoptedNode)) {
rv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
return nullptr;
}
}
} while ((doc = doc->GetParentDocument()));
// Remove from parent.
nsCOMPtr<nsINode> parent = adoptedNode->GetParentNode();
if (parent) {
int32_t idx = parent->IndexOf(adoptedNode);
MOZ_ASSERT(idx >= 0);
parent->RemoveChildAt(idx, true);
} else {
MOZ_ASSERT(!adoptedNode->IsInUncomposedDoc());
// If we're adopting a node that's not in a document, it might still
// have a binding applied. Remove the binding from the element now
// that it's getting adopted into a new document.
// TODO Fully tear down the binding.
adoptedNode->AsContent()->SetXBLBinding(nullptr);
}
break;
}
case nsIDOMNode::DOCUMENT_NODE:
{
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
default:
{
NS_WARNING("Don't know how to adopt this nodetype for adoptNode.");
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
}
nsCOMPtr<nsIDocument> oldDocument = adoptedNode->OwnerDoc();
bool sameDocument = oldDocument == this;
AutoJSContext cx;
JS::Rooted<JSObject*> newScope(cx, nullptr);
if (!sameDocument) {
newScope = GetWrapper();
if (!newScope && GetScopeObject() && GetScopeObject()->GetGlobalJSObject()) {
// Make sure cx is in a semi-sane compartment before we call WrapNative.
// It's kind of irrelevant, given that we're passing aAllowWrapping =
// false, and documents should always insist on being wrapped in an
// canonical scope. But we try to pass something sane anyway.
JSAutoCompartment ac(cx, GetScopeObject()->GetGlobalJSObject());
JS::Rooted<JS::Value> v(cx);
rv = nsContentUtils::WrapNative(cx, this, this, &v,
/* aAllowWrapping = */ false);
if (rv.Failed())
return nullptr;
newScope = &v.toObject();
}
}
nsCOMArray<nsINode> nodesWithProperties;
rv = nsNodeUtils::Adopt(adoptedNode, sameDocument ? nullptr : mNodeInfoManager,
newScope, nodesWithProperties);
if (rv.Failed()) {
// Disconnect all nodes from their parents, since some have the old document
// as their ownerDocument and some have this as their ownerDocument.
nsDOMAttributeMap::BlastSubtreeToPieces(adoptedNode);
if (!sameDocument && oldDocument) {
uint32_t count = nodesWithProperties.Count();
for (uint32_t j = 0; j < oldDocument->GetPropertyTableCount(); ++j) {
for (uint32_t i = 0; i < count; ++i) {
// Remove all properties.
oldDocument->PropertyTable(j)->
DeleteAllPropertiesFor(nodesWithProperties[i]);
}
}
}
return nullptr;
}
uint32_t count = nodesWithProperties.Count();
if (!sameDocument && oldDocument) {
for (uint32_t j = 0; j < oldDocument->GetPropertyTableCount(); ++j) {
nsPropertyTable *oldTable = oldDocument->PropertyTable(j);
nsPropertyTable *newTable = PropertyTable(j);
for (uint32_t i = 0; i < count; ++i) {
rv = oldTable->TransferOrDeleteAllPropertiesFor(nodesWithProperties[i],
newTable);
}
}
if (rv.Failed()) {
// Disconnect all nodes from their parents.
nsDOMAttributeMap::BlastSubtreeToPieces(adoptedNode);
return nullptr;
}
}
NS_ASSERTION(adoptedNode->OwnerDoc() == this,
"Should still be in the document we just got adopted into");
return adoptedNode;
}
nsViewportInfo
nsDocument::GetViewportInfo(const ScreenIntSize& aDisplaySize)
{
// Compute the CSS-to-LayoutDevice pixel scale as the product of the
// widget scale and the full zoom.
nsPresContext* context = mPresShell->GetPresContext();
// When querying the full zoom, get it from the device context rather than
// directly from the pres context, because the device context's value can
// include an adjustment necessay to keep the number of app units per device
// pixel an integer, and we want the adjusted value.
float fullZoom = context ? context->DeviceContext()->GetFullZoom() : 1.0;
fullZoom = (fullZoom == 0.0) ? 1.0 : fullZoom;
CSSToLayoutDeviceScale layoutDeviceScale = context ? context->CSSToDevPixelScale() : CSSToLayoutDeviceScale(1);
CSSToScreenScale defaultScale = layoutDeviceScale
* LayoutDeviceToScreenScale(1.0);
// Special behaviour for desktop mode, provided we are not on an about: page
nsPIDOMWindowOuter* win = GetWindow();
if (win && win->IsDesktopModeViewport() && !IsAboutPage())
{
CSSCoord viewportWidth = gfxPrefs::DesktopViewportWidth() / fullZoom;
CSSToScreenScale scaleToFit(aDisplaySize.width / viewportWidth);
float aspectRatio = (float)aDisplaySize.height / aDisplaySize.width;
CSSSize viewportSize(viewportWidth, viewportWidth * aspectRatio);
ScreenIntSize fakeDesktopSize = RoundedToInt(viewportSize * scaleToFit);
return nsViewportInfo(fakeDesktopSize,
scaleToFit,
/*allowZoom*/ true);
}
if (!gfxPrefs::MetaViewportEnabled()) {
return nsViewportInfo(aDisplaySize,
defaultScale,
/*allowZoom*/ false);
}
// In cases where the width of the CSS viewport is less than or equal to the width
// of the display (i.e. width <= device-width) then we disable double-tap-to-zoom
// behaviour. See bug 941995 for details.
switch (mViewportType) {
case DisplayWidthHeight:
return nsViewportInfo(aDisplaySize,
defaultScale,
/*allowZoom*/ true);
case Unknown:
{
nsAutoString viewport;
GetHeaderData(nsGkAtoms::viewport, viewport);
if (viewport.IsEmpty()) {
// If the docType specifies that we are on a site optimized for mobile,
// then we want to return specially crafted defaults for the viewport info.
nsCOMPtr<nsIDOMDocumentType> docType;
nsresult rv = GetDoctype(getter_AddRefs(docType));
if (NS_SUCCEEDED(rv) && docType) {
nsAutoString docId;
rv = docType->GetPublicId(docId);
if (NS_SUCCEEDED(rv)) {
if ((docId.Find("WAP") != -1) ||
(docId.Find("Mobile") != -1) ||
(docId.Find("WML") != -1))
{
// We're making an assumption that the docType can't change here
mViewportType = DisplayWidthHeight;
return nsViewportInfo(aDisplaySize,
defaultScale,
/*allowZoom*/true);
}
}
}
nsAutoString handheldFriendly;
GetHeaderData(nsGkAtoms::handheldFriendly, handheldFriendly);
if (handheldFriendly.EqualsLiteral("true")) {
mViewportType = DisplayWidthHeight;
return nsViewportInfo(aDisplaySize,
defaultScale,
/*allowZoom*/true);
}
}
nsAutoString minScaleStr;
GetHeaderData(nsGkAtoms::viewport_minimum_scale, minScaleStr);
nsresult errorCode;
mScaleMinFloat = LayoutDeviceToScreenScale(minScaleStr.ToFloat(&errorCode));
if (NS_FAILED(errorCode)) {
mScaleMinFloat = kViewportMinScale;
}
mScaleMinFloat = mozilla::clamped(
mScaleMinFloat, kViewportMinScale, kViewportMaxScale);
nsAutoString maxScaleStr;
GetHeaderData(nsGkAtoms::viewport_maximum_scale, maxScaleStr);
// We define a special error code variable for the scale and max scale,
// because they are used later (see the width calculations).
nsresult scaleMaxErrorCode;
mScaleMaxFloat = LayoutDeviceToScreenScale(maxScaleStr.ToFloat(&scaleMaxErrorCode));
if (NS_FAILED(scaleMaxErrorCode)) {
mScaleMaxFloat = kViewportMaxScale;
}
mScaleMaxFloat = mozilla::clamped(
mScaleMaxFloat, kViewportMinScale, kViewportMaxScale);
nsAutoString scaleStr;
GetHeaderData(nsGkAtoms::viewport_initial_scale, scaleStr);
nsresult scaleErrorCode;
mScaleFloat = LayoutDeviceToScreenScale(scaleStr.ToFloat(&scaleErrorCode));
nsAutoString widthStr, heightStr;
GetHeaderData(nsGkAtoms::viewport_height, heightStr);
GetHeaderData(nsGkAtoms::viewport_width, widthStr);
mAutoSize = false;
if (widthStr.EqualsLiteral("device-width")) {
mAutoSize = true;
}
if (widthStr.IsEmpty() &&
(heightStr.EqualsLiteral("device-height") ||
(mScaleFloat.scale == 1.0)))
{
mAutoSize = true;
}
nsresult widthErrorCode, heightErrorCode;
mViewportSize.width = widthStr.ToInteger(&widthErrorCode);
mViewportSize.height = heightStr.ToInteger(&heightErrorCode);
// If width or height has not been set to a valid number by this point,
// fall back to a default value.
mValidWidth = (!widthStr.IsEmpty() && NS_SUCCEEDED(widthErrorCode) && mViewportSize.width > 0);
mValidHeight = (!heightStr.IsEmpty() && NS_SUCCEEDED(heightErrorCode) && mViewportSize.height > 0);
mAllowZoom = true;
nsAutoString userScalable;
GetHeaderData(nsGkAtoms::viewport_user_scalable, userScalable);
if ((userScalable.EqualsLiteral("0")) ||
(userScalable.EqualsLiteral("no")) ||
(userScalable.EqualsLiteral("false"))) {
mAllowZoom = false;
}
mScaleStrEmpty = scaleStr.IsEmpty();
mWidthStrEmpty = widthStr.IsEmpty();
mValidScaleFloat = !scaleStr.IsEmpty() && NS_SUCCEEDED(scaleErrorCode);
mValidMaxScale = !maxScaleStr.IsEmpty() && NS_SUCCEEDED(scaleMaxErrorCode);
mViewportType = Specified;
MOZ_FALLTHROUGH;
}
case Specified:
default:
LayoutDeviceToScreenScale effectiveMinScale = mScaleMinFloat;
LayoutDeviceToScreenScale effectiveMaxScale = mScaleMaxFloat;
bool effectiveValidMaxScale = mValidMaxScale;
bool effectiveAllowZoom = mAllowZoom;
if (gfxPrefs::ForceUserScalable()) {
// If the pref to force user-scalable is enabled, we ignore the values
// from the meta-viewport tag for these properties and just assume they
// allow the page to be scalable. Note in particular that this code is
// in the "Specified" branch of the enclosing switch statement, so that
// calls to GetViewportInfo always use the latest value of the
// ForceUserScalable pref. Other codepaths that return nsViewportInfo
// instances are all consistent with ForceUserScalable() already.
effectiveMinScale = kViewportMinScale;
effectiveMaxScale = kViewportMaxScale;
effectiveValidMaxScale = true;
effectiveAllowZoom = true;
}
CSSSize size = mViewportSize;
if (!mValidWidth) {
if (mValidHeight && !aDisplaySize.IsEmpty()) {
size.width = size.height * aDisplaySize.width / aDisplaySize.height;
} else {
// Stretch CSS pixel size of viewport to keep device pixel size
// unchanged after full zoom applied.
// See bug 974242.
size.width = gfxPrefs::DesktopViewportWidth() / fullZoom;
}
}
if (!mValidHeight) {
if (!aDisplaySize.IsEmpty()) {
size.height = size.width * aDisplaySize.height / aDisplaySize.width;
} else {
size.height = size.width;
}
}
CSSToScreenScale scaleFloat = mScaleFloat * layoutDeviceScale;
CSSToScreenScale scaleMinFloat = effectiveMinScale * layoutDeviceScale;
CSSToScreenScale scaleMaxFloat = effectiveMaxScale * layoutDeviceScale;
if (mAutoSize) {
// aDisplaySize is in screen pixels; convert them to CSS pixels for the viewport size.
CSSToScreenScale defaultPixelScale = layoutDeviceScale * LayoutDeviceToScreenScale(1.0f);
size = ScreenSize(aDisplaySize) / defaultPixelScale;
}
size.width = clamped(size.width, float(kViewportMinSize.width), float(kViewportMaxSize.width));
// Also recalculate the default zoom, if it wasn't specified in the metadata,
// and the width is specified.
if (mScaleStrEmpty && !mWidthStrEmpty) {
CSSToScreenScale defaultScale(float(aDisplaySize.width) / size.width);
scaleFloat = (scaleFloat > defaultScale) ? scaleFloat : defaultScale;
}
size.height = clamped(size.height, float(kViewportMinSize.height), float(kViewportMaxSize.height));
// We need to perform a conversion, but only if the initial or maximum
// scale were set explicitly by the user.
if (mValidScaleFloat && scaleFloat >= scaleMinFloat && scaleFloat <= scaleMaxFloat) {
CSSSize displaySize = ScreenSize(aDisplaySize) / scaleFloat;
size.width = std::max(size.width, displaySize.width);
size.height = std::max(size.height, displaySize.height);
} else if (effectiveValidMaxScale) {
CSSSize displaySize = ScreenSize(aDisplaySize) / scaleMaxFloat;
size.width = std::max(size.width, displaySize.width);
size.height = std::max(size.height, displaySize.height);
}
return nsViewportInfo(scaleFloat, scaleMinFloat, scaleMaxFloat, size,
mAutoSize, effectiveAllowZoom);
}
}
EventListenerManager*
nsDocument::GetOrCreateListenerManager()
{
if (!mListenerManager) {
mListenerManager =
new EventListenerManager(static_cast<EventTarget*>(this));
SetFlags(NODE_HAS_LISTENERMANAGER);
}
return mListenerManager;
}
EventListenerManager*
nsDocument::GetExistingListenerManager() const
{
return mListenerManager;
}
nsresult
nsDocument::PreHandleEvent(EventChainPreVisitor& aVisitor)
{
aVisitor.mCanHandle = true;
// FIXME! This is a hack to make middle mouse paste working also in Editor.
// Bug 329119
aVisitor.mForceContentDispatch = true;
// Load events must not propagate to |window| object, see bug 335251.
if (aVisitor.mEvent->mMessage != eLoad) {
nsGlobalWindow* window = nsGlobalWindow::Cast(GetWindow());
aVisitor.mParentTarget =
window ? window->GetTargetForEventTargetChain() : nullptr;
}
return NS_OK;
}
NS_IMETHODIMP
nsDocument::CreateEvent(const nsAString& aEventType, nsIDOMEvent** aReturn)
{
NS_ENSURE_ARG_POINTER(aReturn);
ErrorResult rv;
*aReturn = nsIDocument::CreateEvent(aEventType, rv).take();
return rv.StealNSResult();
}
already_AddRefed<Event>
nsIDocument::CreateEvent(const nsAString& aEventType, ErrorResult& rv) const
{
nsIPresShell *shell = GetShell();
nsPresContext *presContext = nullptr;
if (shell) {
// Retrieve the context
presContext = shell->GetPresContext();
}
// Create event even without presContext.
RefPtr<Event> ev =
EventDispatcher::CreateEvent(const_cast<nsIDocument*>(this), presContext,
nullptr, aEventType);
if (!ev) {
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
WidgetEvent* e = ev->WidgetEventPtr();
e->mFlags.mBubbles = false;
e->mFlags.mCancelable = false;
return ev.forget();
}
void
nsDocument::FlushPendingNotifications(mozFlushType aType)
{
nsDocumentOnStack dos(this);
// We need to flush the sink for non-HTML documents (because the XML
// parser still does insertion with deferred notifications). We
// also need to flush the sink if this is a layout-related flush, to
// make sure that layout is started as needed. But we can skip that
// part if we have no presshell or if it's already done an initial
// reflow.
if ((!IsHTMLDocument() ||
(aType > Flush_ContentAndNotify && mPresShell &&
!mPresShell->DidInitialize())) &&
(mParser || mWeakSink)) {
nsCOMPtr<nsIContentSink> sink;
if (mParser) {
sink = mParser->GetContentSink();
} else {
sink = do_QueryReferent(mWeakSink);
if (!sink) {
mWeakSink = nullptr;
}
}
// Determine if it is safe to flush the sink notifications
// by determining if it safe to flush all the presshells.
if (sink && (aType == Flush_Content || IsSafeToFlush())) {
sink->FlushPendingNotifications(aType);
}
}
// Should we be flushing pending binding constructors in here?
if (aType <= Flush_ContentAndNotify) {
// Nothing to do here
return;
}
// If we have a parent we must flush the parent too to ensure that our
// container is reflowed if its size was changed. But if it's not safe to
// flush ourselves, then don't flush the parent, since that can cause things
// like resizes of our frame's widget, which we can't handle while flushing
// is unsafe.
// Since media queries mean that a size change of our container can
// affect style, we need to promote a style flush on ourself to a
// layout flush on our parent, since we need our container to be the
// correct size to determine the correct style.
if (mParentDocument && IsSafeToFlush()) {
mozFlushType parentType = aType;
if (aType >= Flush_Style)
parentType = std::max(Flush_Layout, aType);
mParentDocument->FlushPendingNotifications(parentType);
}
// We can optimize away getting our presshell and calling
// FlushPendingNotifications on it if we don't need a flush of the sort we're
// looking at. The one exception is if mInFlush is true, because in that
// case we might have set mNeedStyleFlush and mNeedLayoutFlush to false
// already but the presshell hasn't actually done the corresponding work yet.
// So if mInFlush and reentering this code, we need to flush the presshell.
if (mNeedStyleFlush ||
(mNeedLayoutFlush && aType >= Flush_InterruptibleLayout) ||
aType >= Flush_Display ||
mInFlush) {
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
mNeedStyleFlush = false;
mNeedLayoutFlush = mNeedLayoutFlush && (aType < Flush_InterruptibleLayout);
// mInFlush is a bitfield, so can't us AutoRestore here. But we
// need to keep track of multi-level reentry correctly, so need
// to restore the old mInFlush value.
bool oldInFlush = mInFlush;
mInFlush = true;
shell->FlushPendingNotifications(aType);
mInFlush = oldInFlush;
}
}
}
static bool
Copy(nsIDocument* aDocument, void* aData)
{
nsTArray<nsCOMPtr<nsIDocument> >* resources =
static_cast<nsTArray<nsCOMPtr<nsIDocument> >* >(aData);
resources->AppendElement(aDocument);
return true;
}
void
nsDocument::FlushExternalResources(mozFlushType aType)
{
NS_ASSERTION(aType >= Flush_Style,
"should only need to flush for style or higher in external resources");
if (GetDisplayDocument()) {
return;
}
nsTArray<nsCOMPtr<nsIDocument> > resources;
EnumerateExternalResources(Copy, &resources);
for (uint32_t i = 0; i < resources.Length(); i++) {
resources[i]->FlushPendingNotifications(aType);
}
}
void
nsDocument::SetXMLDeclaration(const char16_t *aVersion,
const char16_t *aEncoding,
const int32_t aStandalone)
{
if (!aVersion || *aVersion == '\0') {
mXMLDeclarationBits = 0;
return;
}
mXMLDeclarationBits = XML_DECLARATION_BITS_DECLARATION_EXISTS;
if (aEncoding && *aEncoding != '\0') {
mXMLDeclarationBits |= XML_DECLARATION_BITS_ENCODING_EXISTS;
}
if (aStandalone == 1) {
mXMLDeclarationBits |= XML_DECLARATION_BITS_STANDALONE_EXISTS |
XML_DECLARATION_BITS_STANDALONE_YES;
}
else if (aStandalone == 0) {
mXMLDeclarationBits |= XML_DECLARATION_BITS_STANDALONE_EXISTS;
}
}
void
nsDocument::GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
nsAString& aStandalone)
{
aVersion.Truncate();
aEncoding.Truncate();
aStandalone.Truncate();
if (!(mXMLDeclarationBits & XML_DECLARATION_BITS_DECLARATION_EXISTS)) {
return;
}
// always until we start supporting 1.1 etc.
aVersion.AssignLiteral("1.0");
if (mXMLDeclarationBits & XML_DECLARATION_BITS_ENCODING_EXISTS) {
// This is what we have stored, not necessarily what was written
// in the original
GetCharacterSet(aEncoding);
}
if (mXMLDeclarationBits & XML_DECLARATION_BITS_STANDALONE_EXISTS) {
if (mXMLDeclarationBits & XML_DECLARATION_BITS_STANDALONE_YES) {
aStandalone.AssignLiteral("yes");
} else {
aStandalone.AssignLiteral("no");
}
}
}
bool
nsDocument::IsScriptEnabled()
{
// If this document is sandboxed without 'allow-scripts'
// script is not enabled
if (HasScriptsBlockedBySandbox()) {
return false;
}
nsCOMPtr<nsIScriptGlobalObject> globalObject = do_QueryInterface(GetInnerWindow());
if (!globalObject && mMasterDocument) {
globalObject = do_QueryInterface(mMasterDocument->GetInnerWindow());
}
if (!globalObject || !globalObject->GetGlobalJSObject()) {
return false;
}
return xpc::Scriptability::Get(globalObject->GetGlobalJSObject()).Allowed();
}
nsRadioGroupStruct*
nsDocument::GetRadioGroupInternal(const nsAString& aName) const
{
#ifdef DEBUG
if (IsHTMLDocument()) {
nsAutoString lcName;
ToLowerCase(aName, lcName);
MOZ_ASSERT(aName == lcName);
}
#endif
nsRadioGroupStruct* radioGroup;
if (!mRadioGroups.Get(aName, &radioGroup)) {
return nullptr;
}
return radioGroup;
}
nsRadioGroupStruct*
nsDocument::GetRadioGroup(const nsAString& aName) const
{
nsAutoString tmKey(aName);
if (IsHTMLDocument()) {
ToLowerCase(tmKey); //should case-insensitive.
}
return GetRadioGroupInternal(tmKey);
}
nsRadioGroupStruct*
nsDocument::GetOrCreateRadioGroup(const nsAString& aName)
{
nsAutoString tmKey(aName);
if (IsHTMLDocument()) {
ToLowerCase(tmKey); //should case-insensitive.
}
if (nsRadioGroupStruct* radioGroup = GetRadioGroupInternal(tmKey)) {
return radioGroup;
}
nsAutoPtr<nsRadioGroupStruct> newRadioGroup(new nsRadioGroupStruct());
mRadioGroups.Put(tmKey, newRadioGroup);
return newRadioGroup.forget();
}
void
nsDocument::SetCurrentRadioButton(const nsAString& aName,
HTMLInputElement* aRadio)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
radioGroup->mSelectedRadioButton = aRadio;
}
HTMLInputElement*
nsDocument::GetCurrentRadioButton(const nsAString& aName)
{
return GetOrCreateRadioGroup(aName)->mSelectedRadioButton;
}
NS_IMETHODIMP
nsDocument::GetNextRadioButton(const nsAString& aName,
const bool aPrevious,
HTMLInputElement* aFocusedRadio,
HTMLInputElement** aRadioOut)
{
// XXX Can we combine the HTML radio button method impls of
// nsDocument and nsHTMLFormControl?
// XXX Why is HTML radio button stuff in nsDocument, as
// opposed to nsHTMLDocument?
*aRadioOut = nullptr;
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
// Return the radio button relative to the focused radio button.
// If no radio is focused, get the radio relative to the selected one.
RefPtr<HTMLInputElement> currentRadio;
if (aFocusedRadio) {
currentRadio = aFocusedRadio;
}
else {
currentRadio = radioGroup->mSelectedRadioButton;
if (!currentRadio) {
return NS_ERROR_FAILURE;
}
}
int32_t index = radioGroup->mRadioButtons.IndexOf(currentRadio);
if (index < 0) {
return NS_ERROR_FAILURE;
}
int32_t numRadios = radioGroup->mRadioButtons.Count();
RefPtr<HTMLInputElement> radio;
do {
if (aPrevious) {
if (--index < 0) {
index = numRadios -1;
}
}
else if (++index >= numRadios) {
index = 0;
}
NS_ASSERTION(static_cast<nsGenericHTMLFormElement*>(radioGroup->mRadioButtons[index])->IsHTMLElement(nsGkAtoms::input),
"mRadioButtons holding a non-radio button");
radio = static_cast<HTMLInputElement*>(radioGroup->mRadioButtons[index]);
} while (radio->Disabled() && radio != currentRadio);
radio.forget(aRadioOut);
return NS_OK;
}
void
nsDocument::AddToRadioGroup(const nsAString& aName,
nsIFormControl* aRadio)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
radioGroup->mRadioButtons.AppendObject(aRadio);
nsCOMPtr<nsIContent> element = do_QueryInterface(aRadio);
NS_ASSERTION(element, "radio controls have to be content elements");
if (element->HasAttr(kNameSpaceID_None, nsGkAtoms::required)) {
radioGroup->mRequiredRadioCount++;
}
}
void
nsDocument::RemoveFromRadioGroup(const nsAString& aName,
nsIFormControl* aRadio)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
radioGroup->mRadioButtons.RemoveObject(aRadio);
nsCOMPtr<nsIContent> element = do_QueryInterface(aRadio);
NS_ASSERTION(element, "radio controls have to be content elements");
if (element->HasAttr(kNameSpaceID_None, nsGkAtoms::required)) {
NS_ASSERTION(radioGroup->mRequiredRadioCount != 0,
"mRequiredRadioCount about to wrap below 0!");
radioGroup->mRequiredRadioCount--;
}
}
NS_IMETHODIMP
nsDocument::WalkRadioGroup(const nsAString& aName,
nsIRadioVisitor* aVisitor,
bool aFlushContent)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
for (int i = 0; i < radioGroup->mRadioButtons.Count(); i++) {
if (!aVisitor->Visit(radioGroup->mRadioButtons[i])) {
return NS_OK;
}
}
return NS_OK;
}
uint32_t
nsDocument::GetRequiredRadioCount(const nsAString& aName) const
{
nsRadioGroupStruct* radioGroup = GetRadioGroup(aName);
return radioGroup ? radioGroup->mRequiredRadioCount : 0;
}
void
nsDocument::RadioRequiredWillChange(const nsAString& aName, bool aRequiredAdded)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
if (aRequiredAdded) {
radioGroup->mRequiredRadioCount++;
} else {
NS_ASSERTION(radioGroup->mRequiredRadioCount != 0,
"mRequiredRadioCount about to wrap below 0!");
radioGroup->mRequiredRadioCount--;
}
}
bool
nsDocument::GetValueMissingState(const nsAString& aName) const
{
nsRadioGroupStruct* radioGroup = GetRadioGroup(aName);
return radioGroup && radioGroup->mGroupSuffersFromValueMissing;
}
void
nsDocument::SetValueMissingState(const nsAString& aName, bool aValue)
{
nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
radioGroup->mGroupSuffersFromValueMissing = aValue;
}
void
nsDocument::RetrieveRelevantHeaders(nsIChannel *aChannel)
{
PRTime modDate = 0;
nsresult rv;
nsCOMPtr<nsIHttpChannel> httpChannel;
rv = GetHttpChannelHelper(aChannel, getter_AddRefs(httpChannel));
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
if (httpChannel) {
nsAutoCString tmp;
rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("last-modified"),
tmp);
if (NS_SUCCEEDED(rv)) {
PRTime time;
PRStatus st = PR_ParseTimeString(tmp.get(), true, &time);
if (st == PR_SUCCESS) {
modDate = time;
}
}
// The misspelled key 'referer' is as per the HTTP spec
rv = httpChannel->GetRequestHeader(NS_LITERAL_CSTRING("referer"),
mReferrer);
static const char *const headers[] = {
"default-style",
"content-style-type",
"content-language",
"content-disposition",
"refresh",
"x-dns-prefetch-control",
"x-frame-options",
"referrer-policy",
// add more http headers if you need
// XXXbz don't add content-location support without reading bug
// 238654 and its dependencies/dups first.
0
};
nsAutoCString headerVal;
const char *const *name = headers;
while (*name) {
rv =
httpChannel->GetResponseHeader(nsDependentCString(*name), headerVal);
if (NS_SUCCEEDED(rv) && !headerVal.IsEmpty()) {
nsCOMPtr<nsIAtom> key = NS_Atomize(*name);
SetHeaderData(key, NS_ConvertASCIItoUTF16(headerVal));
}
++name;
}
} else {
nsCOMPtr<nsIFileChannel> fileChannel = do_QueryInterface(aChannel);
if (fileChannel) {
nsCOMPtr<nsIFile> file;
fileChannel->GetFile(getter_AddRefs(file));
if (file) {
PRTime msecs;
rv = file->GetLastModifiedTime(&msecs);
if (NS_SUCCEEDED(rv)) {
modDate = msecs * int64_t(PR_USEC_PER_MSEC);
}
}
} else {
nsAutoCString contentDisp;
rv = aChannel->GetContentDispositionHeader(contentDisp);
if (NS_SUCCEEDED(rv)) {
SetHeaderData(nsGkAtoms::headerContentDisposition,
NS_ConvertASCIItoUTF16(contentDisp));
}
}
}
mLastModified.Truncate();
if (modDate != 0) {
GetFormattedTimeString(modDate, mLastModified);
}
}
already_AddRefed<Element>
nsDocument::CreateElem(const nsAString& aName, nsIAtom *aPrefix,
int32_t aNamespaceID, const nsAString* aIs)
{
#ifdef DEBUG
nsAutoString qName;
if (aPrefix) {
aPrefix->ToString(qName);
qName.Append(':');
}
qName.Append(aName);
// Note: "a:b:c" is a valid name in non-namespaces XML, and
// nsDocument::CreateElement can call us with such a name and no prefix,
// which would cause an error if we just used true here.
bool nsAware = aPrefix != nullptr || aNamespaceID != GetDefaultNamespaceID();
NS_ASSERTION(NS_SUCCEEDED(nsContentUtils::CheckQName(qName, nsAware)),
"Don't pass invalid prefixes to nsDocument::CreateElem, "
"check caller.");
#endif
RefPtr<mozilla::dom::NodeInfo> nodeInfo;
mNodeInfoManager->GetNodeInfo(aName, aPrefix, aNamespaceID,
nsIDOMNode::ELEMENT_NODE,
getter_AddRefs(nodeInfo));
NS_ENSURE_TRUE(nodeInfo, nullptr);
nsCOMPtr<Element> element;
nsresult rv = NS_NewElement(getter_AddRefs(element), nodeInfo.forget(),
NOT_FROM_PARSER, aIs);
return NS_SUCCEEDED(rv) ? element.forget() : nullptr;
}
bool
nsDocument::IsSafeToFlush() const
{
nsIPresShell* shell = GetShell();
if (!shell)
return true;
return shell->IsSafeToFlush();
}
void
nsDocument::Sanitize()
{
// Sanitize the document by resetting all password fields and any form
// fields with autocomplete=off to their default values. We do this now,
// instead of when the presentation is restored, to offer some protection
// in case there is ever an exploit that allows a cached document to be
// accessed from a different document.
// First locate all input elements, regardless of whether they are
// in a form, and reset the password and autocomplete=off elements.
RefPtr<nsContentList> nodes = GetElementsByTagName(NS_LITERAL_STRING("input"));
nsAutoString value;
uint32_t length = nodes->Length(true);
for (uint32_t i = 0; i < length; ++i) {
NS_ASSERTION(nodes->Item(i), "null item in node list!");
RefPtr<HTMLInputElement> input = HTMLInputElement::FromContentOrNull(nodes->Item(i));
if (!input)
continue;
bool resetValue = false;
input->GetAttribute(NS_LITERAL_STRING("autocomplete"), value);
if (value.LowerCaseEqualsLiteral("off")) {
resetValue = true;
} else {
input->GetType(value);
if (value.LowerCaseEqualsLiteral("password"))
resetValue = true;
}
if (resetValue) {
input->Reset();
}
}
// Now locate all _form_ elements that have autocomplete=off and reset them
nodes = GetElementsByTagName(NS_LITERAL_STRING("form"));
length = nodes->Length(true);
for (uint32_t i = 0; i < length; ++i) {
NS_ASSERTION(nodes->Item(i), "null item in nodelist");
nsCOMPtr<nsIDOMHTMLFormElement> form = do_QueryInterface(nodes->Item(i));
if (!form)
continue;
nodes->Item(i)->AsElement()->GetAttr(kNameSpaceID_None,
nsGkAtoms::autocomplete, value);
if (value.LowerCaseEqualsLiteral("off"))
form->Reset();
}
}
struct SubDocEnumArgs
{
nsIDocument::nsSubDocEnumFunc callback;
void *data;
};
void
nsDocument::EnumerateSubDocuments(nsSubDocEnumFunc aCallback, void *aData)
{
if (!mSubDocuments) {
return;
}
// PLDHashTable::Iterator can't handle modifications while iterating so we
// copy all entries to an array first before calling any callbacks.
AutoTArray<nsCOMPtr<nsIDocument>, 8> subdocs;
for (auto iter = mSubDocuments->Iter(); !iter.Done(); iter.Next()) {
auto entry = static_cast<SubDocMapEntry*>(iter.Get());
nsIDocument* subdoc = entry->mSubDocument;
if (subdoc) {
subdocs.AppendElement(subdoc);
}
}
for (auto subdoc : subdocs) {
if (!aCallback(subdoc, aData)) {
break;
}
}
}
#ifdef DEBUG_bryner
#define DEBUG_PAGE_CACHE
#endif
bool
nsDocument::CanSavePresentation(nsIRequest *aNewRequest)
{
if (EventHandlingSuppressed()) {
return false;
}
// Do not allow suspended windows to be placed in the
// bfcache. This method is also used to verify a document
// coming out of the bfcache is ok to restore, though. So
// we only want to block suspend windows that aren't also
// frozen.
nsPIDOMWindowInner* win = GetInnerWindow();
if (win && win->IsSuspended() && !win->IsFrozen()) {
return false;
}
// Check our event listener manager for unload/beforeunload listeners.
nsCOMPtr<EventTarget> piTarget = do_QueryInterface(mScriptGlobalObject);
if (piTarget) {
EventListenerManager* manager = piTarget->GetExistingListenerManager();
if (manager && manager->HasUnloadListeners()) {
return false;
}
}
// Check if we have pending network requests
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
if (loadGroup) {
nsCOMPtr<nsISimpleEnumerator> requests;
loadGroup->GetRequests(getter_AddRefs(requests));
bool hasMore = false;
// We want to bail out if we have any requests other than aNewRequest (or
// in the case when aNewRequest is a part of a multipart response the base
// channel the multipart response is coming in on).
nsCOMPtr<nsIChannel> baseChannel;
nsCOMPtr<nsIMultiPartChannel> part(do_QueryInterface(aNewRequest));
if (part) {
part->GetBaseChannel(getter_AddRefs(baseChannel));
}
while (NS_SUCCEEDED(requests->HasMoreElements(&hasMore)) && hasMore) {
nsCOMPtr<nsISupports> elem;
requests->GetNext(getter_AddRefs(elem));
nsCOMPtr<nsIRequest> request = do_QueryInterface(elem);
if (request && request != aNewRequest && request != baseChannel) {
#ifdef DEBUG_PAGE_CACHE
nsAutoCString requestName, docSpec;
request->GetName(requestName);
if (mDocumentURI)
mDocumentURI->GetSpec(docSpec);
printf("document %s has request %s\n",
docSpec.get(), requestName.get());
#endif
return false;
}
}
}
// Check if we have active GetUserMedia use
if (MediaManager::Exists() && win &&
MediaManager::Get()->IsWindowStillActive(win->WindowID())) {
return false;
}
#ifdef MOZ_WEBRTC
// Check if we have active PeerConnections
nsCOMPtr<IPeerConnectionManager> pcManager =
do_GetService(IPEERCONNECTION_MANAGER_CONTRACTID);
if (pcManager && win) {
bool active;
pcManager->HasActivePeerConnection(win->WindowID(), &active);
if (active) {
return false;
}
}
#endif // MOZ_WEBRTC
#ifdef MOZ_EME
// Don't save presentations for documents containing EME content, so that
// CDMs reliably shutdown upon user navigation.
if (ContainsEMEContent()) {
return false;
}
#endif
// Don't save presentations for documents containing MSE content, to
// reduce memory usage.
if (ContainsMSEContent()) {
return false;
}
if (mSubDocuments) {
for (auto iter = mSubDocuments->Iter(); !iter.Done(); iter.Next()) {
auto entry = static_cast<SubDocMapEntry*>(iter.Get());
nsIDocument* subdoc = entry->mSubDocument;
// The aIgnoreRequest we were passed is only for us, so don't pass it on.
bool canCache = subdoc ? subdoc->CanSavePresentation(nullptr) : false;
if (!canCache) {
return false;
}
}
}
#ifdef MOZ_WEBSPEECH
if (win) {
auto* globalWindow = nsGlobalWindow::Cast(win);
if (globalWindow->HasActiveSpeechSynthesis()) {
return false;
}
}
#endif
return true;
}
void
nsDocument::Destroy()
{
// The ContentViewer wants to release the document now. So, tell our content
// to drop any references to the document so that it can be destroyed.
if (mIsGoingAway)
return;
mIsGoingAway = true;
SetScriptGlobalObject(nullptr);
RemovedFromDocShell();
bool oldVal = mInUnlinkOrDeletion;
mInUnlinkOrDeletion = true;
uint32_t i, count = mChildren.ChildCount();
for (i = 0; i < count; ++i) {
mChildren.ChildAt(i)->DestroyContent();
}
mInUnlinkOrDeletion = oldVal;
mLayoutHistoryState = nullptr;
// Shut down our external resource map. We might not need this for
// leak-fixing if we fix nsDocumentViewer to do cycle-collection, but
// tearing down all those frame trees right now is the right thing to do.
mExternalResourceMap.Shutdown();
}
void
nsDocument::RemovedFromDocShell()
{
if (mRemovedFromDocShell)
return;
mRemovedFromDocShell = true;
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
uint32_t i, count = mChildren.ChildCount();
for (i = 0; i < count; ++i) {
mChildren.ChildAt(i)->SaveSubtreeState();
}
}
already_AddRefed<nsILayoutHistoryState>
nsDocument::GetLayoutHistoryState() const
{
nsCOMPtr<nsILayoutHistoryState> state;
if (!mScriptGlobalObject) {
state = mLayoutHistoryState;
} else {
nsCOMPtr<nsIDocShell> docShell(mDocumentContainer);
if (docShell) {
docShell->GetLayoutHistoryState(getter_AddRefs(state));
}
}
return state.forget();
}
void
nsDocument::EnsureOnloadBlocker()
{
// If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
// -- it's not ours.
if (mOnloadBlockCount != 0 && mScriptGlobalObject) {
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
if (loadGroup) {
// Check first to see if mOnloadBlocker is in the loadgroup.
nsCOMPtr<nsISimpleEnumerator> requests;
loadGroup->GetRequests(getter_AddRefs(requests));
bool hasMore = false;
while (NS_SUCCEEDED(requests->HasMoreElements(&hasMore)) && hasMore) {
nsCOMPtr<nsISupports> elem;
requests->GetNext(getter_AddRefs(elem));
nsCOMPtr<nsIRequest> request = do_QueryInterface(elem);
if (request && request == mOnloadBlocker) {
return;
}
}
// Not in the loadgroup, so add it.
loadGroup->AddRequest(mOnloadBlocker, nullptr);
}
}
}
void
nsDocument::AsyncBlockOnload()
{
while (mAsyncOnloadBlockCount) {
--mAsyncOnloadBlockCount;
BlockOnload();
}
}
void
nsDocument::BlockOnload()
{
if (mDisplayDocument) {
mDisplayDocument->BlockOnload();
return;
}
// If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
// -- it's not ours.
if (mOnloadBlockCount == 0 && mScriptGlobalObject) {
if (!nsContentUtils::IsSafeToRunScript()) {
// Because AddRequest may lead to OnStateChange calls in chrome,
// block onload only when there are no script blockers.
++mAsyncOnloadBlockCount;
if (mAsyncOnloadBlockCount == 1) {
nsContentUtils::AddScriptRunner(
NewRunnableMethod(this, &nsDocument::AsyncBlockOnload));
}
return;
}
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
if (loadGroup) {
loadGroup->AddRequest(mOnloadBlocker, nullptr);
}
}
++mOnloadBlockCount;
}
void
nsDocument::UnblockOnload(bool aFireSync)
{
if (mDisplayDocument) {
mDisplayDocument->UnblockOnload(aFireSync);
return;
}
if (mOnloadBlockCount == 0 && mAsyncOnloadBlockCount == 0) {
NS_NOTREACHED("More UnblockOnload() calls than BlockOnload() calls; dropping call");
return;
}
--mOnloadBlockCount;
if (mOnloadBlockCount == 0) {
if (mScriptGlobalObject) {
// Only manipulate the loadgroup in this case, because if mScriptGlobalObject
// is null, it's not ours.
if (aFireSync && mAsyncOnloadBlockCount == 0) {
// Increment mOnloadBlockCount, since DoUnblockOnload will decrement it
++mOnloadBlockCount;
DoUnblockOnload();
} else {
PostUnblockOnloadEvent();
}
} else if (mIsBeingUsedAsImage) {
// To correctly unblock onload for a document that contains an SVG
// image, we need to know when all of the SVG document's resources are
// done loading, in a way comparable to |window.onload|. We fire this
// event to indicate that the SVG should be considered fully loaded.
// Because scripting is disabled on SVG-as-image documents, this event
// is not accessible to content authors. (See bug 837315.)
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(this,
NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"),
false,
false);
asyncDispatcher->PostDOMEvent();
}
}
}
class nsUnblockOnloadEvent : public Runnable {
public:
explicit nsUnblockOnloadEvent(nsDocument* aDoc) : mDoc(aDoc) {}
NS_IMETHOD Run() override {
mDoc->DoUnblockOnload();
return NS_OK;
}
private:
RefPtr<nsDocument> mDoc;
};
void
nsDocument::PostUnblockOnloadEvent()
{
nsCOMPtr<nsIRunnable> evt = new nsUnblockOnloadEvent(this);
nsresult rv = NS_DispatchToCurrentThread(evt);
if (NS_SUCCEEDED(rv)) {
// Stabilize block count so we don't post more events while this one is up
++mOnloadBlockCount;
} else {
NS_WARNING("failed to dispatch nsUnblockOnloadEvent");
}
}
void
nsDocument::DoUnblockOnload()
{
NS_PRECONDITION(!mDisplayDocument,
"Shouldn't get here for resource document");
NS_PRECONDITION(mOnloadBlockCount != 0,
"Shouldn't have a count of zero here, since we stabilized in "
"PostUnblockOnloadEvent");
--mOnloadBlockCount;
if (mOnloadBlockCount != 0) {
// We blocked again after the last unblock. Nothing to do here. We'll
// post a new event when we unblock again.
return;
}
if (mAsyncOnloadBlockCount != 0) {
// We need to wait until the async onload block has been handled.
PostUnblockOnloadEvent();
}
// If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
// -- it's not ours.
if (mScriptGlobalObject) {
nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
if (loadGroup) {
loadGroup->RemoveRequest(mOnloadBlocker, nullptr, NS_OK);
}
}
}
nsIContent*
nsDocument::GetContentInThisDocument(nsIFrame* aFrame) const
{
for (nsIFrame* f = aFrame; f;
f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
nsIContent* content = f->GetContent();
if (!content || content->IsInAnonymousSubtree())
continue;
if (content->OwnerDoc() == this) {
return content;
}
// We must be in a subdocument so jump directly to the root frame.
// GetParentOrPlaceholderForCrossDoc gets called immediately to jump up to
// the containing document.
f = f->PresContext()->GetPresShell()->GetRootFrame();
}
return nullptr;
}
void
nsDocument::DispatchPageTransition(EventTarget* aDispatchTarget,
const nsAString& aType,
bool aPersisted)
{
if (!aDispatchTarget) {
return;
}
PageTransitionEventInit init;
init.mBubbles = true;
init.mCancelable = true;
init.mPersisted = aPersisted;
RefPtr<PageTransitionEvent> event =
PageTransitionEvent::Constructor(this, aType, init);
event->SetTrusted(true);
event->SetTarget(this);
EventDispatcher::DispatchDOMEvent(aDispatchTarget, nullptr, event,
nullptr, nullptr);
}
static bool
NotifyPageShow(nsIDocument* aDocument, void* aData)
{
const bool* aPersistedPtr = static_cast<const bool*>(aData);
aDocument->OnPageShow(*aPersistedPtr, nullptr);
return true;
}
void
nsDocument::OnPageShow(bool aPersisted,
EventTarget* aDispatchStartTarget)
{
mVisible = true;
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
EnumerateExternalResources(NotifyPageShow, &aPersisted);
Element* root = GetRootElement();
if (aPersisted && root) {
// Send out notifications that our <link> elements are attached.
RefPtr<nsContentList> links = NS_GetContentList(root,
kNameSpaceID_XHTML,
NS_LITERAL_STRING("link"));
uint32_t linkCount = links->Length(true);
for (uint32_t i = 0; i < linkCount; ++i) {
static_cast<HTMLLinkElement*>(links->Item(i, false))->LinkAdded();
}
}
// See nsIDocument
if (!aDispatchStartTarget) {
// Set mIsShowing before firing events, in case those event handlers
// move us around.
mIsShowing = true;
}
if (mAnimationController) {
mAnimationController->OnPageShow();
}
if (aPersisted) {
ImageTracker()->SetAnimatingState(true);
}
UpdateVisibilityState();
nsCOMPtr<EventTarget> target = aDispatchStartTarget;
if (!target) {
target = do_QueryInterface(GetWindow());
}
// Dispatch observer notification to notify observers page is shown.
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
nsIPrincipal *principal = GetPrincipal();
os->NotifyObservers(static_cast<nsIDocument*>(this),
nsContentUtils::IsSystemPrincipal(principal) ?
"chrome-page-shown" :
"content-page-shown",
nullptr);
}
DispatchPageTransition(target, NS_LITERAL_STRING("pageshow"), aPersisted);
}
static bool
NotifyPageHide(nsIDocument* aDocument, void* aData)
{
const bool* aPersistedPtr = static_cast<const bool*>(aData);
aDocument->OnPageHide(*aPersistedPtr, nullptr);
return true;
}
static void
DispatchCustomEventWithFlush(nsINode* aTarget, const nsAString& aEventType,
bool aBubbles, bool aOnlyChromeDispatch)
{
RefPtr<Event> event = NS_NewDOMEvent(aTarget, nullptr, nullptr);
event->InitEvent(aEventType, aBubbles, false);
event->SetTrusted(true);
if (aOnlyChromeDispatch) {
event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true;
}
if (nsIPresShell* shell = aTarget->OwnerDoc()->GetShell()) {
shell->GetPresContext()->
RefreshDriver()->ScheduleEventDispatch(aTarget, event);
}
}
static void
DispatchFullScreenChange(nsIDocument* aTarget)
{
DispatchCustomEventWithFlush(
aTarget, NS_LITERAL_STRING("fullscreenchange"),
/* Bubbles */ true, /* OnlyChrome */ false);
}
static void ClearPendingFullscreenRequests(nsIDocument* aDoc);
void
nsDocument::OnPageHide(bool aPersisted,
EventTarget* aDispatchStartTarget)
{
// Send out notifications that our <link> elements are detached,
// but only if this is not a full unload.
Element* root = GetRootElement();
if (aPersisted && root) {
RefPtr<nsContentList> links = NS_GetContentList(root,
kNameSpaceID_XHTML,
NS_LITERAL_STRING("link"));
uint32_t linkCount = links->Length(true);
for (uint32_t i = 0; i < linkCount; ++i) {
static_cast<HTMLLinkElement*>(links->Item(i, false))->LinkRemoved();
}
}
// See nsIDocument
if (!aDispatchStartTarget) {
// Set mIsShowing before firing events, in case those event handlers
// move us around.
mIsShowing = false;
}
if (mAnimationController) {
mAnimationController->OnPageHide();
}
// We do not stop the animations (bug 1024343)
// when the page is refreshing while being dragged out
nsDocShell* docShell = mDocumentContainer.get();
if (aPersisted && !(docShell && docShell->InFrameSwap())) {
ImageTracker()->SetAnimatingState(false);
}
ExitPointerLock();
// Now send out a PageHide event.
nsCOMPtr<EventTarget> target = aDispatchStartTarget;
if (!target) {
target = do_QueryInterface(GetWindow());
}
// Dispatch observer notification to notify observers page is hidden.
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
nsIPrincipal* principal = GetPrincipal();
os->NotifyObservers(static_cast<nsIDocument*>(this),
nsContentUtils::IsSystemPrincipal(principal) ?
"chrome-page-hidden" :
"content-page-hidden",
nullptr);
}
{
PageUnloadingEventTimeStamp timeStamp(this);
DispatchPageTransition(target, NS_LITERAL_STRING("pagehide"), aPersisted);
}
mVisible = false;
UpdateVisibilityState();
EnumerateExternalResources(NotifyPageHide, &aPersisted);
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
ClearPendingFullscreenRequests(this);
if (GetFullscreenElement()) {
// If this document was fullscreen, we should exit fullscreen in this
// doctree branch. This ensures that if the user navigates while in
// fullscreen mode we don't leave its still visible ancestor documents
// in fullscreen mode. So exit fullscreen in the document's fullscreen
// root document, as this will exit fullscreen in all the root's
// descendant documents. Note that documents are removed from the
// doctree by the time OnPageHide() is called, so we must store a
// reference to the root (in nsDocument::mFullscreenRoot) since we can't
// just traverse the doctree to get the root.
nsIDocument::ExitFullscreenInDocTree(this);
// Since the document is removed from the doctree before OnPageHide() is
// called, ExitFullscreen() can't traverse from the root down to *this*
// document, so we must manually call CleanupFullscreenState() below too.
// Note that CleanupFullscreenState() clears nsDocument::mFullscreenRoot,
// so we *must* call it after ExitFullscreen(), not before.
// OnPageHide() is called in every hidden (i.e. descendant) document,
// so calling CleanupFullscreenState() here will ensure all hidden
// documents have their fullscreen state reset.
CleanupFullscreenState();
// If anyone was listening to this document's state, advertizing the state
// change would be the least of the politeness.
DispatchFullScreenChange(this);
}
}
void
nsDocument::WillDispatchMutationEvent(nsINode* aTarget)
{
NS_ASSERTION(mSubtreeModifiedDepth != 0 ||
mSubtreeModifiedTargets.Count() == 0,
"mSubtreeModifiedTargets not cleared after dispatching?");
++mSubtreeModifiedDepth;
if (aTarget) {
// MayDispatchMutationEvent is often called just before this method,
// so it has already appended the node to mSubtreeModifiedTargets.
int32_t count = mSubtreeModifiedTargets.Count();
if (!count || mSubtreeModifiedTargets[count - 1] != aTarget) {
mSubtreeModifiedTargets.AppendObject(aTarget);
}
}
}
void
nsDocument::MutationEventDispatched(nsINode* aTarget)
{
--mSubtreeModifiedDepth;
if (mSubtreeModifiedDepth == 0) {
int32_t count = mSubtreeModifiedTargets.Count();
if (!count) {
return;
}
nsPIDOMWindowInner* window = GetInnerWindow();
if (window &&
!window->HasMutationListeners(NS_EVENT_BITS_MUTATION_SUBTREEMODIFIED)) {
mSubtreeModifiedTargets.Clear();
return;
}
nsCOMArray<nsINode> realTargets;
for (int32_t i = 0; i < count; ++i) {
nsINode* possibleTarget = mSubtreeModifiedTargets[i];
nsCOMPtr<nsIContent> content = do_QueryInterface(possibleTarget);
if (content && content->ChromeOnlyAccess()) {
continue;
}
nsINode* commonAncestor = nullptr;
int32_t realTargetCount = realTargets.Count();
for (int32_t j = 0; j < realTargetCount; ++j) {
commonAncestor =
nsContentUtils::GetCommonAncestor(possibleTarget, realTargets[j]);
if (commonAncestor) {
realTargets.ReplaceObjectAt(commonAncestor, j);
break;
}
}
if (!commonAncestor) {
realTargets.AppendObject(possibleTarget);
}
}
mSubtreeModifiedTargets.Clear();
int32_t realTargetCount = realTargets.Count();
for (int32_t k = 0; k < realTargetCount; ++k) {
InternalMutationEvent mutation(true, eLegacySubtreeModified);
(new AsyncEventDispatcher(realTargets[k], mutation))->
RunDOMEventWhenSafe();
}
}
}
void
nsDocument::AddStyleRelevantLink(Link* aLink)
{
NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
#ifdef DEBUG
nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
NS_ASSERTION(!entry, "Document already knows about this Link!");
mStyledLinksCleared = false;
#endif
(void)mStyledLinks.PutEntry(aLink);
}
void
nsDocument::ForgetLink(Link* aLink)
{
NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
#ifdef DEBUG
nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
NS_ASSERTION(entry || mStyledLinksCleared,
"Document knows nothing about this Link!");
#endif
mStyledLinks.RemoveEntry(aLink);
}
void
nsDocument::DestroyElementMaps()
{
#ifdef DEBUG
mStyledLinksCleared = true;
#endif
mStyledLinks.Clear();
// Notify ID change listeners before clearing the identifier map.
for (auto iter = mIdentifierMap.Iter(); !iter.Done(); iter.Next()) {
iter.Get()->ClearAndNotify();
}
mIdentifierMap.Clear();
++mExpandoAndGeneration.generation;
}
void
nsDocument::RefreshLinkHrefs()
{
// Get a list of all links we know about. We will reset them, which will
// remove them from the document, so we need a copy of what is in the
// hashtable.
LinkArray linksToNotify(mStyledLinks.Count());
for (auto iter = mStyledLinks.ConstIter(); !iter.Done(); iter.Next()) {
linksToNotify.AppendElement(iter.Get()->GetKey());
}
// Reset all of our styled links.
nsAutoScriptBlocker scriptBlocker;
for (LinkArray::size_type i = 0; i < linksToNotify.Length(); i++) {
linksToNotify[i]->ResetLinkState(true, linksToNotify[i]->ElementHasHref());
}
}
nsresult
nsDocument::CloneDocHelper(nsDocument* clone) const
{
clone->mIsStaticDocument = mCreatingStaticClone;
// Init document
nsresult rv = clone->Init();
NS_ENSURE_SUCCESS(rv, rv);
if (mCreatingStaticClone) {
nsCOMPtr<nsILoadGroup> loadGroup;
// |mDocumentContainer| is the container of the document that is being
// created and not the original container. See CreateStaticClone function().
nsCOMPtr<nsIDocumentLoader> docLoader(mDocumentContainer);
if (docLoader) {
docLoader->GetLoadGroup(getter_AddRefs(loadGroup));
}
nsCOMPtr<nsIChannel> channel = GetChannel();
nsCOMPtr<nsIURI> uri;
if (channel) {
NS_GetFinalChannelURI(channel, getter_AddRefs(uri));
} else {
uri = nsIDocument::GetDocumentURI();
}
clone->mChannel = channel;
if (uri) {
clone->ResetToURI(uri, loadGroup, NodePrincipal());
}
clone->SetContainer(mDocumentContainer);
}
// Now ensure that our clone has the same URI, base URI, and principal as us.
// We do this after the mCreatingStaticClone block above, because that block
// can set the base URI to an incorrect value in cases when base URI
// information came from the channel. So we override explicitly, and do it
// for all these properties, in case ResetToURI messes with any of the rest of
// them.
clone->nsDocument::SetDocumentURI(nsIDocument::GetDocumentURI());
clone->SetChromeXHRDocURI(mChromeXHRDocURI);
clone->SetPrincipal(NodePrincipal());
clone->mDocumentBaseURI = mDocumentBaseURI;
clone->SetChromeXHRDocBaseURI(mChromeXHRDocBaseURI);
// Set scripting object
bool hasHadScriptObject = true;
nsIScriptGlobalObject* scriptObject =
GetScriptHandlingObject(hasHadScriptObject);
NS_ENSURE_STATE(scriptObject || !hasHadScriptObject);
if (scriptObject) {
clone->SetScriptHandlingObject(scriptObject);
} else {
clone->SetScopeObject(GetScopeObject());
}
// Make the clone a data document
clone->SetLoadedAsData(true);
// Misc state
// State from nsIDocument
clone->mCharacterSet = mCharacterSet;
clone->mCharacterSetSource = mCharacterSetSource;
clone->mCompatMode = mCompatMode;
clone->mBidiOptions = mBidiOptions;
clone->mContentLanguage = mContentLanguage;
clone->SetContentTypeInternal(GetContentTypeInternal());
clone->mSecurityInfo = mSecurityInfo;
// State from nsDocument
clone->mType = mType;
clone->mXMLDeclarationBits = mXMLDeclarationBits;
clone->mBaseTarget = mBaseTarget;
return NS_OK;
}
void
nsDocument::SetReadyStateInternal(ReadyState rs,
bool updateTimingInformation)
{
mReadyState = rs;
if (rs == READYSTATE_UNINITIALIZED) {
// Transition back to uninitialized happens only to keep assertions happy
// right before readyState transitions to something else. Make this
// transition undetectable by Web content.
return;
}
if (updateTimingInformation && READYSTATE_LOADING == rs) {
mLoadingTimeStamp = mozilla::TimeStamp::Now();
}
if (updateTimingInformation && mTiming) {
switch (rs) {
case READYSTATE_LOADING:
mTiming->NotifyDOMLoading(nsIDocument::GetDocumentURI());
break;
case READYSTATE_INTERACTIVE:
mTiming->NotifyDOMInteractive(nsIDocument::GetDocumentURI());
break;
case READYSTATE_COMPLETE:
mTiming->NotifyDOMComplete(nsIDocument::GetDocumentURI());
break;
default:
NS_WARNING("Unexpected ReadyState value");
break;
}
}
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(this, NS_LITERAL_STRING("readystatechange"),
false, false);
asyncDispatcher->RunDOMEventWhenSafe();
}
NS_IMETHODIMP
nsDocument::GetReadyState(nsAString& aReadyState)
{
nsIDocument::GetReadyState(aReadyState);
return NS_OK;
}
void
nsIDocument::GetReadyState(nsAString& aReadyState) const
{
switch(mReadyState) {
case READYSTATE_LOADING :
aReadyState.AssignLiteral(u"loading");
break;
case READYSTATE_INTERACTIVE :
aReadyState.AssignLiteral(u"interactive");
break;
case READYSTATE_COMPLETE :
aReadyState.AssignLiteral(u"complete");
break;
default:
aReadyState.AssignLiteral(u"uninitialized");
}
}
namespace {
struct SuppressArgs
{
nsIDocument::SuppressionType mWhat;
uint32_t mIncrease;
};
} // namespace
static bool
SuppressEventHandlingInDocument(nsIDocument* aDocument, void* aData)
{
SuppressArgs* args = static_cast<SuppressArgs*>(aData);
aDocument->SuppressEventHandling(args->mWhat, args->mIncrease);
return true;
}
void
nsDocument::SuppressEventHandling(nsIDocument::SuppressionType aWhat,
uint32_t aIncrease)
{
if (aWhat == eAnimationsOnly) {
mAnimationsPaused += aIncrease;
} else {
mEventsSuppressed += aIncrease;
for (uint32_t i = 0; i < aIncrease; ++i) {
ScriptLoader()->AddExecuteBlocker();
}
}
UpdateFrameRequestCallbackSchedulingState();
SuppressArgs args = { aWhat, aIncrease };
EnumerateSubDocuments(SuppressEventHandlingInDocument, &args);
}
static void
FireOrClearDelayedEvents(nsTArray<nsCOMPtr<nsIDocument> >& aDocuments,
bool aFireEvents)
{
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm)
return;
for (uint32_t i = 0; i < aDocuments.Length(); ++i) {
// NB: Don't bother trying to fire delayed events on documents that were
// closed before this event ran.
if (!aDocuments[i]->EventHandlingSuppressed()) {
fm->FireDelayedEvents(aDocuments[i]);
nsCOMPtr<nsIPresShell> shell = aDocuments[i]->GetShell();
if (shell) {
// Only fire events for active documents.
bool fire = aFireEvents &&
aDocuments[i]->GetInnerWindow() &&
aDocuments[i]->GetInnerWindow()->IsCurrentInnerWindow();
shell->FireOrClearDelayedEvents(fire);
}
}
}
}
void
nsDocument::PreloadPictureOpened()
{
mPreloadPictureDepth++;
}
void
nsDocument::PreloadPictureClosed()
{
mPreloadPictureDepth--;
if (mPreloadPictureDepth == 0) {
mPreloadPictureFoundSource.SetIsVoid(true);
} else {
MOZ_ASSERT(mPreloadPictureDepth >= 0);
}
}
void
nsDocument::PreloadPictureImageSource(const nsAString& aSrcsetAttr,
const nsAString& aSizesAttr,
const nsAString& aTypeAttr,
const nsAString& aMediaAttr)
{
// Nested pictures are not valid syntax, so while we'll eventually load them,
// it's not worth tracking sources mixed between nesting levels to preload
// them effectively.
if (mPreloadPictureDepth == 1 && mPreloadPictureFoundSource.IsVoid()) {
// <picture> selects the first matching source, so if this returns a URI we
// needn't consider new sources until a new <picture> is encountered.
bool found =
HTMLImageElement::SelectSourceForTagWithAttrs(this, true, NullString(),
aSrcsetAttr, aSizesAttr,
aTypeAttr, aMediaAttr,
mPreloadPictureFoundSource);
if (found && mPreloadPictureFoundSource.IsVoid()) {
// Found an empty source, which counts
mPreloadPictureFoundSource.SetIsVoid(false);
}
}
}
already_AddRefed<nsIURI>
nsDocument::ResolvePreloadImage(nsIURI *aBaseURI,
const nsAString& aSrcAttr,
const nsAString& aSrcsetAttr,
const nsAString& aSizesAttr,
bool *aIsImgSet)
{
nsString sourceURL;
bool isImgSet;
if (mPreloadPictureDepth == 1 && !mPreloadPictureFoundSource.IsVoid()) {
// We're in a <picture> element and found a URI from a source previous to
// this image, use it.
sourceURL = mPreloadPictureFoundSource;
isImgSet = true;
} else {
// Otherwise try to use this <img> as a source
HTMLImageElement::SelectSourceForTagWithAttrs(this, false, aSrcAttr,
aSrcsetAttr, aSizesAttr,
NullString(), NullString(),
sourceURL);
isImgSet = !aSrcsetAttr.IsEmpty();
}
// Empty sources are not loaded by <img> (i.e. not resolved to the baseURI)
if (sourceURL.IsEmpty()) {
return nullptr;
}
// Construct into URI using passed baseURI (the parser may know of base URI
// changes that have not reached us)
nsresult rv;
nsCOMPtr<nsIURI> uri;
rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri), sourceURL,
this, aBaseURI);
if (NS_FAILED(rv)) {
return nullptr;
}
*aIsImgSet = isImgSet;
// We don't clear mPreloadPictureFoundSource because subsequent <img> tags in
// this this <picture> share the same <sources> (though this is not valid per
// spec)
return uri.forget();
}
void
nsDocument::MaybePreLoadImage(nsIURI* uri, const nsAString &aCrossOriginAttr,
ReferrerPolicy aReferrerPolicy, bool aIsImgSet)
{
// Early exit if the img is already present in the img-cache
// which indicates that the "real" load has already started and
// that we shouldn't preload it.
if (nsContentUtils::IsImageInCache(uri, static_cast<nsIDocument *>(this))) {
return;
}
nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
switch (Element::StringToCORSMode(aCrossOriginAttr)) {
case CORS_NONE:
// Nothing to do
break;
case CORS_ANONYMOUS:
loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
break;
case CORS_USE_CREDENTIALS:
loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
break;
default:
MOZ_CRASH("Unknown CORS mode!");
}
nsContentPolicyType policyType =
aIsImgSet ? nsIContentPolicy::TYPE_IMAGESET :
nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD;
// Image not in cache - trigger preload
RefPtr<imgRequestProxy> request;
nsresult rv =
nsContentUtils::LoadImage(uri,
static_cast<nsINode*>(this),
this,
NodePrincipal(),
mDocumentURI, // uri of document used as referrer
aReferrerPolicy,
nullptr, // no observer
loadFlags,
NS_LITERAL_STRING("img"),
getter_AddRefs(request),
policyType);
// Pin image-reference to avoid evicting it from the img-cache before
// the "real" load occurs. Unpinned in DispatchContentLoadedEvents and
// unlink
if (NS_SUCCEEDED(rv)) {
mPreloadingImages.Put(uri, request.forget());
}
}
void
nsDocument::MaybePreconnect(nsIURI* aOrigURI, mozilla::CORSMode aCORSMode)
{
nsCOMPtr<nsIURI> uri;
if (NS_FAILED(aOrigURI->Clone(getter_AddRefs(uri)))) {
return;
}
// The URI created here is used in 2 contexts. One is nsISpeculativeConnect
// which ignores the path and uses only the origin. The other is for the
// document mPreloadedPreconnects de-duplication hash. Anonymous vs
// non-Anonymous preconnects create different connections on the wire and
// therefore should not be considred duplicates of each other and we
// normalize the path before putting it in the hash to accomplish that.
if (aCORSMode == CORS_ANONYMOUS) {
uri->SetPath(NS_LITERAL_CSTRING("/anonymous"));
} else {
uri->SetPath(NS_LITERAL_CSTRING("/"));
}
if (mPreloadedPreconnects.Contains(uri)) {
return;
}
mPreloadedPreconnects.Put(uri, true);
nsCOMPtr<nsISpeculativeConnect>
speculator(do_QueryInterface(nsContentUtils::GetIOService()));
if (!speculator) {
return;
}
if (aCORSMode == CORS_ANONYMOUS) {
speculator->SpeculativeAnonymousConnect2(uri, NodePrincipal(), nullptr);
} else {
speculator->SpeculativeConnect2(uri, NodePrincipal(), nullptr);
}
}
void
nsDocument::ForgetImagePreload(nsIURI* aURI)
{
// Checking count is faster than hashing the URI in the common
// case of empty table.
if (mPreloadingImages.Count() != 0) {
nsCOMPtr<imgIRequest> req;
mPreloadingImages.Remove(aURI, getter_AddRefs(req));
if (req) {
// Make sure to cancel the request so imagelib knows it's gone.
req->CancelAndForgetObserver(NS_BINDING_ABORTED);
}
}
}
EventStates
nsDocument::GetDocumentState()
{
if (!mGotDocumentState.HasState(NS_DOCUMENT_STATE_RTL_LOCALE)) {
if (IsDocumentRightToLeft()) {
mDocumentState |= NS_DOCUMENT_STATE_RTL_LOCALE;
}
mGotDocumentState |= NS_DOCUMENT_STATE_RTL_LOCALE;
}
if (!mGotDocumentState.HasState(NS_DOCUMENT_STATE_WINDOW_INACTIVE)) {
nsIPresShell* shell = GetShell();
if (shell && shell->GetPresContext() &&
shell->GetPresContext()->IsTopLevelWindowInactive()) {
mDocumentState |= NS_DOCUMENT_STATE_WINDOW_INACTIVE;
}
mGotDocumentState |= NS_DOCUMENT_STATE_WINDOW_INACTIVE;
}
return mDocumentState;
}
namespace {
/**
* Stub for LoadSheet(), since all we want is to get the sheet into
* the CSSLoader's style cache
*/
class StubCSSLoaderObserver final : public nsICSSLoaderObserver {
~StubCSSLoaderObserver() {}
public:
NS_IMETHOD
StyleSheetLoaded(StyleSheet*, bool, nsresult) override
{
return NS_OK;
}
NS_DECL_ISUPPORTS
};
NS_IMPL_ISUPPORTS(StubCSSLoaderObserver, nsICSSLoaderObserver)
} // namespace
void
nsDocument::PreloadStyle(nsIURI* uri, const nsAString& charset,
const nsAString& aCrossOriginAttr,
const ReferrerPolicy aReferrerPolicy,
const nsAString& aIntegrity)
{
// The CSSLoader will retain this object after we return.
nsCOMPtr<nsICSSLoaderObserver> obs = new StubCSSLoaderObserver();
// Charset names are always ASCII.
CSSLoader()->LoadSheet(uri, true, NodePrincipal(),
NS_LossyConvertUTF16toASCII(charset),
obs,
Element::StringToCORSMode(aCrossOriginAttr),
aReferrerPolicy, aIntegrity);
}
nsresult
nsDocument::LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
RefPtr<mozilla::StyleSheet>* aSheet)
{
css::SheetParsingMode mode =
isAgentSheet ? css::eAgentSheetFeatures
: css::eAuthorSheetFeatures;
return CSSLoader()->LoadSheetSync(uri, mode, isAgentSheet, aSheet);
}
class nsDelayedEventDispatcher : public Runnable
{
public:
explicit nsDelayedEventDispatcher(nsTArray<nsCOMPtr<nsIDocument>>& aDocuments)
{
mDocuments.SwapElements(aDocuments);
}
virtual ~nsDelayedEventDispatcher() {}
NS_IMETHOD Run() override
{
FireOrClearDelayedEvents(mDocuments, true);
return NS_OK;
}
private:
nsTArray<nsCOMPtr<nsIDocument> > mDocuments;
};
namespace {
struct UnsuppressArgs
{
explicit UnsuppressArgs(nsIDocument::SuppressionType aWhat)
: mWhat(aWhat)
{
}
nsIDocument::SuppressionType mWhat;
nsTArray<nsCOMPtr<nsIDocument>> mDocs;
};
} // namespace
static bool
GetAndUnsuppressSubDocuments(nsIDocument* aDocument,
void* aData)
{
UnsuppressArgs* args = static_cast<UnsuppressArgs*>(aData);
if (args->mWhat != nsIDocument::eAnimationsOnly &&
aDocument->EventHandlingSuppressed() > 0) {
static_cast<nsDocument*>(aDocument)->DecreaseEventSuppression();
aDocument->ScriptLoader()->RemoveExecuteBlocker();
} else if (args->mWhat == nsIDocument::eAnimationsOnly &&
aDocument->AnimationsPaused()) {
static_cast<nsDocument*>(aDocument)->ResumeAnimations();
}
if (args->mWhat != nsIDocument::eAnimationsOnly) {
// No need to remember documents if we only care about animation frames.
args->mDocs.AppendElement(aDocument);
}
aDocument->EnumerateSubDocuments(GetAndUnsuppressSubDocuments, aData);
return true;
}
void
nsDocument::UnsuppressEventHandlingAndFireEvents(nsIDocument::SuppressionType aWhat,
bool aFireEvents)
{
UnsuppressArgs args(aWhat);
GetAndUnsuppressSubDocuments(this, &args);
if (aWhat == nsIDocument::eAnimationsOnly) {
// No need to fire events if we only care about animations here.
return;
}
if (aFireEvents) {
NS_DispatchToCurrentThread(new nsDelayedEventDispatcher(args.mDocs));
} else {
FireOrClearDelayedEvents(args.mDocs, false);
}
}
nsISupports*
nsDocument::GetCurrentContentSink()
{
return mParser ? mParser->GetContentSink() : nullptr;
}
nsIDocument*
nsDocument::GetTemplateContentsOwner()
{
if (!mTemplateContentsOwner) {
bool hasHadScriptObject = true;
nsIScriptGlobalObject* scriptObject =
GetScriptHandlingObject(hasHadScriptObject);
nsCOMPtr<nsIDOMDocument> domDocument;
nsresult rv = NS_NewDOMDocument(getter_AddRefs(domDocument),
EmptyString(), // aNamespaceURI
EmptyString(), // aQualifiedName
nullptr, // aDoctype
nsIDocument::GetDocumentURI(),
nsIDocument::GetDocBaseURI(),
NodePrincipal(),
true, // aLoadedAsData
scriptObject, // aEventObject
DocumentFlavorHTML);
NS_ENSURE_SUCCESS(rv, nullptr);
mTemplateContentsOwner = do_QueryInterface(domDocument);
NS_ENSURE_TRUE(mTemplateContentsOwner, nullptr);
nsDocument* doc = static_cast<nsDocument*>(mTemplateContentsOwner.get());
if (!scriptObject) {
mTemplateContentsOwner->SetScopeObject(GetScopeObject());
}
doc->mHasHadScriptHandlingObject = hasHadScriptObject;
// Set |doc| as the template contents owner of itself so that
// |doc| is the template contents owner of template elements created
// by |doc|.
doc->mTemplateContentsOwner = doc;
}
return mTemplateContentsOwner;
}
void
nsDocument::SetScrollToRef(nsIURI *aDocumentURI)
{
if (!aDocumentURI) {
return;
}
nsAutoCString ref;
// Since all URI's that pass through here aren't URL's we can't
// rely on the nsIURI implementation for providing a way for
// finding the 'ref' part of the URI, we'll haveto revert to
// string routines for finding the data past '#'
nsresult rv = aDocumentURI->GetSpec(ref);
if (NS_FAILED(rv)) {
Unused << aDocumentURI->GetRef(mScrollToRef);
return;
}
nsReadingIterator<char> start, end;
ref.BeginReading(start);
ref.EndReading(end);
if (FindCharInReadable('#', start, end)) {
++start; // Skip over the '#'
mScrollToRef = Substring(start, end);
}
}
void
nsDocument::ScrollToRef()
{
if (mScrolledToRefAlready) {
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
shell->ScrollToAnchor();
}
return;
}
if (mScrollToRef.IsEmpty()) {
return;
}
char* tmpstr = ToNewCString(mScrollToRef);
if (!tmpstr) {
return;
}
nsUnescape(tmpstr);
nsAutoCString unescapedRef;
unescapedRef.Assign(tmpstr);
free(tmpstr);
nsresult rv = NS_ERROR_FAILURE;
// We assume that the bytes are in UTF-8, as it says in the spec:
// http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.1
NS_ConvertUTF8toUTF16 ref(unescapedRef);
nsCOMPtr<nsIPresShell> shell = GetShell();
if (shell) {
// Check an empty string which might be caused by the UTF-8 conversion
if (!ref.IsEmpty()) {
// Note that GoToAnchor will handle flushing layout as needed.
rv = shell->GoToAnchor(ref, mChangeScrollPosWhenScrollingToRef);
} else {
rv = NS_ERROR_FAILURE;
}
// If UTF-8 URI failed then try to assume the string as a
// document's charset.
if (NS_FAILED(rv)) {
const nsACString &docCharset = GetDocumentCharacterSet();
rv = nsContentUtils::ConvertStringFromEncoding(docCharset,
unescapedRef,
ref);
if (NS_SUCCEEDED(rv) && !ref.IsEmpty()) {
rv = shell->GoToAnchor(ref, mChangeScrollPosWhenScrollingToRef);
}
}
if (NS_SUCCEEDED(rv)) {
mScrolledToRefAlready = true;
}
}
}
void
nsDocument::ResetScrolledToRefAlready()
{
mScrolledToRefAlready = false;
}
void
nsDocument::SetChangeScrollPosWhenScrollingToRef(bool aValue)
{
mChangeScrollPosWhenScrollingToRef = aValue;
}
void
nsIDocument::RegisterActivityObserver(nsISupports* aSupports)
{
if (!mActivityObservers) {
mActivityObservers = new nsTHashtable<nsPtrHashKey<nsISupports> >();
}
mActivityObservers->PutEntry(aSupports);
}
bool
nsIDocument::UnregisterActivityObserver(nsISupports* aSupports)
{
if (!mActivityObservers) {
return false;
}
nsPtrHashKey<nsISupports>* entry = mActivityObservers->GetEntry(aSupports);
if (!entry) {
return false;
}
mActivityObservers->RemoveEntry(entry);
return true;
}
void
nsIDocument::EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator,
void* aData)
{
if (!mActivityObservers)
return;
for (auto iter = mActivityObservers->ConstIter(); !iter.Done();
iter.Next()) {
aEnumerator(iter.Get()->GetKey(), aData);
}
}
void
nsIDocument::RegisterPendingLinkUpdate(Link* aLink)
{
MOZ_ASSERT(!mIsLinkUpdateRegistrationsForbidden);
mLinksToUpdate.PutEntry(aLink);
mHasLinksToUpdate = true;
}
void
nsIDocument::UnregisterPendingLinkUpdate(Link* aLink)
{
MOZ_ASSERT(!mIsLinkUpdateRegistrationsForbidden);
if (!mHasLinksToUpdate)
return;
mLinksToUpdate.RemoveEntry(aLink);
}
void
nsIDocument::FlushPendingLinkUpdates()
{
MOZ_ASSERT(!mIsLinkUpdateRegistrationsForbidden);
if (!mHasLinksToUpdate)
return;
#ifdef DEBUG
AutoRestore<bool> saved(mIsLinkUpdateRegistrationsForbidden);
mIsLinkUpdateRegistrationsForbidden = true;
#endif
for (auto iter = mLinksToUpdate.ConstIter(); !iter.Done(); iter.Next()) {
Link* link = iter.Get()->GetKey();
link->GetElement()->UpdateLinkState(link->LinkState());
}
mLinksToUpdate.Clear();
mHasLinksToUpdate = false;
}
already_AddRefed<nsIDocument>
nsIDocument::CreateStaticClone(nsIDocShell* aCloneContainer)
{
nsDocument* thisAsDoc = static_cast<nsDocument*>(this);
mCreatingStaticClone = true;
// Make document use different container during cloning.
RefPtr<nsDocShell> originalShell = mDocumentContainer.get();
SetContainer(static_cast<nsDocShell*>(aCloneContainer));
nsCOMPtr<nsIDOMNode> clonedNode;
nsresult rv = thisAsDoc->CloneNode(true, 1, getter_AddRefs(clonedNode));
SetContainer(originalShell);
RefPtr<nsDocument> clonedDoc;
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIDocument> tmp = do_QueryInterface(clonedNode);
if (tmp) {
clonedDoc = static_cast<nsDocument*>(tmp.get());
if (IsStaticDocument()) {
clonedDoc->mOriginalDocument = mOriginalDocument;
} else {
clonedDoc->mOriginalDocument = this;
}
clonedDoc->mOriginalDocument->mStaticCloneCount++;
int32_t sheetsCount = GetNumberOfStyleSheets();
for (int32_t i = 0; i < sheetsCount; ++i) {
RefPtr<StyleSheet> sheet = GetStyleSheetAt(i);
if (sheet) {
if (sheet->IsApplicable()) {
// XXXheycam Need to make ServoStyleSheet cloning work.
if (sheet->IsGecko()) {
RefPtr<CSSStyleSheet> clonedSheet =
sheet->AsGecko()->Clone(nullptr, nullptr, clonedDoc, nullptr);
NS_WARNING_ASSERTION(clonedSheet,
"Cloning a stylesheet didn't work!");
if (clonedSheet) {
clonedDoc->AddStyleSheet(clonedSheet);
}
} else {
NS_ERROR("stylo: ServoStyleSheet doesn't support cloning");
}
}
}
}
// Iterate backwards to maintain order
for (StyleSheet* sheet : Reversed(thisAsDoc->mOnDemandBuiltInUASheets)) {
if (sheet) {
if (sheet->IsApplicable()) {
// XXXheycam Need to make ServoStyleSheet cloning work.
if (sheet->IsGecko()) {
RefPtr<CSSStyleSheet> clonedSheet =
sheet->AsGecko()->Clone(nullptr, nullptr, clonedDoc, nullptr);
NS_WARNING_ASSERTION(clonedSheet,
"Cloning a stylesheet didn't work!");
if (clonedSheet) {
clonedDoc->AddOnDemandBuiltInUASheet(clonedSheet);
}
} else {
NS_ERROR("stylo: ServoStyleSheet doesn't support cloning");
}
}
}
}
}
}
mCreatingStaticClone = false;
return clonedDoc.forget();
}
void
nsIDocument::UnlinkOriginalDocumentIfStatic()
{
if (IsStaticDocument() && mOriginalDocument) {
MOZ_ASSERT(mOriginalDocument->mStaticCloneCount > 0);
mOriginalDocument->mStaticCloneCount--;
mOriginalDocument = nullptr;
}
MOZ_ASSERT(!mOriginalDocument);
}
nsresult
nsIDocument::ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
int32_t *aHandle)
{
if (mFrameRequestCallbackCounter == INT32_MAX) {
// Can't increment without overflowing; bail out
return NS_ERROR_NOT_AVAILABLE;
}
int32_t newHandle = ++mFrameRequestCallbackCounter;
DebugOnly<FrameRequest*> request =
mFrameRequestCallbacks.AppendElement(FrameRequest(aCallback, newHandle));
NS_ASSERTION(request, "This is supposed to be infallible!");
UpdateFrameRequestCallbackSchedulingState();
*aHandle = newHandle;
return NS_OK;
}
void
nsIDocument::CancelFrameRequestCallback(int32_t aHandle)
{
// mFrameRequestCallbacks is stored sorted by handle
if (mFrameRequestCallbacks.RemoveElementSorted(aHandle)) {
UpdateFrameRequestCallbackSchedulingState();
}
}
nsresult
nsDocument::GetStateObject(nsIVariant** aState)
{
// Get the document's current state object. This is the object backing both
// history.state and popStateEvent.state.
//
// mStateObjectContainer may be null; this just means that there's no
// current state object.
if (!mStateObjectCached && mStateObjectContainer) {
AutoJSContext cx;
nsIGlobalObject* sgo = GetScopeObject();
NS_ENSURE_TRUE(sgo, NS_ERROR_UNEXPECTED);
JS::Rooted<JSObject*> global(cx, sgo->GetGlobalJSObject());
NS_ENSURE_TRUE(global, NS_ERROR_UNEXPECTED);
JSAutoCompartment ac(cx, global);
mStateObjectContainer->
DeserializeToVariant(cx, getter_AddRefs(mStateObjectCached));
}
NS_IF_ADDREF(*aState = mStateObjectCached);
return NS_OK;
}
nsDOMNavigationTiming*
nsDocument::GetNavigationTiming() const
{
return mTiming;
}
nsresult
nsDocument::SetNavigationTiming(nsDOMNavigationTiming* aTiming)
{
mTiming = aTiming;
if (!mLoadingTimeStamp.IsNull() && mTiming) {
mTiming->SetDOMLoadingTimeStamp(nsIDocument::GetDocumentURI(), mLoadingTimeStamp);
}
return NS_OK;
}
Element*
nsDocument::FindImageMap(const nsAString& aUseMapValue)
{
if (aUseMapValue.IsEmpty()) {
return nullptr;
}
nsAString::const_iterator start, end;
aUseMapValue.BeginReading(start);
aUseMapValue.EndReading(end);
int32_t hash = aUseMapValue.FindChar('#');
if (hash < 0) {
return nullptr;
}
// aUsemap contains a '#', set start to point right after the '#'
start.advance(hash + 1);
if (start == end) {
return nullptr; // aUsemap == "#"
}
const nsAString& mapName = Substring(start, end);
if (!mImageMaps) {
mImageMaps = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::map, nsGkAtoms::map);
}
uint32_t i, n = mImageMaps->Length(true);
nsString name;
for (i = 0; i < n; ++i) {
nsIContent* map = mImageMaps->Item(i);
if (map->AttrValueIs(kNameSpaceID_None, nsGkAtoms::id, mapName,
eCaseMatters) ||
(map->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name) &&
mapName.Equals(name, nsCaseInsensitiveStringComparator()))) {
return map->AsElement();
}
}
return nullptr;
}
#define DEPRECATED_OPERATION(_op) #_op "Warning",
static const char* kDeprecationWarnings[] = {
#include "nsDeprecatedOperationList.h"
nullptr
};
#undef DEPRECATED_OPERATION
#define DOCUMENT_WARNING(_op) #_op "Warning",
static const char* kDocumentWarnings[] = {
#include "nsDocumentWarningList.h"
nullptr
};
#undef DOCUMENT_WARNING
static UseCounter
OperationToUseCounter(nsIDocument::DeprecatedOperations aOperation)
{
switch(aOperation) {
#define DEPRECATED_OPERATION(_op) \
case nsIDocument::e##_op: return eUseCounter_##_op;
#include "nsDeprecatedOperationList.h"
#undef DEPRECATED_OPERATION
default:
MOZ_CRASH();
}
}
bool
nsIDocument::HasWarnedAbout(DeprecatedOperations aOperation) const
{
return mDeprecationWarnedAbout[aOperation];
}
void
nsIDocument::WarnOnceAbout(DeprecatedOperations aOperation,
bool asError /* = false */) const
{
MOZ_ASSERT(NS_IsMainThread());
if (HasWarnedAbout(aOperation)) {
return;
}
mDeprecationWarnedAbout[aOperation] = true;
const_cast<nsIDocument*>(this)->SetDocumentAndPageUseCounter(OperationToUseCounter(aOperation));
uint32_t flags = asError ? nsIScriptError::errorFlag
: nsIScriptError::warningFlag;
nsContentUtils::ReportToConsole(flags,
NS_LITERAL_CSTRING("DOM Core"), this,
nsContentUtils::eDOM_PROPERTIES,
kDeprecationWarnings[aOperation]);
}
bool
nsIDocument::HasWarnedAbout(DocumentWarnings aWarning) const
{
return mDocWarningWarnedAbout[aWarning];
}
void
nsIDocument::WarnOnceAbout(DocumentWarnings aWarning,
bool asError /* = false */,
const char16_t **aParams /* = nullptr */,
uint32_t aParamsLength /* = 0 */) const
{
MOZ_ASSERT(NS_IsMainThread());
if (HasWarnedAbout(aWarning)) {
return;
}
mDocWarningWarnedAbout[aWarning] = true;
uint32_t flags = asError ? nsIScriptError::errorFlag
: nsIScriptError::warningFlag;
nsContentUtils::ReportToConsole(flags,
NS_LITERAL_CSTRING("DOM Core"), this,
nsContentUtils::eDOM_PROPERTIES,
kDocumentWarnings[aWarning],
aParams,
aParamsLength);
}
mozilla::dom::ImageTracker*
nsIDocument::ImageTracker()
{
if (!mImageTracker) {
mImageTracker = new mozilla::dom::ImageTracker;
}
return mImageTracker;
}
nsresult
nsDocument::AddPlugin(nsIObjectLoadingContent* aPlugin)
{
MOZ_ASSERT(aPlugin);
if (!mPlugins.PutEntry(aPlugin)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
void
nsDocument::RemovePlugin(nsIObjectLoadingContent* aPlugin)
{
MOZ_ASSERT(aPlugin);
mPlugins.RemoveEntry(aPlugin);
}
static bool
AllSubDocumentPluginEnum(nsIDocument* aDocument, void* userArg)
{
nsTArray<nsIObjectLoadingContent*>* plugins =
reinterpret_cast< nsTArray<nsIObjectLoadingContent*>* >(userArg);
MOZ_ASSERT(plugins);
aDocument->GetPlugins(*plugins);
return true;
}
void
nsDocument::GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins)
{
aPlugins.SetCapacity(aPlugins.Length() + mPlugins.Count());
for (auto iter = mPlugins.ConstIter(); !iter.Done(); iter.Next()) {
aPlugins.AppendElement(iter.Get()->GetKey());
}
EnumerateSubDocuments(AllSubDocumentPluginEnum, &aPlugins);
}
nsresult
nsDocument::AddResponsiveContent(nsIContent* aContent)
{
MOZ_ASSERT(aContent);
MOZ_ASSERT(aContent->IsHTMLElement(nsGkAtoms::img));
mResponsiveContent.PutEntry(aContent);
return NS_OK;
}
void
nsDocument::RemoveResponsiveContent(nsIContent* aContent)
{
MOZ_ASSERT(aContent);
mResponsiveContent.RemoveEntry(aContent);
}
void
nsDocument::NotifyMediaFeatureValuesChanged()
{
for (auto iter = mResponsiveContent.ConstIter(); !iter.Done();
iter.Next()) {
nsCOMPtr<nsIContent> content = iter.Get()->GetKey();
if (content->IsHTMLElement(nsGkAtoms::img)) {
auto* imageElement = static_cast<HTMLImageElement*>(content.get());
imageElement->MediaFeatureValuesChanged();
}
}
}
already_AddRefed<Touch>
nsIDocument::CreateTouch(nsGlobalWindow* aView,
EventTarget* aTarget,
int32_t aIdentifier,
int32_t aPageX, int32_t aPageY,
int32_t aScreenX, int32_t aScreenY,
int32_t aClientX, int32_t aClientY,
int32_t aRadiusX, int32_t aRadiusY,
float aRotationAngle,
float aForce)
{
MOZ_ASSERT_IF(aView, aView->IsInnerWindow());
RefPtr<Touch> touch = new Touch(aTarget,
aIdentifier,
aPageX, aPageY,
aScreenX, aScreenY,
aClientX, aClientY,
aRadiusX, aRadiusY,
aRotationAngle,
aForce);
return touch.forget();
}
already_AddRefed<TouchList>
nsIDocument::CreateTouchList()
{
RefPtr<TouchList> retval = new TouchList(ToSupports(this));
return retval.forget();
}
already_AddRefed<TouchList>
nsIDocument::CreateTouchList(Touch& aTouch,
const Sequence<OwningNonNull<Touch> >& aTouches)
{
RefPtr<TouchList> retval = new TouchList(ToSupports(this));
retval->Append(&aTouch);
for (uint32_t i = 0; i < aTouches.Length(); ++i) {
retval->Append(aTouches[i].get());
}
return retval.forget();
}
already_AddRefed<TouchList>
nsIDocument::CreateTouchList(const Sequence<OwningNonNull<Touch> >& aTouches)
{
RefPtr<TouchList> retval = new TouchList(ToSupports(this));
for (uint32_t i = 0; i < aTouches.Length(); ++i) {
retval->Append(aTouches[i].get());
}
return retval.forget();
}
already_AddRefed<nsDOMCaretPosition>
nsIDocument::CaretPositionFromPoint(float aX, float aY)
{
nscoord x = nsPresContext::CSSPixelsToAppUnits(aX);
nscoord y = nsPresContext::CSSPixelsToAppUnits(aY);
nsPoint pt(x, y);
FlushPendingNotifications(Flush_Layout);
nsIPresShell *ps = GetShell();
if (!ps) {
return nullptr;
}
nsIFrame *rootFrame = ps->GetRootFrame();
// XUL docs, unlike HTML, have no frame tree until everything's done loading
if (!rootFrame) {
return nullptr;
}
nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, pt,
nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC);
if (!ptFrame) {
return nullptr;
}
// GetContentOffsetsFromPoint requires frame-relative coordinates, so we need
// to adjust to frame-relative coordinates before we can perform this call.
// It should also not take into account the padding of the frame.
nsPoint adjustedPoint = pt - ptFrame->GetOffsetTo(rootFrame);
nsFrame::ContentOffsets offsets =
ptFrame->GetContentOffsetsFromPoint(adjustedPoint);
nsCOMPtr<nsIContent> node = offsets.content;
uint32_t offset = offsets.offset;
nsCOMPtr<nsIContent> anonNode = node;
bool nodeIsAnonymous = node && node->IsInNativeAnonymousSubtree();
if (nodeIsAnonymous) {
node = ptFrame->GetContent();
nsIContent* nonanon = node->FindFirstNonChromeOnlyAccessContent();
nsCOMPtr<nsIDOMHTMLTextAreaElement> textArea = do_QueryInterface(nonanon);
nsITextControlFrame* textFrame = do_QueryFrame(nonanon->GetPrimaryFrame());
nsNumberControlFrame* numberFrame = do_QueryFrame(nonanon->GetPrimaryFrame());
if (textFrame || numberFrame) {
// If the anonymous content node has a child, then we need to make sure
// that we get the appropriate child, as otherwise the offset may not be
// correct when we construct a range for it.
nsCOMPtr<nsIContent> firstChild = anonNode->GetFirstChild();
if (firstChild) {
anonNode = firstChild;
}
if (textArea) {
offset = nsContentUtils::GetAdjustedOffsetInTextControl(ptFrame, offset);
}
node = nonanon;
} else {
node = nullptr;
offset = 0;
}
}
RefPtr<nsDOMCaretPosition> aCaretPos = new nsDOMCaretPosition(node, offset);
if (nodeIsAnonymous) {
aCaretPos->SetAnonymousContentNode(anonNode);
}
return aCaretPos.forget();
}
NS_IMETHODIMP
nsDocument::CaretPositionFromPoint(float aX, float aY, nsISupports** aCaretPos)
{
NS_ENSURE_ARG_POINTER(aCaretPos);
*aCaretPos = nsIDocument::CaretPositionFromPoint(aX, aY).take();
return NS_OK;
}
static bool
IsPotentiallyScrollable(HTMLBodyElement* aBody)
{
// An element is potentially scrollable if all of the following conditions are
// true:
// The element has an associated CSS layout box.
nsIFrame* bodyFrame = aBody->GetPrimaryFrame();
if (!bodyFrame) {
return false;
}
// The element is not the HTML body element, or it is and the root element's
// used value of the overflow-x or overflow-y properties is not visible.
MOZ_ASSERT(aBody->GetParent() == aBody->OwnerDoc()->GetRootElement());
nsIFrame* parentFrame = aBody->GetParent()->GetPrimaryFrame();
if (parentFrame &&
parentFrame->StyleDisplay()->mOverflowX == NS_STYLE_OVERFLOW_VISIBLE &&
parentFrame->StyleDisplay()->mOverflowY == NS_STYLE_OVERFLOW_VISIBLE) {
return false;
}
// The element's used value of the overflow-x or overflow-y properties is not
// visible.
if (bodyFrame->StyleDisplay()->mOverflowX == NS_STYLE_OVERFLOW_VISIBLE &&
bodyFrame->StyleDisplay()->mOverflowY == NS_STYLE_OVERFLOW_VISIBLE) {
return false;
}
return true;
}
Element*
nsIDocument::GetScrollingElement()
{
if (GetCompatibilityMode() == eCompatibility_NavQuirks) {
FlushPendingNotifications(Flush_Layout);
HTMLBodyElement* body = GetBodyElement();
if (body && !IsPotentiallyScrollable(body)) {
return body;
}
return nullptr;
}
return GetRootElement();
}
void
nsIDocument::ObsoleteSheet(nsIURI *aSheetURI, ErrorResult& rv)
{
nsresult res = CSSLoader()->ObsoleteSheet(aSheetURI);
if (NS_FAILED(res)) {
rv.Throw(res);
}
}
void
nsIDocument::ObsoleteSheet(const nsAString& aSheetURI, ErrorResult& rv)
{
nsCOMPtr<nsIURI> uri;
nsresult res = NS_NewURI(getter_AddRefs(uri), aSheetURI);
if (NS_FAILED(res)) {
rv.Throw(res);
return;
}
res = CSSLoader()->ObsoleteSheet(uri);
if (NS_FAILED(res)) {
rv.Throw(res);
}
}
already_AddRefed<nsIURI>
nsIDocument::GetMozDocumentURIIfNotForErrorPages()
{
if (mFailedChannel) {
nsCOMPtr<nsIURI> failedURI;
if (NS_SUCCEEDED(mFailedChannel->GetURI(getter_AddRefs(failedURI)))) {
return failedURI.forget();
}
}
nsCOMPtr<nsIURI> uri = GetDocumentURIObject();
if (!uri) {
return nullptr;
}
return uri.forget();
}
nsIHTMLCollection*
nsIDocument::Children()
{
if (!mChildrenCollection) {
mChildrenCollection = new nsContentList(this, kNameSpaceID_Wildcard,
nsGkAtoms::_asterisk,
nsGkAtoms::_asterisk,
false);
}
return mChildrenCollection;
}
uint32_t
nsIDocument::ChildElementCount()
{
return Children()->Length();
}
namespace mozilla {
// Singleton class to manage the list of fullscreen documents which are the
// root of a branch which contains fullscreen documents. We maintain this list
// so that we can easily exit all windows from fullscreen when the user
// presses the escape key.
class FullscreenRoots {
public:
// Adds the root of given document to the manager. Calling this method
// with a document whose root is already contained has no effect.
static void Add(nsIDocument* aDoc);
// Iterates over every root in the root list, and calls aFunction, passing
// each root once to aFunction. It is safe to call Add() and Remove() while
// iterating over the list (i.e. in aFunction). Documents that are removed
// from the manager during traversal are not traversed, and documents that
// are added to the manager during traversal are also not traversed.
static void ForEach(void(*aFunction)(nsIDocument* aDoc));
// Removes the root of a specific document from the manager.
static void Remove(nsIDocument* aDoc);
// Returns true if all roots added to the list have been removed.
static bool IsEmpty();
private:
FullscreenRoots() {
MOZ_COUNT_CTOR(FullscreenRoots);
}
~FullscreenRoots() {
MOZ_COUNT_DTOR(FullscreenRoots);
}
enum {
NotFound = uint32_t(-1)
};
// Looks in mRoots for aRoot. Returns the index if found, otherwise NotFound.
static uint32_t Find(nsIDocument* aRoot);
// Returns true if aRoot is in the list of fullscreen roots.
static bool Contains(nsIDocument* aRoot);
// Singleton instance of the FullscreenRoots. This is instantiated when a
// root is added, and it is deleted when the last root is removed.
static FullscreenRoots* sInstance;
// List of weak pointers to roots.
nsTArray<nsWeakPtr> mRoots;
};
FullscreenRoots* FullscreenRoots::sInstance = nullptr;
/* static */
void
FullscreenRoots::ForEach(void(*aFunction)(nsIDocument* aDoc))
{
if (!sInstance) {
return;
}
// Create a copy of the roots array, and iterate over the copy. This is so
// that if an element is removed from mRoots we don't mess up our iteration.
nsTArray<nsWeakPtr> roots(sInstance->mRoots);
// Call aFunction on all entries.
for (uint32_t i = 0; i < roots.Length(); i++) {
nsCOMPtr<nsIDocument> root = do_QueryReferent(roots[i]);
// Check that the root isn't in the manager. This is so that new additions
// while we were running don't get traversed.
if (root && FullscreenRoots::Contains(root)) {
aFunction(root);
}
}
}
/* static */
bool
FullscreenRoots::Contains(nsIDocument* aRoot)
{
return FullscreenRoots::Find(aRoot) != NotFound;
}
/* static */
void
FullscreenRoots::Add(nsIDocument* aDoc)
{
nsCOMPtr<nsIDocument> root = nsContentUtils::GetRootDocument(aDoc);
if (!FullscreenRoots::Contains(root)) {
if (!sInstance) {
sInstance = new FullscreenRoots();
}
sInstance->mRoots.AppendElement(do_GetWeakReference(root));
}
}
/* static */
uint32_t
FullscreenRoots::Find(nsIDocument* aRoot)
{
if (!sInstance) {
return NotFound;
}
nsTArray<nsWeakPtr>& roots = sInstance->mRoots;
for (uint32_t i = 0; i < roots.Length(); i++) {
nsCOMPtr<nsIDocument> otherRoot(do_QueryReferent(roots[i]));
if (otherRoot == aRoot) {
return i;
}
}
return NotFound;
}
/* static */
void
FullscreenRoots::Remove(nsIDocument* aDoc)
{
nsCOMPtr<nsIDocument> root = nsContentUtils::GetRootDocument(aDoc);
uint32_t index = Find(root);
NS_ASSERTION(index != NotFound,
"Should only try to remove roots which are still added!");
if (index == NotFound || !sInstance) {
return;
}
sInstance->mRoots.RemoveElementAt(index);
if (sInstance->mRoots.IsEmpty()) {
delete sInstance;
sInstance = nullptr;
}
}
/* static */
bool
FullscreenRoots::IsEmpty()
{
return !sInstance;
}
} // end namespace mozilla.
using mozilla::FullscreenRoots;
nsIDocument*
nsDocument::GetFullscreenRoot()
{
nsCOMPtr<nsIDocument> root = do_QueryReferent(mFullscreenRoot);
return root;
}
void
nsDocument::SetFullscreenRoot(nsIDocument* aRoot)
{
mFullscreenRoot = do_GetWeakReference(aRoot);
}
NS_IMETHODIMP
nsDocument::MozCancelFullScreen()
{
nsIDocument::ExitFullscreen();
return NS_OK;
}
void
nsIDocument::ExitFullscreen()
{
RestorePreviousFullScreenState();
}
static void
AskWindowToExitFullscreen(nsIDocument* aDoc)
{
if (XRE_GetProcessType() == GeckoProcessType_Content) {
nsContentUtils::DispatchEventOnlyToChrome(
aDoc, ToSupports(aDoc), NS_LITERAL_STRING("MozDOMFullscreen:Exit"),
/* Bubbles */ true, /* Cancelable */ false,
/* DefaultAction */ nullptr);
} else {
if (nsPIDOMWindowOuter* win = aDoc->GetWindow()) {
win->SetFullscreenInternal(FullscreenReason::ForFullscreenAPI, false);
}
}
}
class nsCallExitFullscreen : public Runnable
{
public:
explicit nsCallExitFullscreen(nsIDocument* aDoc)
: mDoc(aDoc) {}
NS_IMETHOD Run() override final
{
if (!mDoc) {
FullscreenRoots::ForEach(&AskWindowToExitFullscreen);
} else {
AskWindowToExitFullscreen(mDoc);
}
return NS_OK;
}
private:
nsCOMPtr<nsIDocument> mDoc;
};
/* static */ void
nsIDocument::AsyncExitFullscreen(nsIDocument* aDoc)
{
NS_DispatchToCurrentThread(new nsCallExitFullscreen(aDoc));
}
static bool
CountFullscreenSubDocuments(nsIDocument* aDoc, void* aData)
{
if (aDoc->GetFullscreenElement()) {
uint32_t* count = static_cast<uint32_t*>(aData);
(*count)++;
}
return true;
}
static uint32_t
CountFullscreenSubDocuments(nsIDocument* aDoc)
{
uint32_t count = 0;
aDoc->EnumerateSubDocuments(CountFullscreenSubDocuments, &count);
return count;
}
bool
nsDocument::IsFullscreenLeaf()
{
// A fullscreen leaf document is fullscreen, and has no fullscreen
// subdocuments.
if (!GetFullscreenElement()) {
return false;
}
return CountFullscreenSubDocuments(this) == 0;
}
static bool
ResetFullScreen(nsIDocument* aDocument, void* aData)
{
if (aDocument->GetFullscreenElement()) {
NS_ASSERTION(CountFullscreenSubDocuments(aDocument) <= 1,
"Should have at most 1 fullscreen subdocument.");
static_cast<nsDocument*>(aDocument)->CleanupFullscreenState();
NS_ASSERTION(!aDocument->GetFullscreenElement(),
"Should reset full-screen");
auto changed = reinterpret_cast<nsCOMArray<nsIDocument>*>(aData);
changed->AppendElement(aDocument);
aDocument->EnumerateSubDocuments(ResetFullScreen, aData);
}
return true;
}
// Since nsIDocument::ExitFullscreenInDocTree() could be called from
// Element::UnbindFromTree() where it is not safe to synchronously run
// script. This runnable is the script part of that function.
class ExitFullscreenScriptRunnable : public Runnable
{
public:
explicit ExitFullscreenScriptRunnable(nsCOMArray<nsIDocument>&& aDocuments)
: mDocuments(Move(aDocuments)) { }
NS_IMETHOD Run() override
{
// Dispatch MozDOMFullscreen:Exited to the last document in
// the list since we want this event to follow the same path
// MozDOMFullscreen:Entered dispatched.
nsIDocument* lastDocument = mDocuments[mDocuments.Length() - 1];
nsContentUtils::DispatchEventOnlyToChrome(
lastDocument, ToSupports(lastDocument),
NS_LITERAL_STRING("MozDOMFullscreen:Exited"),
/* Bubbles */ true, /* Cancelable */ false, /* DefaultAction */ nullptr);
// Ensure the window exits fullscreen.
if (nsPIDOMWindowOuter* win = mDocuments[0]->GetWindow()) {
win->SetFullscreenInternal(FullscreenReason::ForForceExitFullscreen, false);
}
return NS_OK;
}
private:
nsCOMArray<nsIDocument> mDocuments;
};
/* static */ void
nsIDocument::ExitFullscreenInDocTree(nsIDocument* aMaybeNotARootDoc)
{
MOZ_ASSERT(aMaybeNotARootDoc);
// Unlock the pointer
UnlockPointer();
nsCOMPtr<nsIDocument> root = aMaybeNotARootDoc->GetFullscreenRoot();
if (!root || !root->GetFullscreenElement()) {
// If a document was detached before exiting from fullscreen, it is
// possible that the root had left fullscreen state. In this case,
// we would not get anything from the ResetFullScreen() call. Root's
// not being a fullscreen doc also means the widget should have
// exited fullscreen state. It means even if we do not return here,
// we would actually do nothing below except crashing ourselves via
// dispatching the "MozDOMFullscreen:Exited" event to an nonexistent
// document.
return;
}
// Stores a list of documents to which we must dispatch "fullscreenchange".
// We're required by the spec to dispatch the events in leaf-to-root
// order when exiting fullscreen, but we traverse the doctree in a
// root-to-leaf order, so we save references to the documents we must
// dispatch to so that we dispatch in the specified order.
nsCOMArray<nsIDocument> changed;
// Walk the tree of fullscreen documents, and reset their fullscreen state.
ResetFullScreen(root, static_cast<void*>(&changed));
// Dispatch "fullscreenchange" events. Note this loop is in reverse
// order so that the events for the leaf document arrives before the root
// document, as required by the spec.
for (uint32_t i = 0; i < changed.Length(); ++i) {
DispatchFullScreenChange(changed[changed.Length() - i - 1]);
}
NS_ASSERTION(!root->GetFullscreenElement(),
"Fullscreen root should no longer be a fullscreen doc...");
// Move the top-level window out of fullscreen mode.
FullscreenRoots::Remove(root);
nsContentUtils::AddScriptRunner(
new ExitFullscreenScriptRunnable(Move(changed)));
}
bool
GetFullscreenLeaf(nsIDocument* aDoc, void* aData)
{
if (aDoc->IsFullscreenLeaf()) {
nsIDocument** result = static_cast<nsIDocument**>(aData);
*result = aDoc;
return false;
} else if (aDoc->GetFullscreenElement()) {
aDoc->EnumerateSubDocuments(GetFullscreenLeaf, aData);
}
return true;
}
static nsIDocument*
GetFullscreenLeaf(nsIDocument* aDoc)
{
nsIDocument* leaf = nullptr;
GetFullscreenLeaf(aDoc, &leaf);
if (leaf) {
return leaf;
}
// Otherwise we could be either in a non-fullscreen doc tree, or we're
// below the fullscreen doc. Start the search from the root.
nsIDocument* root = nsContentUtils::GetRootDocument(aDoc);
// Check that the root is actually fullscreen so we don't waste time walking
// around its descendants.
if (!root->GetFullscreenElement()) {
return nullptr;
}
GetFullscreenLeaf(root, &leaf);
return leaf;
}
void
nsDocument::RestorePreviousFullScreenState()
{
NS_ASSERTION(!GetFullscreenElement() || !FullscreenRoots::IsEmpty(),
"Should have at least 1 fullscreen root when fullscreen!");
if (!GetFullscreenElement() || !GetWindow() || FullscreenRoots::IsEmpty()) {
return;
}
nsCOMPtr<nsIDocument> fullScreenDoc = GetFullscreenLeaf(this);
AutoTArray<nsDocument*, 8> exitDocs;
nsIDocument* doc = fullScreenDoc;
// Collect all subdocuments.
for (; doc != this; doc = doc->GetParentDocument()) {
exitDocs.AppendElement(static_cast<nsDocument*>(doc));
}
MOZ_ASSERT(doc == this, "Must have reached this doc");
// Collect all ancestor documents which we are going to change.
for (; doc; doc = doc->GetParentDocument()) {
nsDocument* theDoc = static_cast<nsDocument*>(doc);
MOZ_ASSERT(!theDoc->mFullScreenStack.IsEmpty(),
"Ancestor of fullscreen document must also be in fullscreen");
if (doc != this) {
Element* top = theDoc->FullScreenStackTop();
if (top->IsHTMLElement(nsGkAtoms::iframe)) {
if (static_cast<HTMLIFrameElement*>(top)->FullscreenFlag()) {
// If this is an iframe, and it explicitly requested
// fullscreen, don't rollback it automatically.
break;
}
}
}
exitDocs.AppendElement(theDoc);
if (theDoc->mFullScreenStack.Length() > 1) {
break;
}
}
nsDocument* lastDoc = exitDocs.LastElement();
if (!lastDoc->GetParentDocument() &&
lastDoc->mFullScreenStack.Length() == 1) {
// If we are fully exiting fullscreen, don't touch anything here,
// just wait for the window to get out from fullscreen first.
AskWindowToExitFullscreen(this);
return;
}
// If fullscreen mode is updated the pointer should be unlocked
UnlockPointer();
// All documents listed in the array except the last one are going to
// completely exit from the fullscreen state.
for (auto i : MakeRange(exitDocs.Length() - 1)) {
exitDocs[i]->CleanupFullscreenState();
}
// The last document will either rollback one fullscreen element, or
// completely exit from the fullscreen state as well.
nsIDocument* newFullscreenDoc;
if (lastDoc->mFullScreenStack.Length() > 1) {
lastDoc->FullScreenStackPop();
newFullscreenDoc = lastDoc;
} else {
lastDoc->CleanupFullscreenState();
newFullscreenDoc = lastDoc->GetParentDocument();
}
// Dispatch the fullscreenchange event to all document listed.
for (nsDocument* d : exitDocs) {
DispatchFullScreenChange(d);
}
MOZ_ASSERT(newFullscreenDoc, "If we were going to exit from fullscreen on "
"all documents in this doctree, we should've asked the window to "
"exit first instead of reaching here.");
if (fullScreenDoc != newFullscreenDoc &&
!nsContentUtils::HaveEqualPrincipals(fullScreenDoc, newFullscreenDoc)) {
// We've popped so enough off the stack that we've rolled back to
// a fullscreen element in a parent document. If this document is
// cross origin, dispatch an event to chrome so it knows to show
// the warning UI.
DispatchCustomEventWithFlush(
newFullscreenDoc, NS_LITERAL_STRING("MozDOMFullscreen:NewOrigin"),
/* Bubbles */ true, /* ChromeOnly */ true);
}
}
class nsCallRequestFullScreen : public Runnable
{
public:
explicit nsCallRequestFullScreen(UniquePtr<FullscreenRequest>&& aRequest)
: mRequest(Move(aRequest)) { }
NS_IMETHOD Run() override
{
mRequest->GetDocument()->RequestFullScreen(Move(mRequest));
return NS_OK;
}
UniquePtr<FullscreenRequest> mRequest;
};
void
nsDocument::AsyncRequestFullScreen(UniquePtr<FullscreenRequest>&& aRequest)
{
if (!aRequest->GetElement()) {
MOZ_ASSERT_UNREACHABLE(
"Must pass non-null element to nsDocument::AsyncRequestFullScreen");
return;
}
// Request full-screen asynchronously.
nsCOMPtr<nsIRunnable> event(new nsCallRequestFullScreen(Move(aRequest)));
NS_DispatchToCurrentThread(event);
}
void
nsIDocument::DispatchFullscreenError(const char* aMessage)
{
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(this,
NS_LITERAL_STRING("fullscreenerror"),
true,
false);
asyncDispatcher->PostDOMEvent();
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM"), this,
nsContentUtils::eDOM_PROPERTIES,
aMessage);
}
static void
UpdateViewportScrollbarOverrideForFullscreen(nsIDocument* aDoc)
{
if (nsIPresShell* presShell = aDoc->GetShell()) {
if (nsPresContext* presContext = presShell->GetPresContext()) {
presContext->UpdateViewportScrollbarStylesOverride();
}
}
}
static void
ClearFullscreenStateOnElement(Element* aElement)
{
// Remove styles from existing top element.
EventStateManager::SetFullScreenState(aElement, false);
// Reset iframe fullscreen flag.
if (aElement->IsHTMLElement(nsGkAtoms::iframe)) {
static_cast<HTMLIFrameElement*>(aElement)->SetFullscreenFlag(false);
}
}
void
nsDocument::CleanupFullscreenState()
{
// Iterate the fullscreen stack and clear the fullscreen states.
// Since we also need to clear the fullscreen-ancestor state, and
// currently fullscreen elements can only be placed in hierarchy
// order in the stack, reversely iterating the stack could be more
// efficient. NOTE that fullscreen-ancestor state would be removed
// in bug 1199529, and the elements may not in hierarchy order
// after bug 1195213.
for (nsWeakPtr& weakPtr : Reversed(mFullScreenStack)) {
if (nsCOMPtr<Element> element = do_QueryReferent(weakPtr)) {
ClearFullscreenStateOnElement(element);
}
}
mFullScreenStack.Clear();
mFullscreenRoot = nullptr;
UpdateViewportScrollbarOverrideForFullscreen(this);
}
bool
nsDocument::FullScreenStackPush(Element* aElement)
{
NS_ASSERTION(aElement, "Must pass non-null to FullScreenStackPush()");
Element* top = FullScreenStackTop();
if (top == aElement || !aElement) {
return false;
}
EventStateManager::SetFullScreenState(aElement, true);
mFullScreenStack.AppendElement(do_GetWeakReference(aElement));
NS_ASSERTION(GetFullscreenElement() == aElement, "Should match");
UpdateViewportScrollbarOverrideForFullscreen(this);
return true;
}
void
nsDocument::FullScreenStackPop()
{
if (mFullScreenStack.IsEmpty()) {
return;
}
ClearFullscreenStateOnElement(FullScreenStackTop());
// Remove top element. Note the remaining top element in the stack
// will not have full-screen style bits set, so we will need to restore
// them on the new top element before returning.
uint32_t last = mFullScreenStack.Length() - 1;
mFullScreenStack.RemoveElementAt(last);
// Pop from the stack null elements (references to elements which have
// been GC'd since they were added to the stack) and elements which are
// no longer in this document.
while (!mFullScreenStack.IsEmpty()) {
Element* element = FullScreenStackTop();
if (!element || !element->IsInUncomposedDoc() || element->OwnerDoc() != this) {
NS_ASSERTION(!element->State().HasState(NS_EVENT_STATE_FULL_SCREEN),
"Should have already removed full-screen styles");
uint32_t last = mFullScreenStack.Length() - 1;
mFullScreenStack.RemoveElementAt(last);
} else {
// The top element of the stack is now an in-doc element. Return here.
break;
}
}
UpdateViewportScrollbarOverrideForFullscreen(this);
}
Element*
nsDocument::FullScreenStackTop()
{
if (mFullScreenStack.IsEmpty()) {
return nullptr;
}
uint32_t last = mFullScreenStack.Length() - 1;
nsCOMPtr<Element> element(do_QueryReferent(mFullScreenStack[last]));
NS_ASSERTION(element, "Should have full-screen element!");
NS_ASSERTION(element->IsInUncomposedDoc(), "Full-screen element should be in doc");
NS_ASSERTION(element->OwnerDoc() == this, "Full-screen element should be in this doc");
return element;
}
/* virtual */ nsTArray<Element*>
nsDocument::GetFullscreenStack() const
{
nsTArray<Element*> elements;
for (const nsWeakPtr& ptr : mFullScreenStack) {
if (nsCOMPtr<Element> elem = do_QueryReferent(ptr)) {
MOZ_ASSERT(elem->State().HasState(NS_EVENT_STATE_FULL_SCREEN));
elements.AppendElement(elem);
}
}
return elements;
}
// Returns true if aDoc is in the focused tab in the active window.
static bool
IsInActiveTab(nsIDocument* aDoc)
{
nsCOMPtr<nsIDocShell> docshell = aDoc->GetDocShell();
if (!docshell) {
return false;
}
bool isActive = false;
docshell->GetIsActive(&isActive);
if (!isActive) {
return false;
}
nsCOMPtr<nsIDocShellTreeItem> rootItem;
docshell->GetRootTreeItem(getter_AddRefs(rootItem));
if (!rootItem) {
return false;
}
nsCOMPtr<nsPIDOMWindowOuter> rootWin = rootItem->GetWindow();
if (!rootWin) {
return false;
}
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
return false;
}
nsCOMPtr<mozIDOMWindowProxy> activeWindow;
fm->GetActiveWindow(getter_AddRefs(activeWindow));
if (!activeWindow) {
return false;
}
return activeWindow == rootWin;
}
nsresult nsDocument::RemoteFrameFullscreenChanged(nsIDOMElement* aFrameElement)
{
// Ensure the frame element is the fullscreen element in this document.
// If the frame element is already the fullscreen element in this document,
// this has no effect.
nsCOMPtr<nsIContent> content(do_QueryInterface(aFrameElement));
auto request = MakeUnique<FullscreenRequest>(content->AsElement());
request->mIsCallerChrome = false;
request->mShouldNotifyNewOrigin = false;
RequestFullScreen(Move(request));
return NS_OK;
}
nsresult nsDocument::RemoteFrameFullscreenReverted()
{
RestorePreviousFullScreenState();
return NS_OK;
}
/* static */ bool
nsDocument::IsUnprefixedFullscreenEnabled(JSContext* aCx, JSObject* aObject)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
nsContentUtils::IsUnprefixedFullscreenApiEnabled();
}
static bool
HasFullScreenSubDocument(nsIDocument* aDoc)
{
uint32_t count = CountFullscreenSubDocuments(aDoc);
NS_ASSERTION(count <= 1, "Fullscreen docs should have at most 1 fullscreen child!");
return count >= 1;
}
// Returns nullptr if a request for Fullscreen API is currently enabled
// in the given document. Returns a static string indicates the reason
// why it is not enabled otherwise.
static const char*
GetFullscreenError(nsIDocument* aDoc, bool aCallerIsChrome)
{
if (nsContentUtils::IsFullScreenApiEnabled() && aCallerIsChrome) {
// Chrome code can always use the full-screen API, provided it's not
// explicitly disabled. Note IsCallerChrome() returns true when running
// in a Runnable, so don't use GetMozFullScreenEnabled() from a
// Runnable!
return nullptr;
}
if (!nsContentUtils::IsFullScreenApiEnabled()) {
return "FullscreenDeniedDisabled";
}
// Ensure that all containing elements are <iframe> and have
// allowfullscreen attribute set.
nsCOMPtr<nsIDocShell> docShell(aDoc->GetDocShell());
if (!docShell || !docShell->GetFullscreenAllowed()) {
return "FullscreenDeniedContainerNotAllowed";
}
return nullptr;
}
bool
nsDocument::FullscreenElementReadyCheck(Element* aElement,
bool aWasCallerChrome)
{
NS_ASSERTION(aElement,
"Must pass non-null element to nsDocument::RequestFullScreen");
if (!aElement || aElement == GetFullscreenElement()) {
return false;
}
if (!aElement->IsInUncomposedDoc()) {
DispatchFullscreenError("FullscreenDeniedNotInDocument");
return false;
}
if (aElement->OwnerDoc() != this) {
DispatchFullscreenError("FullscreenDeniedMovedDocument");
return false;
}
if (!GetWindow()) {
DispatchFullscreenError("FullscreenDeniedLostWindow");
return false;
}
if (const char* msg = GetFullscreenError(this, aWasCallerChrome)) {
DispatchFullscreenError(msg);
return false;
}
if (!IsVisible()) {
DispatchFullscreenError("FullscreenDeniedHidden");
return false;
}
if (HasFullScreenSubDocument(this)) {
DispatchFullscreenError("FullscreenDeniedSubDocFullScreen");
return false;
}
if (GetFullscreenElement() &&
!nsContentUtils::ContentIsDescendantOf(aElement, GetFullscreenElement())) {
// If this document is full-screen, only grant full-screen requests from
// a descendant of the current full-screen element.
DispatchFullscreenError("FullscreenDeniedNotDescendant");
return false;
}
if (!nsContentUtils::IsChromeDoc(this) && !IsInActiveTab(this)) {
DispatchFullscreenError("FullscreenDeniedNotFocusedTab");
return false;
}
// Deny requests when a windowed plugin is focused.
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
NS_WARNING("Failed to retrieve focus manager in full-screen request.");
return false;
}
nsCOMPtr<nsIDOMElement> focusedElement;
fm->GetFocusedElement(getter_AddRefs(focusedElement));
if (focusedElement) {
nsCOMPtr<nsIContent> content = do_QueryInterface(focusedElement);
if (nsContentUtils::HasPluginWithUncontrolledEventDispatch(content)) {
DispatchFullscreenError("FullscreenDeniedFocusedPlugin");
return false;
}
}
return true;
}
FullscreenRequest::FullscreenRequest(Element* aElement)
: mElement(aElement)
, mDocument(static_cast<nsDocument*>(aElement->OwnerDoc()))
{
MOZ_COUNT_CTOR(FullscreenRequest);
}
FullscreenRequest::~FullscreenRequest()
{
MOZ_COUNT_DTOR(FullscreenRequest);
}
// Any fullscreen request waiting for the widget to finish being full-
// screen is queued here. This is declared static instead of a member
// of nsDocument because in the majority of time, there would be at most
// one document requesting fullscreen. We shouldn't waste the space to
// hold for it in every document.
class PendingFullscreenRequestList
{
public:
static void Add(UniquePtr<FullscreenRequest>&& aRequest)
{
sList.insertBack(aRequest.release());
}
static const FullscreenRequest* GetLast()
{
return sList.getLast();
}
enum IteratorOption
{
// When we are committing fullscreen changes or preparing for
// that, we generally want to iterate all requests in the same
// window with eDocumentsWithSameRoot option.
eDocumentsWithSameRoot,
// If we are removing a document from the tree, we would only
// want to remove the requests from the given document and its
// descendants. For that case, use eInclusiveDescendants.
eInclusiveDescendants
};
class Iterator
{
public:
explicit Iterator(nsIDocument* aDoc, IteratorOption aOption)
: mCurrent(PendingFullscreenRequestList::sList.getFirst())
, mRootShellForIteration(aDoc->GetDocShell())
{
if (mCurrent) {
if (mRootShellForIteration && aOption == eDocumentsWithSameRoot) {
mRootShellForIteration->
GetRootTreeItem(getter_AddRefs(mRootShellForIteration));
}
SkipToNextMatch();
}
}
void DeleteAndNext()
{
DeleteAndNextInternal();
SkipToNextMatch();
}
bool AtEnd() const { return mCurrent == nullptr; }
const FullscreenRequest& Get() const { return *mCurrent; }
private:
void DeleteAndNextInternal()
{
FullscreenRequest* thisRequest = mCurrent;
mCurrent = mCurrent->getNext();
delete thisRequest;
}
void SkipToNextMatch()
{
while (mCurrent) {
nsCOMPtr<nsIDocShellTreeItem>
docShell = mCurrent->GetDocument()->GetDocShell();
if (!docShell) {
// Always automatically drop documents which has been
// detached from the doc shell.
DeleteAndNextInternal();
} else {
while (docShell && docShell != mRootShellForIteration) {
docShell->GetParent(getter_AddRefs(docShell));
}
if (!docShell) {
// We've gone over the root, but haven't find the target
// ancestor, so skip this item.
mCurrent = mCurrent->getNext();
} else {
break;
}
}
}
}
FullscreenRequest* mCurrent;
nsCOMPtr<nsIDocShellTreeItem> mRootShellForIteration;
};
private:
PendingFullscreenRequestList() = delete;
static LinkedList<FullscreenRequest> sList;
};
/* static */ LinkedList<FullscreenRequest> PendingFullscreenRequestList::sList;
static nsCOMPtr<nsPIDOMWindowOuter>
GetRootWindow(nsIDocument* aDoc)
{
nsIDocShell* docShell = aDoc->GetDocShell();
if (!docShell) {
return nullptr;
}
nsCOMPtr<nsIDocShellTreeItem> rootItem;
docShell->GetRootTreeItem(getter_AddRefs(rootItem));
return rootItem ? rootItem->GetWindow() : nullptr;
}
static bool
ShouldApplyFullscreenDirectly(nsIDocument* aDoc,
nsPIDOMWindowOuter* aRootWin)
{
if (XRE_GetProcessType() == GeckoProcessType_Content) {
// If we are in the content process, we can apply the fullscreen
// state directly only if we have been in DOM fullscreen, because
// otherwise we always need to notify the chrome.
return !!nsContentUtils::GetRootDocument(aDoc)->GetFullscreenElement();
} else {
// If we are in the chrome process, and the window has not been in
// fullscreen, we certainly need to make that fullscreen first.
if (!aRootWin->GetFullScreen()) {
return false;
}
// The iterator not being at end indicates there is still some
// pending fullscreen request relates to this document. We have to
// push the request to the pending queue so requests are handled
// in the correct order.
PendingFullscreenRequestList::Iterator
iter(aDoc, PendingFullscreenRequestList::eDocumentsWithSameRoot);
if (!iter.AtEnd()) {
return false;
}
// We have to apply the fullscreen state directly in this case,
// because nsGlobalWindow::SetFullscreenInternal() will do nothing
// if it is already in fullscreen. If we do not apply the state but
// instead add it to the queue and wait for the window as normal,
// we would get stuck.
return true;
}
}
void
nsDocument::RequestFullScreen(UniquePtr<FullscreenRequest>&& aRequest)
{
nsCOMPtr<nsPIDOMWindowOuter> rootWin = GetRootWindow(this);
if (!rootWin) {
return;
}
if (ShouldApplyFullscreenDirectly(this, rootWin)) {
ApplyFullscreen(*aRequest);
return;
}
// Per spec only HTML, <svg>, and <math> should be allowed, but
// we also need to allow XUL elements right now.
Element* elem = aRequest->GetElement();
if (!elem->IsHTMLElement() && !elem->IsXULElement() &&
!elem->IsSVGElement(nsGkAtoms::svg) &&
!elem->IsMathMLElement(nsGkAtoms::math)) {
DispatchFullscreenError("FullscreenDeniedNotHTMLSVGOrMathML");
return;
}
// We don't need to check element ready before this point, because
// if we called ApplyFullscreen, it would check that for us.
if (!FullscreenElementReadyCheck(elem, aRequest->mIsCallerChrome)) {
return;
}
PendingFullscreenRequestList::Add(Move(aRequest));
if (XRE_GetProcessType() == GeckoProcessType_Content) {
// If we are not the top level process, dispatch an event to make
// our parent process go fullscreen first.
nsContentUtils::DispatchEventOnlyToChrome(
this, ToSupports(this), NS_LITERAL_STRING("MozDOMFullscreen:Request"),
/* Bubbles */ true, /* Cancelable */ false, /* DefaultAction */ nullptr);
} else {
// Make the window fullscreen.
rootWin->SetFullscreenInternal(FullscreenReason::ForFullscreenAPI, true);
}
}
/* static */ bool
nsIDocument::HandlePendingFullscreenRequests(nsIDocument* aDoc)
{
bool handled = false;
PendingFullscreenRequestList::Iterator iter(
aDoc, PendingFullscreenRequestList::eDocumentsWithSameRoot);
while (!iter.AtEnd()) {
const FullscreenRequest& request = iter.Get();
if (request.GetDocument()->ApplyFullscreen(request)) {
handled = true;
}
iter.DeleteAndNext();
}
return handled;
}
static void
ClearPendingFullscreenRequests(nsIDocument* aDoc)
{
PendingFullscreenRequestList::Iterator iter(
aDoc, PendingFullscreenRequestList::eInclusiveDescendants);
while (!iter.AtEnd()) {
iter.DeleteAndNext();
}
}
bool
nsDocument::ApplyFullscreen(const FullscreenRequest& aRequest)
{
Element* elem = aRequest.GetElement();
if (!FullscreenElementReadyCheck(elem, aRequest.mIsCallerChrome)) {
return false;
}
// Stash a reference to any existing fullscreen doc, we'll use this later
// to detect if the origin which is fullscreen has changed.
nsCOMPtr<nsIDocument> previousFullscreenDoc = GetFullscreenLeaf(this);
// Stores a list of documents which we must dispatch "fullscreenchange"
// too. We're required by the spec to dispatch the events in root-to-leaf
// order, but we traverse the doctree in a leaf-to-root order, so we save
// references to the documents we must dispatch to so that we get the order
// as specified.
AutoTArray<nsIDocument*, 8> changed;
// Remember the root document, so that if a full-screen document is hidden
// we can reset full-screen state in the remaining visible full-screen documents.
nsIDocument* fullScreenRootDoc = nsContentUtils::GetRootDocument(this);
// If a document is already in fullscreen, then unlock the mouse pointer
// before setting a new document to fullscreen
UnlockPointer();
// Set the full-screen element. This sets the full-screen style on the
// element, and the full-screen-ancestor styles on ancestors of the element
// in this document.
DebugOnly<bool> x = FullScreenStackPush(elem);
NS_ASSERTION(x, "Full-screen state of requesting doc should always change!");
// Set the iframe fullscreen flag.
if (elem->IsHTMLElement(nsGkAtoms::iframe)) {
static_cast<HTMLIFrameElement*>(elem)->SetFullscreenFlag(true);
}
changed.AppendElement(this);
// Propagate up the document hierarchy, setting the full-screen element as
// the element's container in ancestor documents. This also sets the
// appropriate css styles as well. Note we don't propagate down the
// document hierarchy, the full-screen element (or its container) is not
// visible there. Stop when we reach the root document.
nsIDocument* child = this;
while (true) {
child->SetFullscreenRoot(fullScreenRootDoc);
NS_ASSERTION(child->GetFullscreenRoot() == fullScreenRootDoc,
"Fullscreen root should be set!");
if (child == fullScreenRootDoc) {
break;
}
nsIDocument* parent = child->GetParentDocument();
Element* element = parent->FindContentForSubDocument(child)->AsElement();
if (static_cast<nsDocument*>(parent)->FullScreenStackPush(element)) {
changed.AppendElement(parent);
child = parent;
} else {
// We've reached either the root, or a point in the doctree where the
// new full-screen element container is the same as the previous
// full-screen element's container. No more changes need to be made
// to the full-screen stacks of documents further up the tree.
break;
}
}
FullscreenRoots::Add(this);
// If it is the first entry of the fullscreen, trigger an event so
// that the UI can response to this change, e.g. hide chrome, or
// notifying parent process to enter fullscreen. Note that chrome
// code may also want to listen to MozDOMFullscreen:NewOrigin event
// to pop up warning UI.
if (!previousFullscreenDoc) {
nsContentUtils::DispatchEventOnlyToChrome(
this, ToSupports(elem), NS_LITERAL_STRING("MozDOMFullscreen:Entered"),
/* Bubbles */ true, /* Cancelable */ false, /* DefaultAction */ nullptr);
}
// The origin which is fullscreen gets changed. Trigger an event so
// that the chrome knows to pop up a warning UI. Note that
// previousFullscreenDoc == nullptr upon first entry, so we always
// take this path on the first entry. Also note that, in a multi-
// process browser, the code in content process is responsible for
// sending message with the origin to its parent, and the parent
// shouldn't rely on this event itself.
if (aRequest.mShouldNotifyNewOrigin &&
!nsContentUtils::HaveEqualPrincipals(previousFullscreenDoc, this)) {
DispatchCustomEventWithFlush(
this, NS_LITERAL_STRING("MozDOMFullscreen:NewOrigin"),
/* Bubbles */ true, /* ChromeOnly */ true);
}
// Dispatch "fullscreenchange" events. Note this loop is in reverse
// order so that the events for the root document arrives before the leaf
// document, as required by the spec.
for (uint32_t i = 0; i < changed.Length(); ++i) {
DispatchFullScreenChange(changed[changed.Length() - i - 1]);
}
return true;
}
NS_IMETHODIMP
nsDocument::GetMozFullScreenElement(nsIDOMElement **aFullScreenElement)
{
Element* el = GetFullscreenElement();
nsCOMPtr<nsIDOMElement> retval = do_QueryInterface(el);
retval.forget(aFullScreenElement);
return NS_OK;
}
Element*
nsDocument::GetFullscreenElement()
{
Element* element = FullScreenStackTop();
NS_ASSERTION(!element ||
element->State().HasState(NS_EVENT_STATE_FULL_SCREEN),
"Fullscreen element should have fullscreen styles applied");
return element;
}
NS_IMETHODIMP
nsDocument::GetMozFullScreen(bool *aFullScreen)
{
*aFullScreen = Fullscreen();
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetMozFullScreenEnabled(bool *aFullScreen)
{
NS_ENSURE_ARG_POINTER(aFullScreen);
*aFullScreen = FullscreenEnabled();
return NS_OK;
}
bool
nsDocument::FullscreenEnabled()
{
return !GetFullscreenError(this, nsContentUtils::IsCallerChrome());
}
uint16_t
nsDocument::CurrentOrientationAngle() const
{
return mCurrentOrientationAngle;
}
OrientationType
nsDocument::CurrentOrientationType() const
{
return mCurrentOrientationType;
}
void
nsDocument::SetCurrentOrientation(mozilla::dom::OrientationType aType,
uint16_t aAngle)
{
mCurrentOrientationType = aType;
mCurrentOrientationAngle = aAngle;
}
Promise*
nsDocument::GetOrientationPendingPromise() const
{
return mOrientationPendingPromise;
}
void
nsDocument::SetOrientationPendingPromise(Promise* aPromise)
{
mOrientationPendingPromise = aPromise;
}
static void
DispatchPointerLockChange(nsIDocument* aTarget)
{
if (!aTarget) {
return;
}
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(aTarget,
NS_LITERAL_STRING("pointerlockchange"),
true,
false);
asyncDispatcher->PostDOMEvent();
}
static void
DispatchPointerLockError(nsIDocument* aTarget, const char* aMessage)
{
if (!aTarget) {
return;
}
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(aTarget,
NS_LITERAL_STRING("pointerlockerror"),
true,
false);
asyncDispatcher->PostDOMEvent();
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("DOM"), aTarget,
nsContentUtils::eDOM_PROPERTIES,
aMessage);
}
class PointerLockRequest final : public Runnable
{
public:
PointerLockRequest(Element* aElement, bool aUserInputOrChromeCaller)
: mElement(do_GetWeakReference(aElement))
, mDocument(do_GetWeakReference(aElement->OwnerDoc()))
, mUserInputOrChromeCaller(aUserInputOrChromeCaller)
{}
NS_IMETHOD Run() final;
private:
nsWeakPtr mElement;
nsWeakPtr mDocument;
bool mUserInputOrChromeCaller;
};
static const char*
GetPointerLockError(Element* aElement, Element* aCurrentLock,
bool aNoFocusCheck = false)
{
// Check if pointer lock pref is enabled
if (!Preferences::GetBool("full-screen-api.pointer-lock.enabled")) {
return "PointerLockDeniedDisabled";
}
nsCOMPtr<nsIDocument> ownerDoc = aElement->OwnerDoc();
if (aCurrentLock && aCurrentLock->OwnerDoc() != ownerDoc) {
return "PointerLockDeniedInUse";
}
if (!aElement->IsInUncomposedDoc()) {
return "PointerLockDeniedNotInDocument";
}
if (ownerDoc->GetSandboxFlags() & SANDBOXED_POINTER_LOCK) {
return "PointerLockDeniedSandboxed";
}
// Check if the element is in a document with a docshell.
if (!ownerDoc->GetContainer()) {
return "PointerLockDeniedHidden";
}
nsCOMPtr<nsPIDOMWindowOuter> ownerWindow = ownerDoc->GetWindow();
if (!ownerWindow) {
return "PointerLockDeniedHidden";
}
nsCOMPtr<nsPIDOMWindowInner> ownerInnerWindow = ownerDoc->GetInnerWindow();
if (!ownerInnerWindow) {
return "PointerLockDeniedHidden";
}
if (ownerWindow->GetCurrentInnerWindow() != ownerInnerWindow) {
return "PointerLockDeniedHidden";
}
nsCOMPtr<nsPIDOMWindowOuter> top = ownerWindow->GetScriptableTop();
if (!top || !top->GetExtantDoc() || top->GetExtantDoc()->Hidden()) {
return "PointerLockDeniedHidden";
}
if (!aNoFocusCheck) {
mozilla::ErrorResult rv;
if (!top->GetExtantDoc()->HasFocus(rv)) {
return "PointerLockDeniedNotFocused";
}
}
return nullptr;
}
static void
ChangePointerLockedElement(Element* aElement, nsIDocument* aDocument,
Element* aPointerLockedElement)
{
// aDocument here is not really necessary, as it is the uncomposed
// document of both aElement and aPointerLockedElement as far as one
// is not nullptr, and they wouldn't both be nullptr in any case.
// But since the caller of this function should have known what the
// document is, we just don't try to figure out what it should be.
MOZ_ASSERT(aDocument);
MOZ_ASSERT(aElement != aPointerLockedElement);
if (aPointerLockedElement) {
MOZ_ASSERT(aPointerLockedElement->GetUncomposedDoc() == aDocument);
aPointerLockedElement->ClearPointerLock();
}
if (aElement) {
MOZ_ASSERT(aElement->GetUncomposedDoc() == aDocument);
aElement->SetPointerLock();
EventStateManager::sPointerLockedElement = do_GetWeakReference(aElement);
EventStateManager::sPointerLockedDoc = do_GetWeakReference(aDocument);
NS_ASSERTION(EventStateManager::sPointerLockedElement &&
EventStateManager::sPointerLockedDoc,
"aElement and this should support weak references!");
} else {
EventStateManager::sPointerLockedElement = nullptr;
EventStateManager::sPointerLockedDoc = nullptr;
}
// Retarget all events to aElement via capture or
// stop retargeting if aElement is nullptr.
nsIPresShell::SetCapturingContent(aElement, CAPTURE_POINTERLOCK);
DispatchPointerLockChange(aDocument);
}
NS_IMETHODIMP
PointerLockRequest::Run()
{
nsCOMPtr<Element> e = do_QueryReferent(mElement);
nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocument);
nsDocument* d = static_cast<nsDocument*>(doc.get());
const char* error = nullptr;
if (!e || !d || !e->GetUncomposedDoc()) {
error = "PointerLockDeniedNotInDocument";
} else if (e->GetUncomposedDoc() != d) {
error = "PointerLockDeniedMovedDocument";
}
if (!error) {
nsCOMPtr<Element> pointerLockedElement =
do_QueryReferent(EventStateManager::sPointerLockedElement);
if (e == pointerLockedElement) {
DispatchPointerLockChange(d);
return NS_OK;
}
// Note, we must bypass focus change, so pass true as the last parameter!
error = GetPointerLockError(e, pointerLockedElement, true);
// Another element in the same document is requesting pointer lock,
// just grant it without user input check.
if (!error && pointerLockedElement) {
ChangePointerLockedElement(e, d, pointerLockedElement);
return NS_OK;
}
}
// If it is neither user input initiated, nor requested in fullscreen,
// it should be rejected.
if (!error && !mUserInputOrChromeCaller && !doc->GetFullscreenElement()) {
error = "PointerLockDeniedNotInputDriven";
}
if (!error && !d->SetPointerLock(e, NS_STYLE_CURSOR_NONE)) {
error = "PointerLockDeniedFailedToLock";
}
if (error) {
DispatchPointerLockError(d, error);
return NS_OK;
}
ChangePointerLockedElement(e, d, nullptr);
nsContentUtils::DispatchEventOnlyToChrome(
doc, ToSupports(e), NS_LITERAL_STRING("MozDOMPointerLock:Entered"),
/* Bubbles */ true, /* Cancelable */ false, /* DefaultAction */ nullptr);
return NS_OK;
}
void
nsDocument::RequestPointerLock(Element* aElement)
{
NS_ASSERTION(aElement,
"Must pass non-null element to nsDocument::RequestPointerLock");
nsCOMPtr<Element> pointerLockedElement =
do_QueryReferent(EventStateManager::sPointerLockedElement);
if (aElement == pointerLockedElement) {
DispatchPointerLockChange(this);
return;
}
if (const char* msg = GetPointerLockError(aElement, pointerLockedElement)) {
DispatchPointerLockError(this, msg);
return;
}
bool userInputOrChromeCaller = EventStateManager::IsHandlingUserInput() ||
nsContentUtils::IsCallerChrome();
NS_DispatchToMainThread(new PointerLockRequest(aElement,
userInputOrChromeCaller));
}
bool
nsDocument::SetPointerLock(Element* aElement, int aCursorStyle)
{
MOZ_ASSERT(!aElement || aElement->OwnerDoc() == this,
"We should be either unlocking pointer (aElement is nullptr), "
"or locking pointer to an element in this document");
#ifdef DEBUG
if (!aElement) {
nsCOMPtr<nsIDocument> pointerLockedDoc =
do_QueryReferent(EventStateManager::sPointerLockedDoc);
MOZ_ASSERT(pointerLockedDoc == this);
}
#endif
nsIPresShell* shell = GetShell();
if (!shell) {
NS_WARNING("SetPointerLock(): No PresShell");
if (!aElement) {
// If we are unlocking pointer lock, but for some reason the doc
// has already detached from the presshell, just ask the event
// state manager to release the pointer.
EventStateManager::SetPointerLock(nullptr, nullptr);
return true;
}
return false;
}
nsPresContext* presContext = shell->GetPresContext();
if (!presContext) {
NS_WARNING("SetPointerLock(): Unable to get PresContext");
return false;
}
nsCOMPtr<nsIWidget> widget;
nsIFrame* rootFrame = shell->GetRootFrame();
if (!NS_WARN_IF(!rootFrame)) {
widget = rootFrame->GetNearestWidget();
NS_WARNING_ASSERTION(
widget,
"SetPointerLock(): Unable to find widget in "
"shell->GetRootFrame()->GetNearestWidget();");
if (aElement && !widget) {
return false;
}
}
// Hide the cursor and set pointer lock for future mouse events
RefPtr<EventStateManager> esm = presContext->EventStateManager();
esm->SetCursor(aCursorStyle, nullptr, false,
0.0f, 0.0f, widget, true);
EventStateManager::SetPointerLock(widget, aElement);
return true;
}
void
nsDocument::UnlockPointer(nsIDocument* aDoc)
{
if (!EventStateManager::sIsPointerLocked) {
return;
}
nsCOMPtr<nsIDocument> pointerLockedDoc =
do_QueryReferent(EventStateManager::sPointerLockedDoc);
if (!pointerLockedDoc || (aDoc && aDoc != pointerLockedDoc)) {
return;
}
nsDocument* doc = static_cast<nsDocument*>(pointerLockedDoc.get());
if (!doc->SetPointerLock(nullptr, NS_STYLE_CURSOR_AUTO)) {
return;
}
nsCOMPtr<Element> pointerLockedElement =
do_QueryReferent(EventStateManager::sPointerLockedElement);
ChangePointerLockedElement(nullptr, doc, pointerLockedElement);
nsContentUtils::DispatchEventOnlyToChrome(
doc, ToSupports(pointerLockedElement),
NS_LITERAL_STRING("MozDOMPointerLock:Exited"),
/* Bubbles */ true, /* Cancelable */ false, /* DefaultAction */ nullptr);
}
void
nsIDocument::UnlockPointer(nsIDocument* aDoc)
{
nsDocument::UnlockPointer(aDoc);
}
NS_IMETHODIMP
nsDocument::MozExitPointerLock()
{
nsIDocument::ExitPointerLock();
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetMozPointerLockElement(nsIDOMElement** aPointerLockedElement)
{
Element* el = nsIDocument::GetPointerLockElement();
nsCOMPtr<nsIDOMElement> retval = do_QueryInterface(el);
retval.forget(aPointerLockedElement);
return NS_OK;
}
Element*
nsIDocument::GetPointerLockElement()
{
nsCOMPtr<Element> pointerLockedElement =
do_QueryReferent(EventStateManager::sPointerLockedElement);
if (!pointerLockedElement) {
return nullptr;
}
// Make sure pointer locked element is in the same document.
nsCOMPtr<nsIDocument> pointerLockedDoc =
do_QueryReferent(EventStateManager::sPointerLockedDoc);
if (pointerLockedDoc != this) {
return nullptr;
}
return pointerLockedElement;
}
nsresult
nsDocument::Observe(nsISupports *aSubject,
const char *aTopic,
const char16_t *aData)
{
if (strcmp("service-worker-get-client", aTopic) == 0) {
// No need to generate the ID if it doesn't exist here. The ID being
// requested must already be generated in order to passed in as
// aSubject.
nsString clientId = GetId();
if (!clientId.IsEmpty() && clientId.Equals(aData)) {
nsCOMPtr<nsISupportsInterfacePointer> ifptr = do_QueryInterface(aSubject);
if (ifptr) {
#ifdef DEBUG
nsCOMPtr<nsISupports> value;
MOZ_ALWAYS_SUCCEEDS(ifptr->GetData(getter_AddRefs(value)));
MOZ_ASSERT(!value);
#endif
ifptr->SetData(static_cast<nsIDocument*>(this));
ifptr->SetDataIID(&NS_GET_IID(nsIDocument));
}
}
}
return NS_OK;
}
void
nsDocument::UpdateVisibilityState()
{
dom::VisibilityState oldState = mVisibilityState;
mVisibilityState = GetVisibilityState();
if (oldState != mVisibilityState) {
nsContentUtils::DispatchTrustedEvent(this, static_cast<nsIDocument*>(this),
NS_LITERAL_STRING("visibilitychange"),
/* bubbles = */ true,
/* cancelable = */ false);
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
}
if (mVisibilityState == dom::VisibilityState::Visible) {
MaybeActiveMediaComponents();
}
}
VisibilityState
nsDocument::GetVisibilityState() const
{
// We have to check a few pieces of information here:
// 1) Are we in bfcache (!IsVisible())? If so, nothing else matters.
// 2) Do we have an outer window? If not, we're hidden. Note that we don't
// want to use GetWindow here because it does weird groveling for windows
// in some cases.
// 3) Is our outer window background? If so, we're hidden.
// Otherwise, we're visible.
if (!IsVisible() || !mWindow || !mWindow->GetOuterWindow() ||
mWindow->GetOuterWindow()->IsBackground()) {
// Check if the document is in prerender state.
nsCOMPtr<nsIDocShell> docshell = GetDocShell();
if (docshell && docshell->GetIsPrerendered()) {
return dom::VisibilityState::Prerender;
}
return dom::VisibilityState::Hidden;
}
return dom::VisibilityState::Visible;
}
/* virtual */ void
nsDocument::PostVisibilityUpdateEvent()
{
nsCOMPtr<nsIRunnable> event =
NewRunnableMethod(this, &nsDocument::UpdateVisibilityState);
NS_DispatchToMainThread(event);
}
void
nsDocument::MaybeActiveMediaComponents()
{
if (mEverInForeground) {
return;
}
if (!mWindow) {
return;
}
mEverInForeground = true;
if (GetWindow()->GetMediaSuspend() == nsISuspendedTypes::SUSPENDED_BLOCK) {
GetWindow()->SetMediaSuspend(nsISuspendedTypes::NONE_SUSPENDED);
}
}
NS_IMETHODIMP
nsDocument::GetHidden(bool* aHidden)
{
*aHidden = Hidden();
return NS_OK;
}
NS_IMETHODIMP
nsDocument::GetVisibilityState(nsAString& aState)
{
const EnumEntry& entry =
VisibilityStateValues::strings[static_cast<int>(mVisibilityState)];
aState.AssignASCII(entry.value, entry.length);
return NS_OK;
}
/* virtual */ void
nsIDocument::DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const
{
aWindowSizes->mDOMOtherSize +=
nsINode::SizeOfExcludingThis(aWindowSizes->mMallocSizeOf);
if (mPresShell) {
mPresShell->AddSizeOfIncludingThis(aWindowSizes->mMallocSizeOf,
&aWindowSizes->mArenaStats,
&aWindowSizes->mLayoutPresShellSize,
&aWindowSizes->mLayoutStyleSetsSize,
&aWindowSizes->mLayoutTextRunsSize,
&aWindowSizes->mLayoutPresContextSize,
&aWindowSizes->mLayoutFramePropertiesSize);
}
aWindowSizes->mPropertyTablesSize +=
mPropertyTable.SizeOfExcludingThis(aWindowSizes->mMallocSizeOf);
for (uint32_t i = 0, count = mExtraPropertyTables.Length();
i < count; ++i) {
aWindowSizes->mPropertyTablesSize +=
mExtraPropertyTables[i]->SizeOfIncludingThis(aWindowSizes->mMallocSizeOf);
}
if (EventListenerManager* elm = GetExistingListenerManager()) {
aWindowSizes->mDOMEventListenersCount += elm->ListenerCount();
}
// Measurement of the following members may be added later if DMD finds it
// is worthwhile:
// - many!
}
void
nsIDocument::DocAddSizeOfIncludingThis(nsWindowSizes* aWindowSizes) const
{
aWindowSizes->mDOMOtherSize += aWindowSizes->mMallocSizeOf(this);
DocAddSizeOfExcludingThis(aWindowSizes);
}
static size_t
SizeOfOwnedSheetArrayExcludingThis(const nsTArray<RefPtr<StyleSheet>>& aSheets,
MallocSizeOf aMallocSizeOf)
{
size_t n = 0;
n += aSheets.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (StyleSheet* sheet : aSheets) {
if (!sheet->GetOwningDocument()) {
// Avoid over-reporting shared sheets.
continue;
}
n += sheet->SizeOfIncludingThis(aMallocSizeOf);
}
return n;
}
size_t
nsDocument::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
// This SizeOfExcludingThis() overrides the one from nsINode. But
// nsDocuments can only appear at the top of the DOM tree, and we use the
// specialized DocAddSizeOfExcludingThis() in that case. So this should never
// be called.
MOZ_CRASH();
}
void
nsDocument::DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const
{
nsIDocument::DocAddSizeOfExcludingThis(aWindowSizes);
for (nsIContent* node = nsINode::GetFirstChild();
node;
node = node->GetNextNode(this))
{
size_t nodeSize = node->SizeOfIncludingThis(aWindowSizes->mMallocSizeOf);
size_t* p;
switch (node->NodeType()) {
case nsIDOMNode::ELEMENT_NODE:
p = &aWindowSizes->mDOMElementNodesSize;
break;
case nsIDOMNode::TEXT_NODE:
p = &aWindowSizes->mDOMTextNodesSize;
break;
case nsIDOMNode::CDATA_SECTION_NODE:
p = &aWindowSizes->mDOMCDATANodesSize;
break;
case nsIDOMNode::COMMENT_NODE:
p = &aWindowSizes->mDOMCommentNodesSize;
break;
default:
p = &aWindowSizes->mDOMOtherSize;
break;
}
*p += nodeSize;
if (EventListenerManager* elm = node->GetExistingListenerManager()) {
aWindowSizes->mDOMEventListenersCount += elm->ListenerCount();
}
}
aWindowSizes->mStyleSheetsSize +=
SizeOfOwnedSheetArrayExcludingThis(mStyleSheets,
aWindowSizes->mMallocSizeOf);
// Note that we do not own the sheets pointed to by mOnDemandBuiltInUASheets
// (the nsLayoutStyleSheetCache singleton does).
aWindowSizes->mStyleSheetsSize +=
mOnDemandBuiltInUASheets.ShallowSizeOfExcludingThis(
aWindowSizes->mMallocSizeOf);
for (auto& sheetArray : mAdditionalSheets) {
aWindowSizes->mStyleSheetsSize +=
SizeOfOwnedSheetArrayExcludingThis(sheetArray,
aWindowSizes->mMallocSizeOf);
}
// Lumping in the loader with the style-sheets size is not ideal,
// but most of the things in there are in fact stylesheets, so it
// doesn't seem worthwhile to separate it out.
aWindowSizes->mStyleSheetsSize +=
CSSLoader()->SizeOfIncludingThis(aWindowSizes->mMallocSizeOf);
aWindowSizes->mDOMOtherSize +=
mAttrStyleSheet ?
mAttrStyleSheet->DOMSizeOfIncludingThis(aWindowSizes->mMallocSizeOf) :
0;
aWindowSizes->mDOMOtherSize +=
mSVGAttrAnimationRuleProcessor ?
mSVGAttrAnimationRuleProcessor->DOMSizeOfIncludingThis(
aWindowSizes->mMallocSizeOf) :
0;
aWindowSizes->mDOMOtherSize +=
mStyledLinks.ShallowSizeOfExcludingThis(aWindowSizes->mMallocSizeOf);
aWindowSizes->mDOMOtherSize +=
mIdentifierMap.SizeOfExcludingThis(aWindowSizes->mMallocSizeOf);
// Measurement of the following members may be added later if DMD finds it
// is worthwhile:
// - many!
}
NS_IMETHODIMP
nsDocument::QuerySelector(const nsAString& aSelector, nsIDOMElement **aReturn)
{
return nsINode::QuerySelector(aSelector, aReturn);
}
NS_IMETHODIMP
nsDocument::QuerySelectorAll(const nsAString& aSelector, nsIDOMNodeList **aReturn)
{
return nsINode::QuerySelectorAll(aSelector, aReturn);
}
void
nsDocument::AddResizeObserver(ResizeObserver* aResizeObserver)
{
if (!mResizeObserverController) {
mResizeObserverController = MakeUnique<ResizeObserverController>(this);
}
mResizeObserverController->AddResizeObserver(aResizeObserver);
}
void
nsDocument::ScheduleResizeObserversNotification() const
{
if (mResizeObserverController) {
mResizeObserverController->ScheduleNotification();
}
}
already_AddRefed<nsIDocument>
nsIDocument::Constructor(const GlobalObject& aGlobal,
ErrorResult& rv)
{
nsCOMPtr<nsIScriptGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
if (!global) {
rv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsCOMPtr<nsIScriptObjectPrincipal> prin = do_QueryInterface(aGlobal.GetAsSupports());
if (!prin) {
rv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsCOMPtr<nsIURI> uri;
NS_NewURI(getter_AddRefs(uri), "about:blank");
if (!uri) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return nullptr;
}
nsCOMPtr<nsIDOMDocument> document;
nsresult res =
NS_NewDOMDocument(getter_AddRefs(document),
NullString(),
EmptyString(),
nullptr,
uri,
uri,
prin->GetPrincipal(),
true,
global,
DocumentFlavorPlain);
if (NS_FAILED(res)) {
rv.Throw(res);
return nullptr;
}
nsCOMPtr<nsIDocument> doc = do_QueryInterface(document);
doc->SetReadyStateInternal(nsIDocument::READYSTATE_COMPLETE);
return doc.forget();
}
XPathExpression*
nsIDocument::CreateExpression(const nsAString& aExpression,
XPathNSResolver* aResolver,
ErrorResult& rv)
{
return XPathEvaluator()->CreateExpression(aExpression, aResolver, rv);
}
nsINode*
nsIDocument::CreateNSResolver(nsINode& aNodeResolver)
{
return XPathEvaluator()->CreateNSResolver(aNodeResolver);
}
already_AddRefed<XPathResult>
nsIDocument::Evaluate(JSContext* aCx, const nsAString& aExpression,
nsINode& aContextNode, XPathNSResolver* aResolver,
uint16_t aType, JS::Handle<JSObject*> aResult,
ErrorResult& rv)
{
return XPathEvaluator()->Evaluate(aCx, aExpression, aContextNode, aResolver,
aType, aResult, rv);
}
NS_IMETHODIMP
nsDocument::Evaluate(const nsAString& aExpression, nsIDOMNode* aContextNode,
nsIDOMNode* aResolver, uint16_t aType,
nsISupports* aInResult, nsISupports** aResult)
{
return XPathEvaluator()->Evaluate(aExpression, aContextNode, aResolver, aType,
aInResult, aResult);
}
nsIDocument*
nsIDocument::GetTopLevelContentDocument()
{
nsDocument* parent;
if (!mLoadedAsData) {
parent = static_cast<nsDocument*>(this);
} else {
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(GetScopeObject());
if (!window) {
return nullptr;
}
parent = static_cast<nsDocument*>(window->GetExtantDoc());
if (!parent) {
return nullptr;
}
}
do {
if (parent->IsTopLevelContentDocument()) {
break;
}
// If we ever have a non-content parent before we hit a toplevel content
// parent, then we're never going to find one. Just bail.
if (!parent->IsContentDocument()) {
return nullptr;
}
nsIDocument* candidate = parent->GetParentDocument();
parent = static_cast<nsDocument*>(candidate);
} while (parent);
return parent;
}
void
nsIDocument::PropagateUseCounters(nsIDocument* aParentDocument)
{
MOZ_ASSERT(this != aParentDocument);
// What really matters here is that our use counters get propagated as
// high up in the content document hierarchy as possible. So,
// starting with aParentDocument, we need to find the toplevel content
// document, and propagate our use counters into its
// mChildDocumentUseCounters.
nsIDocument* contentParent = aParentDocument->GetTopLevelContentDocument();
if (!contentParent) {
return;
}
contentParent->mChildDocumentUseCounters |= mUseCounters;
contentParent->mChildDocumentUseCounters |= mChildDocumentUseCounters;
}
void
nsIDocument::SetPageUseCounter(UseCounter aUseCounter)
{
// We want to set the use counter on the "page" that owns us; the definition
// of "page" depends on what kind of document we are. See the comments below
// for details. In any event, checking all the conditions below is
// reasonably expensive, so we cache whether we've notified our owning page.
if (mNotifiedPageForUseCounter[aUseCounter]) {
return;
}
mNotifiedPageForUseCounter[aUseCounter] = true;
if (mDisplayDocument) {
// If we are a resource document, we won't have a docshell and so we won't
// record any page use counters on this document. Instead, we should
// forward it up to the document that loaded us.
MOZ_ASSERT(!mDocumentContainer);
mDisplayDocument->SetChildDocumentUseCounter(aUseCounter);
return;
}
if (IsBeingUsedAsImage()) {
// If this is an SVG image document, we also won't have a docshell.
MOZ_ASSERT(!mDocumentContainer);
return;
}
// We only care about use counters in content. If we're already a toplevel
// content document, then we should have already set the use counter on
// ourselves, and we are done.
nsIDocument* contentParent = GetTopLevelContentDocument();
if (!contentParent) {
return;
}
if (this == contentParent) {
MOZ_ASSERT(GetUseCounter(aUseCounter));
return;
}
contentParent->SetChildDocumentUseCounter(aUseCounter);
}
bool
nsIDocument::HasScriptsBlockedBySandbox()
{
return mSandboxFlags & SANDBOXED_SCRIPTS;
}
bool
nsIDocument::InlineScriptAllowedByCSP()
{
// this function assumes the inline script is parser created
// (e.g., before setting attribute(!) event handlers)
nsCOMPtr<nsIContentSecurityPolicy> csp;
nsresult rv = NodePrincipal()->GetCsp(getter_AddRefs(csp));
NS_ENSURE_SUCCESS(rv, true);
bool allowsInlineScript = true;
if (csp) {
nsresult rv = csp->GetAllowsInline(nsIContentPolicy::TYPE_SCRIPT,
EmptyString(), // aNonce
true, // aParserCreated
EmptyString(), // FIXME get script sample (bug 1314567)
0, // aLineNumber
&allowsInlineScript);
NS_ENSURE_SUCCESS(rv, true);
}
return allowsInlineScript;
}
void
nsDocument::AddIntersectionObserver(DOMIntersectionObserver* aObserver)
{
MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
"Intersection observer already in the list");
mIntersectionObservers.PutEntry(aObserver);
}
void
nsDocument::RemoveIntersectionObserver(DOMIntersectionObserver* aObserver)
{
mIntersectionObservers.RemoveEntry(aObserver);
}
void
nsDocument::UpdateIntersectionObservations()
{
if (mIntersectionObservers.IsEmpty()) {
return;
}
DOMHighResTimeStamp time = 0;
if (nsPIDOMWindowInner* window = GetInnerWindow()) {
Performance* perf = window->GetPerformance();
if (perf) {
time = perf->Now();
}
}
nsTArray<RefPtr<DOMIntersectionObserver>> observers(mIntersectionObservers.Count());
for (auto iter = mIntersectionObservers.Iter(); !iter.Done(); iter.Next()) {
DOMIntersectionObserver* observer = iter.Get()->GetKey();
observers.AppendElement(observer);
}
for (const auto& observer : observers) {
if (observer) {
observer->Update(this, time);
}
}
}
void
nsDocument::ScheduleIntersectionObserverNotification()
{
if (mIntersectionObservers.IsEmpty()) {
return;
}
nsCOMPtr<nsIRunnable> notification = NewRunnableMethod(this,
&nsDocument::NotifyIntersectionObservers);
NS_DispatchToCurrentThread(notification.forget());
}
void
nsDocument::NotifyIntersectionObservers()
{
nsTArray<RefPtr<DOMIntersectionObserver>> observers(mIntersectionObservers.Count());
for (auto iter = mIntersectionObservers.Iter(); !iter.Done(); iter.Next()) {
DOMIntersectionObserver* observer = iter.Get()->GetKey();
observers.AppendElement(observer);
}
for (const auto& observer : observers) {
if (observer) {
observer->Notify();
}
}
}
static bool
NotifyLayerManagerRecreatedCallback(nsIDocument* aDocument, void* aData)
{
aDocument->NotifyLayerManagerRecreated();
return true;
}
void
nsDocument::NotifyLayerManagerRecreated()
{
EnumerateActivityObservers(NotifyActivityChanged, nullptr);
EnumerateSubDocuments(NotifyLayerManagerRecreatedCallback, nullptr);
}
XPathEvaluator*
nsIDocument::XPathEvaluator()
{
if (!mXPathEvaluator) {
mXPathEvaluator = new dom::XPathEvaluator(this);
}
return mXPathEvaluator;
}
already_AddRefed<nsIDocumentEncoder>
nsIDocument::GetCachedEncoder()
{
return mCachedEncoder.forget();
}
void
nsIDocument::SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder)
{
mCachedEncoder = aEncoder;
}
void
nsIDocument::SetContentTypeInternal(const nsACString& aType)
{
if (!IsHTMLOrXHTML() && mDefaultElementType == kNameSpaceID_None &&
aType.EqualsLiteral("application/xhtml+xml")) {
mDefaultElementType = kNameSpaceID_XHTML;
}
mCachedEncoder = nullptr;
mContentType = aType;
}
nsILoadContext*
nsIDocument::GetLoadContext() const
{
return mDocumentContainer;
}
nsIDocShell*
nsIDocument::GetDocShell() const
{
return mDocumentContainer;
}
void
nsIDocument::SetStateObject(nsIStructuredCloneContainer *scContainer)
{
mStateObjectContainer = scContainer;
mStateObjectCached = nullptr;
}
already_AddRefed<Element>
nsIDocument::CreateHTMLElement(nsIAtom* aTag)
{
RefPtr<mozilla::dom::NodeInfo> nodeInfo;
nodeInfo = mNodeInfoManager->GetNodeInfo(aTag, nullptr, kNameSpaceID_XHTML,
nsIDOMNode::ELEMENT_NODE);
MOZ_ASSERT(nodeInfo, "GetNodeInfo should never fail");
nsCOMPtr<Element> element;
DebugOnly<nsresult> rv = NS_NewHTMLElement(getter_AddRefs(element),
nodeInfo.forget(),
mozilla::dom::NOT_FROM_PARSER);
MOZ_ASSERT(NS_SUCCEEDED(rv), "NS_NewHTMLElement should never fail");
return element.forget();
}
/* static */
nsresult
nsIDocument::GenerateDocumentId(nsAString& aId)
{
nsID id;
nsresult rv = nsContentUtils::GenerateUUIDInPlace(id);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// Build a string in {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} format
char buffer[NSID_LENGTH];
id.ToProvidedString(buffer);
NS_ConvertASCIItoUTF16 uuid(buffer);
// Remove {} and the null terminator
aId.Assign(Substring(uuid, 1, NSID_LENGTH - 3));
return NS_OK;
}
nsresult
nsIDocument::GetOrCreateId(nsAString& aId)
{
if (mId.IsEmpty()) {
nsresult rv = GenerateDocumentId(mId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
aId = mId;
return NS_OK;
}
void
nsIDocument::SetId(const nsAString& aId)
{
// The ID should only be set one time, but we may get the same value
// more than once if the document is controlled coming out of bfcache.
MOZ_ASSERT_IF(mId != aId, mId.IsEmpty());
mId = aId;
}
bool
MarkDocumentTreeToBeInSyncOperation(nsIDocument* aDoc, void* aData)
{
nsCOMArray<nsIDocument>* documents =
static_cast<nsCOMArray<nsIDocument>*>(aData);
if (aDoc) {
aDoc->SetIsInSyncOperation(true);
documents->AppendObject(aDoc);
aDoc->EnumerateSubDocuments(MarkDocumentTreeToBeInSyncOperation, aData);
}
return true;
}
nsAutoSyncOperation::nsAutoSyncOperation(nsIDocument* aDoc)
{
mMicroTaskLevel = nsContentUtils::MicroTaskLevel();
nsContentUtils::SetMicroTaskLevel(0);
if (aDoc) {
if (nsPIDOMWindowOuter* win = aDoc->GetWindow()) {
if (nsCOMPtr<nsPIDOMWindowOuter> top = win->GetTop()) {
nsCOMPtr<nsIDocument> doc = top->GetExtantDoc();
MarkDocumentTreeToBeInSyncOperation(doc, &mDocuments);
}
}
}
}
nsAutoSyncOperation::~nsAutoSyncOperation()
{
for (int32_t i = 0; i < mDocuments.Count(); ++i) {
mDocuments[i]->SetIsInSyncOperation(false);
}
nsContentUtils::SetMicroTaskLevel(mMicroTaskLevel);
}
gfxUserFontSet*
nsIDocument::GetUserFontSet(bool aFlushUserFontSet)
{
// We want to initialize the user font set lazily the first time the
// user asks for it, rather than building it too early and forcing
// rule cascade creation. Thus we try to enforce the invariant that
// we *never* build the user font set until the first call to
// GetUserFontSet. However, once it's been requested, we can't wait
// for somebody to call GetUserFontSet in order to rebuild it (see
// comments below in RebuildUserFontSet for why).
#ifdef DEBUG
bool userFontSetGottenBefore = mGetUserFontSetCalled;
#endif
// Set mGetUserFontSetCalled up front, so that FlushUserFontSet will actually
// flush.
mGetUserFontSetCalled = true;
if (mFontFaceSetDirty && aFlushUserFontSet) {
// If this assertion fails, and there have actually been changes to
// @font-face rules, then we will call StyleChangeReflow in
// FlushUserFontSet. If we're in the middle of reflow,
// that's a bad thing to do, and the caller was responsible for
// flushing first. If we're not (e.g., in frame construction), it's
// ok.
NS_ASSERTION(!userFontSetGottenBefore ||
!GetShell() ||
!GetShell()->IsReflowLocked(),
"FlushUserFontSet should have been called first");
FlushUserFontSet();
}
if (!mFontFaceSet) {
return nullptr;
}
return mFontFaceSet->GetUserFontSet();
}
void
nsIDocument::FlushUserFontSet()
{
if (!mGetUserFontSetCalled) {
return; // No one cares about this font set yet, but we want to be careful
// to not unset our mFontFaceSetDirty bit, so when someone really
// does we'll create it.
}
if (mFontFaceSetDirty) {
if (gfxPlatform::GetPlatform()->DownloadableFontsEnabled()) {
nsTArray<nsFontFaceRuleContainer> rules;
nsIPresShell* shell = GetShell();
if (shell) {
// XXXheycam ServoStyleSets don't support exposing @font-face rules yet.
if (shell->StyleSet()->IsGecko()) {
if (!shell->StyleSet()->AsGecko()->AppendFontFaceRules(rules)) {
return;
}
} else {
NS_WARNING("stylo: ServoStyleSets cannot handle @font-face rules yet. "
"See bug 1290237.");
}
}
bool changed = false;
if (!mFontFaceSet && !rules.IsEmpty()) {
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(GetScopeObject());
mFontFaceSet = new FontFaceSet(window, this);
}
if (mFontFaceSet) {
changed = mFontFaceSet->UpdateRules(rules);
}
// We need to enqueue a style change reflow (for later) to
// reflect that we're modifying @font-face rules. (However,
// without a reflow, nothing will happen to start any downloads
// that are needed.)
if (changed && shell) {
nsPresContext* presContext = shell->GetPresContext();
if (presContext) {
presContext->UserFontSetUpdated();
}
}
}
mFontFaceSetDirty = false;
}
}
void
nsIDocument::RebuildUserFontSet()
{
if (!mGetUserFontSetCalled) {
// We want to lazily build the user font set the first time it's
// requested (so we don't force creation of rule cascades too
// early), so don't do anything now.
return;
}
mFontFaceSetDirty = true;
SetNeedStyleFlush();
// Somebody has already asked for the user font set, so we need to
// post an event to rebuild it. Setting the user font set to be dirty
// and lazily rebuilding it isn't sufficient, since it is only the act
// of rebuilding it that will trigger the style change reflow that
// calls GetUserFontSet. (This reflow causes rebuilding of text runs,
// which starts font loads, whose completion causes another style
// change reflow).
if (!mPostedFlushUserFontSet) {
nsCOMPtr<nsIRunnable> ev =
NewRunnableMethod(this, &nsIDocument::HandleRebuildUserFontSet);
if (NS_SUCCEEDED(NS_DispatchToCurrentThread(ev))) {
mPostedFlushUserFontSet = true;
}
}
}
FontFaceSet*
nsIDocument::Fonts()
{
if (!mFontFaceSet) {
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(GetScopeObject());
mFontFaceSet = new FontFaceSet(window, this);
GetUserFontSet(); // this will cause the user font set to be created/updated
}
return mFontFaceSet;
}
void
nsIDocument::ReportHasScrollLinkedEffect()
{
if (mHasScrollLinkedEffect) {
// We already did this once for this document, don't do it again.
return;
}
mHasScrollLinkedEffect = true;
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("Async Pan/Zoom"),
this, nsContentUtils::eLAYOUT_PROPERTIES,
"ScrollLinkedEffectFound2");
}
void
nsIDocument::UpdateStyleBackendType()
{
MOZ_ASSERT(mStyleBackendType == StyleBackendType(0),
"no need to call UpdateStyleBackendType now");
// Assume Gecko by default.
mStyleBackendType = StyleBackendType::Gecko;
#ifdef MOZ_STYLO
// XXX For now we use a Servo-backed style set only for (X)HTML documents
// in content docshells. This should let us avoid implementing XUL-specific
// CSS features. And apart from not supporting SVG properties in Servo
// yet, the root SVG element likes to create a style sheet for an SVG
// document before we have a pres shell (i.e. before we make the decision
// here about whether to use a Gecko- or Servo-backed style system), so
// we avoid Servo-backed style sets for SVG documents.
if (!mDocumentContainer) {
NS_WARNING("stylo: No docshell yet, assuming Gecko style system");
} else if (nsLayoutUtils::SupportsServoStyleBackend(this)) {
mStyleBackendType = StyleBackendType::Servo;
}
#endif
}
const nsString*
nsDocument::CheckCustomElementName(const ElementCreationOptions& aOptions,
const nsAString& aLocalName,
uint32_t aNamespaceID,
ErrorResult& rv)
{
// only check aOptions if 'is' is passed and the webcomponents preference
// is enabled
if (!aOptions.mIs.WasPassed() ||
!CustomElementRegistry::IsCustomElementEnabled()) {
return nullptr;
}
const nsString* is = &aOptions.mIs.Value();
// Throw NotFoundError if 'is' is not-null and definition is null
if (!nsContentUtils::LookupCustomElementDefinition(this, aLocalName,
aNamespaceID, is)) {
rv.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
}
return is;
}
Selection*
nsIDocument::GetSelection(ErrorResult& aRv)
{
nsCOMPtr<nsPIDOMWindowInner> window = GetInnerWindow();
if (!window) {
return nullptr;
}
NS_ASSERTION(window->IsInnerWindow(), "Should have inner window here!");
if (!window->IsCurrentInnerWindow()) {
return nullptr;
}
return nsGlobalWindow::Cast(window)->GetSelection(aRv);
}
bool
nsIDocument::ModuleScriptsEnabled()
{
static bool sEnabledForContent = false;
static bool sCachedPref = false;
if (!sCachedPref) {
sCachedPref = true;
Preferences::AddBoolVarCache(&sEnabledForContent, "dom.moduleScripts.enabled", false);
}
return nsContentUtils::IsChromeDoc(this) || sEnabledForContent;
}
|