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
|
/**
* This file is part of the DOM implementation for KDE.
*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "config.h"
#include "Document.h"
#include "CDATASection.h"
#include "Comment.h"
#include "DOMImplementation.h"
#include "DocLoader.h"
#include "DocumentFragment.h"
#include "DocumentType.h"
#include "EditingText.h"
#include "EventNames.h"
#include "ExceptionCode.h"
#include "Frame.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HTMLInputElement.h"
#include "HTMLNameCollection.h"
#include "AccessibilityObjectCache.h"
#include "PlatformKeyboardEvent.h"
#include "Logging.h"
#include "MouseEventWithHitTestResults.h"
#include "NameNodeList.h"
#include "SegmentedString.h"
#include "SelectionController.h"
#include "SystemTime.h"
#include "VisiblePosition.h"
#include "css_stylesheetimpl.h"
#include "css_valueimpl.h"
#include "csshelper.h"
#include "cssstyleselector.h"
#include "CSSValueKeywords.h"
#include "decoder.h"
#include "dom2_eventsimpl.h"
#include "Range.h"
#include "AbstractView.h"
#include "dom_xmlimpl.h"
#include "kjs_binding.h"
#include "kjs_proxy.h"
#include "html_baseimpl.h"
#include "HTMLDocument.h"
#include "html_headimpl.h"
#include "html_imageimpl.h"
#include "HTMLElementFactory.h"
#include "HTMLNames.h"
#include "JSEditor.h"
#include "khtml_settings.h"
#include "RenderArena.h"
#include "RenderCanvas.h"
#include "render_frames.h"
#include "TextIterator.h"
#include "xml_tokenizer.h"
#include "xmlhttprequest.h"
#include <qregexp.h>
#ifdef KHTML_XSLT
#include "XSLStyleSheet.h"
#include "XSLTProcessor.h"
#endif
#ifndef KHTML_NO_XBL
#include "xbl_binding_manager.h"
using XBL::XBLBindingManager;
#endif
#if SVG_SUPPORT
#include "SVGNames.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementFactory.h"
#include "SVGZoomEvent.h"
#include "SVGStyleElement.h"
#include "KSVGTimeScheduler.h"
#endif
namespace WebCore {
using namespace EventNames;
using namespace HTMLNames;
// #define INSTRUMENT_LAYOUT_SCHEDULING 1
// 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. :)
const int cLayoutScheduleThreshold = 250;
// Use 1 to represent the document's default form.
HTMLFormElement* const defaultForm = (HTMLFormElement*) 1;
// 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 = U_GC_LL_MASK | U_GC_LU_MASK | U_GC_LO_MASK | U_GC_LT_MASK | U_GC_NL_MASK;
if (!(U_GET_GC_MASK(c) & nameStartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
UDecompositionType decompType = static_cast<UDecompositionType>(u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE));
if (decompType == U_DT_FONT || decompType == U_DT_COMPAT)
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 = U_GC_MC_MASK | U_GC_ME_MASK | U_GC_MN_MASK | U_GC_LM_MASK | U_GC_ND_MASK;
if (!(U_GET_GC_MASK(c) & otherNamePartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
UDecompositionType decompType = static_cast<UDecompositionType>(u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE));
if (decompType == U_DT_FONT || decompType == U_DT_COMPAT)
return false;
return true;
}
DeprecatedPtrList<Document> * Document::changedDocuments = 0;
// FrameView might be 0
Document::Document(DOMImplementation* impl, FrameView *v)
: ContainerNode(0)
, m_implementation(impl)
, m_domtree_version(0)
, m_styleSheets(new StyleSheetList)
, m_title("")
, m_titleSetExplicitly(false)
, m_imageLoadEventTimer(this, &Document::imageLoadEventTimerFired)
#if !KHTML_NO_XBL
, m_bindingManager(new XBLBindingManager(this))
#endif
#ifdef KHTML_XSLT
, m_transformSource(0)
#endif
, m_savedRenderer(0)
, m_passwordFields(0)
, m_secureForms(0)
, m_designMode(inherit)
, m_selfOnlyRefCount(0)
#if SVG_SUPPORT
, m_svgExtensions(0)
#endif
#if __APPLE__
, m_hasDashboardRegions(false)
, m_dashboardRegionsDirty(false)
#endif
, m_accessKeyMapValid(false)
, m_createRenderers(true)
, m_inPageCache(false)
{
document.resetSkippingRef(this);
m_printing = false;
m_view = v;
m_renderArena = 0;
m_accCache = 0;
m_docLoader = new DocLoader(v ? v->frame() : 0, this);
visuallyOrdered = false;
m_loadingSheet = false;
m_bParsing = false;
m_docChanged = false;
m_tokenizer = 0;
pMode = Strict;
hMode = XHtml;
m_textColor = Color::black;
m_elementNames = 0;
m_elementNameAlloc = 0;
m_elementNameCount = 0;
m_attrNames = 0;
m_attrNameAlloc = 0;
m_attrNameCount = 0;
m_defaultView = new AbstractView(this);
m_listenerTypes = 0;
m_inDocument = true;
m_styleSelectorDirty = false;
m_inStyleRecalc = false;
m_closeAfterStyleRecalc = false;
m_usesDescendantRules = false;
m_usesSiblingRules = false;
m_styleSelector = new CSSStyleSelector(this, m_usersheet, m_styleSheets.get(), !inCompatMode());
m_windowEventListeners.setAutoDelete(true);
m_pendingStylesheets = 0;
m_ignorePendingStylesheets = false;
m_cssTarget = 0;
resetLinkColor();
resetVisitedLinkColor();
resetActiveLinkColor();
m_processingLoadEvent = false;
m_startTime = currentTime();
m_overMinimumLayoutThreshold = false;
m_jsEditor = 0;
static int docID = 0;
m_docID = docID++;
}
void Document::removedLastRef()
{
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
DocPtr<Document> guard(this);
// 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_focusNode = 0;
m_hoverNode = 0;
m_activeNode = 0;
m_titleElement = 0;
removeAllChildren();
} else
delete this;
}
Document::~Document()
{
assert(!renderer());
assert(!m_inPageCache);
assert(m_savedRenderer == 0);
#if SVG_SUPPORT
delete m_svgExtensions;
#endif
XMLHttpRequest::detachRequests(this);
KJS::ScriptInterpreter::forgetAllDOMNodesForDocument(this);
if (m_docChanged && changedDocuments)
changedDocuments->remove(this);
delete m_tokenizer;
document.resetSkippingRef(0);
delete m_styleSelector;
delete m_docLoader;
if (m_elementNames) {
for (unsigned short id = 0; id < m_elementNameCount; id++)
m_elementNames[id]->deref();
delete [] m_elementNames;
}
if (m_attrNames) {
for (unsigned short id = 0; id < m_attrNameCount; id++)
m_attrNames[id]->deref();
delete [] m_attrNames;
}
if (m_renderArena) {
delete m_renderArena;
m_renderArena = 0;
}
#ifdef KHTML_XSLT
xmlFreeDoc((xmlDocPtr)m_transformSource);
#endif
#ifndef KHTML_NO_XBL
delete m_bindingManager;
#endif
deleteAllValues(m_markers);
if (m_accCache){
delete m_accCache;
m_accCache = 0;
}
m_decoder = 0;
if (m_jsEditor) {
delete m_jsEditor;
m_jsEditor = 0;
}
deleteAllValues(m_selectedRadioButtons);
}
void Document::resetLinkColor()
{
m_linkColor = Color(0, 0, 238);
}
void Document::resetVisitedLinkColor()
{
m_visitedLinkColor = Color(85, 26, 139);
}
void Document::resetActiveLinkColor()
{
m_activeLinkColor.setNamedColor(DeprecatedString("red"));
}
void Document::setDocType(PassRefPtr<DocumentType> docType)
{
m_docType = docType;
}
DocumentType *Document::doctype() const
{
return m_docType.get();
}
DOMImplementation* Document::implementation() const
{
return m_implementation.get();
}
Element* Document::documentElement() const
{
Node* n = firstChild();
while (n && !n->isElementNode())
n = n->nextSibling();
return static_cast<Element*>(n);
}
PassRefPtr<Element> Document::createElement(const String &name, ExceptionCode& ec)
{
return createElementNS(nullAtom, name, ec);
}
PassRefPtr<DocumentFragment> Document::createDocumentFragment()
{
return new DocumentFragment(getDocument());
}
PassRefPtr<Text> Document::createTextNode(const String &data)
{
return new Text(this, data);
}
PassRefPtr<Comment> Document::createComment (const String &data)
{
return new Comment(this, data);
}
PassRefPtr<CDATASection> Document::createCDATASection(const String &data, ExceptionCode& ec)
{
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return new CDATASection(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 new ProcessingInstruction(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 new EntityReference(this, name.impl());
}
PassRefPtr<EditingText> Document::createEditingTextNode(const String &text)
{
return new EditingText(this, text);
}
PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
{
return new CSSMutableStyleDeclaration;
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
{
ec = 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->tagName().toString(), ec);
if (ec != 0)
return 0;
NamedAttrMap* 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 != 0)
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 != 0)
return 0;
newElement->appendChild(newChild.release(), ec);
if (ec != 0)
return 0;
}
}
return newElement.release();
}
case ATTRIBUTE_NODE:
case ENTITY_NODE:
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case DOCUMENT_FRAGMENT_NODE:
case NOTATION_NODE:
break;
}
ec = NOT_SUPPORTED_ERR;
return 0;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
{
if (!source)
return 0;
switch (source->nodeType()) {
case ENTITY_NODE:
case NOTATION_NODE:
return 0;
case DOCUMENT_NODE:
case DOCUMENT_TYPE_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->m_specified = true;
break;
}
default:
if (source->parentNode())
source->parentNode()->removeChild(source.get(), ec);
}
for (Node* node = source.get(); node; node = node->traverseNextNode(source.get())) {
KJS::ScriptInterpreter::updateDOMNodeDocument(node, node->getDocument(), this);
node->setDocument(this);
}
return source;
}
PassRefPtr<Element> Document::createElementNS(const String &_namespaceURI, const String &qualifiedName, ExceptionCode& ec)
{
// FIXME: We'd like a faster code path that skips this check for calls from inside the engine where the name is known to be valid.
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
RefPtr<Element> e;
QualifiedName qName = QualifiedName(AtomicString(prefix), AtomicString(localName), AtomicString(_namespaceURI));
// FIXME: Use registered namespaces and look up in a hash to find the right factory.
if (_namespaceURI == xhtmlNamespaceURI) {
e = HTMLElementFactory::createHTMLElement(qName.localName(), this, 0, false);
if (e && !prefix.isNull()) {
e->setPrefix(qName.prefix(), ec);
if (ec)
return 0;
}
}
#if SVG_SUPPORT
else if (_namespaceURI == WebCore::SVGNames::svgNamespaceURI)
e = WebCore::SVGElementFactory::createSVGElement(qName, this, false);
#endif
if (!e)
e = new Element(qName, getDocument());
return e.release();
}
Element *Document::getElementById(const AtomicString& elementId) const
{
if (elementId.length() == 0)
return 0;
Element *element = m_elementsById.get(elementId.impl());
if (element)
return element;
if (m_duplicateIds.contains(elementId.impl())) {
for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
if (n->isElementNode()) {
element = static_cast<Element*>(n);
if (element->hasID() && element->getAttribute(idAttr) == elementId) {
m_duplicateIds.remove(elementId.impl());
m_elementsById.set(elementId.impl(), element);
return element;
}
}
}
}
return 0;
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderer())
return 0;
RenderObject::NodeInfo nodeInfo(true, true);
renderer()->layer()->hitTest(nodeInfo, x, y);
Node* n = nodeInfo.innerNode();
while (n && !n->isElementNode())
n = n->parentNode();
return static_cast<Element*>(n);
}
void Document::addElementById(const AtomicString& elementId, Element* element)
{
if (!m_elementsById.contains(elementId.impl()))
m_elementsById.set(elementId.impl(), element);
else
m_duplicateIds.add(elementId.impl());
}
void Document::removeElementById(const AtomicString& elementId, Element* element)
{
if (m_elementsById.get(elementId.impl()) == element)
m_elementsById.remove(elementId.impl());
else
m_duplicateIds.remove(elementId.impl());
}
Element* Document::getElementByAccessKey(const String& key)
{
if (!key.length())
return 0;
if (!m_accessKeyMapValid) {
for (Node* n = this; 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());
}
void Document::updateTitle()
{
Frame *p = frame();
if (!p)
return;
p->setTitle(m_title);
}
void Document::setTitle(const String& title, Node* titleElement)
{
if (!titleElement) {
// Title set by JavaScript -- overrides any title elements.
m_titleSetExplicitly = true;
m_titleElement = 0;
} else if (titleElement != m_titleElement) {
if (m_titleElement)
// Only allow the first title element to change the title -- others have no effect.
return;
m_titleElement = titleElement;
}
if (m_title == title)
return;
m_title = title;
updateTitle();
}
void Document::removeTitle(Node *titleElement)
{
if (m_titleElement != titleElement)
return;
// FIXME: Ideally we might want this to search for the first remaining title element, and use it.
m_titleElement = 0;
if (!m_title.isEmpty()) {
m_title = "";
updateTitle();
}
}
String Document::nodeName() const
{
return "#document";
}
Node::NodeType Document::nodeType() const
{
return DOCUMENT_NODE;
}
DeprecatedString Document::nextState()
{
DeprecatedString state;
if (!m_state.isEmpty())
{
state = m_state.first();
m_state.remove(m_state.begin());
}
return state;
}
DeprecatedStringList Document::docState()
{
DeprecatedStringList s;
for (DeprecatedPtrListIterator<Node> it(m_maintainsState); it.current(); ++it)
s.append(it.current()->state());
return s;
}
Frame *Document::frame() const
{
return m_view ? m_view->frame() : 0;
}
PassRefPtr<Range> Document::createRange()
{
return new Range(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 new NodeIterator(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 new TreeWalker(root, whatToShow, filter, expandEntityReferences);
}
void Document::setDocumentChanged(bool b)
{
if (b) {
if (!m_docChanged) {
if (!changedDocuments)
changedDocuments = new DeprecatedPtrList<Document>;
changedDocuments->append(this);
}
if (m_accessKeyMapValid) {
m_accessKeyMapValid = false;
m_elementsByAccessKey.clear();
}
} else {
if (m_docChanged && changedDocuments)
changedDocuments->remove(this);
}
m_docChanged = b;
}
void Document::recalcStyle(StyleChange change)
{
if (m_inStyleRecalc)
return; // Guard against re-entrancy. -dwh
m_inStyleRecalc = true;
if (!renderer())
goto bail_out;
if (change == Force) {
RenderStyle* oldStyle = renderer()->style();
if (oldStyle) oldStyle->ref();
RenderStyle* _style = new (m_renderArena) RenderStyle();
_style->ref();
_style->setDisplay(BLOCK);
_style->setVisuallyOrdered(visuallyOrdered);
// ### make the font stuff _really_ work!!!!
FontDescription fontDescription;
fontDescription.setUsePrinterFont(printing());
if (m_view) {
const KHTMLSettings *settings = m_view->frame()->settings();
if (printing() && !settings->shouldPrintBackgrounds())
_style->setForceBackgroundsToWhite(true);
const AtomicString& stdfont = settings->stdFontName();
if (!stdfont.isEmpty()) {
fontDescription.firstFamily().setFamily(stdfont);
fontDescription.firstFamily().appendFamily(0);
}
m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSS_VAL_MEDIUM, inCompatMode()));
}
_style->setFontDescription(fontDescription);
_style->font().update();
if (inCompatMode())
_style->setHtmlHacks(true); // enable html specific rendering tricks
StyleChange ch = diff(_style, oldStyle);
if (renderer() && ch != NoChange)
renderer()->setStyle(_style);
if (change != Force)
change = ch;
_style->deref(m_renderArena);
if (oldStyle)
oldStyle->deref(m_renderArena);
}
for (Node* n = fastFirstChild(); n; n = n->nextSibling())
if (change >= Inherit || n->hasChangedChild() || n->changed())
n->recalcStyle(change);
if (changed() && m_view)
m_view->layout();
bail_out:
setChanged(false);
setHasChangedChild(false);
setDocumentChanged(false);
m_inStyleRecalc = false;
// If we wanted to emit the implicitClose() during recalcStyle, do so now that we're finished.
if (m_closeAfterStyleRecalc) {
m_closeAfterStyleRecalc = false;
implicitClose();
}
}
void Document::updateRendering()
{
if (hasChangedChild())
recalcStyle(NoChange);
}
void Document::updateDocumentsRendering()
{
if (!changedDocuments)
return;
while (Document* doc = changedDocuments->take()) {
doc->m_docChanged = false;
doc->updateRendering();
}
}
void Document::updateLayout()
{
// FIXME: Dave Hyatt's pretty sure we can remove this because layout calls recalcStyle as needed.
updateRendering();
// Only do a layout if changes have occurred that make it necessary.
if (m_view && renderer() && renderer()->needsLayout())
m_view->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;
updateStyleSelector();
}
updateLayout();
m_ignorePendingStylesheets = oldIgnore;
}
void Document::attach()
{
assert(!attached());
assert(!m_inPageCache);
if (!m_renderArena)
m_renderArena = new RenderArena();
// Create the rendering tree
setRenderer(new (m_renderArena) RenderCanvas(this, m_view));
recalcStyle(Force);
RenderObject* render = renderer();
setRenderer(0);
ContainerNode::attach();
setRenderer(render);
}
void Document::restoreRenderer(RenderObject* render)
{
setRenderer(render);
}
void Document::detach()
{
RenderObject* render = renderer();
// indicate destruction mode, i.e. attached() but renderer == 0
setRenderer(0);
if (m_inPageCache) {
#if __APPLE__
if (render)
getAccObjectCache()->detach(render);
#endif
return;
}
// Empty out these lists as a performance optimization, since detaching
// all the individual render objects will cause all the RenderImage
// objects to remove themselves from the lists.
m_imageLoadEventDispatchSoonList.clear();
m_imageLoadEventDispatchingList.clear();
m_hoverNode = 0;
m_focusNode = 0;
m_activeNode = 0;
ContainerNode::detach();
if (render)
render->destroy();
m_view = 0;
if (m_renderArena) {
delete m_renderArena;
m_renderArena = 0;
}
}
void Document::removeAllEventListenersFromAllNodes()
{
m_windowEventListeners.clear();
removeAllDisconnectedNodeEventListeners();
for (Node *n = this; n; n = n->traverseNextNode()) {
if (!n->isEventTargetNode())
continue;
EventTargetNodeCast(n)->removeAllEventListeners();
}
}
void Document::registerDisconnectedNodeWithEventListeners(Node* node)
{
m_disconnectedNodesWithEventListeners.add(node);
}
void Document::unregisterDisconnectedNodeWithEventListeners(Node* node)
{
m_disconnectedNodesWithEventListeners.remove(node);
}
void Document::removeAllDisconnectedNodeEventListeners()
{
NodeSet::iterator end = m_disconnectedNodesWithEventListeners.end();
for (NodeSet::iterator i = m_disconnectedNodesWithEventListeners.begin(); i != end; ++i)
EventTargetNodeCast((*i))->removeAllEventListeners();
m_disconnectedNodesWithEventListeners.clear();
}
AccessibilityObjectCache* Document::getAccObjectCache()
{
#if __APPLE__
// The only document that actually has a AccessibilityObjectCache 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_accCache) {
// return already known top-level cache
if (!ownerElement())
return m_accCache;
// 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.
delete m_accCache;
m_accCache = 0;
}
// ask the top-level document for its cache
Document *doc = topDocument();
if (doc != this)
return doc->getAccObjectCache();
// this is the top-level document, so install a new cache
m_accCache = new AccessibilityObjectCache;
#endif
return m_accCache;
}
void Document::setVisuallyOrdered()
{
visuallyOrdered = true;
if (renderer())
renderer()->style()->setVisuallyOrdered(true);
}
void Document::updateSelection()
{
if (!renderer())
return;
RenderCanvas *canvas = static_cast<RenderCanvas*>(renderer());
SelectionController s = frame()->selection();
if (!s.isRange()) {
canvas->clearSelection();
}
else {
Position startPos = VisiblePosition(s.start(), s.affinity()).deepEquivalent();
Position endPos = VisiblePosition(s.end(), s.affinity()).deepEquivalent();
if (startPos.isNotNull() && endPos.isNotNull()) {
RenderObject *startRenderer = startPos.node()->renderer();
RenderObject *endRenderer = endPos.node()->renderer();
static_cast<RenderCanvas*>(renderer())->setSelection(startRenderer, startPos.offset(), endRenderer, endPos.offset());
}
}
#if __APPLE__
// send the AXSelectedTextChanged notification only if the new selection is non-null,
// because null selections are only transitory (e.g. when starting an EditCommand, currently)
if (AccessibilityObjectCache::accessibilityEnabled() && s.start().isNotNull() && s.end().isNotNull()) {
getAccObjectCache()->postNotificationToTopWebArea(renderer(), "AXSelectedTextChanged");
}
#endif
}
Tokenizer *Document::createTokenizer()
{
return newXMLTokenizer(this, m_view);
}
void Document::open()
{
if ((frame() && frame()->isLoadingMainResource()) || (tokenizer() && tokenizer()->executingScript()))
return;
implicitOpen();
if (frame())
frame()->didExplicitOpen();
// This is work that we should probably do in clear(), but we can't have it
// happen when implicitOpen() is called unless we reorganize Frame code.
setURL(DeprecatedString());
if (Document *parent = parentDocument())
setBaseURL(parent->baseURL());
}
void Document::cancelParsing()
{
if (m_tokenizer) {
// We have to clear the tokenizer 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
delete m_tokenizer;
m_tokenizer = 0;
close();
}
}
void Document::implicitOpen()
{
cancelParsing();
clear();
m_tokenizer = createTokenizer();
setParsing(true);
}
HTMLElement* Document::body()
{
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 static_cast<HTMLElement*>(i);
if (i->hasTagName(bodyTag))
body = i;
}
return static_cast<HTMLElement *>(body);
}
void Document::close()
{
if (frame())
frame()->endIfNotLoading();
implicitClose();
}
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()->isScheduledLocationChangePending();
bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
if (!doload)
return;
m_processingLoadEvent = true;
// We have to clear the tokenizer, in case someone document.write()s from the
// onLoad event handler, as in Radar 3206524.
delete m_tokenizer;
m_tokenizer = 0;
// Create a body element if we don't already have one.
// In the case of Radar 3758785, the window.onload was set in some javascript, but never fired because there was no body.
// This behavior now matches Firefox and IE.
HTMLElement *body = this->body();
if (!body && isHTMLDocument()) {
Node *de = documentElement();
if (de) {
body = new HTMLBodyElement(this);
ExceptionCode ec = 0;
de->appendChild(body, ec);
if (ec != 0)
body = 0;
}
}
dispatchImageLoadEventsNow();
this->dispatchWindowEvent(loadEvent, false, false);
if (Frame *p = frame())
p->handledOnloadEvents();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("onload fired at %d\n", elapsedTime());
#endif
m_processingLoadEvent = false;
// 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() && frame()->isScheduledLocationChangePending() && 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;
}
if (frame())
frame()->checkEmitLoadEvent();
// Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
// that has been sized already. Otherwise, our view size would be incorrect, so doing any
// layout/painting now would be pointless.
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateRendering();
// Always do a layout after loading if needed.
if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
view()->layout();
}
#if __APPLE__
if (renderer() && AccessibilityObjectCache::accessibilityEnabled())
getAccObjectCache()->postNotification(renderer(), "AXLoadComplete");
#endif
#if SVG_SUPPORT
// FIXME: Officially, time 0 is when the outermost <svg> recieves 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()->timeScheduler()->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()
{
// We can update layout if:
// (a) we actually need a layout
// (b) our stylesheets are all loaded
// (c) we have a <body>
return (renderer() && renderer()->needsLayout() && haveStylesheetsLoaded() &&
documentElement() && documentElement()->renderer() &&
(!documentElement()->hasTagName(htmlTag) || body()));
}
int Document::minimumLayoutDelay()
{
if (m_overMinimumLayoutThreshold)
return 0;
int elapsed = elapsedTime();
m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
// We'll want to schedule the timer to fire at the minimum layout threshold.
return kMax(0, cLayoutScheduleThreshold - elapsed);
}
int Document::elapsedTime() const
{
return static_cast<int>((currentTime() - m_startTime) * 1000);
}
void Document::write(const String &text)
{
write(text.deprecatedString());
}
void Document::write(const DeprecatedString &text)
{
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning a document.write at %d\n", elapsedTime());
#endif
if (!m_tokenizer) {
open();
assert(m_tokenizer);
write(DeprecatedString("<html>"));
}
m_tokenizer->write(text, false);
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Ending a document.write at %d\n", elapsedTime());
#endif
}
void Document::writeln(const String &text)
{
write(text);
write(String("\n"));
}
void Document::finishParsing()
{
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Received all data at %d\n", elapsedTime());
#endif
// Let the tokenizer 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, tokenizer gets deleted
// (3) Data is still remaining to be parsed.
if (m_tokenizer)
m_tokenizer->finish();
}
void Document::clear()
{
delete m_tokenizer;
m_tokenizer = 0;
removeChildren();
DeprecatedPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
for (; it.current();)
m_windowEventListeners.removeRef(it.current());
}
void Document::setURL(const DeprecatedString& url)
{
m_url = url;
if (m_styleSelector)
m_styleSelector->setEncodedURL(m_url);
}
void Document::setStyleSheet(const String &url, const String &sheet)
{
m_sheet = new CSSStyleSheet(this, url);
m_sheet->parseString(sheet);
m_loadingSheet = false;
updateStyleSelector();
}
void Document::setUserStyleSheet(const DeprecatedString& sheet)
{
if (m_usersheet != sheet) {
m_usersheet = sheet;
updateStyleSelector();
}
}
CSSStyleSheet* Document::elementSheet()
{
if (!m_elemSheet)
m_elemSheet = new CSSStyleSheet(this, baseURL());
return m_elemSheet.get();
}
void Document::determineParseMode(const DeprecatedString &/*str*/)
{
// For XML documents use strict parse mode. HTML docs will override this method to
// determine their parse mode.
pMode = Strict;
hMode = XHtml;
}
Node *Document::nextFocusNode(Node *fromNode)
{
unsigned short fromTabIndex;
if (!fromNode) {
// No starting node supplied; begin with the top of the document
Node *n;
int lowestTabIndex = 65535;
for (n = this; n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable()) {
if ((n->tabIndex() > 0) && (n->tabIndex() < lowestTabIndex))
lowestTabIndex = n->tabIndex();
}
}
if (lowestTabIndex == 65535)
lowestTabIndex = 0;
// Go to the first node in the document that has the desired tab index
for (n = this; n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == lowestTabIndex))
return n;
}
return 0;
}
else {
fromTabIndex = fromNode->tabIndex();
}
if (fromTabIndex == 0) {
// Just need to find the next selectable node after fromNode (in document order) that doesn't have a tab index
Node *n = fromNode->traverseNextNode();
while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
n = n->traverseNextNode();
return n;
}
else {
// Find the lowest tab index out of all the nodes except fromNode, that is greater than or equal to fromNode's
// tab index. For nodes with the same tab index as fromNode, we are only interested in those that come after
// fromNode in document order.
// If we don't find a suitable tab index, the next focus node will be one with a tab index of 0.
unsigned short lowestSuitableTabIndex = 65535;
Node *n;
bool reachedFromNode = false;
for (n = this; n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() &&
((reachedFromNode && (n->tabIndex() >= fromTabIndex)) ||
(!reachedFromNode && (n->tabIndex() > fromTabIndex))) &&
(n->tabIndex() < lowestSuitableTabIndex) &&
(n != fromNode)) {
// We found a selectable node with a tab index at least as high as fromNode's. Keep searching though,
// as there may be another node which has a lower tab index but is still suitable for use.
lowestSuitableTabIndex = n->tabIndex();
}
if (n == fromNode)
reachedFromNode = true;
}
if (lowestSuitableTabIndex == 65535) {
// No next node with a tab index -> just take first node with tab index of 0
Node *n = this;
while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
n = n->traverseNextNode();
return n;
}
// Search forwards from fromNode
for (n = fromNode->traverseNextNode(); n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
return n;
}
// The next node isn't after fromNode, start from the beginning of the document
for (n = this; n != fromNode; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
return n;
}
assert(false); // should never get here
return 0;
}
}
Node *Document::previousFocusNode(Node *fromNode)
{
Node *lastNode = this;
while (lastNode->lastChild())
lastNode = lastNode->lastChild();
if (!fromNode) {
// No starting node supplied; begin with the very last node in the document
Node *n;
int highestTabIndex = 0;
for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
if (n->isKeyboardFocusable()) {
if (n->tabIndex() == 0)
return n;
else if (n->tabIndex() > highestTabIndex)
highestTabIndex = n->tabIndex();
}
}
// No node with a tab index of 0; just go to the last node with the highest tab index
for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
return n;
}
return 0;
}
else {
unsigned short fromTabIndex = fromNode->tabIndex();
if (fromTabIndex == 0) {
// Find the previous selectable node before fromNode (in document order) that doesn't have a tab index
Node *n = fromNode->traversePreviousNode();
while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
n = n->traversePreviousNode();
if (n)
return n;
// No previous nodes with a 0 tab index, go to the last node in the document that has the highest tab index
int highestTabIndex = 0;
for (n = this; n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() > highestTabIndex))
highestTabIndex = n->tabIndex();
}
if (highestTabIndex == 0)
return 0;
for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
return n;
}
assert(false); // should never get here
return 0;
}
else {
// Find the lowest tab index out of all the nodes except fromNode, that is less than or equal to fromNode's
// tab index. For nodes with the same tab index as fromNode, we are only interested in those before
// fromNode.
// If we don't find a suitable tab index, then there will be no previous focus node.
unsigned short highestSuitableTabIndex = 0;
Node *n;
bool reachedFromNode = false;
for (n = this; n != 0; n = n->traverseNextNode()) {
if (n->isKeyboardFocusable() &&
((!reachedFromNode && (n->tabIndex() <= fromTabIndex)) ||
(reachedFromNode && (n->tabIndex() < fromTabIndex))) &&
(n->tabIndex() > highestSuitableTabIndex) &&
(n != fromNode)) {
// We found a selectable node with a tab index no higher than fromNode's. Keep searching though, as
// there may be another node which has a higher tab index but is still suitable for use.
highestSuitableTabIndex = n->tabIndex();
}
if (n == fromNode)
reachedFromNode = true;
}
if (highestSuitableTabIndex == 0) {
// No previous node with a tab index. Since the order specified by HTML is nodes with tab index > 0
// first, this means that there is no previous node.
return 0;
}
// Search backwards from fromNode
for (n = fromNode->traversePreviousNode(); n != 0; n = n->traversePreviousNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
return n;
}
// The previous node isn't before fromNode, start from the end of the document
for (n = lastNode; n != fromNode; n = n->traversePreviousNode()) {
if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
return n;
}
assert(false); // should never get here
return 0;
}
}
}
int Document::nodeAbsIndex(Node *node)
{
assert(node->getDocument() == 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;
}
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;
updateStyleSelector();
}
else if (equalIgnoringCase(equiv, "refresh") && frame->metaRefreshEnabled())
{
// get delay and url
DeprecatedString str = content.deprecatedString().stripWhiteSpace();
int pos = str.find(RegularExpression("[;,]"));
if (pos == -1)
pos = str.find(RegularExpression("[ \t]"));
if (pos == -1) // There can be no url (David)
{
bool ok = false;
int delay = 0;
delay = str.toInt(&ok);
// We want a new history item if the refresh timeout > 1 second
if(ok && frame) frame->scheduleRedirection(delay, frame->url().url(), delay <= 1);
} else {
double delay = 0;
bool ok = false;
delay = str.left(pos).stripWhiteSpace().toDouble(&ok);
pos++;
while(pos < (int)str.length() && str[pos].isSpace()) pos++;
str = str.mid(pos);
if (str.find("url", 0, false) == 0)
str = str.mid(3);
str = str.stripWhiteSpace();
if (str.length() && str[0] == '=')
str = str.mid(1).stripWhiteSpace();
str = parseURL(String(str)).deprecatedString();
if (ok && frame)
// We want a new history item if the refresh timeout > 1 second
frame->scheduleRedirection(delay, completeURL(str), delay <= 1);
}
}
else if (equalIgnoringCase(equiv, "expires"))
{
DeprecatedString str = content.deprecatedString().stripWhiteSpace();
time_t expire_date = str.toInt();
if (m_docLoader)
m_docLoader->setExpireDate(expire_date);
}
else if ((equalIgnoringCase(equiv, "pragma") || equalIgnoringCase(equiv, "cache-control")) && frame)
{
DeprecatedString str = content.deprecatedString().lower().stripWhiteSpace();
KURL url = frame->url();
}
else if (equalIgnoringCase(equiv, "set-cookie"))
{
// ### make setCookie work on XML documents too; e.g. in case of <html:meta .....>
if (isHTMLDocument())
static_cast<HTMLDocument *>(this)->setCookie(content);
}
}
MouseEventWithHitTestResults Document::prepareMouseEvent(bool readonly, bool active, bool mouseMove,
int x, int y, const PlatformMouseEvent& event)
{
if (!renderer())
return MouseEventWithHitTestResults(event, String(), String(), 0);
assert(renderer()->isCanvas());
RenderObject::NodeInfo renderInfo(readonly, active, mouseMove);
renderer()->layer()->hitTest(renderInfo, x, y);
String href;
String target;
if (renderInfo.URLElement()) {
Element* e = renderInfo.URLElement();
href = parseURL(e->getAttribute(hrefAttr));
if (!href.isNull())
target = e->getAttribute(targetAttr);
}
if (!readonly)
updateRendering();
return MouseEventWithHitTestResults(event, href, target, renderInfo.innerNode());
}
// DOM Section 1.1.1
bool Document::childAllowed(Node *newChild)
{
// Documents may contain a maximum of one Element child
if (newChild->isElementNode()) {
Node *c;
for (c = firstChild(); c; c = c->nextSibling()) {
if (c->isElementNode())
return false;
}
}
// Documents may contain a maximum of one DocumentType child
if (newChild->nodeType() == DOCUMENT_TYPE_NODE) {
Node *c;
for (c = firstChild(); c; c = c->nextSibling()) {
if (c->nodeType() == DOCUMENT_TYPE_NODE)
return false;
}
}
return childTypeAllowed(newChild->nodeType());
}
bool Document::childTypeAllowed(NodeType type)
{
switch (type) {
case ELEMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
case COMMENT_NODE:
case DOCUMENT_TYPE_NODE:
return true;
default:
return false;
}
}
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()
{
return m_preferredStylesheetSet;
}
String Document::selectedStylesheetSet()
{
return m_selectedStylesheetSet;
}
void Document::setSelectedStylesheetSet(const String& aString)
{
m_selectedStylesheetSet = aString;
updateStyleSelector();
if (renderer())
renderer()->repaint();
}
// This method is called whenever a top-level stylesheet has finished loading.
void Document::stylesheetLoaded()
{
// 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
updateStyleSelector();
}
void Document::updateStyleSelector()
{
// Don't bother updating, since we haven't loaded all our style info yet.
if (!haveStylesheetsLoaded())
return;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning update of style selector at time %d.\n", elapsedTime());
#endif
recalcStyleSelector();
recalcStyle(Force);
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Finished update of style selector at time %d\n", elapsedTime());
#endif
if (renderer()) {
renderer()->setNeedsLayoutAndMinMaxRecalc();
if (view())
view()->scheduleRelayout();
}
}
DeprecatedStringList Document::availableStyleSheets() const
{
return m_availableSheets;
}
void Document::recalcStyleSelector()
{
if (!renderer() || !attached())
return;
DeprecatedPtrList<StyleSheet> oldStyleSheets = m_styleSheets->styleSheets;
m_styleSheets->styleSheets.clear();
m_availableSheets.clear();
Node *n;
for (n = this; n; n = n->traverseNextNode()) {
StyleSheet *sheet = 0;
if (n->nodeType() == PROCESSING_INSTRUCTION_NODE)
{
// Processing instruction (XML documents only)
ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
sheet = pi->sheet();
#ifdef KHTML_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
if (!sheet && !pi->localHref().isEmpty())
{
// Processing instruction with reference to an element in this document - e.g.
// <?xml-stylesheet href="#mystyle">, with the element
// <foo id="mystyle">heading { color: red; }</foo> at some location in
// the document
Element* elem = getElementById(pi->localHref().impl());
if (elem) {
String sheetText("");
Node *c;
for (c = elem->firstChild(); c; c = c->nextSibling()) {
if (c->nodeType() == TEXT_NODE || c->nodeType() == CDATA_SECTION_NODE)
sheetText += c->nodeValue();
}
CSSStyleSheet *cssSheet = new CSSStyleSheet(this);
cssSheet->parseString(sheetText);
pi->setStyleSheet(cssSheet);
sheet = cssSheet;
}
}
}
else if (n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) {
HTMLElement *e = static_cast<HTMLElement *>(n);
DeprecatedString title = e->getAttribute(titleAttr).deprecatedString();
bool enabledViaScript = false;
if (e->hasLocalName(linkTag)) {
// <LINK> element
HTMLLinkElement* l = static_cast<HTMLLinkElement*>(n);
if (l->isLoading() || l->isDisabled())
continue;
if (!l->sheet())
title = DeprecatedString::null;
enabledViaScript = l->isEnabledViaScript();
}
// Get the current preferred styleset. This is the
// set of sheets that will be enabled.
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.
DeprecatedString rel = e->getAttribute(relAttr).deprecatedString();
if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
m_preferredStylesheetSet = m_selectedStylesheetSet = title;
}
if (!m_availableSheets.contains(title))
m_availableSheets.append(title);
if (title != m_preferredStylesheetSet)
sheet = 0;
}
}
#if SVG_SUPPORT
else if (n->isSVGElement() && n->hasTagName(WebCore::SVGNames::styleTag)) {
DeprecatedString title;
// <STYLE> element
WebCore::SVGStyleElement *s = static_cast<WebCore::SVGStyleElement*>(n);
if (!s->isLoading()) {
sheet = s->sheet();
if(sheet)
title = s->getAttribute(WebCore::SVGNames::titleAttr).deprecatedString();
}
if (!title.isEmpty() && m_preferredStylesheetSet.isEmpty())
m_preferredStylesheetSet = m_selectedStylesheetSet = title;
if (!title.isEmpty()) {
if (title != m_preferredStylesheetSet)
sheet = 0; // don't use it
title = title.replace('&', "&&");
if (!m_availableSheets.contains(title))
m_availableSheets.append(title);
}
}
#endif
if (sheet) {
sheet->ref();
m_styleSheets->styleSheets.append(sheet);
}
// For HTML documents, stylesheets are not allowed within/after the <BODY> tag. So we
// can stop searching here.
if (isHTMLDocument() && n->hasTagName(bodyTag))
break;
}
// De-reference all the stylesheets in the old list
DeprecatedPtrListIterator<StyleSheet> it(oldStyleSheets);
for (; it.current(); ++it)
it.current()->deref();
// Create a new style selector
delete m_styleSelector;
DeprecatedString usersheet = m_usersheet;
if (m_view && m_view->mediaType() == "print")
usersheet += m_printSheet;
m_styleSelector = new CSSStyleSelector(this, usersheet, m_styleSheets.get(), !inCompatMode());
m_styleSelector->setEncodedURL(m_url);
m_styleSelectorDirty = false;
}
void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
{
m_hoverNode = newHoverNode;
}
void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
{
m_activeNode = newActiveNode;
}
void Document::hoveredNodeDetached(Node* node)
{
if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parent())))
return;
m_hoverNode = node->parent();
while (m_hoverNode && !m_hoverNode->renderer())
m_hoverNode = m_hoverNode->parent();
if (view())
view()->scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
{
if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parent())))
return;
m_activeNode = node->parent();
while (m_activeNode && !m_activeNode->renderer())
m_activeNode = m_activeNode->parent();
}
bool Document::relinquishesEditingFocus(Node *node)
{
assert(node);
assert(node->isContentEditable());
Node *root = node->rootEditableElement();
if (!frame() || !root)
return false;
return frame()->shouldEndEditing(rangeOfContents(root).get());
}
bool Document::acceptsEditingFocus(Node *node)
{
assert(node);
assert(node->isContentEditable());
Node *root = node->rootEditableElement();
if (!frame() || !root)
return false;
return frame()->shouldBeginEditing(rangeOfContents(root).get());
}
void Document::didBeginEditing()
{
if (!frame())
return;
frame()->didBeginEditing();
}
void Document::didEndEditing()
{
if (!frame())
return;
frame()->didEndEditing();
}
#if __APPLE__
const DeprecatedValueList<DashboardRegionValue> & Document::dashboardRegions() const
{
return m_dashboardRegions;
}
void Document::setDashboardRegions (const DeprecatedValueList<DashboardRegionValue>& regions)
{
m_dashboardRegions = regions;
setDashboardRegionsDirty (false);
}
#endif
static Widget *widgetForNode(Node *focusNode)
{
if (!focusNode)
return 0;
RenderObject *renderer = focusNode->renderer();
if (!renderer || !renderer->isWidget())
return 0;
return static_cast<RenderWidget *>(renderer)->widget();
}
bool Document::setFocusNode(PassRefPtr<Node> newFocusNode)
{
// Make sure newFocusNode is actually in this document
if (newFocusNode && (newFocusNode->getDocument() != this))
return true;
if (m_focusNode == newFocusNode)
return true;
if (m_focusNode && m_focusNode.get() == m_focusNode->rootEditableElement() && !relinquishesEditingFocus(m_focusNode.get()))
return false;
bool focusChangeBlocked = false;
RefPtr<Node> oldFocusNode = m_focusNode;
m_focusNode = 0;
clearSelectionIfNeeded(newFocusNode.get());
// Remove focus from the existing focus node (if any)
if (oldFocusNode && !oldFocusNode->m_inDetach) {
if (oldFocusNode->active())
oldFocusNode->setActive(false);
oldFocusNode->setFocus(false);
// Dispatch a change event for text fields or textareas that have been edited
RenderObject *r = static_cast<RenderObject*>(oldFocusNode.get()->renderer());
if (r && (r->isTextArea() || r->isTextField()) && r->isEdited()) {
EventTargetNodeCast(oldFocusNode.get())->dispatchHTMLEvent(changeEvent, true, false);
if ((r = static_cast<RenderObject*>(oldFocusNode.get()->renderer())))
r->setEdited(false);
}
EventTargetNodeCast(oldFocusNode.get())->dispatchHTMLEvent(blurEvent, false, false);
if (m_focusNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusNode = 0;
}
clearSelectionIfNeeded(newFocusNode.get());
EventTargetNodeCast(oldFocusNode.get())->dispatchUIEvent(DOMFocusOutEvent);
if (m_focusNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusNode = 0;
}
clearSelectionIfNeeded(newFocusNode.get());
if ((oldFocusNode.get() == this) && oldFocusNode->hasOneRef())
return true;
if (oldFocusNode.get() == oldFocusNode->rootEditableElement())
didEndEditing();
}
if (newFocusNode) {
if (newFocusNode == newFocusNode->rootEditableElement() && !acceptsEditingFocus(newFocusNode.get())) {
// delegate blocks focus change
focusChangeBlocked = true;
goto SetFocusNodeDone;
}
// Set focus on the new node
m_focusNode = newFocusNode.get();
EventTargetNodeCast(m_focusNode.get())->dispatchHTMLEvent(focusEvent, false, false);
if (m_focusNode != newFocusNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusNodeDone;
}
EventTargetNodeCast(m_focusNode.get())->dispatchUIEvent(DOMFocusInEvent);
if (m_focusNode != newFocusNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusNodeDone;
}
m_focusNode->setFocus();
if (m_focusNode.get() == m_focusNode->rootEditableElement())
didBeginEditing();
// eww, I suck. set the qt focus correctly
// ### find a better place in the code for this
if (view()) {
Widget *focusWidget = widgetForNode(m_focusNode.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_focusNode.get());
}
if (focusWidget)
focusWidget->setFocus();
else
view()->setFocus();
}
}
#if __APPLE__
if (!focusChangeBlocked && m_focusNode && AccessibilityObjectCache::accessibilityEnabled())
getAccObjectCache()->handleFocusedUIElementChanged();
#endif
SetFocusNodeDone:
updateRendering();
return !focusChangeBlocked;
}
void Document::clearSelectionIfNeeded(Node *newFocusNode)
{
if (!frame())
return;
// Clear the selection when changing the focus node to null or to a node that is not
// contained by the current selection.
Node *startContainer = frame()->selection().start().node();
if (!newFocusNode || (startContainer && startContainer != newFocusNode && !startContainer->isAncestor(newFocusNode)))
// FIXME: 6498 Should just be able to call m_frame->selection().clear()
frame()->setSelection(SelectionController());
}
void Document::setCSSTarget(Node* n)
{
if (m_cssTarget)
m_cssTarget->setChanged();
m_cssTarget = n;
if (n)
n->setChanged();
}
Node* Document::getCSSTarget()
{
return m_cssTarget;
}
void Document::attachNodeIterator(NodeIterator *ni)
{
m_nodeIterators.append(ni);
}
void Document::detachNodeIterator(NodeIterator *ni)
{
m_nodeIterators.remove(ni);
}
void Document::notifyBeforeNodeRemoval(Node *n)
{
DeprecatedPtrListIterator<NodeIterator> it(m_nodeIterators);
for (; it.current(); ++it)
it.current()->notifyBeforeNodeRemoval(n);
}
AbstractView *Document::defaultView() const
{
return m_defaultView.get();
}
PassRefPtr<Event> Document::createEvent(const String &eventType, ExceptionCode& ec)
{
if (eventType == "UIEvents" || eventType == "UIEvent")
return new UIEvent();
if (eventType == "MouseEvents" || eventType == "MouseEvent")
return new MouseEvent();
if (eventType == "MutationEvents" || eventType == "MutationEvent")
return new MutationEvent();
if (eventType == "KeyboardEvents" || eventType == "KeyboardEvent")
return new KeyboardEvent();
if (eventType == "HTMLEvents" || eventType == "Event" || eventType == "Events")
return new Event();
#if SVG_SUPPORT
if (eventType == "SVGEvents")
return new Event();
if (eventType == "SVGZoomEvents")
return new WebCore::SVGZoomEvent();
#endif
ec = NOT_SUPPORTED_ERR;
return 0;
}
CSSStyleDeclaration *Document::getOverrideStyle(Element */*elt*/, const String &/*pseudoElt*/)
{
return 0; // ###
}
void Document::handleWindowEvent(Event *evt, bool useCapture)
{
if (m_windowEventListeners.isEmpty())
return;
// if any html event listeners are registered on the window, then dispatch them here
DeprecatedPtrList<RegisteredEventListener> listenersCopy = m_windowEventListeners;
DeprecatedPtrListIterator<RegisteredEventListener> it(listenersCopy);
for (; it.current(); ++it)
if (it.current()->eventType() == evt->type() && it.current()->useCapture() == useCapture)
it.current()->listener()->handleEvent(evt, true);
}
void Document::defaultEventHandler(Event *evt)
{
// handle accesskey
if (evt->type() == keydownEvent) {
KeyboardEvent* kevt = static_cast<KeyboardEvent *>(evt);
if (kevt->ctrlKey()) {
const PlatformKeyboardEvent* ev = kevt->keyEvent();
String key = (ev ? ev->unmodifiedText() : kevt->keyIdentifier()).lower();
Element* elem = getElementByAccessKey(key);
if (elem) {
elem->accessKeyAction(false);
evt->setDefaultHandled();
}
}
}
}
void Document::setHTMLWindowEventListener(const AtomicString &eventType, PassRefPtr<EventListener> listener)
{
// If we already have it we don't want removeWindowEventListener to delete it
removeHTMLWindowEventListener(eventType);
if (listener)
addWindowEventListener(eventType, listener, false);
}
EventListener *Document::getHTMLWindowEventListener(const AtomicString &eventType)
{
DeprecatedPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
for (; it.current(); ++it)
if (it.current()->eventType() == eventType && it.current()->listener()->isHTMLEventListener())
return it.current()->listener();
return 0;
}
void Document::removeHTMLWindowEventListener(const AtomicString &eventType)
{
DeprecatedPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
for (; it.current(); ++it)
if (it.current()->eventType() == eventType && it.current()->listener()->isHTMLEventListener()) {
m_windowEventListeners.removeRef(it.current());
return;
}
}
void Document::addWindowEventListener(const AtomicString &eventType, PassRefPtr<EventListener> listener, bool useCapture)
{
// Remove existing identical listener set with identical arguments.
// The DOM 2 spec says that "duplicate instances are discarded" in this case.
removeWindowEventListener(eventType, listener.get(), useCapture);
m_windowEventListeners.append(new RegisteredEventListener(eventType, listener, useCapture));
}
void Document::removeWindowEventListener(const AtomicString &eventType, EventListener *listener, bool useCapture)
{
RegisteredEventListener rl(eventType, listener, useCapture);
DeprecatedPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
for (; it.current(); ++it)
if (*(it.current()) == rl) {
m_windowEventListeners.removeRef(it.current());
return;
}
}
bool Document::hasWindowEventListener(const AtomicString &eventType)
{
DeprecatedPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
for (; it.current(); ++it) {
if (it.current()->eventType() == eventType) {
return true;
}
}
return false;
}
PassRefPtr<EventListener> Document::createHTMLEventListener(const String& code, Node *node)
{
if (Frame *frm = frame()) {
if (KJSProxy *proxy = frm->jScript())
return proxy->createHTMLEventHandler(code, node);
}
return 0;
}
void Document::setHTMLWindowEventListener(const AtomicString& eventType, Attribute* attr)
{
setHTMLWindowEventListener(eventType, createHTMLEventListener(attr->value(), 0));
}
void Document::dispatchImageLoadEventSoon(HTMLImageLoader *image)
{
m_imageLoadEventDispatchSoonList.append(image);
if (!m_imageLoadEventTimer.isActive())
m_imageLoadEventTimer.startOneShot(0);
}
void Document::removeImage(HTMLImageLoader* image)
{
// Remove instances of this image from both lists.
// Use loops because we allow multiple instances to get into the lists.
while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
while (m_imageLoadEventDispatchingList.removeRef(image)) { }
if (m_imageLoadEventDispatchSoonList.isEmpty())
m_imageLoadEventTimer.stop();
}
void Document::dispatchImageLoadEventsNow()
{
// need to avoid re-entering this function; if new dispatches are
// scheduled before the parent finishes processing the list, they
// will set a timer and eventually be processed
if (!m_imageLoadEventDispatchingList.isEmpty()) {
return;
}
m_imageLoadEventTimer.stop();
m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
m_imageLoadEventDispatchSoonList.clear();
for (DeprecatedPtrListIterator<HTMLImageLoader> it(m_imageLoadEventDispatchingList); it.current();) {
HTMLImageLoader* image = it.current();
// Must advance iterator *before* dispatching call.
// Otherwise, it might be advanced automatically if dispatching the call had a side effect
// of destroying the current HTMLImageLoader, and then we would advance past the *next* item,
// missing one altogether.
++it;
image->dispatchLoadEvent();
}
m_imageLoadEventDispatchingList.clear();
}
void Document::imageLoadEventTimerFired(Timer<Document>*)
{
dispatchImageLoadEventsNow();
}
Element *Document::ownerElement()
{
if (!frame())
return 0;
return frame()->ownerElement();
}
String Document::referrer() const
{
if (frame())
return frame()->incomingReferrer();
return String();
}
String Document::domain() const
{
if (m_domain.isEmpty()) // not set yet (we set it on demand to save time and space)
m_domain = KURL(URL()).host(); // Initially set to the host
return m_domain;
}
void Document::setDomain(const String &newDomain, bool force /*=false*/)
{
if (force) {
m_domain = newDomain;
return;
}
if (m_domain.isEmpty()) // not set yet (we set it on demand to save time and space)
m_domain = KURL(URL()).host(); // Initially set to the host
// Both NS and IE specify that changing the domain is only allowed when
// the new domain is a suffix of the old domain.
int oldLength = m_domain.length();
int newLength = newDomain.length();
if (newLength < oldLength) // e.g. newDomain=kde.org (7) and m_domain=www.kde.org (11)
{
String test = m_domain.copy();
if (test[oldLength - newLength - 1] == '.') // Check that it's a subdomain, not e.g. "de.org"
{
test.remove(0, oldLength - newLength); // now test is "kde.org" from m_domain
if (test == newDomain) // and we check that it's the same thing as newDomain
m_domain = newDomain;
}
}
}
bool Document::isValidName(const String &name)
{
const UChar *s = reinterpret_cast<const UChar *>(name.unicode());
unsigned length = name.length();
if (length == 0)
return false;
unsigned i = 0;
UChar32 c;
U16_NEXT(s, i, length, c)
if (!isValidNameStart(c))
return false;
while (i < length) {
U16_NEXT(s, i, length, c)
if (!isValidNamePart(c))
return false;
}
return true;
}
bool Document::parseQualifiedName(const String &qualifiedName, String &prefix, String &localName)
{
unsigned length = qualifiedName.length();
if (length == 0)
return false;
bool nameStart = true;
bool sawColon = false;
int colonPos = 0;
const QChar *s = qualifiedName.unicode();
for (unsigned i = 0; i < length;) {
UChar32 c;
U16_NEXT(s, i, length, c)
if (c == ':') {
if (sawColon)
return false; // multiple colons: not allowed
nameStart = true;
sawColon = true;
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c))
return false;
nameStart = false;
} else {
if (!isValidNamePart(c))
return false;
}
}
if (!sawColon) {
prefix = String();
localName = qualifiedName.copy();
} else {
prefix = qualifiedName.substring(0, colonPos);
localName = qualifiedName.substring(colonPos + 1, length - (colonPos + 1));
}
return true;
}
void Document::addImageMap(HTMLMapElement* imageMap)
{
// Add the image map, unless there's already another with that name.
// "First map wins" is the rule other browsers seem to implement.
m_imageMapsByName.add(imageMap->getName().impl(), imageMap);
}
void Document::removeImageMap(HTMLMapElement* imageMap)
{
// Remove the image map by name.
// But don't remove some other image map that just happens to have the same name.
// FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
// once a map has been removed.
const AtomicString& name = imageMap->getName();
ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
if (it != m_imageMapsByName.end() && it->second == imageMap)
m_imageMapsByName.remove(it);
}
HTMLMapElement *Document::getImageMap(const String& URL) const
{
if (URL.isNull())
return 0;
int hashPos = URL.find('#');
AtomicString name = (hashPos < 0 ? URL : URL.substring(hashPos + 1)).impl();
return m_imageMapsByName.get(name.impl());
}
void Document::setDecoder(Decoder *decoder)
{
m_decoder = decoder;
}
QChar Document::backslashAsCurrencySymbol() const
{
if (!m_decoder)
return '\\';
return m_decoder->encoding().backslashAsCurrencySymbol();
}
DeprecatedString Document::completeURL(const DeprecatedString &URL)
{
if (!m_decoder)
return KURL(baseURL(), URL).url();
return KURL(baseURL(), URL, m_decoder->encoding()).url();
}
String Document::completeURL(const String &URL)
{
if (URL.isNull())
return URL;
return completeURL(URL.deprecatedString());
}
bool Document::inPageCache()
{
return m_inPageCache;
}
void Document::setInPageCache(bool flag)
{
if (m_inPageCache == flag)
return;
m_inPageCache = flag;
if (flag) {
assert(m_savedRenderer == 0);
m_savedRenderer = renderer();
if (m_view) {
m_view->resetScrollBars();
}
} else {
assert(renderer() == 0 || renderer() == m_savedRenderer);
setRenderer(m_savedRenderer);
m_savedRenderer = 0;
}
}
void Document::passwordFieldAdded()
{
m_passwordFields++;
}
void Document::passwordFieldRemoved()
{
assert(m_passwordFields > 0);
m_passwordFields--;
}
bool Document::hasPasswordField() const
{
return m_passwordFields > 0;
}
void Document::secureFormAdded()
{
m_secureForms++;
}
void Document::secureFormRemoved()
{
assert(m_secureForms > 0);
m_secureForms--;
}
bool Document::hasSecureForm() const
{
return m_secureForms > 0;
}
void Document::setShouldCreateRenderers(bool f)
{
m_createRenderers = f;
}
bool Document::shouldCreateRenderers()
{
return m_createRenderers;
}
String Document::toString() const
{
String result;
for (Node *child = firstChild(); child != NULL; child = child->nextSibling()) {
result += child->toString();
}
return result;
}
// Support for Javascript execCommand, and related methods
JSEditor *Document::jsEditor()
{
if (!m_jsEditor)
m_jsEditor = new JSEditor(this);
return m_jsEditor;
}
bool Document::execCommand(const String &command, bool userInterface, const String &value)
{
return jsEditor()->execCommand(command, userInterface, value);
}
bool Document::queryCommandEnabled(const String &command)
{
return jsEditor()->queryCommandEnabled(command);
}
bool Document::queryCommandIndeterm(const String &command)
{
return jsEditor()->queryCommandIndeterm(command);
}
bool Document::queryCommandState(const String &command)
{
return jsEditor()->queryCommandState(command);
}
bool Document::queryCommandSupported(const String &command)
{
return jsEditor()->queryCommandSupported(command);
}
String Document::queryCommandValue(const String &command)
{
return jsEditor()->queryCommandValue(command);
}
void Document::addMarker(Range *range, DocumentMarker::MarkerType type)
{
// Use a TextIterator to visit the potentially multiple nodes the range covers.
for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
RefPtr<Range> textPiece = markedText.range();
int exception = 0;
DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception)};
addMarker(textPiece->startContainer(exception), marker);
}
}
void Document::removeMarkers(Range *range, DocumentMarker::MarkerType markerType)
{
// Use a TextIterator to visit the potentially multiple nodes the range covers.
for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
RefPtr<Range> textPiece = markedText.range();
int exception = 0;
unsigned startOffset = textPiece->startOffset(exception);
unsigned length = textPiece->endOffset(exception) - startOffset + 1;
removeMarkers(textPiece->startContainer(exception), startOffset, length, markerType);
}
}
// Markers are stored in order sorted by their location. They do not overlap each other, as currently
// required by the drawing code in RenderText.cpp.
void Document::addMarker(Node *node, DocumentMarker newMarker)
{
assert(newMarker.endOffset >= newMarker.startOffset);
if (newMarker.endOffset == newMarker.startOffset)
return;
DeprecatedValueList<DocumentMarker>* markers = m_markers.get(node);
if (!markers) {
markers = new DeprecatedValueList<DocumentMarker>;
markers->append(newMarker);
m_markers.set(node, markers);
} else {
DeprecatedValueListIterator<DocumentMarker> it;
for (it = markers->begin(); it != markers->end();) {
DocumentMarker marker = *it;
if (newMarker.endOffset < marker.startOffset+1) {
// This is the first marker that is completely after newMarker, and disjoint from it.
// We found our insertion point.
break;
} else if (newMarker.startOffset > marker.endOffset) {
// maker is before newMarker, and disjoint from it. Keep scanning.
it++;
} else if (newMarker == marker) {
// already have this one, NOP
return;
} else {
// marker and newMarker intersect or touch - merge them into newMarker
newMarker.startOffset = kMin(newMarker.startOffset, marker.startOffset);
newMarker.endOffset = kMax(newMarker.endOffset, marker.endOffset);
// remove old one, we'll add newMarker later
it = markers->remove(it);
// it points to the next marker to consider
}
}
// at this point it points to the node before which we want to insert
markers->insert(it, newMarker);
}
// repaint the affected node
if (node->renderer())
node->renderer()->repaint();
}
// copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
// useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
{
if (length <= 0)
return;
DeprecatedValueList<DocumentMarker>* markers = m_markers.get(srcNode);
if (!markers)
return;
bool docDirty = false;
unsigned endOffset = startOffset + length - 1;
DeprecatedValueListIterator<DocumentMarker> it;
for (it = markers->begin(); it != markers->end(); ++it) {
DocumentMarker marker = *it;
// stop if we are now past the specified range
if (marker.startOffset > endOffset)
break;
// skip marker that is before the specified range or is the wrong type
if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
continue;
// pin the marker to the specified range and apply the shift delta
docDirty = true;
if (marker.startOffset < startOffset)
marker.startOffset = startOffset;
if (marker.endOffset > endOffset)
marker.endOffset = endOffset;
marker.startOffset += delta;
marker.endOffset += delta;
addMarker(dstNode, marker);
}
// repaint the affected node
if (docDirty && dstNode->renderer())
dstNode->renderer()->repaint();
}
void Document::removeMarkers(Node *node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
{
if (length <= 0)
return;
DeprecatedValueList<DocumentMarker>* markers = m_markers.get(node);
if (!markers)
return;
bool docDirty = false;
unsigned endOffset = startOffset + length - 1;
DeprecatedValueListIterator<DocumentMarker> it;
for (it = markers->begin(); it != markers->end();) {
DocumentMarker marker = *it;
// markers are returned in order, so stop if we are now past the specified range
if (marker.startOffset > endOffset)
break;
// skip marker that is wrong type or before target
if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
it++;
continue;
}
// at this point we know that marker and target intersect in some way
docDirty = true;
// pitch the old marker
it = markers->remove(it);
// it now points to the next node
// add either of the resulting slices that are left after removing target
// NOTE: This adds to the list we are iterating! That is OK regardless of
// whether the iterator sees the new node, since the new node is a keeper.
if (startOffset > marker.startOffset) {
DocumentMarker newLeft = marker;
newLeft.endOffset = startOffset;
markers->insert(it, newLeft);
}
if (marker.endOffset > endOffset) {
DocumentMarker newRight = marker;
newRight.startOffset = endOffset;
markers->insert(it, newRight);
}
}
if (markers->isEmpty()) {
m_markers.remove(node);
delete markers;
}
// repaint the affected node
if (docDirty && node->renderer())
node->renderer()->repaint();
}
DeprecatedValueList<DocumentMarker> Document::markersForNode(Node* node)
{
DeprecatedValueList<DocumentMarker>* markers = m_markers.get(node);
if (markers)
return *markers;
return DeprecatedValueList<DocumentMarker>();
}
void Document::removeMarkers(Node* node)
{
MarkerMap::iterator i = m_markers.find(node);
if (i != m_markers.end()) {
delete i->second;
m_markers.remove(i);
if (RenderObject* renderer = node->renderer())
renderer->repaint();
}
}
void Document::removeMarkers(DocumentMarker::MarkerType markerType)
{
// outer loop: process each markered node in the document
MarkerMap markerMapCopy = m_markers;
MarkerMap::iterator end = markerMapCopy.end();
for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
Node* node = i->first;
// inner loop: process each marker in the current node
DeprecatedValueList<DocumentMarker> *markers = i->second;
DeprecatedValueListIterator<DocumentMarker> markerIterator;
for (markerIterator = markers->begin(); markerIterator != markers->end();) {
DocumentMarker marker = *markerIterator;
// skip nodes that are not of the specified type
if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
++markerIterator;
continue;
}
// pitch the old marker
markerIterator = markers->remove(markerIterator);
// markerIterator now points to the next node
}
// delete the node's list if it is now empty
if (markers->isEmpty())
m_markers.remove(node);
// cause the node to be redrawn
if (RenderObject* renderer = node->renderer())
renderer->repaint();
}
}
void Document::shiftMarkers(Node *node, unsigned startOffset, int delta, DocumentMarker::MarkerType markerType)
{
DeprecatedValueList<DocumentMarker>* markers = m_markers.get(node);
if (!markers)
return;
bool docDirty = false;
DeprecatedValueListIterator<DocumentMarker> it;
for (it = markers->begin(); it != markers->end(); ++it) {
DocumentMarker &marker = *it;
if (marker.startOffset >= startOffset && (markerType == DocumentMarker::AllMarkers || marker.type == markerType)) {
assert((int)marker.startOffset + delta >= 0);
marker.startOffset += delta;
marker.endOffset += delta;
docDirty = true;
}
}
// repaint the affected node
if (docDirty && node->renderer())
node->renderer()->repaint();
}
#ifdef KHTML_XSLT
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
RefPtr<XSLTProcessor> processor = new XSLTProcessor;
processor->setXSLStylesheet(static_cast<XSLStyleSheet*>(pi->sheet()));
DeprecatedString resultMIMEType;
DeprecatedString newSource;
DeprecatedString 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, view());
}
#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
{
Frame *childPart = frame();
if (!childPart)
return 0;
Frame *parent = childPart->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()) != 0)
doc = element->getDocument();
return doc;
}
PassRefPtr<Attr> Document::createAttributeNS(const String &namespaceURI, const String &qualifiedName, ExceptionCode& ec)
{
if (qualifiedName.isNull()) {
ec = NAMESPACE_ERR;
return 0;
}
String localName = qualifiedName;
String prefix;
int colonpos;
if ((colonpos = qualifiedName.find(':')) >= 0) {
prefix = qualifiedName.copy();
localName = qualifiedName.copy();
prefix.truncate(colonpos);
localName.remove(0, colonpos+1);
}
if (!isValidName(localName)) {
ec = INVALID_CHARACTER_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 new Attr(0, this, new MappedAttribute(QualifiedName(prefix.impl(),
localName.impl(),
namespaceURI.impl()), String("").impl()));
}
#if SVG_SUPPORT
const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions;
}
SVGDocumentExtensions* Document::accessSVGExtensions()
{
if (!m_svgExtensions)
m_svgExtensions = new SVGDocumentExtensions(this);
return m_svgExtensions;
}
#endif
void Document::radioButtonChecked(HTMLInputElement *caller, HTMLFormElement *form)
{
// Without a name, there is no group.
if (caller->name().isEmpty())
return;
if (!form)
form = defaultForm;
// Uncheck the currently selected item
NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
if (!formRadioButtons) {
formRadioButtons = new NameToInputMap;
m_selectedRadioButtons.set(form, formRadioButtons);
}
HTMLInputElement* currentCheckedRadio = formRadioButtons->get(caller->name().impl());
if (currentCheckedRadio && currentCheckedRadio != caller)
currentCheckedRadio->setChecked(false);
formRadioButtons->set(caller->name().impl(), caller);
}
HTMLInputElement* Document::checkedRadioButtonForGroup(AtomicStringImpl* name, HTMLFormElement *form)
{
if (!form)
form = defaultForm;
NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
if (!formRadioButtons)
return 0;
return formRadioButtons->get(name);
}
void Document::removeRadioButtonGroup(AtomicStringImpl* name, HTMLFormElement *form)
{
if (!form)
form = defaultForm;
NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
if (formRadioButtons) {
formRadioButtons->remove(name);
if (formRadioButtons->isEmpty()) {
m_selectedRadioButtons.remove(form);
delete formRadioButtons;
}
}
}
PassRefPtr<HTMLCollection> Document::images()
{
return new HTMLCollection(this, HTMLCollection::DOC_IMAGES);
}
PassRefPtr<HTMLCollection> Document::applets()
{
return new HTMLCollection(this, HTMLCollection::DOC_APPLETS);
}
PassRefPtr<HTMLCollection> Document::embeds()
{
return new HTMLCollection(this, HTMLCollection::DOC_EMBEDS);
}
PassRefPtr<HTMLCollection> Document::objects()
{
return new HTMLCollection(this, HTMLCollection::DOC_OBJECTS);
}
PassRefPtr<HTMLCollection> Document::links()
{
return new HTMLCollection(this, HTMLCollection::DOC_LINKS);
}
PassRefPtr<HTMLCollection> Document::forms()
{
return new HTMLCollection(this, HTMLCollection::DOC_FORMS);
}
PassRefPtr<HTMLCollection> Document::anchors()
{
return new HTMLCollection(this, HTMLCollection::DOC_ANCHORS);
}
PassRefPtr<HTMLCollection> Document::all()
{
return new HTMLCollection(this, HTMLCollection::DOC_ALL);
}
PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
{
return new HTMLNameCollection(this, HTMLCollection::WINDOW_NAMED_ITEMS, name);
}
PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
{
return new HTMLNameCollection(this, HTMLCollection::DOCUMENT_NAMED_ITEMS, name);
}
PassRefPtr<NameNodeList> Document::getElementsByName(const String &elementName)
{
return new NameNodeList(this, elementName);
}
void Document::finishedParsing()
{
setParsing(false);
if (Frame* f = frame())
f->finishedParsing();
}
}
|