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"
44 static inline bool isRenderingMaskImage(const RenderObject& object)
46 return object.view().frameView().paintBehavior() & PaintBehaviorRenderingSVGMask;
49 SVGRenderingContext::~SVGRenderingContext()
51 // Fast path if we don't need to restore anything.
52 if (!(m_renderingFlags & ActionsNeeded))
55 ASSERT(m_renderer && m_paintInfo);
57 if (m_renderingFlags & EndFilterLayer) {
59 m_filter->postApplyResource(*m_renderer, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
60 m_paintInfo->context = m_savedContext;
61 m_paintInfo->rect = m_savedPaintRect;
64 if (m_renderingFlags & EndOpacityLayer)
65 m_paintInfo->context->endTransparencyLayer();
67 if (m_renderingFlags & EndShadowLayer)
68 m_paintInfo->context->endTransparencyLayer();
70 if (m_renderingFlags & RestoreGraphicsContext)
71 m_paintInfo->context->restore();
74 void SVGRenderingContext::prepareToRenderSVGContent(RenderElement& renderer, PaintInfo& paintInfo, NeedsGraphicsContextSave needsGraphicsContextSave)
77 // This function must not be called twice!
78 ASSERT(!(m_renderingFlags & PrepareToRenderSVGContentWasCalled));
79 m_renderingFlags |= PrepareToRenderSVGContentWasCalled;
82 m_renderer = &renderer;
83 m_paintInfo = &paintInfo;
86 // We need to save / restore the context even if the initialization failed.
87 if (needsGraphicsContextSave == SaveGraphicsContext) {
88 m_paintInfo->context->save();
89 m_renderingFlags |= RestoreGraphicsContext;
92 RenderStyle& style = m_renderer->style();
94 const SVGRenderStyle& svgStyle = style.svgStyle();
96 // Setup transparency layers before setting up SVG resources!
97 bool isRenderingMask = isRenderingMaskImage(*m_renderer);
98 // RenderLayer takes care of root opacity.
99 float opacity = (renderer.isSVGRoot() || isRenderingMask) ? 1 : style.opacity();
100 const ShadowData* shadow = svgStyle.shadow();
101 bool hasBlendMode = style.hasBlendMode();
102 bool hasIsolation = style.hasIsolation();
103 bool isolateMaskForBlending = false;
105 #if ENABLE(CSS_COMPOSITING)
106 if (svgStyle.hasMasker() && is<SVGGraphicsElement>(downcast<SVGElement>(*renderer.element()))) {
107 SVGGraphicsElement& graphicsElement = downcast<SVGGraphicsElement>(*renderer.element());
108 isolateMaskForBlending = graphicsElement.shouldIsolateBlending();
112 if (opacity < 1 || shadow || hasBlendMode || isolateMaskForBlending || hasIsolation) {
113 FloatRect repaintRect = m_renderer->repaintRectInLocalCoordinates();
114 m_paintInfo->context->clip(repaintRect);
116 if (opacity < 1 || hasBlendMode || isolateMaskForBlending || hasIsolation) {
119 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), style.blendMode());
121 m_paintInfo->context->beginTransparencyLayer(opacity);
124 m_paintInfo->context->setCompositeOperation(m_paintInfo->context->compositeOperation(), BlendModeNormal);
126 m_renderingFlags |= EndOpacityLayer;
130 m_paintInfo->context->setShadow(IntSize(roundToInt(shadow->x()), roundToInt(shadow->y())), shadow->radius(), shadow->color(), style.colorSpace());
131 m_paintInfo->context->beginTransparencyLayer(1);
132 m_renderingFlags |= EndShadowLayer;
136 ClipPathOperation* clipPathOperation = style.clipPath();
137 if (is<ShapeClipPathOperation>(clipPathOperation)) {
138 auto& clipPath = downcast<ShapeClipPathOperation>(*clipPathOperation);
139 FloatRect referenceBox;
140 if (clipPath.referenceBox() == Stroke)
141 // FIXME: strokeBoundingBox() takes dasharray into account but shouldn't.
142 referenceBox = renderer.strokeBoundingBox();
143 else if (clipPath.referenceBox() == ViewBox && renderer.element()) {
144 FloatSize viewportSize;
145 SVGLengthContext(downcast<SVGElement>(renderer.element())).determineViewport(viewportSize);
146 referenceBox.setWidth(viewportSize.width());
147 referenceBox.setHeight(viewportSize.height());
149 referenceBox = renderer.objectBoundingBox();
150 m_paintInfo->context->clipPath(clipPath.pathForReferenceRect(referenceBox), clipPath.windRule());
153 auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*m_renderer);
155 if (svgStyle.hasFilter())
158 m_renderingFlags |= RenderingPrepared;
162 if (!isRenderingMask) {
163 if (RenderSVGResourceMasker* masker = resources->masker()) {
164 if (!masker->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
169 RenderSVGResourceClipper* clipper = resources->clipper();
170 if (!clipPathOperation && clipper) {
171 if (!clipper->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
175 if (!isRenderingMask) {
176 m_filter = resources->filter();
178 m_savedContext = m_paintInfo->context;
179 m_savedPaintRect = m_paintInfo->rect;
180 // Return with false here may mean that we don't need to draw the content
181 // (because it was either drawn before or empty) but we still need to apply the filter.
182 m_renderingFlags |= EndFilterLayer;
183 if (!m_filter->applyResource(*m_renderer, style, m_paintInfo->context, ApplyToDefaultMode))
186 // Since we're caching the resulting bitmap and do not invalidate it on repaint rect
187 // changes, we need to paint the whole filter region. Otherwise, elements not visible
188 // at the time of the initial paint (due to scrolling, window size, etc.) will never
190 m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_renderer));
194 m_renderingFlags |= RenderingPrepared;
197 static AffineTransform& currentContentTransformation()
199 DEPRECATED_DEFINE_STATIC_LOCAL(AffineTransform, s_currentContentTransformation, ());
200 return s_currentContentTransformation;
203 float SVGRenderingContext::calculateScreenFontSizeScalingFactor(const RenderObject& renderer)
205 AffineTransform ctm = calculateTransformationToOutermostCoordinateSystem(renderer);
206 return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
209 AffineTransform SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject& renderer)
211 AffineTransform absoluteTransform = currentContentTransformation();
213 float deviceScaleFactor = renderer.document().deviceScaleFactor();
214 // Walk up the render tree, accumulating SVG transforms.
215 const RenderObject* ancestor = &renderer;
217 absoluteTransform = ancestor->localToParentTransform() * absoluteTransform;
218 if (ancestor->isSVGRoot())
220 ancestor = ancestor->parent();
223 // Continue walking up the layer tree, accumulating CSS transforms.
224 RenderLayer* layer = ancestor ? ancestor->enclosingLayer() : nullptr;
226 if (TransformationMatrix* layerTransform = layer->transform())
227 absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
229 // We can stop at compositing layers, to match the backing resolution.
230 if (layer->isComposited())
233 layer = layer->parent();
236 absoluteTransform.scale(deviceScaleFactor);
237 return absoluteTransform;
240 std::unique_ptr<ImageBuffer> SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, ColorSpace colorSpace, RenderingMode renderingMode)
242 IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
243 // Don't create empty ImageBuffers.
244 if (paintRect.isEmpty())
248 FloatSize clampedSize = ImageBuffer::clampedSize(paintRect.size(), scale);
250 auto imageBuffer = ImageBuffer::create(clampedSize, 1, colorSpace, renderingMode);
254 AffineTransform transform;
255 transform.scale(scale).translate(-paintRect.location()).multiply(absoluteTransform);
257 GraphicsContext* imageContext = imageBuffer->context();
258 ASSERT(imageContext);
259 imageContext->concatCTM(transform);
264 std::unique_ptr<ImageBuffer> SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const FloatRect& clampedRect, ColorSpace colorSpace, RenderingMode renderingMode)
266 IntSize clampedSize = roundedIntSize(clampedRect.size());
267 IntSize unclampedSize = roundedIntSize(targetRect.size());
269 // Don't create empty ImageBuffers.
270 if (clampedSize.isEmpty())
273 auto imageBuffer = ImageBuffer::create(clampedSize, 1, colorSpace, renderingMode);
277 GraphicsContext* imageContext = imageBuffer->context();
278 ASSERT(imageContext);
280 // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
281 imageContext->scale(FloatSize(unclampedSize.width() / targetRect.width(), unclampedSize.height() / targetRect.height()));
286 void SVGRenderingContext::renderSubtreeToImageBuffer(ImageBuffer* image, RenderElement& item, const AffineTransform& subtreeContentTransformation)
289 ASSERT(image->context());
291 PaintInfo info(image->context(), LayoutRect::infiniteRect(), PaintPhaseForeground, PaintBehaviorNormal);
293 AffineTransform& contentTransformation = currentContentTransformation();
294 AffineTransform savedContentTransformation = contentTransformation;
295 contentTransformation = subtreeContentTransformation * contentTransformation;
297 ASSERT(!item.needsLayout());
298 item.paint(info, IntPoint());
300 contentTransformation = savedContentTransformation;
303 void SVGRenderingContext::clipToImageBuffer(GraphicsContext* context, const AffineTransform& absoluteTransform, const FloatRect& targetRect, std::unique_ptr<ImageBuffer>& imageBuffer, bool safeToClear)
308 FloatRect absoluteTargetRect = calculateImageBufferRect(targetRect, absoluteTransform);
310 // The mask image has been created in the absolute coordinate space, as the image should not be scaled.
311 // So the actual masking process has to be done in the absolute coordinate space as well.
312 context->concatCTM(absoluteTransform.inverse());
313 context->clipToImageBuffer(imageBuffer.get(), absoluteTargetRect);
314 context->concatCTM(absoluteTransform);
316 // When nesting resources, with objectBoundingBox as content unit types, there's no use in caching the
317 // resulting image buffer as the parent resource already caches the result.
318 if (safeToClear && !currentContentTransformation().isIdentity())
322 void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
324 AffineTransform::DecomposedType decomposition;
325 transform.decompose(decomposition);
326 decomposition.angle = 0;
327 transform.recompose(decomposition);
330 bool SVGRenderingContext::bufferForeground(std::unique_ptr<ImageBuffer>& imageBuffer)
333 ASSERT(is<RenderSVGImage>(*m_renderer));
334 FloatRect boundingBox = m_renderer->objectBoundingBox();
336 // Invalidate an existing buffer if the scale is not correct.
338 AffineTransform transform = m_paintInfo->context->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
339 IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
340 IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
341 if (bufferSize != imageBuffer->internalSize())
345 // Create a new buffer and paint the foreground into it.
347 if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size()), true))) {
348 GraphicsContext* bufferedRenderingContext = imageBuffer->context();
349 bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
350 PaintInfo bufferedInfo(*m_paintInfo);
351 bufferedInfo.context = bufferedRenderingContext;
352 downcast<RenderSVGImage>(*m_renderer).paintForeground(bufferedInfo);
357 m_paintInfo->context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, boundingBox);