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);
59 if (m_renderingFlags & EndFilterLayer) {
61 m_filter->postApplyResource(*m_renderer, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
62 m_paintInfo->context = m_savedContext;
63 m_paintInfo->rect = m_savedPaintRect;
66 if (m_renderingFlags & EndOpacityLayer)
67 m_paintInfo->context->endTransparencyLayer();
69 if (m_renderingFlags & EndShadowLayer)
70 m_paintInfo->context->endTransparencyLayer();
72 if (m_renderingFlags & RestoreGraphicsContext)
73 m_paintInfo->context->restore();
76 void SVGRenderingContext::prepareToRenderSVGContent(RenderElement& renderer, PaintInfo& paintInfo, NeedsGraphicsContextSave needsGraphicsContextSave)
79 // This function must not be called twice!
80 ASSERT(!(m_renderingFlags & PrepareToRenderSVGContentWasCalled));
81 m_renderingFlags |= PrepareToRenderSVGContentWasCalled;
84 m_renderer = &renderer;
85 m_paintInfo = &paintInfo;
88 // We need to save / restore the context even if the initialization failed.
89 if (needsGraphicsContextSave == SaveGraphicsContext) {
90 m_paintInfo->context->save();
91 m_renderingFlags |= RestoreGraphicsContext;
94 RenderStyle& style = m_renderer->style();
96 const SVGRenderStyle& svgStyle = style.svgStyle();
98 // Setup transparency layers before setting up SVG resources!
99 bool isRenderingMask = isRenderingMaskImage(*m_renderer);
100 // RenderLayer takes care of root opacity.
101 float opacity = (renderer.isSVGRoot() || isRenderingMask) ? 1 : style.opacity();
102 const ShadowData* shadow = svgStyle.shadow();
103 bool hasBlendMode = style.hasBlendMode();
104 bool hasIsolation = style.hasIsolation();
105 bool isolateMaskForBlending = false;
107 #if ENABLE(CSS_COMPOSITING)
108 if (svgStyle.hasMasker() && is<SVGGraphicsElement>(downcast<SVGElement>(*renderer.element()))) {
109 SVGGraphicsElement& graphicsElement = downcast<SVGGraphicsElement>(*renderer.element());
110 isolateMaskForBlending = graphicsElement.shouldIsolateBlending();
114 if (opacity < 1 || shadow || hasBlendMode || isolateMaskForBlending || hasIsolation) {
115 FloatRect repaintRect = m_renderer->repaintRectInLocalCoordinates();
116 m_paintInfo->context->clip(repaintRect);
118 if (opacity < 1 || hasBlendMode || isolateMaskForBlending || hasIsolation) {
121 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), style.blendMode());
123 m_paintInfo->context->beginTransparencyLayer(opacity);
126 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), BlendModeNormal);
128 m_renderingFlags |= EndOpacityLayer;
132 m_paintInfo->context->setShadow(IntSize(roundToInt(shadow->x()), roundToInt(shadow->y())), shadow->radius(), shadow->color(), style.colorSpace());
133 m_paintInfo->context->beginTransparencyLayer(1);
134 m_renderingFlags |= EndShadowLayer;
138 ClipPathOperation* clipPathOperation = style.clipPath();
139 if (is<ShapeClipPathOperation>(clipPathOperation)) {
140 auto& clipPath = downcast<ShapeClipPathOperation>(*clipPathOperation);
141 FloatRect referenceBox;
142 if (clipPath.referenceBox() == Stroke)
143 // FIXME: strokeBoundingBox() takes dasharray into account but shouldn't.
144 referenceBox = renderer.strokeBoundingBox();
145 else if (clipPath.referenceBox() == ViewBox && renderer.element()) {
146 FloatSize viewportSize;
147 SVGLengthContext(downcast<SVGElement>(renderer.element())).determineViewport(viewportSize);
148 referenceBox.setWidth(viewportSize.width());
149 referenceBox.setHeight(viewportSize.height());
151 referenceBox = renderer.objectBoundingBox();
152 m_paintInfo->context->clipPath(clipPath.pathForReferenceRect(referenceBox), clipPath.windRule());
155 auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*m_renderer);
157 if (svgStyle.hasFilter())
160 m_renderingFlags |= RenderingPrepared;
164 if (!isRenderingMask) {
165 if (RenderSVGResourceMasker* masker = resources->masker()) {
166 if (!masker->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
171 RenderSVGResourceClipper* clipper = resources->clipper();
172 if (!clipPathOperation && clipper) {
173 if (!clipper->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
177 if (!isRenderingMask) {
178 m_filter = resources->filter();
180 m_savedContext = m_paintInfo->context;
181 m_savedPaintRect = m_paintInfo->rect;
182 // Return with false here may mean that we don't need to draw the content
183 // (because it was either drawn before or empty) but we still need to apply the filter.
184 m_renderingFlags |= EndFilterLayer;
185 if (!m_filter->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
188 // Since we're caching the resulting bitmap and do not invalidate it on repaint rect
189 // changes, we need to paint the whole filter region. Otherwise, elements not visible
190 // at the time of the initial paint (due to scrolling, window size, etc.) will never
192 m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_renderer));
196 m_renderingFlags |= RenderingPrepared;
199 static AffineTransform& currentContentTransformation()
201 DEPRECATED_DEFINE_STATIC_LOCAL(AffineTransform, s_currentContentTransformation, ());
202 return s_currentContentTransformation;
205 float SVGRenderingContext::calculateScreenFontSizeScalingFactor(const RenderObject& renderer)
208 calculateTransformationToOutermostCoordinateSystem(renderer, ctm);
209 return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
212 void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject& renderer, AffineTransform& absoluteTransform)
214 absoluteTransform = currentContentTransformation();
216 float deviceScaleFactor = renderer.document().deviceScaleFactor();
217 // Walk up the render tree, accumulating SVG transforms.
218 const RenderObject* ancestor = &renderer;
220 absoluteTransform = ancestor->localToParentTransform() * absoluteTransform;
221 if (ancestor->isSVGRoot())
223 ancestor = ancestor->parent();
226 // Continue walking up the layer tree, accumulating CSS transforms.
227 RenderLayer* layer = ancestor ? ancestor->enclosingLayer() : nullptr;
229 if (TransformationMatrix* layerTransform = layer->transform())
230 absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
232 // We can stop at compositing layers, to match the backing resolution.
233 if (layer->isComposited())
236 layer = layer->parent();
239 absoluteTransform.scale(deviceScaleFactor);
242 bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, std::unique_ptr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
244 IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
245 // Don't create empty ImageBuffers.
246 if (paintRect.isEmpty())
249 IntSize clampedSize = clampedAbsoluteSize(paintRect.size());
250 std::unique_ptr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, colorSpace, renderingMode);
254 GraphicsContext* imageContext = image->context();
255 ASSERT(imageContext);
257 imageContext->scale(FloatSize(static_cast<float>(clampedSize.width()) / paintRect.width(),
258 static_cast<float>(clampedSize.height()) / paintRect.height()));
259 imageContext->translate(-paintRect.x(), -paintRect.y());
260 imageContext->concatCTM(absoluteTransform);
262 imageBuffer = WTF::move(image);
266 bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, std::unique_ptr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
268 IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
269 IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
271 // Don't create empty ImageBuffers.
272 if (imageSize.isEmpty())
275 std::unique_ptr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, colorSpace, renderingMode);
279 GraphicsContext* imageContext = image->context();
280 ASSERT(imageContext);
282 // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
283 imageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTargetRect.width(), unclampedImageSize.height() / absoluteTargetRect.height()));
285 imageBuffer = WTF::move(image);
289 void SVGRenderingContext::renderSubtreeToImageBuffer(ImageBuffer* image, RenderElement& item, const AffineTransform& subtreeContentTransformation)
292 ASSERT(image->context());
294 PaintInfo info(image->context(), LayoutRect::infiniteRect(), PaintPhaseForeground, PaintBehaviorNormal);
296 AffineTransform& contentTransformation = currentContentTransformation();
297 AffineTransform savedContentTransformation = contentTransformation;
298 contentTransformation = subtreeContentTransformation * contentTransformation;
300 ASSERT(!item.needsLayout());
301 item.paint(info, IntPoint());
303 contentTransformation = savedContentTransformation;
306 void SVGRenderingContext::clipToImageBuffer(GraphicsContext* context, const AffineTransform& absoluteTransform, const FloatRect& targetRect, std::unique_ptr<ImageBuffer>& imageBuffer, bool safeToClear)
311 FloatRect absoluteTargetRect = calculateImageBufferRect(targetRect, absoluteTransform);
313 // The mask image has been created in the absolute coordinate space, as the image should not be scaled.
314 // So the actual masking process has to be done in the absolute coordinate space as well.
315 context->concatCTM(absoluteTransform.inverse());
316 context->clipToImageBuffer(imageBuffer.get(), absoluteTargetRect);
317 context->concatCTM(absoluteTransform);
319 // When nesting resources, with objectBoundingBox as content unit types, there's no use in caching the
320 // resulting image buffer as the parent resource already caches the result.
321 if (safeToClear && !currentContentTransformation().isIdentity())
325 FloatRect SVGRenderingContext::clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect)
327 const FloatSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
328 return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
331 IntSize SVGRenderingContext::clampedAbsoluteSize(const IntSize& absoluteSize)
333 const IntSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
334 return absoluteSize.shrunkTo(maxImageBufferSize);
337 void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
339 AffineTransform::DecomposedType decomposition;
340 transform.decompose(decomposition);
341 decomposition.angle = 0;
342 transform.recompose(decomposition);
345 bool SVGRenderingContext::bufferForeground(std::unique_ptr<ImageBuffer>& imageBuffer)
348 ASSERT(is<RenderSVGImage>(*m_renderer));
349 FloatRect boundingBox = m_renderer->objectBoundingBox();
351 // Invalidate an existing buffer if the scale is not correct.
353 AffineTransform transform = m_paintInfo->context->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
354 IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
355 IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
356 if (bufferSize != imageBuffer->internalSize())
360 // Create a new buffer and paint the foreground into it.
362 if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size()), true))) {
363 GraphicsContext* bufferedRenderingContext = imageBuffer->context();
364 bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
365 PaintInfo bufferedInfo(*m_paintInfo);
366 bufferedInfo.context = bufferedRenderingContext;
367 downcast<RenderSVGImage>(*m_renderer).paintForeground(bufferedInfo);
372 m_paintInfo->context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, boundingBox);