initial import
[vuplus_webkit] / Source / WebCore / page / PageSerializer.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "PageSerializer.h"
33
34 #include "CSSImageValue.h"
35 #include "CSSImportRule.h"
36 #include "CSSStyleRule.h"
37 #include "CachedImage.h"
38 #include "Document.h"
39 #include "Element.h"
40 #include "Frame.h"
41 #include "HTMLFrameOwnerElement.h"
42 #include "HTMLHeadElement.h"
43 #include "HTMLImageElement.h"
44 #include "HTMLLinkElement.h"
45 #include "HTMLMetaCharsetParser.h"
46 #include "HTMLNames.h"
47 #include "HTMLStyleElement.h"
48 #include "HTTPParsers.h"
49 #include "Image.h"
50 #include "MIMETypeRegistry.h"
51 #include "MarkupAccumulator.h"
52 #include "Page.h"
53 #include "StyleCachedImage.h"
54 #include "StyleImage.h"
55 #include "Text.h"
56 #include "TextEncoding.h"
57 #include <wtf/text/CString.h>
58 #include <wtf/text/StringBuilder.h>
59 #include <wtf/text/WTFString.h>
60
61 namespace WebCore {
62
63 static bool isCharsetSpecifyingNode(Node* node)
64 {
65     if (!node->isHTMLElement())
66         return false;
67
68     HTMLElement* element = toHTMLElement(node);
69     if (!element->hasTagName(HTMLNames::metaTag))
70         return false;
71     HTMLMetaCharsetParser::AttributeList attributes;
72     const NamedNodeMap* attributesMap = element->attributes(true);
73     for (unsigned i = 0; i < attributesMap->length(); ++i) {
74         Attribute* item = attributesMap->attributeItem(i);
75         // FIXME: We should deal appropriately with the attribute if they have a namespace.
76         attributes.append(make_pair(item->name().toString(), item->value().string()));
77     }
78     TextEncoding textEncoding = HTMLMetaCharsetParser::encodingFromMetaAttributes(attributes);
79     return textEncoding.isValid();
80 }
81
82 static bool shouldIgnoreElement(Element* element)
83 {
84     return element->hasTagName(HTMLNames::scriptTag) || element->hasTagName(HTMLNames::noscriptTag) || isCharsetSpecifyingNode(element);
85 }
86
87 static const QualifiedName& frameOwnerURLAttributeName(const HTMLFrameOwnerElement& frameOwner)
88 {
89     // FIXME: We should support all frame owners including applets.
90     return frameOwner.hasTagName(HTMLNames::objectTag) ? HTMLNames::dataAttr : HTMLNames::srcAttr;
91 }
92
93 class SerializerMarkupAccumulator : public WebCore::MarkupAccumulator {
94 public:
95     SerializerMarkupAccumulator(PageSerializer*, Document*, Vector<Node*>*);
96     virtual ~SerializerMarkupAccumulator();
97
98 protected:
99     virtual void appendText(StringBuilder& out, Text*);
100     virtual void appendElement(StringBuilder& out, Element*, Namespaces*);
101     virtual void appendCustomAttributes(StringBuilder& out, Element*, Namespaces*);
102     virtual void appendEndTag(Node*);
103
104 private:
105     PageSerializer* m_serializer;
106     Document* m_document;
107 };
108
109 SerializerMarkupAccumulator::SerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes)
110     : MarkupAccumulator(nodes, ResolveAllURLs)
111     , m_serializer(serializer)
112     , m_document(document)
113 {
114     // MarkupAccumulator does not serialize the <?xml ... line, so we add it explicitely to ensure the right encoding is specified.
115     if (m_document->isXHTMLDocument() || m_document->xmlStandalone() || m_document->isSVGDocument())
116         appendString("<?xml version=\"" + m_document->xmlVersion() + "\" encoding=\"" + m_document->charset() + "\"?>");
117 }
118
119 SerializerMarkupAccumulator::~SerializerMarkupAccumulator()
120 {
121 }
122
123 void SerializerMarkupAccumulator::appendText(StringBuilder& out, Text* text)
124 {
125     Element* parent = text->parentElement();
126     if (parent && !shouldIgnoreElement(parent))
127         MarkupAccumulator::appendText(out, text);
128 }
129
130 void SerializerMarkupAccumulator::appendElement(StringBuilder& out, Element* element, Namespaces* namespaces)
131 {
132     if (!shouldIgnoreElement(element))
133         MarkupAccumulator::appendElement(out, element, namespaces);
134
135     if (element->hasTagName(HTMLNames::headTag)) {
136         out.append("<meta charset=\"");
137         out.append(m_document->charset());
138         out.append("\">");
139     }
140
141     // FIXME: For object (plugins) tags and video tag we could replace them by an image of their current contents.
142 }
143
144 void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces)
145 {
146     if (!element->isFrameOwnerElement())
147         return;
148
149     HTMLFrameOwnerElement* frameOwner = static_cast<HTMLFrameOwnerElement*>(element);
150     Frame* frame = frameOwner->contentFrame();
151     if (!frame)
152         return;
153
154     KURL url = frame->document()->url();
155     if (url.isValid() && !url.protocolIs("about"))
156         return;
157
158     // We need to give a fake location to blank frames so they can be referenced by the serialized frame.
159     url = m_serializer->urlForBlankFrame(frame);
160     RefPtr<Attribute> attribute = Attribute::create(frameOwnerURLAttributeName(*frameOwner), url.string());
161     appendAttribute(out, element, *attribute, namespaces);
162 }
163
164 void SerializerMarkupAccumulator::appendEndTag(Node* node)
165 {
166     if (node->isElementNode() && !shouldIgnoreElement(toElement(node)))
167         MarkupAccumulator::appendEndTag(node);
168 }
169
170 PageSerializer::Resource::Resource()
171 {
172 }
173
174 PageSerializer::Resource::Resource(const KURL& url, const String& mimeType, PassRefPtr<SharedBuffer> data)
175     : url(url)
176     , mimeType(mimeType)
177     , data(data)
178 {
179 }
180
181 PageSerializer::PageSerializer(Vector<PageSerializer::Resource>* resources)
182     : m_resources(resources)
183     , m_blankFrameCounter(0)
184 {
185 }
186
187 void PageSerializer::serialize(Page* page)
188 {
189     serializeFrame(page->mainFrame());
190 }
191
192 void PageSerializer::serializeFrame(Frame* frame)
193 {
194     Document* document = frame->document();
195     KURL url = document->url();
196     if (!url.isValid() || url.protocolIs("about")) {
197         // For blank frames we generate a fake URL so they can be referenced by their containing frame.
198         url = urlForBlankFrame(frame);
199     }
200
201     if (m_resourceURLs.contains(url)) {
202         // FIXME: We could have 2 frame with the same URL but which were dynamically changed and have now
203         // different content. So we should serialize both and somehow rename the frame src in the containing
204         // frame. Arg!
205         return;
206     }
207
208     Vector<Node*> nodes;
209     SerializerMarkupAccumulator accumulator(this, document, &nodes);
210     TextEncoding textEncoding(document->charset());
211     CString data;
212     if (!textEncoding.isValid()) {
213         // FIXME: iframes used as images trigger this. We should deal with them correctly.
214         return;
215     }
216     String text = accumulator.serializeNodes(document->documentElement(), 0, IncludeNode);
217     CString frameHTML = textEncoding.encode(text.characters(), text.length(), EntitiesForUnencodables);
218     m_resources->append(Resource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
219     m_resourceURLs.add(url);
220
221     for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
222         Node* node = *iter;
223         if (!node->isElementNode())
224             continue;
225
226         Element* element = toElement(node);
227         // We have to process in-line style as it might contain some resources (typically background images).
228         retrieveResourcesForCSSDeclaration(element->style());
229
230         if (element->hasTagName(HTMLNames::imgTag)) {
231             HTMLImageElement* imageElement = static_cast<HTMLImageElement*>(element);
232             KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr));
233             CachedImage* cachedImage = imageElement->cachedImage();
234             addImageToResources(cachedImage, url);
235         } else if (element->hasTagName(HTMLNames::linkTag)) {
236             HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(element);
237             StyleSheet* sheet = linkElement->sheet();
238             if (sheet && sheet->isCSSStyleSheet()) {
239                 KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr));
240                 serializeCSSStyleSheet(static_cast<CSSStyleSheet*>(sheet), url);
241                 ASSERT(m_resourceURLs.contains(url));
242             }
243         } else if (element->hasTagName(HTMLNames::styleTag)) {
244             HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(element);
245             StyleSheet* sheet = styleElement->sheet();
246             if (sheet && sheet->isCSSStyleSheet())
247                 serializeCSSStyleSheet(static_cast<CSSStyleSheet*>(sheet), KURL());
248         }
249     }
250
251     for (Frame* childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
252         serializeFrame(childFrame);
253 }
254
255 void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const KURL& url)
256 {
257     StringBuilder cssText;
258     for (unsigned i = 0; i < styleSheet->length(); ++i) {
259         StyleBase* item = styleSheet->item(i);
260         String itemText = item->cssText();
261         if (!itemText.isEmpty()) {
262             cssText.append(itemText);
263             if (i < styleSheet->length() - 1)
264                 cssText.append("\n\n");
265         }
266         // Some rules have resources associated with them that we need to retrieve.
267         if (item->isImportRule()) {
268             CSSImportRule* importRule = static_cast<CSSImportRule*>(item);
269             KURL importURL = styleSheet->document()->completeURL(importRule->href());
270             if (m_resourceURLs.contains(importURL))
271                 continue;
272             serializeCSSStyleSheet(importRule->styleSheet(), importURL);
273         } else if (item->isFontFaceRule()) {
274             // FIXME: Add support for font face rule. It is not clear to me at this point if the actual otf/eot file can
275             // be retrieved from the CSSFontFaceRule object.
276         } else if (item->isStyleRule())
277             retrieveResourcesForCSSRule(static_cast<CSSStyleRule*>(item));
278     }
279
280     if (url.isValid() && !m_resourceURLs.contains(url)) {
281         // FIXME: We should check whether a charset has been specified and if none was found add one.
282         TextEncoding textEncoding(styleSheet->charset());
283         ASSERT(textEncoding.isValid());
284         String textString = cssText.toString();
285         CString text = textEncoding.encode(textString.characters(), textString.length(), EntitiesForUnencodables);
286         m_resources->append(Resource(url, String("text/css"), SharedBuffer::create(text.data(), text.length())));
287         m_resourceURLs.add(url);
288     }
289 }
290
291 void PageSerializer::addImageToResources(CachedImage* image, const KURL& url)
292 {
293     if (!url.isValid() || m_resourceURLs.contains(url))
294         return;
295
296     if (!image || image->image() == Image::nullImage())
297         return;
298
299     String mimeType = image->response().mimeType();
300     m_resources->append(Resource(url, mimeType, image->image()->data()));
301     m_resourceURLs.add(url);
302 }
303
304 void PageSerializer::retrieveResourcesForCSSRule(CSSStyleRule* rule)
305 {
306     retrieveResourcesForCSSDeclaration(rule->style());
307 }
308
309 void PageSerializer::retrieveResourcesForCSSDeclaration(CSSStyleDeclaration* styleDeclaration)
310 {
311     if (!styleDeclaration)
312         return;
313
314     if (!styleDeclaration->stylesheet()->isCSSStyleSheet())
315         return;
316
317     CSSStyleSheet* cssStyleSheet = static_cast<CSSStyleSheet*>(styleDeclaration->stylesheet());
318
319     // The background-image and list-style-image (for ul or ol) are the CSS properties
320     // that make use of images. We iterate to make sure we include any other
321     // image properties there might be.
322     for (unsigned i = 0; i < styleDeclaration->length(); ++i) {
323         // FIXME: It's kind of ridiculous to get the property name and then get
324         // the value out of the name. Ideally we would get the value out of the
325         // property ID, but CSSStyleDeclaration only gives access to property
326         // names, not IDs.
327         RefPtr<CSSValue> cssValue = styleDeclaration->getPropertyCSSValue(styleDeclaration->item(i));
328         if (!cssValue->isImageValue())
329             continue;
330
331         CSSImageValue* imageValue = static_cast<CSSImageValue*>(cssValue.get());
332         StyleImage* styleImage = imageValue->cachedOrPendingImage();
333         // Non cached-images are just place-holders and do not contain data.
334         if (!styleImage || !styleImage->isCachedImage())
335             continue;
336
337         CachedImage* image = static_cast<StyleCachedImage*>(styleImage)->cachedImage();
338
339         KURL url = cssStyleSheet->document()->completeURL(image->url());
340         addImageToResources(image, url);
341     }
342 }
343
344 KURL PageSerializer::urlForBlankFrame(Frame* frame)
345 {
346     HashMap<Frame*, KURL>::iterator iter = m_blankFrameURLs.find(frame);
347     if (iter != m_blankFrameURLs.end())
348         return iter->second;
349     String url = "wyciwyg://frame/" + String::number(m_blankFrameCounter++);
350     KURL fakeURL(ParsedURLString, url);
351     m_blankFrameURLs.add(frame, fakeURL);
352
353     return fakeURL;
354 }
355
356 }