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
|
/* HTMLDocument.java --
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.text.html;
import gnu.classpath.NotImplementedException;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.DefaultButtonModel;
import javax.swing.JEditorPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.UndoableEditEvent;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.GapContent;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.PlainDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML.Tag;
/**
* Represents the HTML document that is constructed by defining the text and
* other components (images, buttons, etc) in HTML language. This class can
* becomes the default document for {@link JEditorPane} after setting its
* content type to "text/html". HTML document also serves as an intermediate
* data structure when it is needed to parse HTML and then obtain the content of
* the certain types of tags. This class also has methods for modifying the HTML
* content.
*
* @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
* @author Anthony Balkissoon (abalkiss@redhat.com)
* @author Lillian Angel (langel@redhat.com)
*/
public class HTMLDocument extends DefaultStyledDocument
{
/** A key for document properies. The value for the key is
* a Vector of Strings of comments not found in the body.
*/
public static final String AdditionalComments = "AdditionalComments";
URL baseURL = null;
boolean preservesUnknownTags = true;
int tokenThreshold = Integer.MAX_VALUE;
HTMLEditorKit.Parser parser;
/**
* Indicates whether this document is inside a frame or not.
*/
private boolean frameDocument;
/**
* Package private to avoid accessor methods.
*/
String baseTarget;
/**
* Constructs an HTML document using the default buffer size and a default
* StyleSheet.
*/
public HTMLDocument()
{
this(new GapContent(BUFFER_SIZE_DEFAULT), new StyleSheet());
}
/**
* Constructs an HTML document with the default content storage
* implementation and the specified style/attribute storage mechanism.
*
* @param styles - the style sheet
*/
public HTMLDocument(StyleSheet styles)
{
this(new GapContent(BUFFER_SIZE_DEFAULT), styles);
}
/**
* Constructs an HTML document with the given content storage implementation
* and the given style/attribute storage mechanism.
*
* @param c - the document's content
* @param styles - the style sheet
*/
public HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
{
super(c, styles);
}
/**
* Gets the style sheet with the document display rules (CSS) that were specified
* in the HTML document.
*
* @return - the style sheet
*/
public StyleSheet getStyleSheet()
{
return (StyleSheet) getAttributeContext();
}
/**
* This method creates a root element for the new document.
*
* @return the new default root
*/
protected AbstractElement createDefaultRoot()
{
AbstractDocument.AttributeContext ctx = getAttributeContext();
// Create html element.
AttributeSet atts = ctx.getEmptySet();
atts = ctx.addAttribute(atts, StyleConstants.NameAttribute, HTML.Tag.HTML);
BranchElement html = (BranchElement) createBranchElement(null, atts);
// Create body element.
atts = ctx.getEmptySet();
atts = ctx.addAttribute(atts, StyleConstants.NameAttribute, HTML.Tag.BODY);
BranchElement body = (BranchElement) createBranchElement(html, atts);
html.replace(0, 0, new Element[] { body });
// Create p element.
atts = ctx.getEmptySet();
atts = ctx.addAttribute(atts, StyleConstants.NameAttribute, HTML.Tag.P);
BranchElement p = (BranchElement) createBranchElement(body, atts);
body.replace(0, 0, new Element[] { p });
// Create an empty leaf element.
atts = ctx.getEmptySet();
atts = ctx.addAttribute(atts, StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
Element leaf = createLeafElement(p, atts, 0, 1);
p.replace(0, 0, new Element[]{ leaf });
return html;
}
/**
* This method returns an HTMLDocument.RunElement object attached to
* parent representing a run of text from p0 to p1. The run has
* attributes described by a.
*
* @param parent - the parent element
* @param a - the attributes for the element
* @param p0 - the beginning of the range >= 0
* @param p1 - the end of the range >= p0
*
* @return the new element
*/
protected Element createLeafElement(Element parent, AttributeSet a, int p0,
int p1)
{
return new RunElement(parent, a, p0, p1);
}
/**
* This method returns an HTMLDocument.BlockElement object representing the
* attribute set a and attached to parent.
*
* @param parent - the parent element
* @param a - the attributes for the element
*
* @return the new element
*/
protected Element createBranchElement(Element parent, AttributeSet a)
{
return new BlockElement(parent, a);
}
/**
* Returns the parser used by this HTMLDocument to insert HTML.
*
* @return the parser used by this HTMLDocument to insert HTML.
*/
public HTMLEditorKit.Parser getParser()
{
return parser;
}
/**
* Sets the parser used by this HTMLDocument to insert HTML.
*
* @param p the parser to use
*/
public void setParser (HTMLEditorKit.Parser p)
{
parser = p;
}
/**
* Sets the number of tokens to buffer before trying to display the
* Document.
*
* @param n the number of tokens to buffer
*/
public void setTokenThreshold (int n)
{
tokenThreshold = n;
}
/**
* Returns the number of tokens that are buffered before the document
* is rendered.
*
* @return the number of tokens buffered
*/
public int getTokenThreshold ()
{
return tokenThreshold;
}
/**
* Returns the location against which to resolve relative URLs.
* This is the document's URL if the document was loaded from a URL.
* If a <code>base</code> tag is found, it will be used.
* @return the base URL
*/
public URL getBase()
{
return baseURL;
}
/**
* Sets the location against which to resolve relative URLs.
* @param u the new base URL
*/
public void setBase(URL u)
{
baseURL = u;
getStyleSheet().setBase(u);
}
/**
* Returns whether or not the parser preserves unknown HTML tags.
* @return true if the parser preserves unknown tags
*/
public boolean getPreservesUnknownTags()
{
return preservesUnknownTags;
}
/**
* Sets the behaviour of the parser when it encounters unknown HTML tags.
* @param preservesTags true if the parser should preserve unknown tags.
*/
public void setPreservesUnknownTags(boolean preservesTags)
{
preservesUnknownTags = preservesTags;
}
/**
* An iterator to iterate through LeafElements in the document.
*/
class LeafIterator extends Iterator
{
HTML.Tag tag;
HTMLDocument doc;
ElementIterator it;
public LeafIterator (HTML.Tag t, HTMLDocument d)
{
doc = d;
tag = t;
it = new ElementIterator(doc);
}
/**
* Return the attributes for the tag associated with this iteartor
* @return the AttributeSet
*/
public AttributeSet getAttributes()
{
if (it.current() != null)
return it.current().getAttributes();
return null;
}
/**
* Get the end of the range for the current occurrence of the tag
* being defined and having the same attributes.
* @return the end of the range
*/
public int getEndOffset()
{
if (it.current() != null)
return it.current().getEndOffset();
return -1;
}
/**
* Get the start of the range for the current occurrence of the tag
* being defined and having the same attributes.
* @return the start of the range (-1 if it can't be found).
*/
public int getStartOffset()
{
if (it.current() != null)
return it.current().getStartOffset();
return -1;
}
/**
* Advance the iterator to the next LeafElement .
*/
public void next()
{
it.next();
while (it.current()!= null && !it.current().isLeaf())
it.next();
}
/**
* Indicates whether or not the iterator currently represents an occurrence
* of the tag.
* @return true if the iterator currently represents an occurrence of the
* tag.
*/
public boolean isValid()
{
return it.current() != null;
}
/**
* Type of tag for this iterator.
*/
public Tag getTag()
{
return tag;
}
}
public void processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent event)
{
String target = event.getTarget();
Element el = event.getSourceElement();
URL url = event.getURL();
if (target.equals("_self"))
{
updateFrame(el, url);
}
else if (target.equals("_parent"))
{
updateFrameSet(el.getParentElement(), url);
}
else
{
Element targetFrame = findFrame(target);
if (targetFrame != null)
updateFrame(targetFrame, url);
}
}
/**
* Finds the named frame inside this document.
*
* @param target the name to look for
*
* @return the frame if there is a matching frame, <code>null</code>
* otherwise
*/
private Element findFrame(String target)
{
ElementIterator i = new ElementIterator(this);
Element next = null;
while ((next = i.next()) != null)
{
AttributeSet atts = next.getAttributes();
if (atts.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.FRAME)
{
String name = (String) atts.getAttribute(HTML.Attribute.NAME);
if (name != null && name.equals(target))
break;
}
}
return next;
}
/**
* Updates the frame that is represented by the specified element to
* refer to the specified URL.
*
* @param el the element
* @param url the new url
*/
private void updateFrame(Element el, URL url)
{
try
{
writeLock();
DefaultDocumentEvent ev =
new DefaultDocumentEvent(el.getStartOffset(), 1,
DocumentEvent.EventType.CHANGE);
AttributeSet elAtts = el.getAttributes();
AttributeSet copy = elAtts.copyAttributes();
MutableAttributeSet matts = (MutableAttributeSet) elAtts;
ev.addEdit(new AttributeUndoableEdit(el, copy, false));
matts.removeAttribute(HTML.Attribute.SRC);
matts.addAttribute(HTML.Attribute.SRC, url.toString());
ev.end();
fireChangedUpdate(ev);
fireUndoableEditUpdate(new UndoableEditEvent(this, ev));
}
finally
{
writeUnlock();
}
}
/**
* Updates the frameset that is represented by the specified element
* to create a frame that refers to the specified URL.
*
* @param el the element
* @param url the url
*/
private void updateFrameSet(Element el, URL url)
{
int start = el.getStartOffset();
int end = el.getEndOffset();
StringBuilder html = new StringBuilder();
html.append("<frame");
if (url != null)
{
html.append(" src=\"");
html.append(url.toString());
html.append("\"");
}
html.append('>');
if (getParser() == null)
setParser(new HTMLEditorKit().getParser());
try
{
setOuterHTML(el, html.toString());
}
catch (BadLocationException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
/**
* Gets an iterator for the given HTML.Tag.
* @param t the requested HTML.Tag
* @return the Iterator
*/
public HTMLDocument.Iterator getIterator (HTML.Tag t)
{
return new HTMLDocument.LeafIterator(t, this);
}
/**
* An iterator over a particular type of tag.
*/
public abstract static class Iterator
{
/**
* Return the attribute set for this tag.
* @return the <code>AttributeSet</code> (null if none found).
*/
public abstract AttributeSet getAttributes();
/**
* Get the end of the range for the current occurrence of the tag
* being defined and having the same attributes.
* @return the end of the range
*/
public abstract int getEndOffset();
/**
* Get the start of the range for the current occurrence of the tag
* being defined and having the same attributes.
* @return the start of the range (-1 if it can't be found).
*/
public abstract int getStartOffset();
/**
* Move the iterator forward.
*/
public abstract void next();
/**
* Indicates whether or not the iterator currently represents an occurrence
* of the tag.
* @return true if the iterator currently represents an occurrence of the
* tag.
*/
public abstract boolean isValid();
/**
* Type of tag this iterator represents.
* @return the tag.
*/
public abstract HTML.Tag getTag();
}
public class BlockElement extends AbstractDocument.BranchElement
{
public BlockElement (Element parent, AttributeSet a)
{
super(parent, a);
}
/**
* Gets the resolving parent. Since HTML attributes are not
* inherited at the model level, this returns null.
*/
public AttributeSet getResolveParent()
{
return null;
}
/**
* Gets the name of the element.
*
* @return the name of the element if it exists, null otherwise.
*/
public String getName()
{
Object tag = getAttribute(StyleConstants.NameAttribute);
String name = null;
if (tag != null)
name = tag.toString();
if (name == null)
name = super.getName();
return name;
}
}
/**
* RunElement represents a section of text that has a set of
* HTML character level attributes assigned to it.
*/
public class RunElement extends AbstractDocument.LeafElement
{
/**
* Constructs an element that has no children. It represents content
* within the document.
*
* @param parent - parent of this
* @param a - elements attributes
* @param start - the start offset >= 0
* @param end - the end offset
*/
public RunElement(Element parent, AttributeSet a, int start, int end)
{
super(parent, a, start, end);
}
/**
* Gets the name of the element.
*
* @return the name of the element if it exists, null otherwise.
*/
public String getName()
{
Object tag = getAttribute(StyleConstants.NameAttribute);
String name = null;
if (tag != null)
name = tag.toString();
if (name == null)
name = super.getName();
return name;
}
/**
* Gets the resolving parent. HTML attributes do not inherit at the
* model level, so this method returns null.
*
* @return null
*/
public AttributeSet getResolveParent()
{
return null;
}
}
/**
* A reader to load an HTMLDocument with HTML structure.
*
* @author Anthony Balkissoon abalkiss at redhat dot com
*/
public class HTMLReader extends HTMLEditorKit.ParserCallback
{
/**
* The maximum token threshold. We don't grow it larger than this.
*/
private static final int MAX_THRESHOLD = 10000;
/**
* The threshold growth factor.
*/
private static final int GROW_THRESHOLD = 5;
/**
* Holds the current character attribute set *
*/
protected MutableAttributeSet charAttr = new SimpleAttributeSet();
protected Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>();
/**
* The parse stack. It holds the current element tree path.
*/
private Stack<HTML.Tag> parseStack = new Stack<HTML.Tag>();
/**
* A stack for character attribute sets *
*/
Stack charAttrStack = new Stack();
/** A mapping between HTML.Tag objects and the actions that handle them **/
HashMap tagToAction;
/** Tells us whether we've received the '</html>' tag yet **/
boolean endHTMLEncountered = false;
/**
* Related to the constructor with explicit insertTag
*/
int popDepth;
/**
* Related to the constructor with explicit insertTag
*/
int pushDepth;
/**
* Related to the constructor with explicit insertTag
*/
int offset;
/**
* The tag (inclusve), after that the insertion should start.
*/
HTML.Tag insertTag;
/**
* This variable becomes true after the insert tag has been encountered.
*/
boolean insertTagEncountered;
/** A temporary variable that helps with the printing out of debug information **/
boolean debug = false;
/**
* This is true when we are inside a pre tag.
*/
boolean inPreTag = false;
/**
* This is true when we are inside a style tag. This will add text
* content inside this style tag beeing parsed as CSS.
*
* This is package private to avoid accessor methods.
*/
boolean inStyleTag = false;
/**
* This is true when we are inside a <textarea> tag. Any text
* content will then be added to the text area.
*
* This is package private to avoid accessor methods.
*/
boolean inTextArea = false;
/**
* This contains all stylesheets that are somehow read, either
* via embedded style tags, or via linked stylesheets. The
* elements will be String objects containing a stylesheet each.
*/
ArrayList styles;
/**
* The document model for a textarea.
*
* This is package private to avoid accessor methods.
*/
ResetablePlainDocument textAreaDocument;
/**
* The current model of a select tag. Can be a ComboBoxModel or a
* ListModel depending on the type of the select box.
*/
Object selectModel;
/**
* The current option beeing read.
*/
Option option;
/**
* The current number of options in the current select model.
*/
int numOptions;
/**
* The current button groups mappings.
*/
HashMap buttonGroups;
/**
* The token threshold. This gets increased while loading.
*/
private int threshold;
public class TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action. By default this does nothing.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
// Nothing to do here.
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action. By default does nothing.
*/
public void end(HTML.Tag t)
{
// Nothing to do here.
}
}
public class BlockAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
// Tell the parse buffer to open a new block for this tag.
blockOpen(t, a);
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
// Tell the parse buffer to close this block.
blockClose(t);
}
}
public class CharacterAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
// Put the old attribute set on the stack.
pushCharacterStyle();
// Initialize with link pseudo class.
if (t == HTML.Tag.A)
a.addAttribute(HTML.Attribute.PSEUDO_CLASS, "link");
// Just add the attributes in <code>a</code>.
charAttr.addAttribute(t, a.copyAttributes());
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
popCharacterStyle();
}
}
/**
* Processes elements that make up forms: <input>, <textarea>,
* <select> and <option>.
*/
public class FormAction extends SpecialAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
if (t == HTML.Tag.INPUT)
{
String type = (String) a.getAttribute(HTML.Attribute.TYPE);
if (type == null)
{
type = "text"; // Default to 'text' when nothing was specified.
a.addAttribute(HTML.Attribute.TYPE, type);
}
setModel(type, a);
}
else if (t == HTML.Tag.TEXTAREA)
{
inTextArea = true;
textAreaDocument = new ResetablePlainDocument();
a.addAttribute(StyleConstants.ModelAttribute, textAreaDocument);
}
else if (t == HTML.Tag.SELECT)
{
int size = HTML.getIntegerAttributeValue(a, HTML.Attribute.SIZE,
1);
boolean multi = a.getAttribute(HTML.Attribute.MULTIPLE) != null;
if (size > 1 || multi)
{
SelectListModel m = new SelectListModel();
if (multi)
m.getSelectionModel().setSelectionMode(ListSelectionModel
.MULTIPLE_INTERVAL_SELECTION);
selectModel = m;
}
else
{
selectModel = new SelectComboBoxModel();
}
a.addAttribute(StyleConstants.ModelAttribute, selectModel);
}
if (t == HTML.Tag.OPTION)
{
option = new Option(a);
if (selectModel instanceof SelectListModel)
{
SelectListModel m = (SelectListModel) selectModel;
m.addElement(option);
if (option.isSelected())
{
m.getSelectionModel().addSelectionInterval(numOptions,
numOptions);
m.addInitialSelection(numOptions);
}
}
else if (selectModel instanceof SelectComboBoxModel)
{
SelectComboBoxModel m = (SelectComboBoxModel) selectModel;
m.addElement(option);
if (option.isSelected())
{
m.setSelectedItem(option);
m.setInitialSelection(option);
}
}
numOptions++;
}
else
{
// Build the element.
super.start(t, a);
}
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
if (t == HTML.Tag.OPTION)
{
option = null;
}
else
{
if (t == HTML.Tag.TEXTAREA)
{
inTextArea = false;
}
else if (t == HTML.Tag.SELECT)
{
selectModel = null;
numOptions = 0;
}
// Finish the element.
super.end(t);
}
}
private void setModel(String type, MutableAttributeSet attrs)
{
if (type.equals("submit") || type.equals("reset")
|| type.equals("image"))
{
// Create button.
attrs.addAttribute(StyleConstants.ModelAttribute,
new DefaultButtonModel());
}
else if (type.equals("text") || type.equals("password"))
{
String text = (String) attrs.getAttribute(HTML.Attribute.VALUE);
ResetablePlainDocument doc = new ResetablePlainDocument();
if (text != null)
{
doc.setInitialText(text);
try
{
doc.insertString(0, text, null);
}
catch (BadLocationException ex)
{
// Shouldn't happen.
assert false;
}
}
attrs.addAttribute(StyleConstants.ModelAttribute, doc);
}
else if (type.equals("file"))
{
attrs.addAttribute(StyleConstants.ModelAttribute,
new PlainDocument());
}
else if (type.equals("checkbox") || type.equals("radio"))
{
ResetableToggleButtonModel model =
new ResetableToggleButtonModel();
if (attrs.getAttribute(HTML.Attribute.SELECTED) != null)
{
model.setSelected(true);
model.setInitial(true);
}
if (type.equals("radio"))
{
String name = (String) attrs.getAttribute(HTML.Attribute.NAME);
if (name != null)
{
if (buttonGroups == null)
buttonGroups = new HashMap();
ButtonGroup group = (ButtonGroup) buttonGroups.get(name);
if (group == null)
{
group = new ButtonGroup();
buttonGroups.put(name, group);
}
model.setGroup(group);
}
}
attrs.addAttribute(StyleConstants.ModelAttribute, model);
}
}
}
/**
* Called for form tags.
*/
class FormTagAction
extends BlockAction
{
/**
* Clears the button group mapping.
*/
public void end(HTML.Tag t)
{
super.end(t);
buttonGroups = null;
}
}
/**
* This action indicates that the content between starting and closing HTML
* elements (like script - /script) should not be visible. The content is
* still inserted and can be accessed when iterating the HTML document. The
* parser will only fire
* {@link javax.swing.text.html.HTMLEditorKit.ParserCallback#handleText} for
* the hidden tags, regardless from that html tags the hidden section may
* contain.
*/
public class HiddenAction
extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
blockOpen(t, a);
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
blockClose(t);
}
}
/**
* Handles <isindex> tags.
*/
public class IsindexAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
addSpecialElement(t, a);
blockClose(HTML.Tag.IMPLIED);
}
}
public class ParagraphAction extends BlockAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
super.start(t, a);
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
super.end(t);
}
}
/**
* This action is performed when a <pre> tag is parsed.
*/
public class PreAction extends BlockAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
inPreTag = true;
blockOpen(t, a);
a.addAttribute(CSS.Attribute.WHITE_SPACE, "pre");
blockOpen(HTML.Tag.IMPLIED, a);
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
blockClose(HTML.Tag.IMPLIED);
inPreTag = false;
blockClose(t);
}
}
/**
* Inserts the elements that are represented by ths single tag with
* attributes (only). The closing tag, even if present, mut follow
* immediately after the starting tag without providing any additional
* information. Hence the {@link TagAction#end} method need not be
* overridden and still does nothing.
*/
public class SpecialAction extends TagAction
{
/**
* The functionality is delegated to {@link HTMLReader#addSpecialElement}
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
addSpecialElement(t, a);
}
}
class AreaAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
throws NotImplementedException
{
// FIXME: Implement.
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
throws NotImplementedException
{
// FIXME: Implement.
}
}
/**
* Converts HTML tags to CSS attributes.
*/
class ConvertAction
extends TagAction
{
public void start(HTML.Tag tag, MutableAttributeSet atts)
{
pushCharacterStyle();
charAttr.addAttribute(tag, atts.copyAttributes());
StyleSheet styleSheet = getStyleSheet();
// TODO: Add other tags here.
if (tag == HTML.Tag.FONT)
{
String color = (String) atts.getAttribute(HTML.Attribute.COLOR);
if (color != null)
styleSheet.addCSSAttribute(charAttr, CSS.Attribute.COLOR, color);
String face = (String) atts.getAttribute(HTML.Attribute.FACE);
if (face != null)
styleSheet.addCSSAttribute(charAttr, CSS.Attribute.FONT_FAMILY,
face);
String size = (String) atts.getAttribute(HTML.Attribute.SIZE);
if (size != null)
styleSheet.addCSSAttribute(charAttr, CSS.Attribute.FONT_SIZE,
size);
}
}
public void end(HTML.Tag tag)
{
popCharacterStyle();
}
}
class BaseAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
baseTarget = (String) a.getAttribute(HTML.Attribute.TARGET);
}
}
class HeadAction extends BlockAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
throws NotImplementedException
{
// FIXME: Implement.
super.start(t, a);
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
// We read in all the stylesheets that are embedded or referenced
// inside the header.
if (styles != null)
{
int numStyles = styles.size();
for (int i = 0; i < numStyles; i++)
{
String style = (String) styles.get(i);
getStyleSheet().addRule(style);
}
}
super.end(t);
}
}
class LinkAction extends HiddenAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
super.start(t, a);
String type = (String) a.getAttribute(HTML.Attribute.TYPE);
if (type == null)
type = "text/css";
if (type.equals("text/css"))
{
String rel = (String) a.getAttribute(HTML.Attribute.REL);
String media = (String) a.getAttribute(HTML.Attribute.MEDIA);
String title = (String) a.getAttribute(HTML.Attribute.TITLE);
if (media == null)
media = "all";
else
media = media.toLowerCase();
if (rel != null)
{
rel = rel.toLowerCase();
if ((media.indexOf("all") != -1
|| media.indexOf("screen") != -1)
&& (rel.equals("stylesheet")))
{
String href = (String) a.getAttribute(HTML.Attribute.HREF);
URL url = null;
try
{
url = new URL(baseURL, href);
}
catch (MalformedURLException ex)
{
try
{
url = new URL(href);
}
catch (MalformedURLException ex2)
{
url = null;
}
}
if (url != null)
{
try
{
getStyleSheet().importStyleSheet(url);
}
catch (Exception ex)
{
// Don't let exceptions and runtime exceptions
// in CSS parsing disprupt the HTML parsing
// process. But inform the user/developer
// on the console about it.
ex.printStackTrace();
}
}
}
}
}
}
}
class MapAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
throws NotImplementedException
{
// FIXME: Implement.
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
throws NotImplementedException
{
// FIXME: Implement.
}
}
class MetaAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
throws NotImplementedException
{
// FIXME: Implement.
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
throws NotImplementedException
{
// FIXME: Implement.
}
}
class StyleAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
{
inStyleTag = true;
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
{
inStyleTag = false;
}
}
class TitleAction extends TagAction
{
/**
* This method is called when a start tag is seen for one of the types
* of tags associated with this Action.
*/
public void start(HTML.Tag t, MutableAttributeSet a)
throws NotImplementedException
{
// FIXME: Implement.
}
/**
* Called when an end tag is seen for one of the types of tags associated
* with this Action.
*/
public void end(HTML.Tag t)
throws NotImplementedException
{
// FIXME: Implement.
}
}
public HTMLReader(int offset)
{
this (offset, 0, 0, null);
}
public HTMLReader(int offset, int popDepth, int pushDepth,
HTML.Tag insertTag)
{
this.insertTag = insertTag;
this.offset = offset;
this.popDepth = popDepth;
this.pushDepth = pushDepth;
threshold = getTokenThreshold();
initTags();
}
void initTags()
{
tagToAction = new HashMap(72);
CharacterAction characterAction = new CharacterAction();
HiddenAction hiddenAction = new HiddenAction();
AreaAction areaAction = new AreaAction();
BaseAction baseAction = new BaseAction();
BlockAction blockAction = new BlockAction();
SpecialAction specialAction = new SpecialAction();
ParagraphAction paragraphAction = new ParagraphAction();
HeadAction headAction = new HeadAction();
FormAction formAction = new FormAction();
IsindexAction isindexAction = new IsindexAction();
LinkAction linkAction = new LinkAction();
MapAction mapAction = new MapAction();
PreAction preAction = new PreAction();
MetaAction metaAction = new MetaAction();
StyleAction styleAction = new StyleAction();
TitleAction titleAction = new TitleAction();
ConvertAction convertAction = new ConvertAction();
tagToAction.put(HTML.Tag.A, characterAction);
tagToAction.put(HTML.Tag.ADDRESS, characterAction);
tagToAction.put(HTML.Tag.APPLET, hiddenAction);
tagToAction.put(HTML.Tag.AREA, areaAction);
tagToAction.put(HTML.Tag.B, characterAction);
tagToAction.put(HTML.Tag.BASE, baseAction);
tagToAction.put(HTML.Tag.BASEFONT, characterAction);
tagToAction.put(HTML.Tag.BIG, characterAction);
tagToAction.put(HTML.Tag.BLOCKQUOTE, blockAction);
tagToAction.put(HTML.Tag.BODY, blockAction);
tagToAction.put(HTML.Tag.BR, specialAction);
tagToAction.put(HTML.Tag.CAPTION, blockAction);
tagToAction.put(HTML.Tag.CENTER, blockAction);
tagToAction.put(HTML.Tag.CITE, characterAction);
tagToAction.put(HTML.Tag.CODE, characterAction);
tagToAction.put(HTML.Tag.DD, blockAction);
tagToAction.put(HTML.Tag.DFN, characterAction);
tagToAction.put(HTML.Tag.DIR, blockAction);
tagToAction.put(HTML.Tag.DIV, blockAction);
tagToAction.put(HTML.Tag.DL, blockAction);
tagToAction.put(HTML.Tag.DT, paragraphAction);
tagToAction.put(HTML.Tag.EM, characterAction);
tagToAction.put(HTML.Tag.FONT, convertAction);
tagToAction.put(HTML.Tag.FORM, new FormTagAction());
tagToAction.put(HTML.Tag.FRAME, specialAction);
tagToAction.put(HTML.Tag.FRAMESET, blockAction);
tagToAction.put(HTML.Tag.H1, paragraphAction);
tagToAction.put(HTML.Tag.H2, paragraphAction);
tagToAction.put(HTML.Tag.H3, paragraphAction);
tagToAction.put(HTML.Tag.H4, paragraphAction);
tagToAction.put(HTML.Tag.H5, paragraphAction);
tagToAction.put(HTML.Tag.H6, paragraphAction);
tagToAction.put(HTML.Tag.HEAD, headAction);
tagToAction.put(HTML.Tag.HR, specialAction);
tagToAction.put(HTML.Tag.HTML, blockAction);
tagToAction.put(HTML.Tag.I, characterAction);
tagToAction.put(HTML.Tag.IMG, specialAction);
tagToAction.put(HTML.Tag.INPUT, formAction);
tagToAction.put(HTML.Tag.ISINDEX, isindexAction);
tagToAction.put(HTML.Tag.KBD, characterAction);
tagToAction.put(HTML.Tag.LI, blockAction);
tagToAction.put(HTML.Tag.LINK, linkAction);
tagToAction.put(HTML.Tag.MAP, mapAction);
tagToAction.put(HTML.Tag.MENU, blockAction);
tagToAction.put(HTML.Tag.META, metaAction);
tagToAction.put(HTML.Tag.NOFRAMES, blockAction);
tagToAction.put(HTML.Tag.OBJECT, specialAction);
tagToAction.put(HTML.Tag.OL, blockAction);
tagToAction.put(HTML.Tag.OPTION, formAction);
tagToAction.put(HTML.Tag.P, paragraphAction);
tagToAction.put(HTML.Tag.PARAM, hiddenAction);
tagToAction.put(HTML.Tag.PRE, preAction);
tagToAction.put(HTML.Tag.SAMP, characterAction);
tagToAction.put(HTML.Tag.SCRIPT, hiddenAction);
tagToAction.put(HTML.Tag.SELECT, formAction);
tagToAction.put(HTML.Tag.SMALL, characterAction);
tagToAction.put(HTML.Tag.STRIKE, characterAction);
tagToAction.put(HTML.Tag.S, characterAction);
tagToAction.put(HTML.Tag.STRONG, characterAction);
tagToAction.put(HTML.Tag.STYLE, styleAction);
tagToAction.put(HTML.Tag.SUB, characterAction);
tagToAction.put(HTML.Tag.SUP, characterAction);
tagToAction.put(HTML.Tag.TABLE, blockAction);
tagToAction.put(HTML.Tag.TD, blockAction);
tagToAction.put(HTML.Tag.TEXTAREA, formAction);
tagToAction.put(HTML.Tag.TH, blockAction);
tagToAction.put(HTML.Tag.TITLE, titleAction);
tagToAction.put(HTML.Tag.TR, blockAction);
tagToAction.put(HTML.Tag.TT, characterAction);
tagToAction.put(HTML.Tag.U, characterAction);
tagToAction.put(HTML.Tag.UL, blockAction);
tagToAction.put(HTML.Tag.VAR, characterAction);
}
/**
* Pushes the current character style onto the stack.
*
*/
protected void pushCharacterStyle()
{
charAttrStack.push(charAttr.copyAttributes());
}
/**
* Pops a character style off of the stack and uses it as the
* current character style.
*
*/
protected void popCharacterStyle()
{
if (!charAttrStack.isEmpty())
charAttr = (MutableAttributeSet) charAttrStack.pop();
}
/**
* Registers a given tag with a given Action. All of the well-known tags
* are registered by default, but this method can change their behaviour
* or add support for custom or currently unsupported tags.
*
* @param t the Tag to register
* @param a the Action for the Tag
*/
protected void registerTag(HTML.Tag t, HTMLDocument.HTMLReader.TagAction a)
{
tagToAction.put (t, a);
}
/**
* This is the last method called on the HTMLReader, allowing any pending
* changes to be flushed to the HTMLDocument.
*/
public void flush() throws BadLocationException
{
flushImpl();
}
/**
* Flushes the buffer and handle partial inserts.
*
*/
private void flushImpl()
throws BadLocationException
{
int oldLen = getLength();
int size = parseBuffer.size();
ElementSpec[] elems = new ElementSpec[size];
parseBuffer.copyInto(elems);
if (oldLen == 0)
create(elems);
else
insert(offset, elems);
parseBuffer.removeAllElements();
offset += getLength() - oldLen;
}
/**
* This method is called by the parser to indicate a block of
* text was encountered. Should insert the text appropriately.
*
* @param data the text that was inserted
* @param pos the position at which the text was inserted
*/
public void handleText(char[] data, int pos)
{
if (shouldInsert() && data != null && data.length > 0)
{
if (inTextArea)
textAreaContent(data);
else if (inPreTag)
preContent(data);
else if (option != null)
option.setLabel(new String(data));
else if (inStyleTag)
{
if (styles == null)
styles = new ArrayList();
styles.add(new String(data));
}
else
addContent(data, 0, data.length);
}
}
/**
* Checks if the HTML tag should be inserted. The tags before insert tag (if
* specified) are not inserted. Also, the tags after the end of the html are
* not inserted.
*
* @return true if the tag should be inserted, false otherwise.
*/
private boolean shouldInsert()
{
return ! endHTMLEncountered
&& (insertTagEncountered || insertTag == null);
}
/**
* This method is called by the parser and should route the call to the
* proper handler for the tag.
*
* @param t the HTML.Tag
* @param a the attribute set
* @param pos the position at which the tag was encountered
*/
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
{
if (t == insertTag)
insertTagEncountered = true;
if (shouldInsert())
{
TagAction action = (TagAction) tagToAction.get(t);
if (action != null)
action.start(t, a);
}
}
/**
* This method called by parser to handle a comment block.
*
* @param data the comment
* @param pos the position at which the comment was encountered
*/
public void handleComment(char[] data, int pos)
{
if (shouldInsert())
{
TagAction action = (TagAction) tagToAction.get(HTML.Tag.COMMENT);
if (action != null)
{
action.start(HTML.Tag.COMMENT, new SimpleAttributeSet());
action.end(HTML.Tag.COMMENT);
}
}
}
/**
* This method is called by the parser and should route the call to the
* proper handler for the tag.
*
* @param t the HTML.Tag
* @param pos the position at which the tag was encountered
*/
public void handleEndTag(HTML.Tag t, int pos)
{
if (shouldInsert())
{
// If this is the </html> tag we need to stop calling the Actions
if (t == HTML.Tag.HTML)
endHTMLEncountered = true;
TagAction action = (TagAction) tagToAction.get(t);
if (action != null)
action.end(t);
}
}
/**
* This is a callback from the parser that should be routed to the
* appropriate handler for the tag.
*
* @param t the HTML.Tag that was encountered
* @param a the attribute set
* @param pos the position at which the tag was encountered
*/
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
{
if (t == insertTag)
insertTagEncountered = true;
if (shouldInsert())
{
TagAction action = (TagAction) tagToAction.get(t);
if (action != null)
{
action.start(t, a);
action.end(t);
}
}
}
/**
* This is invoked after the stream has been parsed but before it has been
* flushed.
*
* @param eol one of \n, \r, or \r\n, whichever was encountered the most in
* parsing the stream
* @since 1.3
*/
public void handleEndOfLineString(String eol)
{
// FIXME: Implement.
}
/**
* Adds the given text to the textarea document. Called only when we are
* within a textarea.
*
* @param data the text to add to the textarea
*/
protected void textAreaContent(char[] data)
{
try
{
int offset = textAreaDocument.getLength();
String text = new String(data);
textAreaDocument.setInitialText(text);
textAreaDocument.insertString(offset, text, null);
}
catch (BadLocationException ex)
{
// Must not happen as we insert at a model location that we
// got from the document itself.
assert false;
}
}
/**
* Adds the given text that was encountered in a <PRE> element.
* This adds synthesized lines to hold the text runs.
*
* @param data the text
*/
protected void preContent(char[] data)
{
int start = 0;
for (int i = 0; i < data.length; i++)
{
if (data[i] == '\n')
{
addContent(data, start, i - start + 1);
blockClose(HTML.Tag.IMPLIED);
MutableAttributeSet atts = new SimpleAttributeSet();
atts.addAttribute(CSS.Attribute.WHITE_SPACE, "pre");
blockOpen(HTML.Tag.IMPLIED, atts);
start = i + 1;
}
}
if (start < data.length)
{
// Add remaining last line.
addContent(data, start, data.length - start);
}
}
/**
* Instructs the parse buffer to create a block element with the given
* attributes.
*
* @param t the tag that requires opening a new block
* @param attr the attribute set for the new block
*/
protected void blockOpen(HTML.Tag t, MutableAttributeSet attr)
{
if (inImpliedParagraph())
blockClose(HTML.Tag.IMPLIED);
// Push the new tag on top of the stack.
parseStack.push(t);
DefaultStyledDocument.ElementSpec element;
AbstractDocument.AttributeContext ctx = getAttributeContext();
AttributeSet copy = attr.copyAttributes();
copy = ctx.addAttribute(copy, StyleConstants.NameAttribute, t);
element = new DefaultStyledDocument.ElementSpec(copy,
DefaultStyledDocument.ElementSpec.StartTagType);
parseBuffer.addElement(element);
}
/**
* Returns true when we are currently inside a paragraph, either
* a real one or an implied, false otherwise.
*
* @return
*/
private boolean inParagraph()
{
boolean inParagraph = false;
if (! parseStack.isEmpty())
{
HTML.Tag top = parseStack.peek();
inParagraph = top == HTML.Tag.P || top == HTML.Tag.IMPLIED;
}
return inParagraph;
}
private boolean inImpliedParagraph()
{
boolean inParagraph = false;
if (! parseStack.isEmpty())
{
HTML.Tag top = parseStack.peek();
inParagraph = top == HTML.Tag.IMPLIED;
}
return inParagraph;
}
/**
* Instructs the parse buffer to close the block element associated with
* the given HTML.Tag
*
* @param t the HTML.Tag that is closing its block
*/
protected void blockClose(HTML.Tag t)
{
DefaultStyledDocument.ElementSpec element;
if (inImpliedParagraph() && t != HTML.Tag.IMPLIED)
blockClose(HTML.Tag.IMPLIED);
// Pull the token from the stack.
if (! parseStack.isEmpty()) // Just to be sure.
parseStack.pop();
// If the previous tag is a start tag then we insert a synthetic
// content tag.
DefaultStyledDocument.ElementSpec prev;
prev = parseBuffer.size() > 0 ? (DefaultStyledDocument.ElementSpec)
parseBuffer.get(parseBuffer.size() - 1) : null;
if (prev != null &&
prev.getType() == DefaultStyledDocument.ElementSpec.StartTagType)
{
addContent(new char[]{' '}, 0, 1);
}
element = new DefaultStyledDocument.ElementSpec(null,
DefaultStyledDocument.ElementSpec.EndTagType);
parseBuffer.addElement(element);
}
/**
* Adds text to the appropriate context using the current character
* attribute set.
*
* @param data the text to add
* @param offs the offset at which to add it
* @param length the length of the text to add
*/
protected void addContent(char[] data, int offs, int length)
{
addContent(data, offs, length, true);
}
/**
* Adds text to the appropriate context using the current character
* attribute set, and possibly generating an IMPLIED Tag if necessary.
*
* @param data the text to add
* @param offs the offset at which to add it
* @param length the length of the text to add
* @param generateImpliedPIfNecessary whether or not we should generate
* an HTML.Tag.IMPLIED tag if necessary
*/
protected void addContent(char[] data, int offs, int length,
boolean generateImpliedPIfNecessary)
{
if (generateImpliedPIfNecessary && ! inParagraph())
{
blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
}
AbstractDocument.AttributeContext ctx = getAttributeContext();
DefaultStyledDocument.ElementSpec element;
AttributeSet attributes = null;
// Copy the attribute set, don't use the same object because
// it may change
if (charAttr != null)
attributes = charAttr.copyAttributes();
else
attributes = ctx.getEmptySet();
attributes = ctx.addAttribute(attributes, StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
element = new DefaultStyledDocument.ElementSpec(attributes,
DefaultStyledDocument.ElementSpec.ContentType,
data, offs, length);
// Add the element to the buffer
parseBuffer.addElement(element);
if (parseBuffer.size() > threshold)
{
if (threshold <= MAX_THRESHOLD)
threshold *= GROW_THRESHOLD;
try
{
flushImpl();
}
catch (BadLocationException ble)
{
// TODO: what to do here?
}
}
}
/**
* Adds content that is specified in the attribute set.
*
* @param t the HTML.Tag
* @param a the attribute set specifying the special content
*/
protected void addSpecialElement(HTML.Tag t, MutableAttributeSet a)
{
if (t != HTML.Tag.FRAME && ! inParagraph())
{
blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
}
a.addAttribute(StyleConstants.NameAttribute, t);
// The two spaces are required because some special elements like HR
// must be broken. At least two characters are needed to break into the
// two parts.
DefaultStyledDocument.ElementSpec spec =
new DefaultStyledDocument.ElementSpec(a.copyAttributes(),
DefaultStyledDocument.ElementSpec.ContentType,
new char[] {' '}, 0, 1 );
parseBuffer.add(spec);
}
}
/**
* Gets the reader for the parser to use when loading the document with HTML.
*
* @param pos - the starting position
* @return - the reader
*/
public HTMLEditorKit.ParserCallback getReader(int pos)
{
return new HTMLReader(pos);
}
/**
* Gets the reader for the parser to use when loading the document with HTML.
*
* @param pos - the starting position
* @param popDepth - the number of EndTagTypes to generate before inserting
* @param pushDepth - the number of StartTagTypes with a direction
* of JoinNextDirection that should be generated before inserting,
* but after the end tags have been generated.
* @param insertTag - the first tag to start inserting into document
* @return - the reader
*/
public HTMLEditorKit.ParserCallback getReader(int pos,
int popDepth,
int pushDepth,
HTML.Tag insertTag)
{
return new HTMLReader(pos, popDepth, pushDepth, insertTag);
}
/**
* Gets the reader for the parser to use when inserting the HTML fragment into
* the document. Checks if the parser is present, sets the parent in the
* element stack and removes any actions for BODY (it can be only one body in
* a HTMLDocument).
*
* @param pos - the starting position
* @param popDepth - the number of EndTagTypes to generate before inserting
* @param pushDepth - the number of StartTagTypes with a direction of
* JoinNextDirection that should be generated before inserting, but
* after the end tags have been generated.
* @param insertTag - the first tag to start inserting into document
* @param parent the element that will be the parent in the document. HTML
* parsing includes checks for the parent, so it must be available.
* @return - the reader
* @throws IllegalStateException if the parsert is not set.
*/
public HTMLEditorKit.ParserCallback getInsertingReader(int pos, int popDepth,
int pushDepth,
HTML.Tag insertTag,
final Element parent)
throws IllegalStateException
{
if (parser == null)
throw new IllegalStateException("Parser has not been set");
HTMLReader reader = new HTMLReader(pos, popDepth, pushDepth, insertTag)
{
/**
* Ignore BODY.
*/
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
{
if (t != HTML.Tag.BODY)
super.handleStartTag(t, a, pos);
}
/**
* Ignore BODY.
*/
public void handleEndTag(HTML.Tag t, int pos)
{
if (t != HTML.Tag.BODY)
super.handleEndTag(t, pos);
}
};
return reader;
}
/**
* Gets the child element that contains the attribute with the value or null.
* Not thread-safe.
*
* @param e - the element to begin search at
* @param attribute - the desired attribute
* @param value - the desired value
* @return the element found with the attribute and value specified or null if
* it is not found.
*/
public Element getElement(Element e, Object attribute, Object value)
{
if (e != null)
{
if (e.getAttributes().containsAttribute(attribute, value))
return e;
int count = e.getElementCount();
for (int j = 0; j < count; j++)
{
Element child = e.getElement(j);
if (child.getAttributes().containsAttribute(attribute, value))
return child;
Element grandChild = getElement(child, attribute, value);
if (grandChild != null)
return grandChild;
}
}
return null;
}
/**
* Returns the element that has the given id Attribute (for instance, <p id
* ='my paragraph >'). If it is not found, null is returned. The HTML tag,
* having this attribute, is not checked by this method and can be any. The
* method is not thread-safe.
*
* @param attrId - the value of the attribute id to look for
* @return the element that has the given id.
*/
public Element getElement(String attrId)
{
return getElement(getDefaultRootElement(), HTML.Attribute.ID,
attrId);
}
/**
* Replaces the children of the given element with the contents of
* the string. The document must have an HTMLEditorKit.Parser set.
* This will be seen as at least two events, n inserts followed by a remove.
*
* @param elem - the brance element whose children will be replaced
* @param htmlText - the string to be parsed and assigned to element.
* @throws BadLocationException
* @throws IOException
* @throws IllegalArgumentException - if elem is a leaf
* @throws IllegalStateException - if an HTMLEditorKit.Parser has not been set
*/
public void setInnerHTML(Element elem, String htmlText)
throws BadLocationException, IOException
{
if (elem.isLeaf())
throw new IllegalArgumentException("Element is a leaf");
int start = elem.getStartOffset();
int end = elem.getEndOffset();
HTMLEditorKit.ParserCallback reader = getInsertingReader(
end, 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
// Remove the previous content
remove(start, end - start);
}
/**
* Replaces the given element in the parent with the string. When replacing a
* leaf, this will attempt to make sure there is a newline present if one is
* needed. This may result in an additional element being inserted. This will
* be seen as at least two events, n inserts followed by a remove. The
* HTMLEditorKit.Parser must be set.
*
* @param elem - the branch element whose parent will be replaced
* @param htmlText - the string to be parsed and assigned to elem
* @throws BadLocationException
* @throws IOException
* @throws IllegalStateException - if parser is not set
*/
public void setOuterHTML(Element elem, String htmlText)
throws BadLocationException, IOException
{
// Remove the current element:
int start = elem.getStartOffset();
int end = elem.getEndOffset();
remove(start, end-start);
HTMLEditorKit.ParserCallback reader = getInsertingReader(
start, 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
}
/**
* Inserts the string before the start of the given element. The parser must
* be set.
*
* @param elem - the element to be the root for the new text.
* @param htmlText - the string to be parsed and assigned to elem
* @throws BadLocationException
* @throws IOException
* @throws IllegalStateException - if parser has not been set
*/
public void insertBeforeStart(Element elem, String htmlText)
throws BadLocationException, IOException
{
HTMLEditorKit.ParserCallback reader = getInsertingReader(
elem.getStartOffset(), 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
}
/**
* Inserts the string at the end of the element. If elem's children are
* leaves, and the character at elem.getEndOffset() - 1 is a newline, then it
* will be inserted before the newline. The parser must be set.
*
* @param elem - the element to be the root for the new text
* @param htmlText - the text to insert
* @throws BadLocationException
* @throws IOException
* @throws IllegalStateException - if parser is not set
*/
public void insertBeforeEnd(Element elem, String htmlText)
throws BadLocationException, IOException
{
HTMLEditorKit.ParserCallback reader = getInsertingReader(
elem.getEndOffset(), 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
}
/**
* Inserts the string after the end of the given element.
* The parser must be set.
*
* @param elem - the element to be the root for the new text
* @param htmlText - the text to insert
* @throws BadLocationException
* @throws IOException
* @throws IllegalStateException - if parser is not set
*/
public void insertAfterEnd(Element elem, String htmlText)
throws BadLocationException, IOException
{
HTMLEditorKit.ParserCallback reader = getInsertingReader(
elem.getEndOffset(), 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
}
/**
* Inserts the string at the start of the element.
* The parser must be set.
*
* @param elem - the element to be the root for the new text
* @param htmlText - the text to insert
* @throws BadLocationException
* @throws IOException
* @throws IllegalStateException - if parser is not set
*/
public void insertAfterStart(Element elem, String htmlText)
throws BadLocationException, IOException
{
HTMLEditorKit.ParserCallback reader = getInsertingReader(
elem.getStartOffset(), 0, 0, HTML.Tag.BODY, elem);
// TODO charset
getParser().parse(new StringReader(htmlText), reader, true);
}
/**
* Overridden to tag content with the synthetic HTML.Tag.CONTENT
* tag.
*/
protected void insertUpdate(DefaultDocumentEvent evt, AttributeSet att)
{
if (att == null)
{
SimpleAttributeSet sas = new SimpleAttributeSet();
sas.addAttribute(StyleConstants.NameAttribute, HTML.Tag.CONTENT);
att = sas;
}
super.insertUpdate(evt, att);
}
/**
* Returns <code>true</code> when this document is inside a frame,
* <code>false</code> otherwise.
*
* @return <code>true</code> when this document is inside a frame,
* <code>false</code> otherwise
*/
boolean isFrameDocument()
{
return frameDocument;
}
/**
* Set <code>true</code> when this document is inside a frame,
* <code>false</code> otherwise.
*
* @param frameDoc <code>true</code> when this document is inside a frame,
* <code>false</code> otherwise
*/
void setFrameDocument(boolean frameDoc)
{
frameDocument = frameDoc;
}
/**
* Returns the target that is specified in the base tag, if this is the case.
*
* @return the target that is specified in the base tag, if this is the case
*/
String getBaseTarget()
{
return baseTarget;
}
/**
* Updates the A tag's pseudo class value in response to a hyperlink
* action.
*
* @param el the corresponding element
* @param value the new value
*/
void updateSpecialClass(Element el, HTML.Attribute cl, String value)
{
try
{
writeLock();
DefaultDocumentEvent ev =
new DefaultDocumentEvent(el.getStartOffset(), 1,
DocumentEvent.EventType.CHANGE);
AttributeSet elAtts = el.getAttributes();
AttributeSet anchorAtts = (AttributeSet) elAtts.getAttribute(HTML.Tag.A);
if (anchorAtts != null)
{
AttributeSet copy = elAtts.copyAttributes();
StyleSheet ss = getStyleSheet();
if (value != null)
{
anchorAtts = ss.addAttribute(anchorAtts, cl, value);
}
else
{
anchorAtts = ss.removeAttribute(anchorAtts, cl);
}
MutableAttributeSet matts = (MutableAttributeSet) elAtts;
ev.addEdit(new AttributeUndoableEdit(el, copy, false));
matts.removeAttribute(HTML.Tag.A);
matts.addAttribute(HTML.Tag.A, anchorAtts);
ev.end();
fireChangedUpdate(ev);
fireUndoableEditUpdate(new UndoableEditEvent(this, ev));
}
}
finally
{
writeUnlock();
}
}
}
|