2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "PageSerializer.h"
34 #include "CSSImageValue.h"
35 #include "CSSImportRule.h"
36 #include "CSSStyleRule.h"
37 #include "CachedImage.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"
50 #include "MIMETypeRegistry.h"
51 #include "MarkupAccumulator.h"
53 #include "StyleCachedImage.h"
54 #include "StyleImage.h"
56 #include "TextEncoding.h"
57 #include <wtf/text/CString.h>
58 #include <wtf/text/StringBuilder.h>
59 #include <wtf/text/WTFString.h>
63 static bool isCharsetSpecifyingNode(Node* node)
65 if (!node->isHTMLElement())
68 HTMLElement* element = toHTMLElement(node);
69 if (!element->hasTagName(HTMLNames::metaTag))
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()));
78 TextEncoding textEncoding = HTMLMetaCharsetParser::encodingFromMetaAttributes(attributes);
79 return textEncoding.isValid();
82 static bool shouldIgnoreElement(Element* element)
84 return element->hasTagName(HTMLNames::scriptTag) || element->hasTagName(HTMLNames::noscriptTag) || isCharsetSpecifyingNode(element);
87 static const QualifiedName& frameOwnerURLAttributeName(const HTMLFrameOwnerElement& frameOwner)
89 // FIXME: We should support all frame owners including applets.
90 return frameOwner.hasTagName(HTMLNames::objectTag) ? HTMLNames::dataAttr : HTMLNames::srcAttr;
93 class SerializerMarkupAccumulator : public WebCore::MarkupAccumulator {
95 SerializerMarkupAccumulator(PageSerializer*, Document*, Vector<Node*>*);
96 virtual ~SerializerMarkupAccumulator();
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*);
105 PageSerializer* m_serializer;
106 Document* m_document;
109 SerializerMarkupAccumulator::SerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes)
110 : MarkupAccumulator(nodes, ResolveAllURLs)
111 , m_serializer(serializer)
112 , m_document(document)
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() + "\"?>");
119 SerializerMarkupAccumulator::~SerializerMarkupAccumulator()
123 void SerializerMarkupAccumulator::appendText(StringBuilder& out, Text* text)
125 Element* parent = text->parentElement();
126 if (parent && !shouldIgnoreElement(parent))
127 MarkupAccumulator::appendText(out, text);
130 void SerializerMarkupAccumulator::appendElement(StringBuilder& out, Element* element, Namespaces* namespaces)
132 if (!shouldIgnoreElement(element))
133 MarkupAccumulator::appendElement(out, element, namespaces);
135 if (element->hasTagName(HTMLNames::headTag)) {
136 out.append("<meta charset=\"");
137 out.append(m_document->charset());
141 // FIXME: For object (plugins) tags and video tag we could replace them by an image of their current contents.
144 void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces)
146 if (!element->isFrameOwnerElement())
149 HTMLFrameOwnerElement* frameOwner = static_cast<HTMLFrameOwnerElement*>(element);
150 Frame* frame = frameOwner->contentFrame();
154 KURL url = frame->document()->url();
155 if (url.isValid() && !url.protocolIs("about"))
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);
164 void SerializerMarkupAccumulator::appendEndTag(Node* node)
166 if (node->isElementNode() && !shouldIgnoreElement(toElement(node)))
167 MarkupAccumulator::appendEndTag(node);
170 PageSerializer::Resource::Resource()
174 PageSerializer::Resource::Resource(const KURL& url, const String& mimeType, PassRefPtr<SharedBuffer> data)
181 PageSerializer::PageSerializer(Vector<PageSerializer::Resource>* resources)
182 : m_resources(resources)
183 , m_blankFrameCounter(0)
187 void PageSerializer::serialize(Page* page)
189 serializeFrame(page->mainFrame());
192 void PageSerializer::serializeFrame(Frame* frame)
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);
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
209 SerializerMarkupAccumulator accumulator(this, document, &nodes);
210 TextEncoding textEncoding(document->charset());
212 if (!textEncoding.isValid()) {
213 // FIXME: iframes used as images trigger this. We should deal with them correctly.
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);
221 for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
223 if (!node->isElementNode())
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());
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));
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());
251 for (Frame* childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
252 serializeFrame(childFrame);
255 void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const KURL& url)
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");
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))
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));
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);
291 void PageSerializer::addImageToResources(CachedImage* image, const KURL& url)
293 if (!url.isValid() || m_resourceURLs.contains(url))
296 if (!image || image->image() == Image::nullImage())
299 String mimeType = image->response().mimeType();
300 m_resources->append(Resource(url, mimeType, image->image()->data()));
301 m_resourceURLs.add(url);
304 void PageSerializer::retrieveResourcesForCSSRule(CSSStyleRule* rule)
306 retrieveResourcesForCSSDeclaration(rule->style());
309 void PageSerializer::retrieveResourcesForCSSDeclaration(CSSStyleDeclaration* styleDeclaration)
311 if (!styleDeclaration)
314 if (!styleDeclaration->stylesheet()->isCSSStyleSheet())
317 CSSStyleSheet* cssStyleSheet = static_cast<CSSStyleSheet*>(styleDeclaration->stylesheet());
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
327 RefPtr<CSSValue> cssValue = styleDeclaration->getPropertyCSSValue(styleDeclaration->item(i));
328 if (!cssValue->isImageValue())
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())
337 CachedImage* image = static_cast<StyleCachedImage*>(styleImage)->cachedImage();
339 KURL url = cssStyleSheet->document()->completeURL(image->url());
340 addImageToResources(image, url);
344 KURL PageSerializer::urlForBlankFrame(Frame* frame)
346 HashMap<Frame*, KURL>::iterator iter = m_blankFrameURLs.find(frame);
347 if (iter != m_blankFrameURLs.end())
349 String url = "wyciwyg://frame/" + String::number(m_blankFrameCounter++);
350 KURL fakeURL(ParsedURLString, url);
351 m_blankFrameURLs.add(frame, fakeURL);