2 * Copyright (C) 2007, 2008 Rob Buis <buis@kde.org>
3 * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
4 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
5 * Copyright (C) 2009 Google, Inc. All rights reserved.
6 * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
7 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
26 #include "SVGRenderingContext.h"
28 #include "BasicShapes.h"
30 #include "FrameView.h"
32 #include "RenderLayer.h"
33 #include "RenderSVGImage.h"
34 #include "RenderSVGResourceClipper.h"
35 #include "RenderSVGResourceFilter.h"
36 #include "RenderSVGResourceMasker.h"
37 #include "RenderView.h"
38 #include "SVGLengthContext.h"
39 #include "SVGResources.h"
40 #include "SVGResourcesCache.h"
42 static int kMaxImageBufferSize = 4096;
46 static inline bool isRenderingMaskImage(const RenderObject& object)
48 return object.view().frameView().paintBehavior() & PaintBehaviorRenderingSVGMask;
51 SVGRenderingContext::~SVGRenderingContext()
53 // Fast path if we don't need to restore anything.
54 if (!(m_renderingFlags & ActionsNeeded))
57 ASSERT(m_renderer && m_paintInfo);
60 if (m_renderingFlags & EndFilterLayer) {
62 m_filter->postApplyResource(*m_renderer, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
63 m_paintInfo->context = m_savedContext;
64 m_paintInfo->rect = m_savedPaintRect;
68 if (m_renderingFlags & EndOpacityLayer)
69 m_paintInfo->context->endTransparencyLayer();
71 if (m_renderingFlags & EndShadowLayer)
72 m_paintInfo->context->endTransparencyLayer();
74 if (m_renderingFlags & RestoreGraphicsContext)
75 m_paintInfo->context->restore();
78 void SVGRenderingContext::prepareToRenderSVGContent(RenderElement& renderer, PaintInfo& paintInfo, NeedsGraphicsContextSave needsGraphicsContextSave)
81 // This function must not be called twice!
82 ASSERT(!(m_renderingFlags & PrepareToRenderSVGContentWasCalled));
83 m_renderingFlags |= PrepareToRenderSVGContentWasCalled;
86 m_renderer = &renderer;
87 m_paintInfo = &paintInfo;
92 // We need to save / restore the context even if the initialization failed.
93 if (needsGraphicsContextSave == SaveGraphicsContext) {
94 m_paintInfo->context->save();
95 m_renderingFlags |= RestoreGraphicsContext;
98 RenderStyle& style = m_renderer->style();
100 const SVGRenderStyle& svgStyle = style.svgStyle();
102 // Setup transparency layers before setting up SVG resources!
103 bool isRenderingMask = isRenderingMaskImage(*m_renderer);
104 // RenderLayer takes care of root opacity.
105 float opacity = (renderer.isSVGRoot() || isRenderingMask) ? 1 : style.opacity();
106 const ShadowData* shadow = svgStyle.shadow();
107 bool hasBlendMode = style.hasBlendMode();
108 bool hasIsolation = style.hasIsolation();
109 bool isolateMaskForBlending = false;
111 #if ENABLE(CSS_COMPOSITING)
112 if (svgStyle.hasMasker() && toSVGElement(renderer.element())->isSVGGraphicsElement()) {
113 SVGGraphicsElement& graphicsElement = *toSVGGraphicsElement(renderer.element());
114 isolateMaskForBlending = graphicsElement.shouldIsolateBlending();
118 if (opacity < 1 || shadow || hasBlendMode || isolateMaskForBlending || hasIsolation) {
119 FloatRect repaintRect = m_renderer->repaintRectInLocalCoordinates();
120 m_paintInfo->context->clip(repaintRect);
122 if (opacity < 1 || hasBlendMode || isolateMaskForBlending || hasIsolation) {
125 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), style.blendMode());
127 m_paintInfo->context->beginTransparencyLayer(opacity);
130 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), BlendModeNormal);
132 m_renderingFlags |= EndOpacityLayer;
136 m_paintInfo->context->setShadow(IntSize(roundToInt(shadow->x()), roundToInt(shadow->y())), shadow->radius(), shadow->color(), style.colorSpace());
137 m_paintInfo->context->beginTransparencyLayer(1);
138 m_renderingFlags |= EndShadowLayer;
142 ClipPathOperation* clipPathOperation = style.clipPath();
143 if (clipPathOperation && clipPathOperation->type() == ClipPathOperation::Shape) {
144 ShapeClipPathOperation& clipPath = toShapeClipPathOperation(*clipPathOperation);
145 FloatRect referenceBox;
146 if (clipPath.referenceBox() == Stroke)
147 // FIXME: strokeBoundingBox() takes dasharray into account but shouldn't.
148 referenceBox = renderer.strokeBoundingBox();
149 else if (clipPath.referenceBox() == ViewBox && renderer.element()) {
150 FloatSize viewportSize;
151 SVGLengthContext(toSVGElement(renderer.element())).determineViewport(viewportSize);
152 referenceBox.setWidth(viewportSize.width());
153 referenceBox.setHeight(viewportSize.height());
155 referenceBox = renderer.objectBoundingBox();
156 m_paintInfo->context->clipPath(clipPath.pathForReferenceRect(referenceBox), clipPath.windRule());
159 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(*m_renderer);
162 if (svgStyle.hasFilter())
165 m_renderingFlags |= RenderingPrepared;
169 if (!isRenderingMask) {
170 if (RenderSVGResourceMasker* masker = resources->masker()) {
171 if (!masker->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
176 RenderSVGResourceClipper* clipper = resources->clipper();
177 if (!clipPathOperation && clipper) {
178 if (!clipper->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
183 if (!isRenderingMask) {
184 m_filter = resources->filter();
186 m_savedContext = m_paintInfo->context;
187 m_savedPaintRect = m_paintInfo->rect;
188 // Return with false here may mean that we don't need to draw the content
189 // (because it was either drawn before or empty) but we still need to apply the filter.
190 m_renderingFlags |= EndFilterLayer;
191 if (!m_filter->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
194 // Since we're caching the resulting bitmap and do not invalidate it on repaint rect
195 // changes, we need to paint the whole filter region. Otherwise, elements not visible
196 // at the time of the initial paint (due to scrolling, window size, etc.) will never
198 m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_renderer));
203 m_renderingFlags |= RenderingPrepared;
206 static AffineTransform& currentContentTransformation()
208 DEPRECATED_DEFINE_STATIC_LOCAL(AffineTransform, s_currentContentTransformation, ());
209 return s_currentContentTransformation;
212 float SVGRenderingContext::calculateScreenFontSizeScalingFactor(const RenderObject& renderer)
215 calculateTransformationToOutermostCoordinateSystem(renderer, ctm);
216 return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
219 void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject& renderer, AffineTransform& absoluteTransform)
221 absoluteTransform = currentContentTransformation();
223 float deviceScaleFactor = renderer.document().deviceScaleFactor();
224 // Walk up the render tree, accumulating SVG transforms.
225 const RenderObject* ancestor = &renderer;
227 absoluteTransform = ancestor->localToParentTransform() * absoluteTransform;
228 if (ancestor->isSVGRoot())
230 ancestor = ancestor->parent();
233 // Continue walking up the layer tree, accumulating CSS transforms.
234 RenderLayer* layer = ancestor ? ancestor->enclosingLayer() : nullptr;
236 if (TransformationMatrix* layerTransform = layer->transform())
237 absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
239 // We can stop at compositing layers, to match the backing resolution.
240 if (layer->isComposited())
243 layer = layer->parent();
246 absoluteTransform.scale(deviceScaleFactor);
249 bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, std::unique_ptr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
251 IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
252 // Don't create empty ImageBuffers.
253 if (paintRect.isEmpty())
256 IntSize clampedSize = clampedAbsoluteSize(paintRect.size());
257 std::unique_ptr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, colorSpace, renderingMode);
261 GraphicsContext* imageContext = image->context();
262 ASSERT(imageContext);
264 imageContext->scale(FloatSize(static_cast<float>(clampedSize.width()) / paintRect.width(),
265 static_cast<float>(clampedSize.height()) / paintRect.height()));
266 imageContext->translate(-paintRect.x(), -paintRect.y());
267 imageContext->concatCTM(absoluteTransform);
269 imageBuffer = WTF::move(image);
273 bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, std::unique_ptr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
275 IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
276 IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
278 // Don't create empty ImageBuffers.
279 if (imageSize.isEmpty())
282 std::unique_ptr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, colorSpace, renderingMode);
286 GraphicsContext* imageContext = image->context();
287 ASSERT(imageContext);
289 // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
290 imageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTargetRect.width(), unclampedImageSize.height() / absoluteTargetRect.height()));
292 imageBuffer = WTF::move(image);
296 void SVGRenderingContext::renderSubtreeToImageBuffer(ImageBuffer* image, RenderElement& item, const AffineTransform& subtreeContentTransformation)
299 ASSERT(image->context());
301 PaintInfo info(image->context(), LayoutRect::infiniteRect(), PaintPhaseForeground, PaintBehaviorNormal);
303 AffineTransform& contentTransformation = currentContentTransformation();
304 AffineTransform savedContentTransformation = contentTransformation;
305 contentTransformation = subtreeContentTransformation * contentTransformation;
307 ASSERT(!item.needsLayout());
308 item.paint(info, IntPoint());
310 contentTransformation = savedContentTransformation;
313 void SVGRenderingContext::clipToImageBuffer(GraphicsContext* context, const AffineTransform& absoluteTransform, const FloatRect& targetRect, std::unique_ptr<ImageBuffer>& imageBuffer, bool safeToClear)
318 FloatRect absoluteTargetRect = calculateImageBufferRect(targetRect, absoluteTransform);
320 // The mask image has been created in the absolute coordinate space, as the image should not be scaled.
321 // So the actual masking process has to be done in the absolute coordinate space as well.
322 context->concatCTM(absoluteTransform.inverse());
323 context->clipToImageBuffer(imageBuffer.get(), absoluteTargetRect);
324 context->concatCTM(absoluteTransform);
326 // When nesting resources, with objectBoundingBox as content unit types, there's no use in caching the
327 // resulting image buffer as the parent resource already caches the result.
328 if (safeToClear && !currentContentTransformation().isIdentity())
332 FloatRect SVGRenderingContext::clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect)
334 const FloatSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
335 return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
338 IntSize SVGRenderingContext::clampedAbsoluteSize(const IntSize& absoluteSize)
340 const IntSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
341 return absoluteSize.shrunkTo(maxImageBufferSize);
344 void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
346 AffineTransform::DecomposedType decomposition;
347 transform.decompose(decomposition);
348 decomposition.angle = 0;
349 transform.recompose(decomposition);
352 bool SVGRenderingContext::bufferForeground(std::unique_ptr<ImageBuffer>& imageBuffer)
355 ASSERT(m_renderer->isSVGImage());
356 FloatRect boundingBox = m_renderer->objectBoundingBox();
358 // Invalidate an existing buffer if the scale is not correct.
360 AffineTransform transform = m_paintInfo->context->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
361 IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
362 IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
363 if (bufferSize != imageBuffer->internalSize())
367 // Create a new buffer and paint the foreground into it.
369 if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size()), true))) {
370 GraphicsContext* bufferedRenderingContext = imageBuffer->context();
371 bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
372 PaintInfo bufferedInfo(*m_paintInfo);
373 bufferedInfo.context = bufferedRenderingContext;
374 toRenderSVGImage(m_renderer)->paintForeground(bufferedInfo);
379 m_paintInfo->context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, boundingBox);