1/*
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.
8 *
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.
13 *
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.
18 *
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.
23 */
24
25#include "config.h"
26
27#include "core/rendering/svg/SVGRenderingContext.h"
28
29#include "core/page/Frame.h"
30#include "core/page/FrameView.h"
31#include "core/rendering/RenderLayer.h"
32#include "core/rendering/svg/RenderSVGImage.h"
33#include "core/rendering/svg/RenderSVGResource.h"
34#include "core/rendering/svg/RenderSVGResourceClipper.h"
35#include "core/rendering/svg/RenderSVGResourceFilter.h"
36#include "core/rendering/svg/RenderSVGResourceMasker.h"
37#include "core/rendering/svg/SVGResources.h"
38#include "core/rendering/svg/SVGResourcesCache.h"
39
40static int kMaxImageBufferSize = 4096;
41
42namespace WebCore {
43
44static inline bool isRenderingMaskImage(RenderObject* object)
45{
46    if (object->frame() && object->frame()->view())
47        return object->frame()->view()->paintBehavior() & PaintBehaviorRenderingSVGMask;
48    return false;
49}
50
51SVGRenderingContext::~SVGRenderingContext()
52{
53    // Fast path if we don't need to restore anything.
54    if (!(m_renderingFlags & ActionsNeeded))
55        return;
56
57    ASSERT(m_object && m_paintInfo);
58
59    if (m_renderingFlags & EndFilterLayer) {
60        ASSERT(m_filter);
61        m_filter->postApplyResource(m_object, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
62        m_paintInfo->context = m_savedContext;
63        m_paintInfo->rect = m_savedPaintRect;
64    }
65
66    if (m_renderingFlags & EndOpacityLayer)
67        m_paintInfo->context->endTransparencyLayer();
68
69    if (m_renderingFlags & RestoreGraphicsContext)
70        m_paintInfo->context->restore();
71}
72
73void SVGRenderingContext::prepareToRenderSVGContent(RenderObject* object, PaintInfo& paintInfo, NeedsGraphicsContextSave needsGraphicsContextSave)
74{
75    ASSERT(object);
76
77#ifndef NDEBUG
78    // This function must not be called twice!
79    ASSERT(!(m_renderingFlags & PrepareToRenderSVGContentWasCalled));
80    m_renderingFlags |= PrepareToRenderSVGContentWasCalled;
81#endif
82
83    m_object = object;
84    m_paintInfo = &paintInfo;
85    m_filter = 0;
86
87    // We need to save / restore the context even if the initialization failed.
88    if (needsGraphicsContextSave == SaveGraphicsContext) {
89        m_paintInfo->context->save();
90        m_renderingFlags |= RestoreGraphicsContext;
91    }
92
93    RenderStyle* style = m_object->style();
94    ASSERT(style);
95
96    const SVGRenderStyle* svgStyle = style->svgStyle();
97    ASSERT(svgStyle);
98
99    // Setup transparency layers before setting up SVG resources!
100    bool isRenderingMask = isRenderingMaskImage(m_object);
101    float opacity = isRenderingMask ? 1 : style->opacity();
102    BlendMode blendMode = isRenderingMask ? BlendModeNormal : style->blendMode();
103    if (opacity < 1 || blendMode != BlendModeNormal) {
104        FloatRect repaintRect = m_object->repaintRectInLocalCoordinates();
105
106        if (opacity < 1 || blendMode != BlendModeNormal) {
107            m_paintInfo->context->clip(repaintRect);
108            if (blendMode != BlendModeNormal) {
109                if (!(m_renderingFlags & RestoreGraphicsContext)) {
110                    m_paintInfo->context->save();
111                    m_renderingFlags |= RestoreGraphicsContext;
112                }
113                m_paintInfo->context->setCompositeOperation(CompositeSourceOver, blendMode);
114            }
115            m_paintInfo->context->beginTransparencyLayer(opacity);
116            m_renderingFlags |= EndOpacityLayer;
117        }
118    }
119
120    ClipPathOperation* clipPathOperation = style->clipPath();
121    if (clipPathOperation && clipPathOperation->getOperationType() == ClipPathOperation::SHAPE) {
122        ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(clipPathOperation);
123        m_paintInfo->context->clipPath(clipPath->path(object->objectBoundingBox()), clipPath->windRule());
124    }
125
126    SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(m_object);
127    if (!resources) {
128        if (svgStyle->hasFilter())
129            return;
130
131        m_renderingFlags |= RenderingPrepared;
132        return;
133    }
134
135    if (!isRenderingMask) {
136        if (RenderSVGResourceMasker* masker = resources->masker()) {
137            if (!masker->applyResource(m_object, style, m_paintInfo->context, ApplyToDefaultMode))
138                return;
139        }
140    }
141
142    RenderSVGResourceClipper* clipper = resources->clipper();
143    if (!clipPathOperation && clipper) {
144        if (!clipper->applyResource(m_object, style, m_paintInfo->context, ApplyToDefaultMode))
145            return;
146    }
147
148    if (!isRenderingMask) {
149        m_filter = resources->filter();
150        if (m_filter) {
151            m_savedContext = m_paintInfo->context;
152            m_savedPaintRect = m_paintInfo->rect;
153            // Return with false here may mean that we don't need to draw the content
154            // (because it was either drawn before or empty) but we still need to apply the filter.
155            m_renderingFlags |= EndFilterLayer;
156            if (!m_filter->applyResource(m_object, style, m_paintInfo->context, ApplyToDefaultMode))
157                return;
158
159            // Since we're caching the resulting bitmap and do not invalidate it on repaint rect
160            // changes, we need to paint the whole filter region. Otherwise, elements not visible
161            // at the time of the initial paint (due to scrolling, window size, etc.) will never
162            // be drawn.
163            m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_object));
164        }
165    }
166
167    m_renderingFlags |= RenderingPrepared;
168}
169
170static AffineTransform& currentContentTransformation()
171{
172    DEFINE_STATIC_LOCAL(AffineTransform, s_currentContentTransformation, ());
173    return s_currentContentTransformation;
174}
175
176float SVGRenderingContext::calculateScreenFontSizeScalingFactor(const RenderObject* renderer)
177{
178    ASSERT(renderer);
179
180    AffineTransform ctm;
181    calculateTransformationToOutermostCoordinateSystem(renderer, ctm);
182    return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
183}
184
185void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject* renderer, AffineTransform& absoluteTransform)
186{
187    ASSERT(renderer);
188    absoluteTransform = currentContentTransformation();
189
190    // Walk up the render tree, accumulating SVG transforms.
191    while (renderer) {
192        absoluteTransform = renderer->localToParentTransform() * absoluteTransform;
193        if (renderer->isSVGRoot())
194            break;
195        renderer = renderer->parent();
196    }
197
198    // Continue walking up the layer tree, accumulating CSS transforms.
199    RenderLayer* layer = renderer ? renderer->enclosingLayer() : 0;
200    while (layer) {
201        if (TransformationMatrix* layerTransform = layer->transform())
202            absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
203
204        // We can stop at compositing layers, to match the backing resolution.
205        if (layer->isComposited())
206            break;
207
208        layer = layer->parent();
209    }
210}
211
212bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
213{
214    IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
215    // Don't create empty ImageBuffers.
216    if (paintRect.isEmpty())
217        return false;
218
219    IntSize clampedSize = clampedAbsoluteSize(paintRect.size());
220    OwnPtr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, renderingMode);
221    if (!image)
222        return false;
223
224    GraphicsContext* imageContext = image->context();
225    ASSERT(imageContext);
226
227    imageContext->scale(FloatSize(static_cast<float>(clampedSize.width()) / paintRect.width(),
228                                  static_cast<float>(clampedSize.height()) / paintRect.height()));
229    imageContext->translate(-paintRect.x(), -paintRect.y());
230    imageContext->concatCTM(absoluteTransform);
231
232    imageBuffer = image.release();
233    return true;
234}
235
236bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
237{
238    IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
239    IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
240
241    // Don't create empty ImageBuffers.
242    if (imageSize.isEmpty())
243        return false;
244
245    OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, renderingMode);
246    if (!image)
247        return false;
248
249    GraphicsContext* imageContext = image->context();
250    ASSERT(imageContext);
251
252    // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
253    imageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTargetRect.width(), unclampedImageSize.height() / absoluteTargetRect.height()));
254
255    imageBuffer = image.release();
256    return true;
257}
258
259void SVGRenderingContext::renderSubtreeToImageBuffer(ImageBuffer* image, RenderObject* item, const AffineTransform& subtreeContentTransformation)
260{
261    ASSERT(item);
262    ASSERT(image);
263    ASSERT(image->context());
264
265    PaintInfo info(image->context(), PaintInfo::infiniteRect(), PaintPhaseForeground, PaintBehaviorNormal);
266
267    AffineTransform& contentTransformation = currentContentTransformation();
268    AffineTransform savedContentTransformation = contentTransformation;
269    contentTransformation = subtreeContentTransformation * contentTransformation;
270
271    ASSERT(!item->needsLayout());
272    item->paint(info, IntPoint());
273
274    contentTransformation = savedContentTransformation;
275}
276
277void SVGRenderingContext::clipToImageBuffer(GraphicsContext* context, const AffineTransform& absoluteTransform, const FloatRect& targetRect, OwnPtr<ImageBuffer>& imageBuffer, bool safeToClear)
278{
279    ASSERT(context);
280    ASSERT(imageBuffer);
281
282    FloatRect absoluteTargetRect = calculateImageBufferRect(targetRect, absoluteTransform);
283
284    // The mask image has been created in the absolute coordinate space, as the image should not be scaled.
285    // So the actual masking process has to be done in the absolute coordinate space as well.
286    context->concatCTM(absoluteTransform.inverse());
287    context->clipToImageBuffer(imageBuffer.get(), absoluteTargetRect);
288    context->concatCTM(absoluteTransform);
289
290    // When nesting resources, with objectBoundingBox as content unit types, there's no use in caching the
291    // resulting image buffer as the parent resource already caches the result.
292    if (safeToClear && !currentContentTransformation().isIdentity())
293        imageBuffer.clear();
294}
295
296FloatRect SVGRenderingContext::clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect)
297{
298    const FloatSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
299    return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
300}
301
302IntSize SVGRenderingContext::clampedAbsoluteSize(const IntSize& absoluteSize)
303{
304    const IntSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
305    return absoluteSize.shrunkTo(maxImageBufferSize);
306}
307
308void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
309{
310    AffineTransform::DecomposedType decomposition;
311    transform.decompose(decomposition);
312    decomposition.angle = 0;
313    transform.recompose(decomposition);
314}
315
316bool SVGRenderingContext::bufferForeground(OwnPtr<ImageBuffer>& imageBuffer)
317{
318    ASSERT(m_paintInfo);
319    ASSERT(m_object->isSVGImage());
320    FloatRect boundingBox = m_object->objectBoundingBox();
321
322    // Invalidate an existing buffer if the scale is not correct.
323    if (imageBuffer) {
324        AffineTransform transform = m_paintInfo->context->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
325        IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
326        IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
327        if (bufferSize != imageBuffer->internalSize())
328            imageBuffer.clear();
329    }
330
331    // Create a new buffer and paint the foreground into it.
332    if (!imageBuffer) {
333        if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size()), true))) {
334            GraphicsContext* bufferedRenderingContext = imageBuffer->context();
335            bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
336            PaintInfo bufferedInfo(*m_paintInfo);
337            bufferedInfo.context = bufferedRenderingContext;
338            toRenderSVGImage(m_object)->paintForeground(bufferedInfo);
339        } else
340            return false;
341    }
342
343    m_paintInfo->context->drawImageBuffer(imageBuffer.get(), boundingBox);
344    return true;
345}
346
347}
348