initial import
[vuplus_webkit] / Source / WebCore / editing / MarkupAccumulator.cpp
1 /*
2  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2009, 2010 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "MarkupAccumulator.h"
29
30 #include "CDATASection.h"
31 #include "Comment.h"
32 #include "DocumentFragment.h"
33 #include "DocumentType.h"
34 #include "Editor.h"
35 #include "HTMLElement.h"
36 #include "HTMLNames.h"
37 #include "KURL.h"
38 #include "ProcessingInstruction.h"
39 #include "XMLNSNames.h"
40 #include <wtf/text/StringBuilder.h>
41 #include <wtf/unicode/CharacterNames.h>
42
43 namespace WebCore {
44
45 using namespace HTMLNames;
46
47 void appendCharactersReplacingEntities(StringBuilder& out, const UChar* content, size_t length, EntityMask entityMask)
48 {
49     DEFINE_STATIC_LOCAL(const String, ampReference, ("&amp;"));
50     DEFINE_STATIC_LOCAL(const String, ltReference, ("&lt;"));
51     DEFINE_STATIC_LOCAL(const String, gtReference, ("&gt;"));
52     DEFINE_STATIC_LOCAL(const String, quotReference, ("&quot;"));
53     DEFINE_STATIC_LOCAL(const String, nbspReference, ("&nbsp;"));
54
55     static const EntityDescription entityMaps[] = {
56         { '&', ampReference, EntityAmp },
57         { '<', ltReference, EntityLt },
58         { '>', gtReference, EntityGt },
59         { '"', quotReference, EntityQuot },
60         { noBreakSpace, nbspReference, EntityNbsp },
61     };
62
63     size_t positionAfterLastEntity = 0;
64     for (size_t i = 0; i < length; ++i) {
65         for (size_t m = 0; m < WTF_ARRAY_LENGTH(entityMaps); ++m) {
66             if (content[i] == entityMaps[m].entity && entityMaps[m].mask & entityMask) {
67                 out.append(content + positionAfterLastEntity, i - positionAfterLastEntity);
68                 out.append(entityMaps[m].reference);
69                 positionAfterLastEntity = i + 1;
70                 break;
71             }
72         }
73     }
74     out.append(content + positionAfterLastEntity, length - positionAfterLastEntity);
75 }
76
77 MarkupAccumulator::MarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs resolveUrlsMethod, const Range* range)
78     : m_nodes(nodes)
79     , m_range(range)
80     , m_resolveURLsMethod(resolveUrlsMethod)
81 {
82 }
83
84 MarkupAccumulator::~MarkupAccumulator()
85 {
86 }
87
88 String MarkupAccumulator::serializeNodes(Node* node, Node* nodeToSkip, EChildrenOnly childrenOnly)
89 {
90     StringBuilder out;
91     serializeNodesWithNamespaces(node, nodeToSkip, childrenOnly, 0);
92     out.reserveCapacity(length());
93     concatenateMarkup(out);
94     return out.toString();
95 }
96
97 void MarkupAccumulator::serializeNodesWithNamespaces(Node* node, Node* nodeToSkip, EChildrenOnly childrenOnly, const Namespaces* namespaces)
98 {
99     if (node == nodeToSkip)
100         return;
101
102     Namespaces namespaceHash;
103     if (namespaces)
104         namespaceHash = *namespaces;
105
106     if (!childrenOnly)
107         appendStartTag(node, &namespaceHash);
108
109     if (!(node->document()->isHTMLDocument() && elementCannotHaveEndTag(node))) {
110         for (Node* current = node->firstChild(); current; current = current->nextSibling())
111             serializeNodesWithNamespaces(current, nodeToSkip, IncludeNode, &namespaceHash);
112     }
113
114     if (!childrenOnly)
115         appendEndTag(node);
116 }
117
118 String MarkupAccumulator::resolveURLIfNeeded(const Element* element, const String& urlString) const
119 {
120     switch (m_resolveURLsMethod) {
121     case ResolveAllURLs:
122         return element->document()->completeURL(urlString).string();
123
124     case ResolveNonLocalURLs:
125         if (!element->document()->url().isLocalFile())
126             return element->document()->completeURL(urlString).string();
127         break;
128
129     case DoNotResolveURLs:
130         break;
131     }
132     return urlString;
133 }
134
135 void MarkupAccumulator::appendString(const String& string)
136 {
137     m_succeedingMarkup.append(string);
138 }
139
140 void MarkupAccumulator::appendStartTag(Node* node, Namespaces* namespaces)
141 {
142     StringBuilder markup;
143     appendStartMarkup(markup, node, namespaces);
144     appendString(markup.toString());
145     if (m_nodes)
146         m_nodes->append(node);
147 }
148
149 void MarkupAccumulator::appendEndTag(Node* node)
150 {
151     StringBuilder markup;
152     appendEndMarkup(markup, node);
153     appendString(markup.toString());
154 }
155
156 size_t MarkupAccumulator::totalLength(const Vector<String>& strings)
157 {
158     size_t length = 0;
159     for (size_t i = 0; i < strings.size(); ++i)
160         length += strings[i].length();
161     return length;
162 }
163
164 // FIXME: This is a very inefficient way of accumulating the markup.
165 // We're converting results of appendStartMarkup and appendEndMarkup from StringBuilder to String
166 // and then back to StringBuilder and again to String here.
167 void MarkupAccumulator::concatenateMarkup(StringBuilder& out)
168 {
169     for (size_t i = 0; i < m_succeedingMarkup.size(); ++i)
170         out.append(m_succeedingMarkup[i]);
171 }
172
173 void MarkupAccumulator::appendAttributeValue(StringBuilder& result, const String& attribute, bool documentIsHTML)
174 {
175     appendCharactersReplacingEntities(result, attribute.characters(), attribute.length(),
176         documentIsHTML ? EntityMaskInHTMLAttributeValue : EntityMaskInAttributeValue);
177 }
178
179 void MarkupAccumulator::appendCustomAttributes(StringBuilder&, Element*, Namespaces*)
180 {
181 }
182
183 void MarkupAccumulator::appendQuotedURLAttributeValue(StringBuilder& result, const Element* element, const Attribute& attribute)
184 {
185     ASSERT(element->isURLAttribute(const_cast<Attribute*>(&attribute)));
186     const String resolvedURLString = resolveURLIfNeeded(element, attribute.value());
187     UChar quoteChar = '\"';
188     String strippedURLString = resolvedURLString.stripWhiteSpace();
189     if (protocolIsJavaScript(strippedURLString)) {
190         // minimal escaping for javascript urls
191         if (strippedURLString.contains('"')) {
192             if (strippedURLString.contains('\''))
193                 strippedURLString.replace('\"', "&quot;");
194             else
195                 quoteChar = '\'';
196         }
197         result.append(quoteChar);
198         result.append(strippedURLString);
199         result.append(quoteChar);
200         return;
201     }
202
203     // FIXME: This does not fully match other browsers. Firefox percent-escapes non-ASCII characters for innerHTML.
204     result.append(quoteChar);
205     appendAttributeValue(result, resolvedURLString, false);
206     result.append(quoteChar);
207 }
208
209 void MarkupAccumulator::appendNodeValue(StringBuilder& out, const Node* node, const Range* range, EntityMask entityMask)
210 {
211     String str = node->nodeValue();
212     const UChar* characters = str.characters();
213     size_t length = str.length();
214
215     if (range) {
216         ExceptionCode ec;
217         if (node == range->endContainer(ec))
218             length = range->endOffset(ec);
219         if (node == range->startContainer(ec)) {
220             size_t start = range->startOffset(ec);
221             characters += start;
222             length -= start;
223         }
224     }
225
226     appendCharactersReplacingEntities(out, characters, length, entityMask);
227 }
228
229 bool MarkupAccumulator::shouldAddNamespaceElement(const Element* element)
230 {
231     // Don't add namespace attribute if it is already defined for this elem.
232     const AtomicString& prefix = element->prefix();
233     if (prefix.isEmpty())
234         return !element->hasAttribute(xmlnsAtom);
235
236     DEFINE_STATIC_LOCAL(String, xmlnsWithColon, ("xmlns:"));
237     return !element->hasAttribute(xmlnsWithColon + prefix);
238 }
239
240 bool MarkupAccumulator::shouldAddNamespaceAttribute(const Attribute& attribute, Namespaces& namespaces)
241 {
242     namespaces.checkConsistency();
243
244     // Don't add namespace attributes twice
245     if (attribute.name() == XMLNSNames::xmlnsAttr) {
246         namespaces.set(emptyAtom.impl(), attribute.value().impl());
247         return false;
248     }
249     
250     QualifiedName xmlnsPrefixAttr(xmlnsAtom, attribute.localName(), XMLNSNames::xmlnsNamespaceURI);
251     if (attribute.name() == xmlnsPrefixAttr) {
252         namespaces.set(attribute.localName().impl(), attribute.value().impl());
253         return false;
254     }
255     
256     return true;
257 }
258
259 void MarkupAccumulator::appendNamespace(StringBuilder& result, const AtomicString& prefix, const AtomicString& namespaceURI, Namespaces& namespaces)
260 {
261     namespaces.checkConsistency();
262     if (namespaceURI.isEmpty())
263         return;
264         
265     // Use emptyAtoms's impl() for both null and empty strings since the HashMap can't handle 0 as a key
266     AtomicStringImpl* pre = prefix.isEmpty() ? emptyAtom.impl() : prefix.impl();
267     AtomicStringImpl* foundNS = namespaces.get(pre);
268     if (foundNS != namespaceURI.impl()) {
269         namespaces.set(pre, namespaceURI.impl());
270         result.append(' ');
271         result.append(xmlnsAtom.string());
272         if (!prefix.isEmpty()) {
273             result.append(':');
274             result.append(prefix);
275         }
276
277         result.append('=');
278         result.append('"');
279         appendAttributeValue(result, namespaceURI, false);
280         result.append('"');
281     }
282 }
283
284 EntityMask MarkupAccumulator::entityMaskForText(Text* text) const
285 {
286     const QualifiedName* parentName = 0;
287     if (text->parentElement())
288         parentName = &static_cast<Element*>(text->parentElement())->tagQName();
289     
290     if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
291         return EntityMaskInCDATA;
292
293     return text->document()->isHTMLDocument() ? EntityMaskInHTMLPCDATA : EntityMaskInPCDATA;
294 }
295
296 void MarkupAccumulator::appendText(StringBuilder& out, Text* text)
297 {
298     appendNodeValue(out, text, m_range, entityMaskForText(text));
299 }
300
301 void MarkupAccumulator::appendComment(StringBuilder& out, const String& comment)
302 {
303     // FIXME: Comment content is not escaped, but XMLSerializer (and possibly other callers) should raise an exception if it includes "-->".
304     out.append("<!--");
305     out.append(comment);
306     out.append("-->");
307 }
308
309 void MarkupAccumulator::appendDocumentType(StringBuilder& result, const DocumentType* n)
310 {
311     if (n->name().isEmpty())
312         return;
313
314     result.append("<!DOCTYPE ");
315     result.append(n->name());
316     if (!n->publicId().isEmpty()) {
317         result.append(" PUBLIC \"");
318         result.append(n->publicId());
319         result.append("\"");
320         if (!n->systemId().isEmpty()) {
321             result.append(" \"");
322             result.append(n->systemId());
323             result.append("\"");
324         }
325     } else if (!n->systemId().isEmpty()) {
326         result.append(" SYSTEM \"");
327         result.append(n->systemId());
328         result.append("\"");
329     }
330     if (!n->internalSubset().isEmpty()) {
331         result.append(" [");
332         result.append(n->internalSubset());
333         result.append("]");
334     }
335     result.append(">");
336 }
337
338 void MarkupAccumulator::appendProcessingInstruction(StringBuilder& out, const String& target, const String& data)
339 {
340     // FIXME: PI data is not escaped, but XMLSerializer (and possibly other callers) this should raise an exception if it includes "?>".
341     out.append("<?");
342     out.append(target);
343     out.append(" ");
344     out.append(data);
345     out.append("?>");
346 }
347
348 void MarkupAccumulator::appendElement(StringBuilder& out, Element* element, Namespaces* namespaces)
349 {
350     appendOpenTag(out, element, namespaces);
351
352     NamedNodeMap* attributes = element->attributes();
353     unsigned length = attributes->length();
354     for (unsigned int i = 0; i < length; i++)
355         appendAttribute(out, element, *attributes->attributeItem(i), namespaces);
356
357     // Give an opportunity to subclasses to add their own attributes.
358     appendCustomAttributes(out, element, namespaces);
359
360     appendCloseTag(out, element);
361 }
362
363 void MarkupAccumulator::appendOpenTag(StringBuilder& out, Element* element, Namespaces* namespaces)
364 {
365     out.append('<');
366     out.append(element->nodeNamePreservingCase());
367     if (!element->document()->isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
368         appendNamespace(out, element->prefix(), element->namespaceURI(), *namespaces);    
369 }
370
371 void MarkupAccumulator::appendCloseTag(StringBuilder& out, Element* element)
372 {
373     if (shouldSelfClose(element)) {
374         if (element->isHTMLElement())
375             out.append(' '); // XHTML 1.0 <-> HTML compatibility.
376         out.append('/');
377     }
378     out.append('>');
379 }
380
381 void MarkupAccumulator::appendAttribute(StringBuilder& out, Element* element, const Attribute& attribute, Namespaces* namespaces)
382 {
383     bool documentIsHTML = element->document()->isHTMLDocument();
384
385     out.append(' ');
386
387     if (documentIsHTML)
388         out.append(attribute.name().localName());
389     else
390         out.append(attribute.name().toString());
391
392     out.append('=');
393
394     if (element->isURLAttribute(const_cast<Attribute*>(&attribute)))
395         appendQuotedURLAttributeValue(out, element, attribute);
396     else {
397         out.append('\"');
398         appendAttributeValue(out, attribute.value(), documentIsHTML);
399         out.append('\"');
400     }
401
402     if (!documentIsHTML && namespaces && shouldAddNamespaceAttribute(attribute, *namespaces))
403         appendNamespace(out, attribute.prefix(), attribute.namespaceURI(), *namespaces);
404 }
405
406 void MarkupAccumulator::appendCDATASection(StringBuilder& out, const String& section)
407 {
408     // FIXME: CDATA content is not escaped, but XMLSerializer (and possibly other callers) should raise an exception if it includes "]]>".
409     out.append("<![CDATA[");
410     out.append(section);
411     out.append("]]>");
412 }
413
414 void MarkupAccumulator::appendStartMarkup(StringBuilder& result, const Node* node, Namespaces* namespaces)
415 {
416     if (namespaces)
417         namespaces->checkConsistency();
418
419     switch (node->nodeType()) {
420     case Node::TEXT_NODE:
421         appendText(result, static_cast<Text*>(const_cast<Node*>(node)));
422         break;
423     case Node::COMMENT_NODE:
424         appendComment(result, static_cast<const Comment*>(node)->data());
425         break;
426     case Node::DOCUMENT_NODE:
427     case Node::DOCUMENT_FRAGMENT_NODE:
428         break;
429     case Node::DOCUMENT_TYPE_NODE:
430         appendDocumentType(result, static_cast<const DocumentType*>(node));
431         break;
432     case Node::PROCESSING_INSTRUCTION_NODE:
433         appendProcessingInstruction(result, static_cast<const ProcessingInstruction*>(node)->target(), static_cast<const ProcessingInstruction*>(node)->data());
434         break;
435     case Node::ELEMENT_NODE:
436         appendElement(result, static_cast<Element*>(const_cast<Node*>(node)), namespaces);
437         break;
438     case Node::CDATA_SECTION_NODE:
439         appendCDATASection(result, static_cast<const CDATASection*>(node)->data());
440         break;
441     case Node::ATTRIBUTE_NODE:
442     case Node::ENTITY_NODE:
443     case Node::ENTITY_REFERENCE_NODE:
444     case Node::NOTATION_NODE:
445     case Node::XPATH_NAMESPACE_NODE:
446     case Node::SHADOW_ROOT_NODE:
447         ASSERT_NOT_REACHED();
448         break;
449     }
450 }
451
452 // Rules of self-closure
453 // 1. No elements in HTML documents use the self-closing syntax.
454 // 2. Elements w/ children never self-close because they use a separate end tag.
455 // 3. HTML elements which do not have a "forbidden" end tag will close with a separate end tag.
456 // 4. Other elements self-close.
457 bool MarkupAccumulator::shouldSelfClose(const Node* node)
458 {
459     if (node->document()->isHTMLDocument())
460         return false;
461     if (node->hasChildNodes())
462         return false;
463     if (node->isHTMLElement() && !elementCannotHaveEndTag(node))
464         return false;
465     return true;
466 }
467
468 bool MarkupAccumulator::elementCannotHaveEndTag(const Node* node)
469 {
470     if (!node->isHTMLElement())
471         return false;
472     
473     // FIXME: ieForbidsInsertHTML may not be the right function to call here
474     // ieForbidsInsertHTML is used to disallow setting innerHTML/outerHTML
475     // or createContextualFragment.  It does not necessarily align with
476     // which elements should be serialized w/o end tags.
477     return static_cast<const HTMLElement*>(node)->ieForbidsInsertHTML();
478 }
479
480 void MarkupAccumulator::appendEndMarkup(StringBuilder& result, const Node* node)
481 {
482     if (!node->isElementNode() || shouldSelfClose(node) || (!node->hasChildNodes() && elementCannotHaveEndTag(node)))
483         return;
484
485     result.append('<');
486     result.append('/');
487     result.append(static_cast<const Element*>(node)->nodeNamePreservingCase());
488     result.append('>');
489 }
490
491 }