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
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (C) 2008, 2009 Google Inc. All rights reserved.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Document.h"
#include "AXObjectCache.h"
#include "AnimationController.h"
#include "AsyncScriptRunner.h"
#include "Attr.h"
#include "Attribute.h"
#include "CDATASection.h"
#include "CSSStyleSelector.h"
#include "CSSStyleSheet.h"
#include "CSSValueKeywords.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResourceLoader.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "Comment.h"
#include "Console.h"
#include "CookieJar.h"
#include "CustomEvent.h"
#include "DateComponents.h"
#include "DOMImplementation.h"
#include "DOMWindow.h"
#include "DeviceMotionEvent.h"
#include "DeviceOrientationEvent.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DocumentMarkerController.h"
#include "DocumentType.h"
#include "EditingText.h"
#include "Editor.h"
#include "Element.h"
#include "EntityReference.h"
#include "Event.h"
#include "EventHandler.h"
#include "EventListener.h"
#include "EventNames.h"
#include "EventQueue.h"
#include "ExceptionCode.h"
#include "FocusController.h"
#include "FormAssociatedElement.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HashChangeEvent.h"
#include "HTMLAllCollection.h"
#include "HTMLAnchorElement.h"
#include "HTMLBodyElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLCollection.h"
#include "HTMLDocument.h"
#include "HTMLElementFactory.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHeadElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLInputElement.h"
#include "HTMLLinkElement.h"
#include "HTMLMapElement.h"
#include "HTMLNameCollection.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HTMLStyleElement.h"
#include "HTMLTitleElement.h"
#include "HTTPParsers.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "ImageLoader.h"
#include "InspectorInstrumentation.h"
#include "KeyboardEvent.h"
#include "Logging.h"
#include "MediaQueryList.h"
#include "MediaQueryMatcher.h"
#include "MessageEvent.h"
#include "MouseEvent.h"
#include "MouseEventWithHitTestResults.h"
#include "MutationEvent.h"
#include "NameNodeList.h"
#include "NestingLevelIncrementer.h"
#include "NodeFilter.h"
#include "NodeIterator.h"
#include "NodeWithIndex.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "PageGroup.h"
#include "PageTransitionEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PopStateEvent.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "RegisteredEventListener.h"
#include "RenderArena.h"
#include "RenderLayer.h"
#include "RenderTextControl.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ScriptCallStack.h"
#include "ScriptController.h"
#include "ScriptElement.h"
#include "ScriptEventListener.h"
#include "SecurityOrigin.h"
#include "SegmentedString.h"
#include "SelectionController.h"
#include "Settings.h"
#include "StaticHashSetNodeList.h"
#include "StyleSheetList.h"
#include "TextEvent.h"
#include "TextResourceDecoder.h"
#include "Timer.h"
#include "TransformSource.h"
#include "TreeWalker.h"
#include "UIEvent.h"
#include "UserContentURLPattern.h"
#include "WebKitAnimationEvent.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLDocumentParser.h"
#include "XMLHttpRequest.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "htmlediting.h"
#include <wtf/CurrentTime.h>
#include <wtf/HashFunctions.h>
#include <wtf/MainThread.h>
#include <wtf/PassRefPtr.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuffer.h>
#if ENABLE(SHARED_WORKERS)
#include "SharedWorkerRepository.h"
#endif
#if ENABLE(DOM_STORAGE)
#include "StorageEvent.h"
#endif
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#endif
#if ENABLE(XSLT)
#include "XSLTProcessor.h"
#endif
#if ENABLE(SVG)
#include "SVGDocumentExtensions.h"
#include "SVGElementFactory.h"
#include "SVGNames.h"
#include "SVGStyleElement.h"
#include "SVGZoomEvent.h"
#endif
#ifdef ANDROID_META_SUPPORT
#include "PlatformBridge.h"
#include "Settings.h"
#endif
#ifdef ANDROID_RESET_SELECTION
#include "CacheBuilder.h"
#include "HTMLTextAreaElement.h"
#endif
#ifdef ANDROID_INSTRUMENT
#include "TimeCounter.h"
#endif
#if ENABLE(TOUCH_EVENTS)
#if USE(V8)
#include "RuntimeEnabledFeatures.h"
#endif
#include "TouchEvent.h"
#endif
#if ENABLE(WML)
#include "WMLDocument.h"
#include "WMLElement.h"
#include "WMLElementFactory.h"
#include "WMLNames.h"
#endif
#if ENABLE(MATHML)
#include "MathMLElement.h"
#include "MathMLElementFactory.h"
#include "MathMLNames.h"
#endif
#if ENABLE(XHTMLMP)
#include "HTMLNoScriptElement.h"
#endif
#if ENABLE(FULLSCREEN_API)
#include "RenderFullScreen.h"
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
#include "RequestAnimationFrameCallback.h"
#endif
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
// #define INSTRUMENT_LAYOUT_SCHEDULING 1
static const unsigned cMaxWriteRecursionDepth = 21;
// This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
// FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
// for dual G5s. :)
static const int cLayoutScheduleThreshold = 250;
// DOM Level 2 says (letters added):
//
// a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
// b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
// c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
// d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
// e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
// f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
// g) Character #x00B7 is classified as an extender, because the property list so identifies it.
// h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
// i) Characters ':' and '_' are allowed as name-start characters.
// j) Characters '-' and '.' are allowed as name characters.
//
// It also contains complete tables. If we decide it's better, we could include those instead of the following code.
static inline bool isValidNameStart(UChar32 c)
{
// rule (e) above
if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
return true;
// rule (i) above
if (c == ':' || c == '_')
return true;
// rules (a) and (f) above
const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
if (!(Unicode::category(c) & nameStartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static inline bool isValidNamePart(UChar32 c)
{
// rules (a), (e), and (i) above
if (isValidNameStart(c))
return true;
// rules (g) and (h) above
if (c == 0x00B7 || c == 0x0387)
return true;
// rule (j) above
if (c == '-' || c == '.')
return true;
// rules (b) and (f) above
const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
if (!(Unicode::category(c) & otherNamePartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static Widget* widgetForNode(Node* focusedNode)
{
if (!focusedNode)
return 0;
RenderObject* renderer = focusedNode->renderer();
if (!renderer || !renderer->isWidget())
return 0;
return toRenderWidget(renderer)->widget();
}
static bool acceptsEditingFocus(Node* node)
{
ASSERT(node);
ASSERT(node->isContentEditable());
Node* root = node->rootEditableElement();
Frame* frame = node->document()->frame();
if (!frame || !root)
return false;
return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
}
static bool disableRangeMutation(Page* page)
{
#if PLATFORM(MAC)
// Disable Range mutation on document modifications in Tiger and Leopard Mail
// See <rdar://problem/5865171>
return page && (page->settings()->needsLeopardMailQuirks() || page->settings()->needsTigerMailQuirks());
#else
return false;
#endif
}
static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
class DocumentWeakReference : public ThreadSafeShared<DocumentWeakReference> {
public:
static PassRefPtr<DocumentWeakReference> create(Document* document)
{
return adoptRef(new DocumentWeakReference(document));
}
Document* document()
{
ASSERT(isMainThread());
return m_document;
}
void clear()
{
ASSERT(isMainThread());
m_document = 0;
}
private:
DocumentWeakReference(Document* document)
: m_document(document)
{
ASSERT(isMainThread());
}
Document* m_document;
};
Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
: ContainerNode(0)
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_domTreeVersion(0)
#ifdef ANDROID_STYLE_VERSION
, m_styleVersion(0)
#endif
, m_styleSheets(StyleSheetList::create(this))
, m_readyState(Complete)
, m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
, m_pendingStyleRecalcShouldForce(false)
, m_frameElementsShouldIgnoreScrolling(false)
, m_containsValidityStyleRules(false)
, m_updateFocusAppearanceRestoresSelection(false)
, m_ignoreDestructiveWriteCount(0)
, m_title("")
, m_rawTitle("")
, m_titleSetExplicitly(false)
, m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
, m_startTime(currentTime())
, m_overMinimumLayoutThreshold(false)
, m_extraLayoutDelay(0)
, m_asyncScriptRunner(AsyncScriptRunner::create(this))
, m_xmlVersion("1.0")
, m_xmlStandalone(false)
, m_savedRenderer(0)
, m_designMode(inherit)
, m_selfOnlyRefCount(0)
#if ENABLE(SVG)
, m_svgExtensions(0)
#endif
#if ENABLE(DASHBOARD_SUPPORT)
, m_hasDashboardRegions(false)
, m_dashboardRegionsDirty(false)
#endif
, m_accessKeyMapValid(false)
, m_createRenderers(true)
, m_inPageCache(false)
, m_useSecureKeyboardEntryWhenActive(false)
, m_isXHTML(isXHTML)
, m_isHTML(isHTML)
, m_numNodeListCaches(0)
#if USE(JSC)
, m_normalWorldWrapperCache(0)
#endif
, m_usingGeolocation(false)
, m_eventQueue(EventQueue::create(this))
#if ENABLE(WML)
, m_containsWMLContent(false)
#endif
, m_weakReference(DocumentWeakReference::create(this))
, m_idAttributeName(idAttr)
#if ENABLE(FULLSCREEN_API)
, m_isFullScreen(0)
, m_areKeysEnabledInFullScreen(0)
, m_fullScreenRenderer(0)
, m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
#endif
, m_loadEventDelayCount(0)
, m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
, m_directionSetOnDocumentElement(false)
, m_writingModeSetOnDocumentElement(false)
, m_writeRecursionIsTooDeep(false)
, m_writeRecursionDepth(0)
#if ENABLE(REQUEST_ANIMATION_FRAME)
, m_nextRequestAnimationFrameCallbackId(0)
#endif
{
m_document = this;
m_pageGroupUserSheetCacheValid = false;
m_printing = false;
m_paginatedForScreen = false;
m_ignoreAutofocus = false;
m_frame = frame;
m_documentLoader = frame ? frame->loader()->activeDocumentLoader() : 0;
// We depend on the url getting immediately set in subframes, but we
// also depend on the url NOT getting immediately set in opened windows.
// See fast/dom/early-frame-url.html
// and fast/dom/location-new-window-no-crash.html, respectively.
// FIXME: Can/should we unify this behavior?
if ((frame && frame->ownerElement()) || !url.isEmpty())
setURL(url);
#if !PLATFORM(ANDROID)
m_axObjectCache = 0;
#endif
m_markers = new DocumentMarkerController();
m_cachedResourceLoader = new CachedResourceLoader(this);
m_visuallyOrdered = false;
m_bParsing = false;
m_wellFormed = false;
m_textColor = Color::black;
m_listenerTypes = 0;
setInDocument();
m_inStyleRecalc = false;
m_closeAfterStyleRecalc = false;
m_usesDescendantRules = false;
m_usesSiblingRules = false;
m_usesFirstLineRules = false;
m_usesFirstLetterRules = false;
m_usesBeforeAfterRules = false;
m_usesRemUnits = false;
m_usesLinkRules = false;
m_gotoAnchorNeededAfterStylesheetsLoad = false;
m_didCalculateStyleSelector = false;
m_pendingStylesheets = 0;
m_ignorePendingStylesheets = false;
m_hasNodesWithPlaceholderStyle = false;
m_pendingSheetLayout = NoLayoutWithPendingSheets;
m_cssTarget = 0;
resetLinkColor();
resetVisitedLinkColor();
resetActiveLinkColor();
m_processingLoadEvent = false;
initSecurityContext();
initDNSPrefetch();
static int docID = 0;
m_docID = docID++;
#if ENABLE(XHTMLMP)
m_shouldProcessNoScriptElement = !(m_frame && m_frame->script()->canExecuteScripts(NotAboutToExecuteScript));
#endif
}
void Document::removedLastRef()
{
ASSERT(!m_deletionHasBegun);
if (m_selfOnlyRefCount) {
// If removing a child removes the last self-only ref, we don't
// want the document to be destructed until after
// removeAllChildren returns, so we guard ourselves with an
// extra self-only ref.
selfOnlyRef();
// We must make sure not to be retaining any of our children through
// these extra pointers or we will create a reference cycle.
m_docType = 0;
m_focusedNode = 0;
m_hoverNode = 0;
m_activeNode = 0;
m_titleElement = 0;
m_documentElement = 0;
#if ENABLE(FULLSCREEN_API)
m_fullScreenElement = 0;
#endif
// removeAllChildren() doesn't always unregister IDs, do it upfront to avoid having stale references in the map.
m_elementsById.clear();
removeAllChildren();
m_markers->detach();
detachParser();
m_cssCanvasElements.clear();
#ifndef NDEBUG
m_inRemovedLastRefFunction = false;
#endif
selfOnlyDeref();
} else {
#ifndef NDEBUG
m_deletionHasBegun = true;
#endif
delete this;
}
}
Document::~Document()
{
ASSERT(!renderer());
ASSERT(!m_inPageCache);
ASSERT(!m_savedRenderer);
ASSERT(m_ranges.isEmpty());
ASSERT(!m_styleRecalcTimer.isActive());
m_asyncScriptRunner.clear();
removeAllEventListeners();
#if USE(JSC)
destroyAllWrapperCaches();
#endif
// Currently we believe that Document can never outlive the parser.
// Although the Document may be replaced synchronously, DocumentParsers
// generally keep at least one reference to an Element which would in turn
// has a reference to the Document. If you hit this ASSERT, then that
// assumption is wrong. DocumentParser::detach() should ensure that even
// if the DocumentParser outlives the Document it won't cause badness.
ASSERT(!m_parser || m_parser->refCount() == 1);
detachParser();
m_document = 0;
m_cachedResourceLoader.clear();
m_renderArena.clear();
clearAXObjectCache();
m_decoder = 0;
for (size_t i = 0; i < m_nameCollectionInfo.size(); ++i)
deleteAllValues(m_nameCollectionInfo[i]);
if (m_styleSheets)
m_styleSheets->documentDestroyed();
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
if (m_mappedElementSheet)
m_mappedElementSheet->clearOwnerNode();
if (m_pageUserSheet)
m_pageUserSheet->clearOwnerNode();
if (m_pageGroupUserSheets) {
for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
(*m_pageGroupUserSheets)[i]->clearOwnerNode();
}
m_weakReference->clear();
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
}
MediaQueryMatcher* Document::mediaQueryMatcher()
{
if (!m_mediaQueryMatcher)
m_mediaQueryMatcher = MediaQueryMatcher::create(this);
return m_mediaQueryMatcher.get();
}
#if USE(JSC)
Document::JSWrapperCache* Document::createWrapperCache(DOMWrapperWorld* world)
{
JSWrapperCache* wrapperCache = new JSWrapperCache;
m_wrapperCacheMap.set(world, wrapperCache);
if (world->isNormal()) {
ASSERT(!m_normalWorldWrapperCache);
m_normalWorldWrapperCache = wrapperCache;
}
world->didCreateWrapperCache(this);
return wrapperCache;
}
void Document::destroyWrapperCache(DOMWrapperWorld* world)
{
Document::JSWrapperCache* wrappers = wrapperCacheMap().take(world);
ASSERT(wrappers);
delete wrappers;
world->didDestroyWrapperCache(this);
}
void Document::destroyAllWrapperCaches()
{
JSWrapperCacheMap& wrapperCacheMap = this->wrapperCacheMap();
while (!wrapperCacheMap.isEmpty())
destroyWrapperCache(wrapperCacheMap.begin()->first);
}
#endif
void Document::setCompatibilityMode(CompatibilityMode mode)
{
if (m_compatibilityModeLocked || mode == m_compatibilityMode)
return;
ASSERT(!documentElement() && !m_styleSheets->length());
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
if (inQuirksMode() != wasInQuirksMode) {
// All user stylesheets have to reparse using the different mode.
clearPageUserSheet();
clearPageGroupUserSheets();
}
}
String Document::compatMode() const
{
return inQuirksMode() ? "BackCompat" : "CSS1Compat";
}
void Document::resetLinkColor()
{
m_linkColor = Color(0, 0, 238);
}
void Document::resetVisitedLinkColor()
{
m_visitedLinkColor = Color(85, 26, 139);
}
void Document::resetActiveLinkColor()
{
m_activeLinkColor.setNamedColor("red");
}
void Document::setDocType(PassRefPtr<DocumentType> docType)
{
// This should never be called more than once.
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType)
m_docType->setDocument(this);
#ifdef ANDROID_META_SUPPORT
if (m_docType && !ownerElement()
&& m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", false)) {
// fit mobile sites directly in the screen
if (Frame *f = frame())
f->settings()->setMetadataSettings("width", "device-width");
if (FrameView* frameView = view())
PlatformBridge::updateViewport(frameView);
}
#endif
}
DOMImplementation* Document::implementation() const
{
if (!m_implementation)
m_implementation = DOMImplementation::create();
return m_implementation.get();
}
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
// Invalidate the document element we have cached in case it was replaced.
m_documentElement = 0;
}
void Document::cacheDocumentElement() const
{
ASSERT(!m_documentElement);
m_documentElement = firstElementChild(this);
}
PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (m_isXHTML)
return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
return createElement(QualifiedName(nullAtom, name, nullAtom), false);
}
PassRefPtr<DocumentFragment> Document::createDocumentFragment()
{
return DocumentFragment::create(document());
}
PassRefPtr<Text> Document::createTextNode(const String& data)
{
return Text::create(this, data);
}
PassRefPtr<Comment> Document::createComment(const String& data)
{
return Comment::create(this, data);
}
PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
{
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return CDATASection::create(this, data);
}
PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
{
if (!isValidName(target)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return ProcessingInstruction::create(this, target, data);
}
PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return EntityReference::create(this, name);
}
PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
{
return EditingText::create(this, text);
}
PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
{
return CSSMutableStyleDeclaration::create();
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
{
ec = 0;
if (!importedNode
#if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
|| (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
#endif
) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
switch (importedNode->nodeType()) {
case TEXT_NODE:
return createTextNode(importedNode->nodeValue());
case CDATA_SECTION_NODE:
return createCDATASection(importedNode->nodeValue(), ec);
case ENTITY_REFERENCE_NODE:
return createEntityReference(importedNode->nodeName(), ec);
case PROCESSING_INSTRUCTION_NODE:
return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
case COMMENT_NODE:
return createComment(importedNode->nodeValue());
case ELEMENT_NODE: {
Element* oldElement = static_cast<Element*>(importedNode);
RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
if (ec)
return 0;
NamedNodeMap* attrs = oldElement->attributes(true);
if (attrs) {
unsigned length = attrs->length();
for (unsigned i = 0; i < length; i++) {
Attribute* attr = attrs->attributeItem(i);
newElement->setAttribute(attr->name(), attr->value().impl(), ec);
if (ec)
return 0;
}
}
newElement->copyNonAttributeProperties(oldElement);
if (deep) {
for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newElement->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newElement.release();
}
case ATTRIBUTE_NODE:
return Attr::create(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
case DOCUMENT_FRAGMENT_NODE: {
DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep) {
for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newFragment->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newFragment.release();
}
case ENTITY_NODE:
case NOTATION_NODE:
// FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
// Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
break;
}
ec = NOT_SUPPORTED_ERR;
return 0;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
{
if (!source) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
if (source->isReadOnlyNode()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return 0;
}
switch (source->nodeType()) {
case ENTITY_NODE:
case NOTATION_NODE:
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
ec = NOT_SUPPORTED_ERR;
return 0;
case ATTRIBUTE_NODE: {
Attr* attr = static_cast<Attr*>(source.get());
if (attr->ownerElement())
attr->ownerElement()->removeAttributeNode(attr, ec);
attr->setSpecified(true);
break;
}
default:
if (source->hasTagName(iframeTag)) {
HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
iframe->setRemainsAliveOnRemovalFromTree(attached() && source->attached());
}
if (source->parentNode())
source->parentNode()->removeChild(source.get(), ec);
}
source->setDocumentRecursively(this);
return source;
}
bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
{
// These checks are from DOM Core Level 2, createElementNS
// http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
return true;
if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
return true;
// Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
// http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
// createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
return true;
return false;
}
// FIXME: This should really be in a possible ElementFactory class
PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
{
RefPtr<Element> e;
// FIXME: Use registered namespaces and look up in a hash to find the right factory.
if (qName.namespaceURI() == xhtmlNamespaceURI)
e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
#if ENABLE(SVG)
else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
#endif
#if ENABLE(WML)
else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI)
e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
else if (isWMLDocument())
e = WMLElementFactory::createWMLElement(QualifiedName(nullAtom, qName.localName(), WMLNames::wmlNamespaceURI), this, createdByParser);
#endif
#if ENABLE(MATHML)
else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
#endif
if (!e)
e = Element::create(qName, document());
// <image> uses imgTag so we need a special rule.
#if ENABLE(WML)
if (!isWMLDocument())
#endif
ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
return e.release();
}
PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (hasPrefixNamespaceMismatch(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
return createElement(qName, false);
}
Element* Document::getElementById(const AtomicString& elementId) const
{
if (elementId.isEmpty())
return 0;
return m_elementsById.getElementById(elementId.impl(), this);
}
String Document::readyState() const
{
DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
switch (m_readyState) {
case Loading:
return loading;
case Interactive:
return interactive;
case Complete:
return complete;
}
ASSERT_NOT_REACHED();
return String();
}
void Document::setReadyState(ReadyState readyState)
{
if (readyState == m_readyState)
return;
switch (readyState) {
case Loading:
if (!m_documentTiming.domLoading)
m_documentTiming.domLoading = currentTime();
break;
case Interactive:
if (!m_documentTiming.domInteractive)
m_documentTiming.domInteractive = currentTime();
break;
case Complete:
if (!m_documentTiming.domComplete)
m_documentTiming.domComplete = currentTime();
break;
}
m_readyState = readyState;
dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
}
String Document::encoding() const
{
if (TextResourceDecoder* d = decoder())
return d->encoding().domName();
return String();
}
String Document::defaultCharset() const
{
if (Settings* settings = this->settings())
return settings->defaultTextEncodingName();
return String();
}
void Document::setCharset(const String& charset)
{
if (!decoder())
return;
decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
}
void Document::setXMLVersion(const String& version, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlVersion = version;
}
void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlStandalone = standalone;
}
void Document::setDocumentURI(const String& uri)
{
m_documentURI = uri;
updateBaseURL();
}
KURL Document::baseURI() const
{
return m_baseURL;
}
void Document::setContent(const String& content)
{
removeAllChildren();
open();
m_parser->append(content);
m_parser->finish();
explicitClose();
}
// FIXME: We need to discuss the DOM API here at some point. Ideas:
// * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
// * making it receive the expading size of each direction separately,
// i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping) const
{
// FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
if (!renderer())
return 0;
Frame* frame = this->frame();
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
// When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
if (ignoreClipping)
type |= HitTestRequest::IgnoreClipping;
else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
return 0;
HitTestRequest request(type);
// Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
// we special handle this case in order to return a valid NodeList.
if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
HitTestResult result(point);
return handleZeroPadding(request, result);
}
HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
renderView()->layer()->hitTest(request, result);
return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
}
PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
{
renderView()->layer()->hitTest(request, result);
Node* node = result.innerNode();
if (!node)
return 0;
node = node->shadowAncestorNode();
ListHashSet<RefPtr<Node> > list;
list.add(node);
return StaticHashSetNodeList::adopt(list);
}
Element* Document::elementFromPoint(int x, int y) const
{
// FIXME: Share code between this and caretRangeFromPoint.
if (!renderer())
return 0;
Frame* frame = this->frame();
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + view()->scrollX(), y * zoomFactor + view()->scrollY()));
if (!frameView->visibleContentRect().contains(point))
return 0;
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
HitTestResult result(point);
renderView()->layer()->hitTest(request, result);
Node* n = result.innerNode();
while (n && !n->isElementNode())
n = n->parentNode();
if (n)
n = n->shadowAncestorNode();
return static_cast<Element*>(n);
}
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
// FIXME: Share code between this and elementFromPoint.
if (!renderer())
return 0;
Frame* frame = this->frame();
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + view()->scrollX(), y * zoomFactor + view()->scrollY()));
if (!frameView->visibleContentRect().contains(point))
return 0;
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
HitTestResult result(point);
renderView()->layer()->hitTest(request, result);
Node* node = result.innerNode();
if (!node)
return 0;
Node* shadowAncestorNode = node->shadowAncestorNode();
if (shadowAncestorNode != node) {
unsigned offset = shadowAncestorNode->nodeIndex();
ContainerNode* container = shadowAncestorNode->parentNode();
return Range::create(this, container, offset, container, offset);
}
RenderObject* renderer = node->renderer();
if (!renderer)
return 0;
VisiblePosition visiblePosition = renderer->positionForPoint(result.localPoint());
if (visiblePosition.isNull())
return 0;
Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
}
void Document::addElementById(const AtomicString& elementId, Element* element)
{
m_elementsById.add(elementId.impl(), element);
}
void Document::removeElementById(const AtomicString& elementId, Element* element)
{
m_elementsById.remove(elementId.impl(), element);
}
Element* Document::getElementByAccessKey(const String& key) const
{
if (key.isEmpty())
return 0;
if (!m_accessKeyMapValid) {
for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
if (!n->isElementNode())
continue;
Element* element = static_cast<Element*>(n);
const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
if (!accessKey.isEmpty())
m_elementsByAccessKey.set(accessKey.impl(), element);
}
m_accessKeyMapValid = true;
}
return m_elementsByAccessKey.get(key.impl());
}
/*
* Performs three operations:
* 1. Convert control characters to spaces
* 2. Trim leading and trailing spaces
* 3. Collapse internal whitespace.
*/
static inline String canonicalizedTitle(Document* document, const String& title)
{
const UChar* characters = title.characters();
unsigned length = title.length();
unsigned i;
StringBuffer buffer(length);
unsigned builderIndex = 0;
// Skip leading spaces and leading characters that would convert to spaces
for (i = 0; i < length; ++i) {
UChar c = characters[i];
if (!(c <= 0x20 || c == 0x7F))
break;
}
if (i == length)
return "";
// Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
bool previousCharWasWS = false;
for (; i < length; ++i) {
UChar c = characters[i];
if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
if (previousCharWasWS)
continue;
buffer[builderIndex++] = ' ';
previousCharWasWS = true;
} else {
buffer[builderIndex++] = c;
previousCharWasWS = false;
}
}
// Strip trailing spaces
while (builderIndex > 0) {
--builderIndex;
if (buffer[builderIndex] != ' ')
break;
}
if (!builderIndex && buffer[builderIndex] == ' ')
return "";
buffer.shrink(builderIndex + 1);
// Replace the backslashes with currency symbols if the encoding requires it.
document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
return String::adopt(buffer);
}
void Document::updateTitle()
{
m_title = canonicalizedTitle(this, m_rawTitle);
if (Frame* f = frame())
f->loader()->setTitle(m_title);
}
void Document::setTitle(const String& title, Element* titleElement)
{
if (!titleElement) {
// Title set by JavaScript -- overrides any title elements.
m_titleSetExplicitly = true;
if (!isHTMLDocument())
m_titleElement = 0;
else if (!m_titleElement) {
if (HTMLElement* headElement = head()) {
m_titleElement = createElement(titleTag, false);
ExceptionCode ec = 0;
headElement->appendChild(m_titleElement, ec);
ASSERT(!ec);
}
}
} else if (titleElement != m_titleElement) {
if (m_titleElement || m_titleSetExplicitly)
// Only allow the first title element to change the title -- others have no effect.
return;
m_titleElement = titleElement;
}
if (m_rawTitle == title)
return;
m_rawTitle = title;
updateTitle();
if (m_titleSetExplicitly && m_titleElement && m_titleElement->hasTagName(titleTag) && !titleElement)
static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(m_title);
}
void Document::removeTitle(Element* titleElement)
{
if (m_titleElement != titleElement)
return;
m_titleElement = 0;
m_titleSetExplicitly = false;
// Update title based on first title element in the head, if one exists.
if (HTMLElement* headElement = head()) {
for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(titleTag)) {
HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
setTitle(titleElement->text(), titleElement);
break;
}
}
if (!m_titleElement && !m_rawTitle.isEmpty()) {
m_rawTitle = "";
updateTitle();
}
}
String Document::nodeName() const
{
return "#document";
}
Node::NodeType Document::nodeType() const
{
return DOCUMENT_NODE;
}
FrameView* Document::view() const
{
return m_frame ? m_frame->view() : 0;
}
Page* Document::page() const
{
return m_frame ? m_frame->page() : 0;
}
Settings* Document::settings() const
{
return m_frame ? m_frame->settings() : 0;
}
PassRefPtr<Range> Document::createRange()
{
return Range::create(this);
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
}
void Document::scheduleForcedStyleRecalc()
{
m_pendingStyleRecalcShouldForce = true;
scheduleStyleRecalc();
}
void Document::scheduleStyleRecalc()
{
if (m_styleRecalcTimer.isActive() || inPageCache())
return;
ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
if (!documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc = new HashSet<Document*>;
documentsThatNeedStyleRecalc->add(this);
// FIXME: Why on earth is this here? This is clearly misplaced.
if (m_accessKeyMapValid) {
m_accessKeyMapValid = false;
m_elementsByAccessKey.clear();
}
m_styleRecalcTimer.startOneShot(0);
}
void Document::unscheduleStyleRecalc()
{
ASSERT(!childNeedsStyleRecalc());
if (documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc->remove(this);
m_styleRecalcTimer.stop();
m_pendingStyleRecalcShouldForce = false;
}
bool Document::isPendingStyleRecalc() const
{
return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
}
void Document::styleRecalcTimerFired(Timer<Document>*)
{
updateStyleIfNeeded();
}
bool Document::childNeedsAndNotInStyleRecalc()
{
return childNeedsStyleRecalc() && !m_inStyleRecalc;
}
void Document::recalcStyle(StyleChange change)
{
// we should not enter style recalc while painting
if (view() && view()->isPainting()) {
ASSERT(!view()->isPainting());
return;
}
if (m_inStyleRecalc)
return; // Guard against re-entrancy. -dwh
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
m_inStyleRecalc = true;
suspendPostAttachCallbacks();
RenderWidget::suspendWidgetHierarchyUpdates();
if (view())
view()->pauseScheduledEvents();
#ifdef ANDROID_INSTRUMENT
android::TimeCounter::start(android::TimeCounter::CalculateStyleTimeCounter);
#endif
ASSERT(!renderer() || renderArena());
if (!renderer() || !renderArena())
goto bail_out;
if (m_pendingStyleRecalcShouldForce)
change = Force;
if (change == Force) {
// style selector may set this again during recalc
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = CSSStyleSelector::styleForDocument(this);
StyleChange ch = diff(documentStyle.get(), renderer()->style());
if (renderer() && ch != NoChange)
renderer()->setStyle(documentStyle.release());
}
for (Node* n = firstChild(); n; n = n->nextSibling())
if (change >= Inherit || n->childNeedsStyleRecalc() || n->needsStyleRecalc())
n->recalcStyle(change);
#ifdef ANDROID_INSTRUMENT
android::TimeCounter::record(android::TimeCounter::CalculateStyleTimeCounter, __FUNCTION__);
#endif
#if USE(ACCELERATED_COMPOSITING)
if (view()) {
bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
// If we didn't update compositing layers because of layout(), we need to do so here.
if (!layoutPending)
view()->updateCompositingLayers();
}
#endif
bail_out:
clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
unscheduleStyleRecalc();
if (view())
view()->resumeScheduledEvents();
RenderWidget::resumeWidgetHierarchyUpdates();
resumePostAttachCallbacks();
m_inStyleRecalc = false;
// If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
if (m_closeAfterStyleRecalc) {
m_closeAfterStyleRecalc = false;
implicitClose();
}
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyleIfNeeded()
{
ASSERT(isMainThread());
ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
return;
if (m_frame)
m_frame->animation()->beginAnimationUpdate();
recalcStyle(NoChange);
// Tell the animation controller that updateStyleIfNeeded is finished and it can do any post-processing
if (m_frame)
m_frame->animation()->endAnimationUpdate();
}
void Document::updateStyleForAllDocuments()
{
ASSERT(isMainThread());
if (!documentsThatNeedStyleRecalc)
return;
while (documentsThatNeedStyleRecalc->size()) {
HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
Document* doc = *it;
documentsThatNeedStyleRecalc->remove(doc);
doc->updateStyleIfNeeded();
}
}
void Document::updateLayout()
{
ASSERT(isMainThread());
if (Element* oe = ownerElement())
oe->document()->updateLayout();
updateStyleIfNeeded();
// Only do a layout if changes have occurred that make it necessary.
FrameView* v = view();
if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
v->layout();
}
// FIXME: This is a bad idea and needs to be removed eventually.
// Other browsers load stylesheets before they continue parsing the web page.
// Since we don't, we can run JavaScript code that needs answers before the
// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
void Document::updateLayoutIgnorePendingStylesheets()
{
bool oldIgnore = m_ignorePendingStylesheets;
if (!haveStylesheetsLoaded()) {
m_ignorePendingStylesheets = true;
// FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
// dangerous to try to stop it a second time, after page content has already been loaded and displayed
// with accurate style information. (Our suppression involves blanking the whole page at the
// moment. If it were more refined, we might be able to do something better.)
// It's worth noting though that this entire method is a hack, since what we really want to do is
// suspend JS instead of doing a layout with inaccurate information.
if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleSelectorChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle)
// If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
// may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
// but here we need up-to-date style immediately.
recalcStyle(Force);
}
updateLayout();
m_ignorePendingStylesheets = oldIgnore;
}
PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
{
ASSERT_ARG(element, element->document() == this);
bool oldIgnore = m_ignorePendingStylesheets;
m_ignorePendingStylesheets = true;
RefPtr<RenderStyle> style = styleSelector()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
m_ignorePendingStylesheets = oldIgnore;
return style.release();
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
RefPtr<RenderStyle> style = styleSelector()->styleForPage(pageIndex);
return style.release();
}
bool Document::isPageBoxVisible(int pageIndex)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
return style->visibility() != HIDDEN; // display property doesn't apply to @page.
}
void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
int width = pageSize.width();
int height = pageSize.height();
switch (style->pageSizeType()) {
case PAGE_SIZE_AUTO:
break;
case PAGE_SIZE_AUTO_LANDSCAPE:
if (width < height)
std::swap(width, height);
break;
case PAGE_SIZE_AUTO_PORTRAIT:
if (width > height)
std::swap(width, height);
break;
case PAGE_SIZE_RESOLVED: {
LengthSize size = style->pageSize();
ASSERT(size.width().isFixed());
ASSERT(size.height().isFixed());
width = size.width().calcValue(0);
height = size.height().calcValue(0);
break;
}
default:
ASSERT_NOT_REACHED();
}
pageSize = IntSize(width, height);
// The percentage is calculated with respect to the width even for margin top and bottom.
// http://www.w3.org/TR/CSS2/box.html#margin-properties
marginTop = style->marginTop().isAuto() ? marginTop : style->marginTop().calcValue(width);
marginRight = style->marginRight().isAuto() ? marginRight : style->marginRight().calcValue(width);
marginBottom = style->marginBottom().isAuto() ? marginBottom : style->marginBottom().calcValue(width);
marginLeft = style->marginLeft().isAuto() ? marginLeft : style->marginLeft().calcValue(width);
}
void Document::createStyleSelector()
{
bool matchAuthorAndUserStyles = true;
if (Settings* docSettings = settings())
matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
m_styleSelector.set(new CSSStyleSelector(this, m_styleSheets.get(), m_mappedElementSheet.get(), pageUserSheet(), pageGroupUserSheets(),
!inQuirksMode(), matchAuthorAndUserStyles));
}
void Document::attach()
{
ASSERT(!attached());
ASSERT(!m_inPageCache);
#if !PLATFORM(ANDROID)
ASSERT(!m_axObjectCache);
#endif
if (!m_renderArena)
m_renderArena = new RenderArena();
// Create the rendering tree
setRenderer(new (m_renderArena.get()) RenderView(this, view()));
#if USE(ACCELERATED_COMPOSITING)
renderView()->didMoveOnscreen();
#endif
recalcStyle(Force);
RenderObject* render = renderer();
setRenderer(0);
ContainerNode::attach();
setRenderer(render);
}
void Document::detach()
{
ASSERT(attached());
ASSERT(!m_inPageCache);
clearAXObjectCache();
stopActiveDOMObjects();
RenderObject* render = renderer();
// Send out documentWillBecomeInactive() notifications to registered elements,
// in order to stop media elements
documentWillBecomeInactive();
#if ENABLE(SHARED_WORKERS)
SharedWorkerRepository::documentDetached(this);
#endif
if (m_frame) {
FrameView* view = m_frame->view();
if (view)
view->detachCustomScrollbars();
}
// indicate destruction mode, i.e. attached() but renderer == 0
setRenderer(0);
#if ENABLE(FULLSCREEN_API)
if (m_fullScreenRenderer)
setFullScreenRenderer(0);
#endif
m_hoverNode = 0;
m_focusedNode = 0;
m_activeNode = 0;
ContainerNode::detach();
unscheduleStyleRecalc();
if (render)
render->destroy();
// This is required, as our Frame might delete itself as soon as it detaches
// us. However, this violates Node::detach() semantics, as it's never
// possible to re-attach. Eventually Document::detach() should be renamed,
// or this setting of the frame to 0 could be made explicit in each of the
// callers of Document::detach().
m_frame = 0;
m_renderArena.clear();
}
void Document::removeAllEventListeners()
{
#if ENABLE(TOUCH_EVENTS)
Page* ownerPage = page();
if (!m_inPageCache && ownerPage && (m_frame == ownerPage->mainFrame()) && hasListenerType(Document::TOUCH_LISTENER)) {
// Inform the Chrome Client that it no longer needs to forward touch
// events to WebCore as the document removes all the event listeners.
ownerPage->chrome()->client()->needTouchEvents(false);
}
#endif
EventTarget::removeAllEventListeners();
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
for (Node* node = firstChild(); node; node = node->traverseNextNode())
node->removeAllEventListeners();
}
RenderView* Document::renderView() const
{
return toRenderView(renderer());
}
void Document::clearAXObjectCache()
{
#if PLATFORM(ANDROID)
return;
#else
// clear cache in top document
if (m_axObjectCache) {
// Clear the cache member variable before calling delete because attempts
// are made to access it during destruction.
AXObjectCache* axObjectCache = m_axObjectCache;
m_axObjectCache = 0;
delete axObjectCache;
return;
}
// ask the top-level document to clear its cache
Document* doc = topDocument();
if (doc != this)
doc->clearAXObjectCache();
#endif
}
bool Document::axObjectCacheExists() const
{
#if PLATFORM(ANDROID)
return false;
#else
if (m_axObjectCache)
return true;
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCacheExists();
return false;
#endif
}
AXObjectCache* Document::axObjectCache() const
{
#if PLATFORM(ANDROID)
return 0;
#else
// The only document that actually has a AXObjectCache is the top-level
// document. This is because we need to be able to get from any WebCoreAXObject
// to any other WebCoreAXObject on the same page. Using a single cache allows
// lookups across nested webareas (i.e. multiple documents).
if (m_axObjectCache) {
// return already known top-level cache
if (!ownerElement())
return m_axObjectCache;
// In some pages with frames, the cache is created before the sub-webarea is
// inserted into the tree. Here, we catch that case and just toss the old
// cache and start over.
// NOTE: This recovery may no longer be needed. I have been unable to trigger
// it again. See rdar://5794454
// FIXME: Can this be fixed when inserting the subframe instead of now?
// FIXME: If this function was called to get the cache in order to remove
// an AXObject, we are now deleting the cache as a whole and returning a
// new empty cache that does not contain the AXObject! That should actually
// be OK. I am concerned about other cases like this where accessing the
// cache blows away the AXObject being operated on.
delete m_axObjectCache;
m_axObjectCache = 0;
}
// ask the top-level document for its cache
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCache();
// this is the top-level document, so install a new cache
m_axObjectCache = new AXObjectCache(this);
return m_axObjectCache;
#endif // ANDROID
}
void Document::setVisuallyOrdered()
{
m_visuallyOrdered = true;
if (renderer())
renderer()->style()->setVisuallyOrdered(true);
}
PassRefPtr<DocumentParser> Document::createParser()
{
// FIXME: this should probably pass the frame instead
return XMLDocumentParser::create(this, view());
}
ScriptableDocumentParser* Document::scriptableDocumentParser() const
{
return parser() ? parser()->asScriptableDocumentParser() : 0;
}
void Document::open(Document* ownerDocument)
{
if (ownerDocument) {
setURL(ownerDocument->url());
m_cookieURL = ownerDocument->cookieURL();
ScriptExecutionContext::setSecurityOrigin(ownerDocument->securityOrigin());
}
if (m_frame) {
ScriptableDocumentParser* parser = scriptableDocumentParser();
if (m_frame->loader()->isLoadingMainResource() || (parser && parser->isParsing() && parser->isExecutingScript()))
return;
if (m_frame->loader()->state() == FrameStateProvisional)
m_frame->loader()->stopAllLoaders();
}
removeAllEventListeners();
implicitOpen();
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
if (m_frame)
m_frame->loader()->didExplicitOpen();
}
void Document::detachParser()
{
if (!m_parser)
return;
m_parser->detach();
m_parser.clear();
}
void Document::cancelParsing()
{
if (!m_parser)
return;
// We have to clear the parser to avoid possibly triggering
// the onload handler when closing as a side effect of a cancel-style
// change, such as opening a new document or closing the window while
// still parsing
detachParser();
explicitClose();
}
void Document::implicitOpen()
{
cancelParsing();
removeChildren();
setCompatibilityMode(NoQuirksMode);
m_parser = createParser();
setParsing(true);
setReadyState(Loading);
// If we reload, the animation controller sticks around and has
// a stale animation time. We need to update it here.
if (m_frame && m_frame->animation())
m_frame->animation()->beginAnimationUpdate();
}
HTMLElement* Document::body() const
{
Node* de = documentElement();
if (!de)
return 0;
// try to prefer a FRAMESET element over BODY
Node* body = 0;
for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
if (i->hasTagName(framesetTag))
return toHTMLElement(i);
if (i->hasTagName(bodyTag) && !body)
body = i;
}
return toHTMLElement(body);
}
void Document::setBody(PassRefPtr<HTMLElement> newBody, ExceptionCode& ec)
{
if (!newBody || !documentElement()) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
HTMLElement* b = body();
if (!b)
documentElement()->appendChild(newBody, ec);
else
documentElement()->replaceChild(newBody, b, ec);
}
HTMLHeadElement* Document::head()
{
Node* de = documentElement();
if (!de)
return 0;
for (Node* e = de->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(headTag))
return static_cast<HTMLHeadElement*>(e);
return 0;
}
void Document::close()
{
// FIXME: We should follow the specification more closely:
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript())
return;
explicitClose();
}
void Document::explicitClose()
{
if (!m_frame) {
// Because we have no frame, we don't know if all loading has completed,
// so we just call implicitClose() immediately. FIXME: This might fire
// the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
implicitClose();
return;
}
// This code calls implicitClose() if all loading has completed.
loader()->writer()->endIfNotLoadingMainResource();
m_frame->loader()->checkCompleted();
}
void Document::implicitClose()
{
// If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
if (m_inStyleRecalc) {
m_closeAfterStyleRecalc = true;
return;
}
bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
if (!doload)
return;
m_processingLoadEvent = true;
ScriptableDocumentParser* parser = scriptableDocumentParser();
m_wellFormed = parser && parser->wellFormed();
// We have to clear the parser, in case someone document.write()s from the
// onLoad event handler, as in Radar 3206524.
detachParser();
// Parser should have picked up all preloads by now
m_cachedResourceLoader->clearPreloads();
// FIXME: We kick off the icon loader when the Document is done parsing.
// There are earlier opportunities we could start it:
// -When the <head> finishes parsing
// -When any new HTMLLinkElement is inserted into the document
// But those add a dynamic component to the favicon that has UI
// ramifications, and we need to decide what is the Right Thing To Do(tm)
Frame* f = frame();
if (f)
f->loader()->startIconLoader();
// Resume the animations (or start them)
if (f)
f->animation()->resumeAnimationsForDocument(this);
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
dispatchWindowLoadEvent();
enqueuePageshowEvent(PageshowEventNotPersisted);
enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
if (f)
f->loader()->handledOnloadEvents();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("onload fired at %d\n", elapsedTime());
#endif
m_processingLoadEvent = false;
// An event handler may have removed the frame
if (!frame())
return;
// Make sure both the initial layout and reflow happen after the onload
// fires. This will improve onload scores, and other browsers do it.
// If they wanna cheat, we can too. -dwh
if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
// Just bail out. Before or during the onload we were shifted to another page.
// The old i-Bench suite does this. When this happens don't bother painting or laying out.
view()->unscheduleRelayout();
return;
}
frame()->loader()->checkCallImplicitClose();
RenderObject* renderObject = renderer();
// We used to force a synchronous display and flush here. This really isn't
// necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
// (if your platform is syncing flushes and limiting them to 60fps).
m_overMinimumLayoutThreshold = true;
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateStyleIfNeeded();
// Always do a layout after loading if needed.
if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
view()->layout();
}
#if PLATFORM(MAC) || PLATFORM(CHROMIUM)
if (f && renderObject && this == topDocument() && AXObjectCache::accessibilityEnabled()) {
// The AX cache may have been cleared at this point, but we need to make sure it contains an
// AX object to send the notification to. getOrCreate will make sure that an valid AX object
// exists in the cache (we ignore the return value because we don't need it here). This is
// only safe to call when a layout is not in progress, so it can not be used in postNotification.
axObjectCache()->getOrCreate(renderObject);
axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
}
#endif
#if ENABLE(SVG)
// FIXME: Officially, time 0 is when the outermost <svg> receives its
// SVGLoad event, but we don't implement those yet. This is close enough
// for now. In some cases we should have fired earlier.
if (svgExtensions())
accessSVGExtensions()->startAnimations();
#endif
}
void Document::setParsing(bool b)
{
m_bParsing = b;
if (!m_bParsing && view())
view()->scheduleRelayout();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement() && !m_bParsing)
printf("Parsing finished at %d\n", elapsedTime());
#endif
}
bool Document::shouldScheduleLayout()
{
// This function will only be called when FrameView thinks a layout is needed.
// This enforces a couple extra rules.
//
// (a) Only schedule a layout once the stylesheets are loaded.
// (b) Only schedule layout once we have a body element.
return (haveStylesheetsLoaded() && body())
|| (documentElement() && !documentElement()->hasTagName(htmlTag));
}
int Document::minimumLayoutDelay()
{
if (m_overMinimumLayoutThreshold)
return m_extraLayoutDelay;
int elapsed = elapsedTime();
m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
// We'll want to schedule the timer to fire at the minimum layout threshold.
return max(0, cLayoutScheduleThreshold - elapsed) + m_extraLayoutDelay;
}
int Document::elapsedTime() const
{
return static_cast<int>((currentTime() - m_startTime) * 1000);
}
void Document::write(const SegmentedString& text, Document* ownerDocument)
{
NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
if (m_writeRecursionIsTooDeep)
return;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning a document.write at %d\n", elapsedTime());
#endif
bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
return;
if (!hasInsertionPoint)
open(ownerDocument);
ASSERT(m_parser);
m_parser->insert(text);
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Ending a document.write at %d\n", elapsedTime());
#endif
}
void Document::write(const String& text, Document* ownerDocument)
{
write(SegmentedString(text), ownerDocument);
}
void Document::writeln(const String& text, Document* ownerDocument)
{
write(text, ownerDocument);
write("\n", ownerDocument);
}
void Document::finishParsing()
{
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Received all data at %d\n", elapsedTime());
#endif
// Let the parser go through as much data as it can. There will be three possible outcomes after
// finish() is called:
// (1) All remaining data is parsed, document isn't loaded yet
// (2) All remaining data is parsed, document is loaded, parser gets deleted
// (3) Data is still remaining to be parsed.
if (m_parser)
m_parser->finish();
}
const KURL& Document::virtualURL() const
{
return m_url;
}
KURL Document::virtualCompleteURL(const String& url) const
{
return completeURL(url);
}
EventTarget* Document::errorEventTarget()
{
return domWindow();
}
void Document::logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
{
MessageType messageType = callStack ? UncaughtExceptionMessageType : LogMessageType;
addMessage(JSMessageSource, messageType, ErrorMessageLevel, errorMessage, lineNumber, sourceURL, callStack);
}
void Document::setURL(const KURL& url)
{
const KURL& newURL = url.isEmpty() ? blankURL() : url;
if (newURL == m_url)
return;
m_url = newURL;
m_documentURI = m_url.string();
updateBaseURL();
}
void Document::updateBaseURL()
{
// DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
// first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
// from the Document interface otherwise.
if (m_baseElementURL.isEmpty()) {
// The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
// so we use a null base URL.
m_baseURL = KURL(KURL(), documentURI());
} else
m_baseURL = m_baseElementURL;
if (!m_baseURL.isValid())
m_baseURL = KURL();
if (m_elemSheet)
m_elemSheet->setFinalURL(m_baseURL);
if (m_mappedElementSheet)
m_mappedElementSheet->setFinalURL(m_baseURL);
}
void Document::processBaseElement()
{
// Find the first href attribute in a base element and the first target attribute in a base element.
const AtomicString* href = 0;
const AtomicString* target = 0;
for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
if (node->hasTagName(baseTag)) {
if (!href) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
if (!value.isNull())
href = &value;
}
if (!target) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
if (!value.isNull())
target = &value;
}
}
}
// FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
KURL baseElementURL;
if (href) {
String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
if (!strippedHref.isEmpty())
baseElementURL = KURL(url(), strippedHref);
}
if (m_baseElementURL != baseElementURL) {
m_baseElementURL = baseElementURL;
updateBaseURL();
}
m_baseTarget = target ? *target : nullAtom;
}
String Document::userAgent(const KURL& url) const
{
return frame() ? frame()->loader()->userAgent(url) : String();
}
CSSStyleSheet* Document::pageUserSheet()
{
if (m_pageUserSheet)
return m_pageUserSheet.get();
Page* owningPage = page();
if (!owningPage)
return 0;
String userSheetText = owningPage->userStyleSheet();
if (userSheetText.isEmpty())
return 0;
// Parse the sheet and cache it.
m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
m_pageUserSheet->setIsUserStyleSheet(true);
m_pageUserSheet->parseString(userSheetText, !inQuirksMode());
return m_pageUserSheet.get();
}
void Document::clearPageUserSheet()
{
if (m_pageUserSheet) {
m_pageUserSheet = 0;
styleSelectorChanged(DeferRecalcStyle);
}
}
void Document::updatePageUserSheet()
{
clearPageUserSheet();
if (pageUserSheet())
styleSelectorChanged(RecalcStyleImmediately);
}
const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
{
if (m_pageGroupUserSheetCacheValid)
return m_pageGroupUserSheets.get();
m_pageGroupUserSheetCacheValid = true;
Page* owningPage = page();
if (!owningPage)
return 0;
const PageGroup& pageGroup = owningPage->group();
const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
if (!sheetsMap)
return 0;
UserStyleSheetMap::const_iterator end = sheetsMap->end();
for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
const UserStyleSheetVector* sheets = it->second;
for (unsigned i = 0; i < sheets->size(); ++i) {
const UserStyleSheet* sheet = sheets->at(i).get();
if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
continue;
if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
continue;
RefPtr<CSSStyleSheet> parsedSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
parsedSheet->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
parsedSheet->parseString(sheet->source(), !inQuirksMode());
if (!m_pageGroupUserSheets)
m_pageGroupUserSheets.set(new Vector<RefPtr<CSSStyleSheet> >);
m_pageGroupUserSheets->append(parsedSheet.release());
}
}
return m_pageGroupUserSheets.get();
}
void Document::clearPageGroupUserSheets()
{
m_pageGroupUserSheetCacheValid = false;
if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
m_pageGroupUserSheets->clear();
styleSelectorChanged(DeferRecalcStyle);
}
}
void Document::updatePageGroupUserSheets()
{
clearPageGroupUserSheets();
if (pageGroupUserSheets() && pageGroupUserSheets()->size())
styleSelectorChanged(RecalcStyleImmediately);
}
CSSStyleSheet* Document::elementSheet()
{
if (!m_elemSheet)
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
return m_elemSheet.get();
}
CSSStyleSheet* Document::mappedElementSheet()
{
if (!m_mappedElementSheet)
m_mappedElementSheet = CSSStyleSheet::createInline(this, m_baseURL);
return m_mappedElementSheet.get();
}
static Node* nextNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
for (Node* n = start; n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
return n;
return 0;
}
static Node* previousNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
for (Node* n = start; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
return n;
return 0;
}
static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
int winningTabIndex = SHRT_MAX + 1;
Node* winner = 0;
for (Node* n = start; n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() > tabIndex && n->tabIndex() < winningTabIndex) {
winner = n;
winningTabIndex = n->tabIndex();
}
return winner;
}
static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
int winningTabIndex = 0;
Node* winner = 0;
for (Node* n = start; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() < tabIndex && n->tabIndex() > winningTabIndex) {
winner = n;
winningTabIndex = n->tabIndex();
}
return winner;
}
Node* Document::nextFocusableNode(Node* start, KeyboardEvent* event)
{
if (start) {
// If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
if (start->tabIndex() < 0) {
for (Node* n = start->traverseNextNode(); n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
return n;
}
// First try to find a node with the same tabindex as start that comes after start in the document.
if (Node* winner = nextNodeWithExactTabIndex(start->traverseNextNode(), start->tabIndex(), event))
return winner;
if (!start->tabIndex())
// We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
return 0;
}
// Look for the first node in the document that:
// 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
// 2) comes first in the document, if there's a tie.
if (Node* winner = nextNodeWithGreaterTabIndex(this, start ? start->tabIndex() : 0, event))
return winner;
// There are no nodes with a tabindex greater than start's tabindex,
// so find the first node with a tabindex of 0.
return nextNodeWithExactTabIndex(this, 0, event);
}
Node* Document::previousFocusableNode(Node* start, KeyboardEvent* event)
{
Node* last;
for (last = this; last->lastChild(); last = last->lastChild()) { }
// First try to find the last node in the document that comes before start and has the same tabindex as start.
// If start is null, find the last node in the document with a tabindex of 0.
Node* startingNode;
int startingTabIndex;
if (start) {
startingNode = start->traversePreviousNode();
startingTabIndex = start->tabIndex();
} else {
startingNode = last;
startingTabIndex = 0;
}
// However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
if (startingTabIndex < 0) {
for (Node* n = startingNode; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
return n;
}
if (Node* winner = previousNodeWithExactTabIndex(startingNode, startingTabIndex, event))
return winner;
// There are no nodes before start with the same tabindex as start, so look for a node that:
// 1) has the highest non-zero tabindex (that is less than start's tabindex), and
// 2) comes last in the document, if there's a tie.
startingTabIndex = (start && start->tabIndex()) ? start->tabIndex() : SHRT_MAX;
return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
}
int Document::nodeAbsIndex(Node *node)
{
ASSERT(node->document() == this);
int absIndex = 0;
for (Node* n = node; n && n != this; n = n->traversePreviousNode())
absIndex++;
return absIndex;
}
Node* Document::nodeWithAbsIndex(int absIndex)
{
Node* n = this;
for (int i = 0; n && (i < absIndex); i++)
n = n->traverseNextNode();
return n;
}
#ifdef ANDROID_META_SUPPORT
void Document::processMetadataSettings(const String& content)
{
ASSERT(!content.isNull());
processArguments(content, 0, 0);
}
#endif
void Document::processHttpEquiv(const String& equiv, const String& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
Frame* frame = this->frame();
if (equalIgnoringCase(equiv, "default-style")) {
// The preferred style set has been overridden as per section
// 14.3.2 of the HTML4.0 specification. We need to update the
// sheet used variable and then update our style selector.
// For more info, see the test at:
// http://www.hixie.ch/tests/evil/css/import/main/preferred.html
// -dwh
m_selectedStylesheetSet = content;
m_preferredStylesheetSet = content;
styleSelectorChanged(DeferRecalcStyle);
} else if (equalIgnoringCase(equiv, "refresh")) {
double delay;
String url;
if (frame && parseHTTPRefresh(content, true, delay, url)) {
if (url.isEmpty())
url = m_url.string();
else
url = completeURL(url).string();
frame->navigationScheduler()->scheduleRedirect(delay, url);
}
} else if (equalIgnoringCase(equiv, "set-cookie")) {
// FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
if (isHTMLDocument()) {
ExceptionCode ec; // Exception (for sandboxed documents) ignored.
static_cast<HTMLDocument*>(this)->setCookie(content, ec);
}
} else if (equalIgnoringCase(equiv, "content-language"))
setContentLanguage(content);
else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
parseDNSPrefetchControlHeader(content);
else if (equalIgnoringCase(equiv, "x-frame-options")) {
if (frame) {
FrameLoader* frameLoader = frame->loader();
if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
frameLoader->stopAllLoaders();
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage, 1, String());
}
}
}
}
// Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
static bool isSeparator(UChar c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
}
void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
{
// Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
int keyBegin, keyEnd;
int valueBegin, valueEnd;
int i = 0;
int length = features.length();
String buffer = features.lower();
while (i < length) {
// skip to first non-separator, but don't skip past the end of the string
while (isSeparator(buffer[i])) {
if (i >= length)
break;
i++;
}
keyBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
keyEnd = i;
// skip to first '=', but don't skip past a ',' or the end of the string
while (buffer[i] != '=') {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
// skip to first non-separator, but don't skip past a ',' or the end of the string
while (isSeparator(buffer[i])) {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
valueBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
valueEnd = i;
ASSERT(i <= length);
String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
#ifdef ANDROID_META_SUPPORT
if (frame())
frame()->settings()->setMetadataSettings(keyString, valueString);
#else
callback(keyString, valueString, this, data);
#endif
}
}
void Document::processViewport(const String& features)
{
ASSERT(!features.isNull());
m_viewportArguments = ViewportArguments();
processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
Frame* frame = this->frame();
if (!frame || !frame->page())
return;
frame->page()->updateViewportArguments();
}
MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const IntPoint& documentPoint, const PlatformMouseEvent& event)
{
ASSERT(!renderer() || renderer()->isRenderView());
if (!renderer())
return MouseEventWithHitTestResults(event, HitTestResult(IntPoint()));
HitTestResult result(documentPoint);
renderView()->layer()->hitTest(request, result);
if (!request.readOnly())
updateStyleIfNeeded();
return MouseEventWithHitTestResults(event, result);
}
// DOM Section 1.1.1
bool Document::childTypeAllowed(NodeType type)
{
switch (type) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
case ELEMENT_NODE:
// Documents may contain no more than one of each of these.
// (One Element and one DocumentType.)
for (Node* c = firstChild(); c; c = c->nextSibling())
if (c->nodeType() == type)
return false;
return true;
}
return false;
}
bool Document::canReplaceChild(Node* newChild, Node* oldChild)
{
if (!oldChild)
// ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
return true;
if (oldChild->nodeType() == newChild->nodeType())
return true;
int numDoctypes = 0;
int numElements = 0;
// First, check how many doctypes and elements we have, not counting
// the child we're about to remove.
for (Node* c = firstChild(); c; c = c->nextSibling()) {
if (c == oldChild)
continue;
switch (c->nodeType()) {
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
default:
break;
}
}
// Then, see how many doctypes and elements might be added by the new child.
if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
for (Node* c = firstChild(); c; c = c->nextSibling()) {
switch (c->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
break;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
} else {
switch (newChild->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
if (numElements > 1 || numDoctypes > 1)
return false;
return true;
}
PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
{
// Spec says cloning Document nodes is "implementation dependent"
// so we do not support it...
return 0;
}
StyleSheetList* Document::styleSheets()
{
return m_styleSheets.get();
}
String Document::preferredStylesheetSet() const
{
return m_preferredStylesheetSet;
}
String Document::selectedStylesheetSet() const
{
return m_selectedStylesheetSet;
}
void Document::setSelectedStylesheetSet(const String& aString)
{
m_selectedStylesheetSet = aString;
styleSelectorChanged(DeferRecalcStyle);
}
// This method is called whenever a top-level stylesheet has finished loading.
void Document::removePendingSheet()
{
// Make sure we knew this sheet was pending, and that our count isn't out of sync.
ASSERT(m_pendingStylesheets > 0);
m_pendingStylesheets--;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
#endif
if (m_pendingStylesheets)
return;
styleSelectorChanged(RecalcStyleImmediately);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->executeScriptsWaitingForStylesheets();
if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
view()->scrollToFragment(m_url);
}
void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
{
// Don't bother updating, since we haven't loaded all our style info yet
// and haven't calculated the style selector for the first time.
if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
return;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning update of style selector at time %d.\n", elapsedTime());
#endif
recalcStyleSelector();
if (updateFlag == DeferRecalcStyle) {
scheduleForcedStyleRecalc();
return;
}
if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
if (renderer())
renderer()->repaint();
}
// This recalcStyle initiates a new recalc cycle. We need to bracket it to
// make sure animations get the correct update time
if (m_frame)
m_frame->animation()->beginAnimationUpdate();
recalcStyle(Force);
if (m_frame)
m_frame->animation()->endAnimationUpdate();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Finished update of style selector at time %d\n", elapsedTime());
#endif
if (renderer()) {
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
if (view())
view()->scheduleRelayout();
}
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->styleSelectorChanged();
}
void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
if (!node->inDocument())
return;
// Until the <body> exists, we have no choice but to compare document positions,
// since styles outside of the body and head continue to be shunted into the head
// (and thus can shift to end up before dynamically added DOM content that is also
// outside the body).
if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
m_styleSheetCandidateNodes.add(node);
return;
}
// Determine an appropriate insertion point.
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
StyleSheetCandidateListHashSet::iterator it = end;
Node* followingNode = 0;
do {
--it;
Node* n = *it;
unsigned short position = n->compareDocumentPosition(node);
if (position == DOCUMENT_POSITION_FOLLOWING) {
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
return;
}
followingNode = n;
} while (it != begin);
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
}
void Document::removeStyleSheetCandidateNode(Node* node)
{
m_styleSheetCandidateNodes.remove(node);
}
void Document::recalcStyleSelector()
{
if (!renderer() || !attached())
return;
StyleSheetVector sheets;
bool matchAuthorAndUserStyles = true;
if (Settings* settings = this->settings())
matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
if (!matchAuthorAndUserStyles)
end = begin;
for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
Node* n = *it;
StyleSheet* sheet = 0;
if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
// Processing instruction (XML documents only).
// We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
sheet = pi->sheet();
#if ENABLE(XSLT)
// Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
if (pi->isXSL() && !transformSourceDocument()) {
// Don't apply XSL transforms until loading is finished.
if (!parsing())
applyXSLTransform(pi);
return;
}
#endif
} else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
#if ENABLE(SVG)
|| (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
#endif
) {
Element* e = static_cast<Element*>(n);
AtomicString title = e->getAttribute(titleAttr);
bool enabledViaScript = false;
if (e->hasLocalName(linkTag)) {
// <LINK> element
HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
if (linkElement->isDisabled())
continue;
enabledViaScript = linkElement->isEnabledViaScript();
if (linkElement->isLoading()) {
// it is loading but we should still decide which style sheet set to use
if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
const AtomicString& rel = e->getAttribute(relAttr);
if (!rel.contains("alternate")) {
m_preferredStylesheetSet = title;
m_selectedStylesheetSet = title;
}
}
continue;
}
if (!linkElement->sheet())
title = nullAtom;
}
// Get the current preferred styleset. This is the
// set of sheets that will be enabled.
#if ENABLE(SVG)
if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
sheet = static_cast<SVGStyleElement*>(n)->sheet();
else
#endif
if (e->hasLocalName(linkTag))
sheet = static_cast<HTMLLinkElement*>(n)->sheet();
else
// <STYLE> element
sheet = static_cast<HTMLStyleElement*>(n)->sheet();
// Check to see if this sheet belongs to a styleset
// (thus making it PREFERRED or ALTERNATE rather than
// PERSISTENT).
if (!enabledViaScript && !title.isEmpty()) {
// Yes, we have a title.
if (m_preferredStylesheetSet.isEmpty()) {
// No preferred set has been established. If
// we are NOT an alternate sheet, then establish
// us as the preferred set. Otherwise, just ignore
// this sheet.
AtomicString rel = e->getAttribute(relAttr);
if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
m_preferredStylesheetSet = m_selectedStylesheetSet = title;
}
if (title != m_preferredStylesheetSet)
sheet = 0;
}
}
if (sheet)
sheets.append(sheet);
}
m_styleSheets->swap(sheets);
m_styleSelector.clear();
m_didCalculateStyleSelector = true;
}
void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
{
m_hoverNode = newHoverNode;
}
void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
{
m_activeNode = newActiveNode;
}
void Document::focusedNodeRemoved()
{
setFocusedNode(0);
}
void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
return;
bool nodeInSubtree = false;
if (amongChildrenOnly)
nodeInSubtree = m_focusedNode->isDescendantOf(node);
else
nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
if (nodeInSubtree)
document()->focusedNodeRemoved();
}
void Document::hoveredNodeDetached(Node* node)
{
if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
return;
m_hoverNode = node->parentNode();
while (m_hoverNode && !m_hoverNode->renderer())
m_hoverNode = m_hoverNode->parentNode();
if (frame())
frame()->eventHandler()->scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
{
if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
return;
m_activeNode = node->parentNode();
while (m_activeNode && !m_activeNode->renderer())
m_activeNode = m_activeNode->parentNode();
}
#if ENABLE(DASHBOARD_SUPPORT)
const Vector<DashboardRegionValue>& Document::dashboardRegions() const
{
return m_dashboardRegions;
}
void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
{
m_dashboardRegions = regions;
setDashboardRegionsDirty(false);
}
#endif
bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
{
// Make sure newFocusedNode is actually in this document
if (newFocusedNode && (newFocusedNode->document() != this))
return true;
if (m_focusedNode == newFocusedNode)
return true;
if (m_inPageCache)
return false;
bool focusChangeBlocked = false;
RefPtr<Node> oldFocusedNode = m_focusedNode;
m_focusedNode = 0;
// Remove focus from the existing focus node (if any)
if (oldFocusedNode && !oldFocusedNode->inDetach()) {
if (oldFocusedNode->active())
oldFocusedNode->setActive(false);
oldFocusedNode->setFocus(false);
// Dispatch a change event for text fields or textareas that have been edited
RenderObject* r = oldFocusedNode->renderer();
if (r && r->isTextControl() && toRenderTextControl(r)->wasChangedSinceLastChangeEvent()) {
static_cast<Element*>(oldFocusedNode.get())->dispatchFormControlChangeEvent();
r = oldFocusedNode->renderer();
if (r && r->isTextControl())
toRenderTextControl(r)->setChangedSinceLastChangeEvent(false);
}
// Dispatch the blur event and let the node do any other blur related activities (important for text fields)
oldFocusedNode->dispatchBlurEvent();
if (m_focusedNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusedNode = 0;
}
oldFocusedNode->dispatchUIEvent(eventNames().focusoutEvent, 0, 0); // DOM level 3 name for the bubbling blur event.
// FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is resolved.
oldFocusedNode->dispatchUIEvent(eventNames().DOMFocusOutEvent, 0, 0); // DOM level 2 name for compatibility.
if (m_focusedNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusedNode = 0;
}
if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
return true;
if (oldFocusedNode == oldFocusedNode->rootEditableElement())
frame()->editor()->didEndEditing();
if (view()) {
Widget* oldWidget = widgetForNode(oldFocusedNode.get());
if (oldWidget)
oldWidget->setFocus(false);
else
view()->setFocus(false);
}
}
if (newFocusedNode) {
if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
// delegate blocks focus change
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
// Set focus on the new node
m_focusedNode = newFocusedNode.get();
// Dispatch the focus event and let the node do any other focus related activities (important for text fields)
m_focusedNode->dispatchFocusEvent();
if (m_focusedNode != newFocusedNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->dispatchUIEvent(eventNames().focusinEvent, 0, 0); // DOM level 3 bubbling focus event.
// FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is resolved.
m_focusedNode->dispatchUIEvent(eventNames().DOMFocusInEvent, 0, 0); // DOM level 2 for compatibility.
if (m_focusedNode != newFocusedNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->setFocus(true);
if (m_focusedNode == m_focusedNode->rootEditableElement())
frame()->editor()->didBeginEditing();
// eww, I suck. set the qt focus correctly
// ### find a better place in the code for this
if (view()) {
Widget* focusWidget = widgetForNode(m_focusedNode.get());
if (focusWidget) {
// Make sure a widget has the right size before giving it focus.
// Otherwise, we are testing edge cases of the Widget code.
// Specifically, in WebCore this does not work well for text fields.
updateLayout();
// Re-get the widget in case updating the layout changed things.
focusWidget = widgetForNode(m_focusedNode.get());
}
if (focusWidget)
focusWidget->setFocus(true);
else
view()->setFocus(true);
}
}
#if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
RenderObject* oldFocusedRenderer = 0;
RenderObject* newFocusedRenderer = 0;
if (oldFocusedNode)
oldFocusedRenderer = oldFocusedNode->renderer();
if (newFocusedNode)
newFocusedRenderer = newFocusedNode->renderer();
axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
}
#endif
if (!focusChangeBlocked)
page()->chrome()->focusedNodeChanged(m_focusedNode.get());
SetFocusedNodeDone:
updateStyleIfNeeded();
return !focusChangeBlocked;
}
void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
{
updateLayout();
for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
if (node->isFocusable())
nodes.append(node);
}
}
void Document::setCSSTarget(Element* n)
{
if (m_cssTarget)
m_cssTarget->setNeedsStyleRecalc();
m_cssTarget = n;
if (n)
n->setNeedsStyleRecalc();
}
void Document::attachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.add(ni);
}
void Document::detachNodeIterator(NodeIterator* ni)
{
// The node iterator can be detached without having been attached if its root node didn't have a document
// when the iterator was created, but has it now.
m_nodeIterators.remove(ni);
}
void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
{
HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
if ((*it)->root() == node) {
detachNodeIterator(*it);
newDocument->attachNodeIterator(*it);
}
}
}
void Document::nodeChildrenChanged(ContainerNode* container)
{
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenChanged(container);
}
}
void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
{
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenWillBeRemoved(container);
}
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
for (Node* n = container->firstChild(); n; n = n->nextSibling())
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
}
}
void Document::nodeWillBeRemoved(Node* n)
{
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
(*it)->nodeWillBeRemoved(n);
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
#if ENABLE(FULLSCREEN_API)
// If the current full screen element or any of its ancestors is removed, set the current
// full screen element to the document root, and fire a fullscreenchange event to inform
// clients of the DOM.
ASSERT(n);
if (n->contains(m_fullScreenElement.get())) {
ASSERT(n != documentElement());
if (m_fullScreenRenderer)
m_fullScreenRenderer->remove();
setFullScreenRenderer(0);
m_fullScreenElement = documentElement();
recalcStyle(Force);
m_fullScreenChangeDelayTimer.startOneShot(0);
}
#endif
}
void Document::textInserted(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textInserted(text, offset, length);
}
// Update the markers for spelling and grammar checking.
m_markers->shiftMarkers(text, offset, length);
}
void Document::textRemoved(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textRemoved(text, offset, length);
}
// Update the markers for spelling and grammar checking.
m_markers->removeMarkers(text, offset, length);
m_markers->shiftMarkers(text, offset + length, 0 - length);
}
void Document::textNodesMerged(Text* oldNode, unsigned offset)
{
if (!disableRangeMutation(page())) {
NodeWithIndex oldNodeWithIndex(oldNode);
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodesMerged(oldNodeWithIndex, offset);
}
// FIXME: This should update markers for spelling and grammar checking.
}
void Document::textNodeSplit(Text* oldNode)
{
if (!disableRangeMutation(page())) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodeSplit(oldNode);
}
// FIXME: This should update markers for spelling and grammar checking.
}
// FIXME: eventually, this should return a DOMWindow stored in the document.
DOMWindow* Document::domWindow() const
{
if (!frame())
return 0;
// The m_frame pointer is not (not always?) zeroed out when the document is put into b/f cache, so the frame can hold an unrelated document/window pair.
// FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
if (m_frame->document() != this)
return 0;
return frame()->domWindow();
}
void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->setAttributeEventListener(eventType, listener);
}
EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return 0;
return domWindow->getAttributeEventListener(eventType);
}
void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchEvent(event, target);
}
void Document::dispatchWindowLoadEvent()
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchLoadEvent();
}
void Document::enqueueWindowEvent(PassRefPtr<Event> event)
{
event->setTarget(domWindow());
m_eventQueue->enqueueEvent(event);
}
PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
{
RefPtr<Event> event;
if (eventType == "Event" || eventType == "Events" || eventType == "HTMLEvents")
event = Event::create();
else if (eventType == "CustomEvent")
event = CustomEvent::create();
else if (eventType == "KeyboardEvent" || eventType == "KeyboardEvents")
event = KeyboardEvent::create();
else if (eventType == "MessageEvent")
event = MessageEvent::create();
else if (eventType == "MouseEvent" || eventType == "MouseEvents")
event = MouseEvent::create();
else if (eventType == "MutationEvent" || eventType == "MutationEvents")
event = MutationEvent::create();
else if (eventType == "OverflowEvent")
event = OverflowEvent::create();
else if (eventType == "PageTransitionEvent")
event = PageTransitionEvent::create();
else if (eventType == "ProgressEvent")
event = ProgressEvent::create();
#if ENABLE(DOM_STORAGE)
else if (eventType == "StorageEvent")
event = StorageEvent::create();
#endif
else if (eventType == "TextEvent")
event = TextEvent::create();
else if (eventType == "UIEvent" || eventType == "UIEvents")
event = UIEvent::create();
else if (eventType == "WebKitAnimationEvent")
event = WebKitAnimationEvent::create();
else if (eventType == "WebKitTransitionEvent")
event = WebKitTransitionEvent::create();
else if (eventType == "WheelEvent")
event = WheelEvent::create();
#if ENABLE(SVG)
else if (eventType == "SVGEvents")
event = Event::create();
else if (eventType == "SVGZoomEvents")
event = SVGZoomEvent::create();
#endif
#if ENABLE(TOUCH_EVENTS)
#if USE(V8)
else if (eventType == "TouchEvent" && RuntimeEnabledFeatures::touchEnabled())
#else
else if (eventType == "TouchEvent")
#endif
event = TouchEvent::create();
#endif
#if ENABLE(DEVICE_ORIENTATION)
else if (eventType == "DeviceMotionEvent")
event = DeviceMotionEvent::create();
else if (eventType == "DeviceOrientationEvent")
event = DeviceOrientationEvent::create();
#endif
#if ENABLE(ORIENTATION_EVENTS)
else if (eventType == "OrientationEvent")
event = Event::create();
#endif
if (event)
return event.release();
ec = NOT_SUPPORTED_ERR;
return 0;
}
void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
{
if (eventType == eventNames().DOMSubtreeModifiedEvent)
addListenerType(DOMSUBTREEMODIFIED_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedEvent)
addListenerType(DOMNODEINSERTED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedEvent)
addListenerType(DOMNODEREMOVED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
else if (eventType == eventNames().DOMAttrModifiedEvent)
addListenerType(DOMATTRMODIFIED_LISTENER);
else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
else if (eventType == eventNames().overflowchangedEvent)
addListenerType(OVERFLOWCHANGED_LISTENER);
else if (eventType == eventNames().webkitAnimationStartEvent)
addListenerType(ANIMATIONSTART_LISTENER);
else if (eventType == eventNames().webkitAnimationEndEvent)
addListenerType(ANIMATIONEND_LISTENER);
else if (eventType == eventNames().webkitAnimationIterationEvent)
addListenerType(ANIMATIONITERATION_LISTENER);
else if (eventType == eventNames().webkitTransitionEndEvent)
addListenerType(TRANSITIONEND_LISTENER);
else if (eventType == eventNames().beforeloadEvent)
addListenerType(BEFORELOAD_LISTENER);
else if (eventType == eventNames().beforeprocessEvent)
addListenerType(BEFOREPROCESS_LISTENER);
#if ENABLE(TOUCH_EVENTS)
else if (eventType == eventNames().touchstartEvent
|| eventType == eventNames().touchmoveEvent
|| eventType == eventNames().touchendEvent
|| eventType == eventNames().touchcancelEvent) {
addListenerType(TOUCH_LISTENER);
if (Page* page = this->page())
page->chrome()->client()->needTouchEvents(true);
}
#endif
}
CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
{
return 0;
}
HTMLFrameOwnerElement* Document::ownerElement() const
{
if (!frame())
return 0;
return frame()->ownerElement();
}
String Document::cookie(ExceptionCode& ec) const
{
if (page() && !page()->cookieEnabled())
return String();
// FIXME: The HTML5 DOM spec states that this attribute can raise an
// INVALID_STATE_ERR exception on getting if the Document has no
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return String();
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return String();
return cookies(this, cookieURL);
}
void Document::setCookie(const String& value, ExceptionCode& ec)
{
if (page() && !page()->cookieEnabled())
return;
// FIXME: The HTML5 DOM spec states that this attribute can raise an
// INVALID_STATE_ERR exception on setting if the Document has no
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return;
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return;
setCookies(this, cookieURL, value);
}
String Document::referrer() const
{
if (frame())
return frame()->loader()->referrer();
return String();
}
String Document::domain() const
{
return securityOrigin()->domain();
}
void Document::setDomain(const String& newDomain, ExceptionCode& ec)
{
if (SecurityOrigin::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
ec = SECURITY_ERR;
return;
}
// Both NS and IE specify that changing the domain is only allowed when
// the new domain is a suffix of the old domain.
// FIXME: We should add logging indicating why a domain was not allowed.
// If the new domain is the same as the old domain, still call
// securityOrigin()->setDomainForDOM. This will change the
// security check behavior. For example, if a page loaded on port 8000
// assigns its current domain using document.domain, the page will
// allow other pages loaded on different ports in the same domain that
// have also assigned to access this page.
if (equalIgnoringCase(domain(), newDomain)) {
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
return;
}
int oldLength = domain().length();
int newLength = newDomain.length();
// e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
if (newLength >= oldLength) {
ec = SECURITY_ERR;
return;
}
String test = domain();
// Check that it's a subdomain, not e.g. "ebkit.org"
if (test[oldLength - newLength - 1] != '.') {
ec = SECURITY_ERR;
return;
}
// Now test is "webkit.org" from domain()
// and we check that it's the same thing as newDomain
test.remove(0, oldLength - newLength);
if (test != newDomain) {
ec = SECURITY_ERR;
return;
}
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
}
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
String Document::lastModified() const
{
DateComponents date;
bool foundDate = false;
if (m_frame) {
String httpLastModified = m_documentLoader->response().httpHeaderField("Last-Modified");
if (!httpLastModified.isEmpty()) {
date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
foundDate = true;
}
}
// FIXME: If this document came from the file system, the HTML5
// specificiation tells us to read the last modification date from the file
// system.
if (!foundDate)
date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
}
static bool isValidNameNonASCII(const UChar* characters, unsigned length)
{
unsigned i = 0;
UChar32 c;
U16_NEXT(characters, i, length, c)
if (!isValidNameStart(c))
return false;
while (i < length) {
U16_NEXT(characters, i, length, c)
if (!isValidNamePart(c))
return false;
}
return true;
}
static inline bool isValidNameASCII(const UChar* characters, unsigned length)
{
UChar c = characters[0];
if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
return false;
for (unsigned i = 1; i < length; ++i) {
c = characters[i];
if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
return false;
}
return true;
}
bool Document::isValidName(const String& name)
{
unsigned length = name.length();
if (!length)
return false;
const UChar* characters = name.characters();
return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
}
bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
{
unsigned length = qualifiedName.length();
if (!length) {
ec = INVALID_CHARACTER_ERR;
return false;
}
bool nameStart = true;
bool sawColon = false;
int colonPos = 0;
const UChar* s = qualifiedName.characters();
for (unsigned i = 0; i < length;) {
UChar32 c;
U16_NEXT(s, i, length, c)
if (c == ':') {
if (sawColon) {
ec = NAMESPACE_ERR;
return false; // multiple colons: not allowed
}
nameStart = true;
sawColon = true;
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
nameStart = false;
} else {
if (!isValidNamePart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
}
}
if (!sawColon) {
prefix = String();
localName = qualifiedName;
} else {
prefix = qualifiedName.substring(0, colonPos);
if (prefix.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
localName = qualifiedName.substring(colonPos + 1);
}
if (localName.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
return true;
}
void Document::addImageMap(HTMLMapElement* imageMap)
{
AtomicStringImpl* name = imageMap->getName().impl();
if (!name)
return;
m_imageMapsByName.add(name, imageMap);
}
void Document::removeImageMap(HTMLMapElement* imageMap)
{
AtomicStringImpl* name = imageMap->getName().impl();
if (!name)
return;
m_imageMapsByName.remove(name, imageMap);
}
HTMLMapElement* Document::getImageMap(const String& url) const
{
if (url.isNull())
return 0;
size_t hashPos = url.find('#');
String name = (hashPos == notFound ? url : url.substring(hashPos + 1)).impl();
if (isHTMLDocument())
return static_cast<HTMLMapElement*>(m_imageMapsByName.getElementByLowercasedMapName(AtomicString(name.lower()).impl(), this));
return static_cast<HTMLMapElement*>(m_imageMapsByName.getElementByMapName(AtomicString(name).impl(), this));
}
void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
{
m_decoder = decoder;
}
KURL Document::completeURL(const String& url) const
{
// Always return a null URL when passed a null string.
// FIXME: Should we change the KURL constructor to have this behavior?
// See also [CSS]StyleSheet::completeURL(const String&)
if (url.isNull())
return KURL();
const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
if (!m_decoder)
return KURL(baseURL, url);
return KURL(baseURL, url, m_decoder->encoding());
}
void Document::setInPageCache(bool flag)
{
if (m_inPageCache == flag)
return;
m_inPageCache = flag;
if (flag) {
ASSERT(!m_savedRenderer);
m_savedRenderer = renderer();
if (FrameView* v = view())
v->resetScrollbars();
m_styleRecalcTimer.stop();
} else {
ASSERT(!renderer() || renderer() == m_savedRenderer);
ASSERT(m_renderArena);
setRenderer(m_savedRenderer);
m_savedRenderer = 0;
if (frame() && frame()->page())
frame()->page()->updateViewportArguments();
if (childNeedsStyleRecalc())
scheduleStyleRecalc();
}
}
void Document::documentWillBecomeInactive()
{
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->willMoveOffscreen();
#endif
HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
(*i)->documentWillBecomeInactive();
}
void Document::documentDidBecomeActive()
{
HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
(*i)->documentDidBecomeActive();
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->didMoveOnscreen();
#endif
ASSERT(m_frame);
m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
}
void Document::registerForDocumentActivationCallbacks(Element* e)
{
m_documentActivationCallbackElements.add(e);
}
void Document::unregisterForDocumentActivationCallbacks(Element* e)
{
m_documentActivationCallbackElements.remove(e);
}
void Document::mediaVolumeDidChange()
{
HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
(*i)->mediaVolumeDidChange();
}
void Document::registerForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.add(e);
}
void Document::unregisterForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.remove(e);
}
void Document::setShouldCreateRenderers(bool f)
{
m_createRenderers = f;
}
bool Document::shouldCreateRenderers()
{
return m_createRenderers;
}
// Support for Javascript execCommand, and related methods
static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
{
Frame* frame = document->frame();
if (!frame || frame->document() != document)
return Editor::Command();
document->updateStyleIfNeeded();
return frame->editor()->command(commandName,
userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
}
bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
{
return command(this, commandName, userInterface).execute(value);
}
bool Document::queryCommandEnabled(const String& commandName)
{
return command(this, commandName).isEnabled();
}
bool Document::queryCommandIndeterm(const String& commandName)
{
return command(this, commandName).state() == MixedTriState;
}
bool Document::queryCommandState(const String& commandName)
{
return command(this, commandName).state() == TrueTriState;
}
bool Document::queryCommandSupported(const String& commandName)
{
return command(this, commandName).isSupported();
}
String Document::queryCommandValue(const String& commandName)
{
return command(this, commandName).value();
}
#if ENABLE(XSLT)
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
String resultMIMEType;
String newSource;
String resultEncoding;
if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
return;
// FIXME: If the transform failed we should probably report an error (like Mozilla does).
processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
}
void Document::setTransformSource(PassOwnPtr<TransformSource> source)
{
if (m_transformSource == source)
return;
m_transformSource = source;
}
#endif
void Document::setDesignMode(InheritedBool value)
{
m_designMode = value;
}
Document::InheritedBool Document::getDesignMode() const
{
return m_designMode;
}
bool Document::inDesignMode() const
{
for (const Document* d = this; d; d = d->parentDocument()) {
if (d->m_designMode != inherit)
return d->m_designMode;
}
return false;
}
Document* Document::parentDocument() const
{
if (!m_frame)
return 0;
Frame* parent = m_frame->tree()->parent();
if (!parent)
return 0;
return parent->document();
}
Document* Document::topDocument() const
{
Document* doc = const_cast<Document *>(this);
Element* element;
while ((element = doc->ownerElement()))
doc = element->document();
return doc;
}
PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
{
return createAttributeNS(String(), name, ec, true);
}
PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
// Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
if (!shouldIgnoreNamespaceChecks && qName.localName() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
ec = NAMESPACE_ERR;
return 0;
}
// FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
// documents if we're wrong.
return Attr::create(0, this, Attribute::createMapped(qName, StringImpl::empty()));
}
#if ENABLE(SVG)
const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions.get();
}
SVGDocumentExtensions* Document::accessSVGExtensions()
{
if (!m_svgExtensions)
m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
return m_svgExtensions.get();
}
bool Document::hasSVGRootNode() const
{
return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
}
#endif
PassRefPtr<HTMLCollection> Document::images()
{
return HTMLCollection::create(this, DocImages);
}
PassRefPtr<HTMLCollection> Document::applets()
{
return HTMLCollection::create(this, DocApplets);
}
PassRefPtr<HTMLCollection> Document::embeds()
{
return HTMLCollection::create(this, DocEmbeds);
}
PassRefPtr<HTMLCollection> Document::plugins()
{
// This is an alias for embeds() required for the JS DOM bindings.
return HTMLCollection::create(this, DocEmbeds);
}
PassRefPtr<HTMLCollection> Document::objects()
{
return HTMLCollection::create(this, DocObjects);
}
PassRefPtr<HTMLCollection> Document::scripts()
{
return HTMLCollection::create(this, DocScripts);
}
PassRefPtr<HTMLCollection> Document::links()
{
return HTMLCollection::create(this, DocLinks);
}
PassRefPtr<HTMLCollection> Document::forms()
{
return HTMLCollection::create(this, DocForms);
}
PassRefPtr<HTMLCollection> Document::anchors()
{
return HTMLCollection::create(this, DocAnchors);
}
PassRefPtr<HTMLAllCollection> Document::all()
{
return HTMLAllCollection::create(this);
}
PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
{
return HTMLNameCollection::create(this, WindowNamedItems, name);
}
PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
{
return HTMLNameCollection::create(this, DocumentNamedItems, name);
}
CollectionCache* Document::nameCollectionInfo(CollectionType type, const AtomicString& name)
{
ASSERT(type >= FirstNamedDocumentCachedType);
unsigned index = type - FirstNamedDocumentCachedType;
ASSERT(index < NumNamedDocumentCachedTypes);
NamedCollectionMap& map = m_nameCollectionInfo[index];
NamedCollectionMap::iterator iter = map.find(name.impl());
if (iter == map.end())
iter = map.add(name.impl(), new CollectionCache).first;
iter->second->checkConsistency();
return iter->second;
}
void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsing(false);
if (!m_documentTiming.domContentLoadedEventStart)
m_documentTiming.domContentLoadedEventStart = currentTime();
dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
if (!m_documentTiming.domContentLoadedEventEnd)
m_documentTiming.domContentLoadedEventEnd = currentTime();
if (Frame* f = frame()) {
// FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
// resource loads are complete. HTMLObjectElements can start loading their resources from
// post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
// tag and then reach the end of the document without updating styles, we might not have yet
// started the resource load and might fire the window load event too early. To avoid this
// we force the styles to be up to date before calling FrameLoader::finishedParsing().
// See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
updateStyleIfNeeded();
f->loader()->finishedParsing();
InspectorInstrumentation::domContentLoadedEventFired(f, url());
}
}
Vector<String> Document::formElementsState() const
{
Vector<String> stateVector;
stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
typedef FormElementListHashSet::const_iterator Iterator;
Iterator end = m_formElementsWithState.end();
for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
Element* elementWithState = *it;
String value;
if (!elementWithState->shouldSaveAndRestoreFormControlState())
continue;
if (!elementWithState->saveFormControlState(value))
continue;
stateVector.append(elementWithState->formControlName().string());
stateVector.append(elementWithState->formControlType().string());
stateVector.append(value);
}
return stateVector;
}
#if ENABLE(XPATH)
PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
XPathNSResolver* resolver,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createExpression(expression, resolver, ec);
}
PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createNSResolver(nodeResolver);
}
PassRefPtr<XPathResult> Document::evaluate(const String& expression,
Node* contextNode,
XPathNSResolver* resolver,
unsigned short type,
XPathResult* result,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
}
#endif // ENABLE(XPATH)
void Document::setStateForNewFormElements(const Vector<String>& stateVector)
{
// Walk the state vector backwards so that the value to use for each
// name/type pair first is the one at the end of each individual vector
// in the FormElementStateMap. We're using them like stacks.
typedef FormElementStateMap::iterator Iterator;
m_formElementsWithState.clear();
for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
AtomicString a = stateVector[i - 3];
AtomicString b = stateVector[i - 2];
const String& c = stateVector[i - 1];
FormElementKey key(a.impl(), b.impl());
Iterator it = m_stateForNewFormElements.find(key);
if (it != m_stateForNewFormElements.end())
it->second.append(c);
else {
Vector<String> v(1);
v[0] = c;
m_stateForNewFormElements.set(key, v);
}
}
}
bool Document::hasStateForNewFormElements() const
{
return !m_stateForNewFormElements.isEmpty();
}
bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
{
typedef FormElementStateMap::iterator Iterator;
Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
if (it == m_stateForNewFormElements.end())
return false;
ASSERT(it->second.size());
state = it->second.last();
if (it->second.size() > 1)
it->second.removeLast();
else
m_stateForNewFormElements.remove(it);
return true;
}
FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
: m_name(name), m_type(type)
{
ref();
}
FormElementKey::~FormElementKey()
{
deref();
}
FormElementKey::FormElementKey(const FormElementKey& other)
: m_name(other.name()), m_type(other.type())
{
ref();
}
FormElementKey& FormElementKey::operator=(const FormElementKey& other)
{
other.ref();
deref();
m_name = other.name();
m_type = other.type();
return *this;
}
void FormElementKey::ref() const
{
if (name())
name()->ref();
if (type())
type()->ref();
}
void FormElementKey::deref() const
{
if (name())
name()->deref();
if (type())
type()->deref();
}
unsigned FormElementKeyHash::hash(const FormElementKey& key)
{
return WTF::StringHasher::createBlobHash<sizeof(FormElementKey)>(&key);
}
void Document::setIconURL(const String& iconURL, const String& type)
{
// FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "type"
if (m_iconURL.isEmpty())
m_iconURL = iconURL;
else if (!type.isEmpty())
m_iconURL = iconURL;
if (Frame* f = frame())
f->loader()->setIconURL(m_iconURL);
}
void Document::registerFormElementWithFormAttribute(FormAssociatedElement* element)
{
ASSERT(toHTMLElement(element)->fastHasAttribute(formAttr));
m_formElementsWithFormAttribute.add(element);
}
void Document::unregisterFormElementWithFormAttribute(FormAssociatedElement* element)
{
m_formElementsWithFormAttribute.remove(element);
}
void Document::resetFormElementsOwner(HTMLFormElement* form)
{
typedef FormAssociatedElementListHashSet::iterator Iterator;
Iterator end = m_formElementsWithFormAttribute.end();
for (Iterator it = m_formElementsWithFormAttribute.begin(); it != end; ++it)
(*it)->resetFormOwner(form);
}
void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
{
if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
return;
m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
m_frame->selection()->updateSecureKeyboardEntryIfActive();
}
bool Document::useSecureKeyboardEntryWhenActive() const
{
return m_useSecureKeyboardEntryWhenActive;
}
void Document::initSecurityContext()
{
if (securityOrigin() && !securityOrigin()->isEmpty())
return; // m_securityOrigin has already been initialized.
if (!m_frame) {
// No source for a security context.
// This can occur via document.implementation.createDocument().
m_cookieURL = KURL(ParsedURLString, "");
ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::createEmpty());
return;
}
// In the common case, create the security context from the currently
// loading URL.
m_cookieURL = m_url;
ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::create(m_url, m_frame->loader()->sandboxFlags()));
if (SecurityOrigin::allowSubstituteDataAccessToLocal()) {
// If this document was loaded with substituteData, then the document can
// load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
// and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
// discussion.
if (m_documentLoader->substituteData().isValid())
securityOrigin()->grantLoadLocalResources();
}
if (Settings* settings = this->settings()) {
if (!settings->isWebSecurityEnabled()) {
// Web security is turned off. We should let this document access every
// other document. This is used primary by testing harnesses for web
// sites.
securityOrigin()->grantUniversalAccess();
} else if (settings->allowUniversalAccessFromFileURLs() && securityOrigin()->isLocal()) {
// Some clients want file:// URLs to have universal access, but that
// setting is dangerous for other clients.
securityOrigin()->grantUniversalAccess();
} else if (!settings->allowFileAccessFromFileURLs() && securityOrigin()->isLocal()) {
// Some clients want file:// URLs to have even tighter restrictions by
// default, and not be able to access other local files.
securityOrigin()->enforceFilePathSeparation();
}
}
if (!securityOrigin()->isEmpty())
return;
// If we do not obtain a meaningful origin from the URL, then we try to
// find one via the frame hierarchy.
Frame* ownerFrame = m_frame->tree()->parent();
if (!ownerFrame)
ownerFrame = m_frame->loader()->opener();
if (ownerFrame) {
m_cookieURL = ownerFrame->document()->cookieURL();
// We alias the SecurityOrigins to match Firefox, see Bug 15313
// https://bugs.webkit.org/show_bug.cgi?id=15313
ScriptExecutionContext::setSecurityOrigin(ownerFrame->document()->securityOrigin());
}
}
void Document::setSecurityOrigin(SecurityOrigin* securityOrigin)
{
ScriptExecutionContext::setSecurityOrigin(securityOrigin);
// FIXME: Find a better place to enable DNS prefetch, which is a loader concept,
// not applicable to arbitrary documents.
initDNSPrefetch();
}
#if ENABLE(DATABASE)
bool Document::allowDatabaseAccess() const
{
if (!page() || page()->settings()->privateBrowsingEnabled())
return false;
return true;
}
void Document::databaseExceededQuota(const String& name)
{
Page* currentPage = page();
if (currentPage)
currentPage->chrome()->client()->exceededDatabaseQuota(document()->frame(), name);
}
#endif
bool Document::isContextThread() const
{
return isMainThread();
}
void Document::updateURLForPushOrReplaceState(const KURL& url)
{
Frame* f = frame();
if (!f)
return;
setURL(url);
f->loader()->setOutgoingReferrer(url);
m_documentLoader->replaceRequestURLForSameDocumentNavigation(url);
}
void Document::statePopped(SerializedScriptValue* stateObject)
{
if (!frame())
return;
// Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
// defer firing of popstate until we're in the complete state.
if (m_readyState == Complete)
enqueuePopstateEvent(stateObject);
else
m_pendingStateObject = stateObject;
}
void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
{
m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
if (!m_updateFocusAppearanceTimer.isActive())
m_updateFocusAppearanceTimer.startOneShot(0);
}
void Document::cancelFocusAppearanceUpdate()
{
m_updateFocusAppearanceTimer.stop();
}
void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
{
Node* node = focusedNode();
if (!node)
return;
if (!node->isElementNode())
return;
updateLayout();
Element* element = static_cast<Element*>(node);
if (element->isFocusable())
element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
}
// FF method for accessing the selection added for compatibility.
DOMSelection* Document::getSelection() const
{
return frame() ? frame()->domWindow()->getSelection() : 0;
}
#if ENABLE(WML)
void Document::resetWMLPageState()
{
if (WMLPageState* pageState = wmlPageStateForDocument(this))
pageState->reset();
}
void Document::initializeWMLPageState()
{
if (!isWMLDocument())
return;
static_cast<WMLDocument*>(this)->initialize();
}
#endif
void Document::attachRange(Range* range)
{
ASSERT(!m_ranges.contains(range));
m_ranges.add(range);
}
void Document::detachRange(Range* range)
{
// We don't ASSERT m_ranges.contains(range) to allow us to call this
// unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
m_ranges.remove(range);
}
CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
{
HTMLCanvasElement* result = getCSSCanvasElement(name);
if (!result)
return 0;
result->setSize(IntSize(width, height));
return result->getContext(type);
}
HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
{
RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
if (!result) {
result = HTMLCanvasElement::create(this);
m_cssCanvasElements.set(name, result);
}
return result.get();
}
void Document::initDNSPrefetch()
{
Settings* settings = this->settings();
m_haveExplicitlyDisabledDNSPrefetch = false;
m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
// Inherit DNS prefetch opt-out from parent frame
if (Document* parent = parentDocument()) {
if (!parent->isDNSPrefetchEnabled())
m_isDNSPrefetchEnabled = false;
}
}
void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
{
if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
m_isDNSPrefetchEnabled = true;
return;
}
m_isDNSPrefetchEnabled = false;
m_haveExplicitlyDisabledDNSPrefetch = true;
}
void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
{
if (DOMWindow* window = domWindow())
window->console()->addMessage(source, type, level, message, lineNumber, sourceURL, callStack);
}
struct PerformTaskContext {
WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
public:
PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
: documentReference(documentReference)
, task(task)
{
}
RefPtr<DocumentWeakReference> documentReference;
OwnPtr<ScriptExecutionContext::Task> task;
};
static void performTask(void* ctx)
{
ASSERT(isMainThread());
PerformTaskContext* context = reinterpret_cast<PerformTaskContext*>(ctx);
ASSERT(context);
if (Document* document = context->documentReference->document())
context->task->performTask(document);
delete context;
}
void Document::postTask(PassOwnPtr<Task> task)
{
callOnMainThread(performTask, new PerformTaskContext(m_weakReference, task));
}
Element* Document::findAnchor(const String& name)
{
if (name.isEmpty())
return 0;
if (Element* element = getElementById(name))
return element;
for (Node* node = this; node; node = node->traverseNextNode()) {
if (node->hasTagName(aTag)) {
HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(node);
if (inQuirksMode()) {
// Quirks mode, case insensitive comparison of names.
if (equalIgnoringCase(anchor->name(), name))
return anchor;
} else {
// Strict mode, names need to match exactly.
if (anchor->name() == name)
return anchor;
}
}
}
return 0;
}
String Document::displayStringModifiedByEncoding(const String& str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str.impl());
return str;
}
PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str);
return str;
}
void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
{
if (m_decoder)
m_decoder->encoding().displayBuffer(buffer, len);
}
void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
{
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
}
void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
{
enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
}
void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
{
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
dispatchWindowEvent(PopStateEvent::create(stateObject));
}
void Document::addMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(!m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.add(listener);
}
void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.remove(listener);
}
MediaCanStartListener* Document::takeAnyMediaCanStartListener()
{
HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
if (slot == m_mediaCanStartListeners.end())
return 0;
MediaCanStartListener* listener = *slot;
m_mediaCanStartListeners.remove(slot);
return listener;
}
#if ENABLE(XHTMLMP)
bool Document::isXHTMLMPDocument() const
{
if (!frame() || !frame()->loader())
return false;
// As per section 7.2 of OMA-WAP-XHTMLMP-V1_1-20061020-A.pdf, a conforming user agent
// MUST accept XHTMLMP document identified as "application/vnd.wap.xhtml+xml"
// and SHOULD accept it identified as "application/xhtml+xml" , "application/xhtml+xml" is a
// general MIME type for all XHTML documents, not only for XHTMLMP
return frame()->loader()->writer()->mimeType() == "application/vnd.wap.xhtml+xml";
}
#endif
#if ENABLE(FULLSCREEN_API)
void Document::webkitRequestFullScreenForElement(Element* element, unsigned short flags)
{
if (!page() || !page()->settings()->fullScreenEnabled())
return;
if (!element)
element = documentElement();
if (!page()->chrome()->client()->supportsFullScreenForElement(element))
return;
m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
page()->chrome()->client()->enterFullScreenForElement(element);
}
void Document::webkitCancelFullScreen()
{
if (!page() || !m_fullScreenElement)
return;
page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
}
void Document::webkitWillEnterFullScreenForElement(Element* element)
{
ASSERT(element);
ASSERT(page() && page()->settings()->fullScreenEnabled());
m_fullScreenElement = element;
m_isFullScreen = true;
if (m_fullScreenElement != documentElement())
m_fullScreenElement->detach();
recalcStyle(Force);
if (m_fullScreenRenderer)
m_fullScreenRenderer->setAnimating(true);
}
void Document::webkitDidEnterFullScreenForElement(Element*)
{
if (m_fullScreenRenderer)
m_fullScreenRenderer->setAnimating(false);
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::webkitWillExitFullScreenForElement(Element*)
{
if (m_fullScreenRenderer)
m_fullScreenRenderer->setAnimating(true);
recalcStyle(Force);
}
void Document::webkitDidExitFullScreenForElement(Element*)
{
m_isFullScreen = false;
m_areKeysEnabledInFullScreen = false;
if (m_fullScreenRenderer)
m_fullScreenRenderer->remove();
if (m_fullScreenElement != documentElement())
m_fullScreenElement->detach();
setFullScreenRenderer(0);
recalcStyle(Force);
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::setFullScreenRenderer(RenderFullScreen* renderer)
{
m_fullScreenRenderer = renderer;
// This notification can come in after the page has been destroyed.
if (page())
page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
}
void Document::setFullScreenRendererSize(const IntSize& size)
{
ASSERT(m_fullScreenRenderer);
if (!m_fullScreenRenderer)
return;
if (m_fullScreenRenderer) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setWidth(Length(size.width(), WebCore::Fixed));
newStyle->setHeight(Length(size.height(), WebCore::Fixed));
newStyle->setTop(Length(0, WebCore::Fixed));
newStyle->setLeft(Length(0, WebCore::Fixed));
m_fullScreenRenderer->setStyle(newStyle);
}
}
void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
{
if (!m_fullScreenRenderer)
return;
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setBackgroundColor(backgroundColor);
m_fullScreenRenderer->setStyle(newStyle);
}
void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
{
Element* element = m_fullScreenElement.get();
if (!element)
element = documentElement();
element->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
}
#endif
void Document::decrementLoadEventDelayCount()
{
ASSERT(m_loadEventDelayCount);
--m_loadEventDelayCount;
if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
m_loadEventDelayTimer.startOneShot(0);
}
void Document::loadEventDelayTimerFired(Timer<Document>*)
{
if (frame())
frame()->loader()->checkCompleted();
}
#if ENABLE(REQUEST_ANIMATION_FRAME)
int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* e)
{
if (!m_requestAnimationFrameCallbacks)
m_requestAnimationFrameCallbacks = new RequestAnimationFrameCallbackList;
int id = m_nextRequestAnimationFrameCallbackId++;
callback->m_firedOrCancelled = false;
callback->m_id = id;
callback->m_element = e;
m_requestAnimationFrameCallbacks->append(callback);
if (FrameView* v = view())
v->scheduleAnimation();
return id;
}
void Document::webkitCancelRequestAnimationFrame(int id)
{
if (!m_requestAnimationFrameCallbacks)
return;
for (size_t i = 0; i < m_requestAnimationFrameCallbacks->size(); ++i) {
if (m_requestAnimationFrameCallbacks->at(i)->m_id == id) {
m_requestAnimationFrameCallbacks->at(i)->m_firedOrCancelled = true;
m_requestAnimationFrameCallbacks->remove(i);
return;
}
}
}
void Document::serviceScriptedAnimations(DOMTimeStamp time)
{
if (!m_requestAnimationFrameCallbacks)
return;
// We want to run the callback for all elements in the document that have registered
// for a callback and that are visible. Running the callbacks can cause new callbacks
// to be registered, existing callbacks to be cancelled, and elements to gain or lose
// visibility so this code has to iterate carefully.
// FIXME: Currently, this code doesn't do any visibility tests beyond checking display:
// First, generate a list of callbacks to consider. Callbacks registered from this point
// on are considered only for the "next" frame, not this one.
RequestAnimationFrameCallbackList callbacks(*m_requestAnimationFrameCallbacks);
// Firing the callback may cause the visibility of other elements to change. To avoid
// missing any callbacks, we keep iterating through the list of candiate callbacks and firing
// them until nothing new becomes visible.
bool firedCallback;
do {
firedCallback = false;
// A previous iteration may have invalidated style (or layout). Update styles for each iteration
// for now since all we check is the existence of a renderer.
updateStyleIfNeeded();
for (size_t i = 0; i < callbacks.size(); ++i) {
RequestAnimationFrameCallback* callback = callbacks[i].get();
if (!callback->m_firedOrCancelled && (!callback->m_element || callback->m_element->renderer())) {
callback->m_firedOrCancelled = true;
callback->handleEvent(time);
firedCallback = true;
callbacks.remove(i);
break;
}
}
} while (firedCallback);
// Remove any callbacks we fired from the list of pending callbacks.
for (size_t i = 0; i < m_requestAnimationFrameCallbacks->size();) {
if (m_requestAnimationFrameCallbacks->at(i)->m_firedOrCancelled)
m_requestAnimationFrameCallbacks->remove(i);
else
++i;
}
// In most cases we expect this list to be empty, so no need to keep around the vector's inline buffer.
if (!m_requestAnimationFrameCallbacks->size())
m_requestAnimationFrameCallbacks.clear();
else if (FrameView* v = view())
v->scheduleAnimation();
}
#endif
#if ENABLE(TOUCH_EVENTS)
PassRefPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, ExceptionCode&) const
{
// FIXME: It's not clear from the documentation at
// http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
// when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
// and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
// Ditto for the createTouchList method below.
Frame* frame = window ? window->frame() : this->frame();
return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY);
}
PassRefPtr<TouchList> Document::createTouchList(ExceptionCode&) const
{
return TouchList::create();
}
#endif
static bool hasHeadSibling(const Document* document)
{
Node* de = document->documentElement();
if (!de)
return false;
for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
// A child of the document element which is rather than <head> is
// typically visible and FOUC safe. So we return true here.
if (!i->hasTagName(headTag))
return true;
}
return false;
}
bool Document::mayCauseFlashOfUnstyledContent() const
{
// Some kind of FOUC is caused by a repaint request before page's <body> arrival
// because page authors often give background styles to <body>, not to <html>.
// (And these styles are unavailable before <style> or <link> is given.)
// This functions is used for checking such possibility of FOUCs.
// Note that the implementation considers only empty or <head> only contents as a FOUC cause
// rather than missing <body>, because non-HTML document like SVG and arbitrary XML from foreign namespace
// should be painted even if there is no <body>.
if (didLayoutWithPendingStylesheets())
return true;
return !hasHeadSibling(this);
}
} // namespace WebCore
|