2 * Copyright (C) 2006 Eric Seidel <eric@webkit.org>
3 * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "core/svg/graphics/SVGImage.h"
32 #include "core/dom/NodeTraversal.h"
33 #include "core/dom/shadow/ComposedTreeWalker.h"
34 #include "core/loader/FrameLoadRequest.h"
35 #include "core/page/Chrome.h"
36 #include "core/frame/Frame.h"
37 #include "core/frame/FrameView.h"
38 #include "core/frame/Settings.h"
39 #include "core/rendering/style/RenderStyle.h"
40 #include "core/rendering/svg/RenderSVGRoot.h"
41 #include "core/svg/SVGDocument.h"
42 #include "core/svg/SVGFEImageElement.h"
43 #include "core/svg/SVGImageElement.h"
44 #include "core/svg/SVGSVGElement.h"
45 #include "core/svg/graphics/SVGImageChromeClient.h"
46 #include "platform/LengthFunctions.h"
47 #include "platform/geometry/IntRect.h"
48 #include "platform/graphics/GraphicsContextStateSaver.h"
49 #include "platform/graphics/ImageBuffer.h"
50 #include "platform/graphics/ImageObserver.h"
51 #include "wtf/PassRefPtr.h"
55 SVGImage::SVGImage(ImageObserver* observer)
63 // Store m_page in a local variable, clearing m_page, so that SVGImageChromeClient knows we're destructed.
64 OwnPtr<Page> currentPage = m_page.release();
65 currentPage->mainFrame()->loader().frameDetached(); // Break both the loader and view references to the frame
68 // Verify that page teardown destroyed the Chrome
69 ASSERT(!m_chromeClient || !m_chromeClient->image());
72 bool SVGImage::isInSVGImage(const Element* element)
76 Page* page = element->document().page();
80 return page->chrome().client().isSVGImageChromeClient();
83 bool SVGImage::currentFrameHasSingleSecurityOrigin() const
88 Frame* frame = m_page->mainFrame();
90 RELEASE_ASSERT(frame->document()->loadEventFinished());
92 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
96 // Don't allow foreignObject elements or images that are not known to be
97 // single-origin since these can leak cross-origin information.
98 ComposedTreeWalker walker(rootElement);
99 while (Node* node = walker.get()) {
100 if (node->hasTagName(SVGNames::foreignObjectTag))
102 if (node->hasTagName(SVGNames::imageTag))
103 return toSVGImageElement(node)->currentFrameHasSingleSecurityOrigin();
104 if (node->hasTagName(SVGNames::feImageTag))
105 return toSVGFEImageElement(node)->currentFrameHasSingleSecurityOrigin();
109 // Because SVG image rendering disallows external resources and links, these
110 // images effectively are restricted to a single security origin.
114 void SVGImage::setContainerSize(const IntSize& size)
116 if (!m_page || !usesContainerSize())
119 Frame* frame = m_page->mainFrame();
120 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
123 RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
127 FrameView* view = frameView();
128 view->resize(this->containerSize());
130 renderer->setContainerSize(size);
133 IntSize SVGImage::containerSize() const
137 Frame* frame = m_page->mainFrame();
138 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
142 RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
146 // If a container size is available it has precedence.
147 IntSize containerSize = renderer->containerSize();
148 if (!containerSize.isEmpty())
149 return containerSize;
151 // Assure that a container size is always given for a non-identity zoom level.
152 ASSERT(renderer->style()->effectiveZoom() == 1);
154 FloatSize currentSize;
155 if (rootElement->intrinsicWidth().isFixed() && rootElement->intrinsicHeight().isFixed())
156 currentSize = rootElement->currentViewportSize();
158 currentSize = rootElement->currentViewBoxRect().size();
160 if (!currentSize.isEmpty())
161 return IntSize(static_cast<int>(ceilf(currentSize.width())), static_cast<int>(ceilf(currentSize.height())));
163 // As last resort, use CSS default intrinsic size.
164 return IntSize(300, 150);
167 void SVGImage::drawForContainer(GraphicsContext* context, const FloatSize containerSize, float zoom, const FloatRect& dstRect,
168 const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
173 // Temporarily disable the image observer to prevent changeInRect() calls due re-laying out the image.
174 ImageObserverDisabler imageObserverDisabler(this);
176 IntSize roundedContainerSize = roundedIntSize(containerSize);
177 setContainerSize(roundedContainerSize);
179 FloatRect scaledSrc = srcRect;
180 scaledSrc.scale(1 / zoom);
182 // Compensate for the container size rounding by adjusting the source rect.
183 FloatSize adjustedSrcSize = scaledSrc.size();
184 adjustedSrcSize.scale(roundedContainerSize.width() / containerSize.width(), roundedContainerSize.height() / containerSize.height());
185 scaledSrc.setSize(adjustedSrcSize);
187 draw(context, dstRect, scaledSrc, compositeOp, blendMode);
190 PassRefPtr<NativeImageSkia> SVGImage::nativeImageForCurrentFrame()
195 OwnPtr<ImageBuffer> buffer = ImageBuffer::create(size());
199 drawForContainer(buffer->context(), size(), 1, rect(), rect(), CompositeSourceOver, blink::WebBlendModeNormal);
201 // FIXME: WK(Bug 113657): We should use DontCopyBackingStore here.
202 return buffer->copyImage(CopyBackingStore)->nativeImageForCurrentFrame();
205 void SVGImage::drawPatternForContainer(GraphicsContext* context, const FloatSize containerSize, float zoom, const FloatRect& srcRect,
206 const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, blink::WebBlendMode blendMode, const IntSize& repeatSpacing)
208 FloatRect zoomedContainerRect = FloatRect(FloatPoint(), containerSize);
209 zoomedContainerRect.scale(zoom);
211 // The ImageBuffer size needs to be scaled to match the final resolution.
212 // FIXME: No need to get the full CTM here, we just need the scale.
213 AffineTransform transform = context->getCTM();
214 FloatSize imageBufferScale = FloatSize(transform.xScale(), transform.yScale());
215 ASSERT(imageBufferScale.width());
216 ASSERT(imageBufferScale.height());
218 FloatSize scaleWithoutCTM(scale.width() / imageBufferScale.width(), scale.height() / imageBufferScale.height());
220 FloatRect imageBufferSize = zoomedContainerRect;
221 imageBufferSize.scale(imageBufferScale.width(), imageBufferScale.height());
223 OwnPtr<ImageBuffer> buffer = ImageBuffer::create(expandedIntSize(imageBufferSize.size()));
224 if (!buffer) // Failed to allocate buffer.
227 drawForContainer(buffer->context(), containerSize, zoom, imageBufferSize, zoomedContainerRect, CompositeSourceOver, blink::WebBlendModeNormal);
228 RefPtr<Image> image = buffer->copyImage(DontCopyBackingStore, Unscaled);
230 // Adjust the source rect and transform due to the image buffer's scaling.
231 FloatRect scaledSrcRect = srcRect;
232 scaledSrcRect.scale(imageBufferScale.width(), imageBufferScale.height());
234 image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect, blendMode, repeatSpacing);
237 void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
242 GraphicsContextStateSaver stateSaver(*context);
243 context->setCompositeOperation(compositeOp, blendMode);
244 context->clip(enclosingIntRect(dstRect));
246 bool compositingRequiresTransparencyLayer = compositeOp != CompositeSourceOver || blendMode != blink::WebBlendModeNormal;
247 if (compositingRequiresTransparencyLayer) {
248 context->beginTransparencyLayer(1);
249 context->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
252 FloatSize scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height());
254 // We can only draw the entire frame, clipped to the rect we want. So compute where the top left
255 // of the image would be if we were drawing without clipping, and translate accordingly.
256 FloatSize topLeftOffset(srcRect.location().x() * scale.width(), srcRect.location().y() * scale.height());
257 FloatPoint destOffset = dstRect.location() - topLeftOffset;
259 context->translate(destOffset.x(), destOffset.y());
260 context->scale(scale);
262 FrameView* view = frameView();
263 view->resize(containerSize());
265 if (view->needsLayout())
268 view->paint(context, enclosingIntRect(srcRect));
270 if (compositingRequiresTransparencyLayer)
273 stateSaver.restore();
276 imageObserver()->didDraw(this);
279 RenderBox* SVGImage::embeddedContentBox() const
283 Frame* frame = m_page->mainFrame();
284 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
287 return toRenderBox(rootElement->renderer());
290 FrameView* SVGImage::frameView() const
295 return m_page->mainFrame()->view();
298 bool SVGImage::hasRelativeWidth() const
302 Frame* frame = m_page->mainFrame();
303 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
306 return rootElement->intrinsicWidth().isPercent();
309 bool SVGImage::hasRelativeHeight() const
313 Frame* frame = m_page->mainFrame();
314 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
317 return rootElement->intrinsicHeight().isPercent();
320 void SVGImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
324 Frame* frame = m_page->mainFrame();
325 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
329 intrinsicWidth = rootElement->intrinsicWidth();
330 intrinsicHeight = rootElement->intrinsicHeight();
331 if (rootElement->preserveAspectRatio()->currentValue()->align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
334 intrinsicRatio = rootElement->viewBox()->currentValue()->value().size();
335 if (intrinsicRatio.isEmpty() && intrinsicWidth.isFixed() && intrinsicHeight.isFixed())
336 intrinsicRatio = FloatSize(floatValueForLength(intrinsicWidth, 0), floatValueForLength(intrinsicHeight, 0));
339 // FIXME: support catchUpIfNecessary.
340 void SVGImage::startAnimation(bool /* catchUpIfNecessary */)
344 Frame* frame = m_page->mainFrame();
345 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
348 rootElement->unpauseAnimations();
349 rootElement->setCurrentTime(0);
352 void SVGImage::stopAnimation()
356 Frame* frame = m_page->mainFrame();
357 SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
360 rootElement->pauseAnimations();
363 void SVGImage::resetAnimation()
368 bool SVGImage::dataChanged(bool allDataReceived)
370 TRACE_EVENT0("webkit", "SVGImage::dataChanged");
372 // Don't do anything if is an empty image.
376 if (allDataReceived) {
377 static FrameLoaderClient* dummyFrameLoaderClient = new EmptyFrameLoaderClient;
379 Page::PageClients pageClients;
380 fillWithEmptyClients(pageClients);
381 m_chromeClient = adoptPtr(new SVGImageChromeClient(this));
382 pageClients.chromeClient = m_chromeClient.get();
384 // FIXME: If this SVG ends up loading itself, we might leak the world.
385 // The Cache code does not know about ImageResources holding Frames and
386 // won't know to break the cycle.
387 // This will become an issue when SVGImage will be able to load other
388 // SVGImage objects, but we're safe now, because SVGImage can only be
389 // loaded by a top-level document.
390 m_page = adoptPtr(new Page(pageClients));
391 m_page->settings().setMediaEnabled(false);
392 m_page->settings().setScriptEnabled(false);
393 m_page->settings().setPluginsEnabled(false);
394 m_page->settings().setAcceleratedCompositingEnabled(false);
396 RefPtr<Frame> frame = Frame::create(FrameInit::create(0, &m_page->frameHost(), dummyFrameLoaderClient));
397 frame->setView(FrameView::create(frame.get()));
399 FrameLoader& loader = frame->loader();
400 loader.forceSandboxFlags(SandboxAll);
402 frame->view()->setScrollbarsSuppressed(true);
403 frame->view()->setCanHaveScrollbars(false); // SVG Images will always synthesize a viewBox, if it's not available, and thus never see scrollbars.
404 frame->view()->setTransparent(true); // SVG Images are transparent.
406 loader.load(FrameLoadRequest(0, blankURL(), SubstituteData(data(), "image/svg+xml", "UTF-8", KURL(), ForceSynchronousLoad)));
407 // Set the intrinsic size before a container size is available.
408 m_intrinsicSize = containerSize();
414 String SVGImage::filenameExtension() const