Debian Codegraph @

net/sf/saxon/serialize/HTMLEmitter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize;
9
10 import net.sf.saxon.event.ReceiverOptions;
11 import net.sf.saxon.expr.parser.Location;
12 import net.sf.saxon.lib.SaxonOutputKeys;
13 import net.sf.saxon.om.NodeName;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.tiny.CompressedWhitespace;
16 import net.sf.saxon.type.SchemaType;
17
18 import javax.xml.transform.OutputKeys;
19 import java.util.Stack;
20
21 /**
22 * This class generates HTML output
23 */
24
25 public abstract class HTMLEmitter extends XMLEmitter {
26
27 /**
28 * Preferred character representations
29 */
30
31 private static final int REP_NATIVE = 0;
32 private static final int REP_ENTITY = 1;
33 private static final int REP_DECIMAL = 2;
34 private static final int REP_HEX = 3;
35
36 private int nonASCIIRepresentation = REP_NATIVE;
37 private int excludedRepresentation = REP_ENTITY;
38
39 private int inScript;
40 protected int version = 4;
41 private String parentElement;
42 private String uri;
43 private boolean escapeNonAscii = false;
44 private Stack<NodeName> nodeNameStack = new Stack<>();
45
46 /**
47 * Decode preferred representation
48 *
49 * @param rep string containing preferred representation (native, entity, decimal, or hex)
50 * @return integer code for the preferred representation
51 */
52
53 private static int representationCode(String rep) {
54 rep = rep.toLowerCase();
55 switch (rep) {
56 case "native":
57 return REP_NATIVE;
58 case "entity":
59 return REP_ENTITY;
60 case "decimal":
61 return REP_DECIMAL;
62 case "hex":
63 return REP_HEX;
64 default:
65 return REP_ENTITY;
66 }
67 }
68
69 /**
70 * Table of HTML tags that have no closing tag
71 */
72
73 static HTMLTagHashSet emptyTags = new HTMLTagHashSet(31);
74
75
76 protected static void setEmptyTag(String tag) {
77 emptyTags.add(tag);
78 }
79
80 protected static boolean isEmptyTag(String tag) {
81 return emptyTags.contains(tag);
82 }
83
84 /**
85 * Table of boolean attributes
86 */
87
88 // we use two HashMaps to avoid unnecessary string concatenations
89
90 // Sizes must be large enough: this hash set cannot grow beyond the initial size
91 private static HTMLTagHashSet booleanAttributes = new HTMLTagHashSet(43);
92 private static HTMLTagHashSet booleanCombinations = new HTMLTagHashSet(57);
93
94 // See http://www.w3.org/TR/html5/index.html#attributes-1 (checked 2014-01-07)
95
96 static {
97 setBooleanAttribute("*", "hidden"); // HTML5
98 setBooleanAttribute("area", "nohref");
99 setBooleanAttribute("audio", "autoplay"); // HTML5
100 setBooleanAttribute("audio", "controls"); // HTML5
101 setBooleanAttribute("audio", "loop"); // HTML5
102 setBooleanAttribute("audio", "muted"); // HTML5
103 setBooleanAttribute("button", "disabled");
104 setBooleanAttribute("button", "autofocus"); // HTML5
105 setBooleanAttribute("button", "formnovalidate"); //HTML5
106 setBooleanAttribute("details", "open"); // HTML5
107 setBooleanAttribute("dialog", "open"); // HTML5
108 setBooleanAttribute("dir", "compact");
109 setBooleanAttribute("dl", "compact");
110 setBooleanAttribute("fieldset", "disabled"); //HTML5
111 setBooleanAttribute("form", "novalidate"); // HTML5
112 setBooleanAttribute("frame", "noresize");
113 setBooleanAttribute("hr", "noshade");
114 setBooleanAttribute("img", "ismap");
115 setBooleanAttribute("input", "checked");
116 setBooleanAttribute("input", "disabled");
117 setBooleanAttribute("input", "multiple"); //HTML5
118 setBooleanAttribute("input", "readonly");
119 setBooleanAttribute("input", "required"); //HTML5
120 setBooleanAttribute("input", "autofocus"); // HTML5
121 setBooleanAttribute("input", "formnovalidate"); //HTML5
122 setBooleanAttribute("iframe", "seamless"); // HTML5
123 setBooleanAttribute("keygen", "autofocus"); // HTML5
124 setBooleanAttribute("keygen", "disabled"); //HTML5
125 setBooleanAttribute("menu", "compact");
126 setBooleanAttribute("object", "declare");
127 setBooleanAttribute("object", "typemustmatch"); // HTML5
128 setBooleanAttribute("ol", "compact");
129 setBooleanAttribute("ol", "reversed"); // HTML5
130 setBooleanAttribute("optgroup", "disabled");
131 setBooleanAttribute("option", "selected");
132 setBooleanAttribute("option", "disabled");
133 setBooleanAttribute("script", "defer");
134 setBooleanAttribute("script", "async"); // HTML5
135 setBooleanAttribute("select", "multiple");
136 setBooleanAttribute("select", "disabled");
137 setBooleanAttribute("select", "autofocus"); // HTML5
138 setBooleanAttribute("select", "required"); // HTML5
139 setBooleanAttribute("style", "scoped"); // HTML5
140 setBooleanAttribute("td", "nowrap");
141 setBooleanAttribute("textarea", "disabled");
142 setBooleanAttribute("textarea", "readonly");
143 setBooleanAttribute("textarea", "autofocus"); // HTML5
144 setBooleanAttribute("textarea", "required"); // HTML5
145 setBooleanAttribute("th", "nowrap");
146 setBooleanAttribute("track", "default"); // HTML5
147 setBooleanAttribute("ul", "compact");
148 setBooleanAttribute("video", "autoplay"); // HTML5
149 setBooleanAttribute("video", "controls"); // HTML5
150 setBooleanAttribute("video", "loop"); // HTML5
151 setBooleanAttribute("video", "muted"); // HTML5
152 }
153
154 private static void setBooleanAttribute(String element, String attribute) {
155 booleanAttributes.add(attribute);
156 booleanCombinations.add(element + '+' + attribute);
157 }
158
159 private static boolean isBooleanAttribute(String element, String attribute, String value) {
160 return attribute.equalsIgnoreCase(value) &&
161 booleanAttributes.contains(attribute) &&
162 ( booleanCombinations.contains(element + '+' + attribute) ||
163 booleanCombinations.contains("*+" + attribute));
164 }
165
166 /**
167 * Constructor
168 */
169
170 public HTMLEmitter() {
171
172 }
173
174 /**
175 * Say that all non-ASCII characters should be escaped, regardless of the character encoding
176 *
177 * @param escape true if all non ASCII characters should be escaped
178 */
179
180 public void setEscapeNonAscii(Boolean escape) {
181 escapeNonAscii = escape;
182 }
183
184 /**
185 * Decide whether an element is "serialized as an HTML element" in the language of the 3.0 specification
186 *
187 * @return true if the element
188 */
189
190 protected abstract boolean isHTMLElement(NodeName name);
191
192 /**
193 * Output start of document
194 */
195
196 public void open() throws XPathException {
197 }
198
199 protected void openDocument() throws XPathException {
200 if (writer == null) {
201 makeWriter();
202 }
203 if (started) {
204 return;
205 }
206 started = true;
207 // This method is sometimes called twice, especially during an identity transform
208 // This check stops two DOCTYPE declarations being output.
209
210
211 String byteOrderMark = outputProperties.getProperty(SaxonOutputKeys.BYTE_ORDER_MARK);
212
213 if ("yes".equals(byteOrderMark) &&
214 "UTF-8".equalsIgnoreCase(outputProperties.getProperty(OutputKeys.ENCODING))) {
215 try {
216 writer.write('\uFEFF');
217 } catch (java.io.IOException err) {
218 // Might be an encoding exception; just ignore it
219 }
220 }
221 if ("yes".equals(outputProperties.getProperty(SaxonOutputKeys.SINGLE_QUOTES))) {
222 delimiter = '\'';
223 attSpecials = specialInAttSingle;
224 }
225 inScript = -1000000;
226 }
227
228 /**
229 * Output the document type declaration
230 *
231 * @param displayName The element name
232 * @param systemId The DOCTYPE system identifier
233 * @param publicId The DOCTYPE public identifier
234 */
235
236 protected void writeDocType(NodeName name, String displayName, String systemId, String publicId) throws XPathException {
237 super.writeDocType(name, displayName, systemId, publicId);
238 }
239
240 /**
241 * Output element start tag
242 */
243
244 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
245
246 super.startElement(elemName, typeCode, location, properties);
247 uri = elemName.getURI();
248 parentElement = elementStack.peek();
249 if (elemName.hasURI("") &&
250 (parentElement.equalsIgnoreCase("script") ||
251 parentElement.equalsIgnoreCase("style"))) {
252 inScript = 0;
253 }
254 inScript++;
255 nodeNameStack.push(elemName);
256 }
257
258 public void startContent() throws XPathException {
259 closeStartTag(); // prevent <xxx/> syntax
260 }
261
262 /**
263 * Write attribute name=value pair. Overrides the XML behaviour if the name and value
264 * are the same (we assume this is a boolean attribute to be minimised), or if the value is
265 * a URL.
266 */
267
268 protected void writeAttribute(NodeName elCode, String attname, CharSequence value, int properties) throws XPathException {
269 try {
270 if (uri.isEmpty()) {
271 if (isBooleanAttribute(parentElement, attname, value.toString())) {
272 writer.write(attname);
273 return;
274 }
275 }
276 super.writeAttribute(elCode, attname, value, properties);
277 } catch (java.io.IOException err) {
278 throw new XPathException(err);
279 }
280 }
281
282
283 /**
284 * Escape characters. Overrides the XML behaviour
285 */
286
287 protected void writeEscape(final CharSequence chars, final boolean inAttribute)
288 throws java.io.IOException, XPathException {
289
290 int segstart = 0;
291 final boolean[] specialChars = inAttribute ? attSpecials : specialInText;
292
293 if (chars instanceof CompressedWhitespace) {
294 ((CompressedWhitespace) chars).writeEscape(specialChars, writer);
295 return;
296 }
297 boolean disabled = false;
298
299 while (segstart < chars.length()) {
300 int i = segstart;
301
302 // find a maximal sequence of "ordinary" characters
303
304 if (escapeNonAscii) {
305 char c;
306 while (i < chars.length() && (c = chars.charAt(i)) < 127 && !specialChars[c]) {
307 i++;
308 }
309 } else {
310 char c;
311 while (i < chars.length() &&
312 ((c = chars.charAt(i)) < 127 ? !specialChars[c] : (characterSet.inCharset(c) && c > 160)
313 )
314 ) {
315 i++;
316 }
317 }
318
319 // if this was the whole string, output the string and quit
320
321 if (i == chars.length()) {
322 if (segstart == 0) {
323 writeCharSequence(chars);
324 } else {
325 writeCharSequence(chars.subSequence(segstart, i));
326 }
327 return;
328 }
329
330 // otherwise, output this sequence and continue
331 if (i > segstart) {
332 writeCharSequence(chars.subSequence(segstart, i));
333 }
334
335 final char c = chars.charAt(i);
336 if (c == 0) {
337 // used to switch escaping on and off
338 disabled = !disabled;
339 } else if (disabled) {
340 writer.write(c);
341 } else if (c <= 127) {
342 // handle a special ASCII character
343 if (inAttribute) {
344 if (c == '<') {
345 writer.write('<'); // not escaped
346 } else if (c == '>') {
347 writer.write("&gt;"); // recommended for older browsers
348 } else if (c == '&') {
349 if (i + 1 < chars.length() && chars.charAt(i + 1) == '{') {
350 writer.write('&'); // not escaped if followed by '{'
351 } else {
352 writer.write("&amp;");
353 }
354 } else if (c == '\"') {
355 writer.write("&#34;");
356 } else if (c == '\'') {
357 writer.write("&#39;");
358 } else if (c == '\n') {
359 writer.write("&#xA;");
360 } else if (c == '\t') {
361 writer.write("&#x9;");
362 } else if (c == '\r') {
363 writer.write("&#xD;");
364 }
365 } else {
366 if (c == '<') {
367 writer.write("&lt;");
368 } else if (c == '>') {
369 writer.write("&gt;"); // changed to allow for "]]>"
370 } else if (c == '&') {
371 writer.write("&amp;");
372 } else if (c == '\r') {
373 writer.write("&#xD;");
374 }
375 }
376
377 } else if (c < 160) {
378 // these control characters are illegal in HTML
379 XPathException err = new XPathException("Illegal HTML character: decimal " + (int) c);
380 err.setErrorCode("SERE0014");
381 throw err;
382
383 } else if (c == 160) {
384 // always output NBSP as an entity reference
385 writer.write("&nbsp;");
386
387 } else if (c >= 55296 && c <= 56319) { //handle surrogate pair
388
389 //A surrogate pair is two consecutive Unicode characters. The first
390 //is in the range D800 to DBFF, the second is in the range DC00 to DFFF.
391 //To compute the numeric value of the character corresponding to a surrogate
392 //pair, use this formula (all numbers are hex):
393 //(FirstChar - D800) * 400 + (SecondChar - DC00) + 10000
394
395 // we'll trust the data to be sound
396 int charval = (((int) c - 55296) * 1024) + ((int) chars.charAt(i + 1) - 56320) + 65536;
397 characterReferenceGenerator.outputCharacterReference(charval, writer);
398 i++;
399
400 } else if (escapeNonAscii || !characterSet.inCharset(c)) {
401 characterReferenceGenerator.outputCharacterReference(c, writer);
402 } else {
403 writer.write(c);
404 }
405 segstart = ++i;
406 }
407
408 }
409
410 /**
411 * Output an element end tag.
412 */
413
414 public void endElement() throws XPathException {
415 NodeName nodeName = nodeNameStack.pop();
416 String name = elementStack.peek();
417 inScript--;
418 if (inScript == 0) {
419 inScript = -1000000;
420 }
421
422 if (isEmptyTag(name) && isHTMLElement(nodeName)) {
423 // no end tag required
424 elementStack.pop();
425 } else {
426 super.endElement();
427 }
428
429 }
430
431 /**
432 * Character data.
433 */
434
435 public void characters(CharSequence chars, Location locationId, int properties)
436 throws XPathException {
437 int options = properties;
438 if (inScript > 0) {
439 options |= ReceiverOptions.DISABLE_ESCAPING;
440 }
441 super.characters(chars, locationId, options);
442 }
443
444 /**
445 * Handle a processing instruction.
446 */
447
448 public void processingInstruction(String target, CharSequence data, Location locationId, int properties)
449 throws XPathException {
450 if (!started) {
451 openDocument();
452 }
453 for (int i = 0; i < data.length(); i++) {
454 if (data.charAt(i) == '>') {
455 XPathException err = new XPathException("A processing instruction in HTML must not contain a > character");
456 err.setErrorCode("SERE0015");
457 throw err;
458 }
459 }
460 try {
461 writer.write("<?");
462 writer.write(target);
463 writer.write(' ');
464 writeCharSequence(data);
465 writer.write('>');
466 } catch (java.io.IOException err) {
467 throw new XPathException(err);
468 }
469 }
470
471
472 }
473