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/frame/FrameHost.h"
30#include "core/frame/FrameView.h"
31#include "core/frame/LocalFrame.h"
32#include "core/frame/Settings.h"
33#include "core/rendering/RenderLayer.h"
34#include "core/rendering/svg/RenderSVGImage.h"
35#include "core/rendering/svg/RenderSVGResource.h"
36#include "core/rendering/svg/RenderSVGResourceFilter.h"
37#include "core/rendering/svg/RenderSVGResourceMasker.h"
38#include "core/rendering/svg/SVGResources.h"
39#include "core/rendering/svg/SVGResourcesCache.h"
40
41static int kMaxImageBufferSize = 4096;
42
43namespace WebCore {
44
45static inline bool isRenderingMaskImage(RenderObject* object)
46{
47    if (object->frame() && object->frame()->view())
48        return object->frame()->view()->paintBehavior() & PaintBehaviorRenderingSVGMask;
49    return false;
50}
51
52SVGRenderingContext::~SVGRenderingContext()
53{
54    // Fast path if we don't need to restore anything.
55    if (!(m_renderingFlags & ActionsNeeded))
56        return;
57
58    ASSERT(m_object && m_paintInfo);
59
60    if (m_renderingFlags & PostApplyResources) {
61        ASSERT(m_masker || m_clipper || m_filter);
62        ASSERT(SVGResourcesCache::cachedResourcesForRenderObject(m_object));
63
64        if (m_filter) {
65            ASSERT(SVGResourcesCache::cachedResourcesForRenderObject(m_object)->filter() == m_filter);
66            m_filter->postApplyResource(m_object, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
67            m_paintInfo->context = m_savedContext;
68            m_paintInfo->rect = m_savedPaintRect;
69        }
70
71        if (m_clipper) {
72            ASSERT(SVGResourcesCache::cachedResourcesForRenderObject(m_object)->clipper() == m_clipper);
73            m_clipper->postApplyStatefulResource(m_object, m_paintInfo->context, m_clipperContext);
74        }
75
76        if (m_masker) {
77            ASSERT(SVGResourcesCache::cachedResourcesForRenderObject(m_object)->masker() == m_masker);
78            m_masker->postApplyResource(m_object, m_paintInfo->context, ApplyToDefaultMode, 0, 0);
79        }
80    }
81
82    if (m_renderingFlags & EndOpacityLayer)
83        m_paintInfo->context->endLayer();
84
85    if (m_renderingFlags & RestoreGraphicsContext)
86        m_paintInfo->context->restore();
87}
88
89void SVGRenderingContext::prepareToRenderSVGContent(RenderObject* object, PaintInfo& paintInfo, NeedsGraphicsContextSave needsGraphicsContextSave)
90{
91    ASSERT(object);
92
93#ifndef NDEBUG
94    // This function must not be called twice!
95    ASSERT(!(m_renderingFlags & PrepareToRenderSVGContentWasCalled));
96    m_renderingFlags |= PrepareToRenderSVGContentWasCalled;
97#endif
98
99    m_object = object;
100    m_paintInfo = &paintInfo;
101    m_filter = 0;
102
103    // We need to save / restore the context even if the initialization failed.
104    if (needsGraphicsContextSave == SaveGraphicsContext) {
105        m_paintInfo->context->save();
106        m_renderingFlags |= RestoreGraphicsContext;
107    }
108
109    RenderStyle* style = m_object->style();
110    ASSERT(style);
111
112    const SVGRenderStyle* svgStyle = style->svgStyle();
113    ASSERT(svgStyle);
114
115    // Setup transparency layers before setting up SVG resources!
116    bool isRenderingMask = isRenderingMaskImage(m_object);
117    // RenderLayer takes care of root opacity.
118    float opacity = (object->isSVGRoot() || isRenderingMask) ? 1 : style->opacity();
119    bool hasBlendMode = style->hasBlendMode() && !isRenderingMask;
120
121    if (opacity < 1 || hasBlendMode || style->hasIsolation()) {
122        FloatRect repaintRect = m_object->paintInvalidationRectInLocalCoordinates();
123        m_paintInfo->context->clip(repaintRect);
124
125        if (hasBlendMode) {
126            if (!(m_renderingFlags & RestoreGraphicsContext)) {
127                m_paintInfo->context->save();
128                m_renderingFlags |= RestoreGraphicsContext;
129            }
130            m_paintInfo->context->setCompositeOperation(CompositeSourceOver, style->blendMode());
131        }
132
133        m_paintInfo->context->beginTransparencyLayer(opacity);
134
135        if (hasBlendMode)
136            m_paintInfo->context->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
137
138        m_renderingFlags |= EndOpacityLayer;
139    }
140
141    ClipPathOperation* clipPathOperation = style->clipPath();
142    if (clipPathOperation && clipPathOperation->type() == ClipPathOperation::SHAPE) {
143        ShapeClipPathOperation* clipPath = toShapeClipPathOperation(clipPathOperation);
144        m_paintInfo->context->clipPath(clipPath->path(object->objectBoundingBox()), clipPath->windRule());
145    }
146
147    SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(m_object);
148    if (!resources) {
149        if (svgStyle->hasFilter())
150            return;
151
152        m_renderingFlags |= RenderingPrepared;
153        return;
154    }
155
156    if (!isRenderingMask) {
157        if (RenderSVGResourceMasker* masker = resources->masker()) {
158            if (!masker->applyResource(m_object, style, m_paintInfo->context, ApplyToDefaultMode))
159                return;
160            m_masker = masker;
161            m_renderingFlags |= PostApplyResources;
162        }
163    }
164
165    RenderSVGResourceClipper* clipper = resources->clipper();
166    if (!clipPathOperation && clipper) {
167        if (!clipper->applyStatefulResource(m_object, m_paintInfo->context, m_clipperContext))
168            return;
169        m_clipper = clipper;
170        m_renderingFlags |= PostApplyResources;
171    }
172
173    if (!isRenderingMask) {
174        m_filter = resources->filter();
175        if (m_filter) {
176            m_savedContext = m_paintInfo->context;
177            m_savedPaintRect = m_paintInfo->rect;
178            // Return with false here may mean that we don't need to draw the content
179            // (because it was either drawn before or empty) but we still need to apply the filter.
180            m_renderingFlags |= PostApplyResources;
181            if (!m_filter->applyResource(m_object, style, m_paintInfo->context, ApplyToDefaultMode))
182                return;
183
184            // Since we're caching the resulting bitmap and do not invalidate it on repaint rect
185            // changes, we need to paint the whole filter region. Otherwise, elements not visible
186            // at the time of the initial paint (due to scrolling, window size, etc.) will never
187            // be drawn.
188            m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_object));
189        }
190    }
191
192    m_renderingFlags |= RenderingPrepared;
193}
194
195static AffineTransform& currentContentTransformation()
196{
197    DEFINE_STATIC_LOCAL(AffineTransform, s_currentContentTransformation, ());
198    return s_currentContentTransformation;
199}
200
201float SVGRenderingContext::calculateScreenFontSizeScalingFactor(const RenderObject* renderer)
202{
203    ASSERT(renderer);
204
205    AffineTransform ctm;
206    // FIXME: calculateDeviceSpaceTransformation() queries layer compositing state - which is not
207    // supported during layout. Hence, the result may not include all CSS transforms.
208    calculateDeviceSpaceTransformation(renderer, ctm);
209    return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
210}
211
212void SVGRenderingContext::calculateDeviceSpaceTransformation(const RenderObject* renderer, AffineTransform& absoluteTransform)
213{
214    // FIXME: trying to compute a device space transform at record time is wrong. All clients
215    // should be updated to avoid relying on this information, and the method should be removed.
216
217    ASSERT(renderer);
218    // We're about to possibly clear renderer, so save the deviceScaleFactor now.
219    float deviceScaleFactor = renderer->document().frameHost()->deviceScaleFactor();
220
221    // Walk up the render tree, accumulating SVG transforms.
222    absoluteTransform = currentContentTransformation();
223    while (renderer) {
224        absoluteTransform = renderer->localToParentTransform() * absoluteTransform;
225        if (renderer->isSVGRoot())
226            break;
227        renderer = renderer->parent();
228    }
229
230    // Continue walking up the layer tree, accumulating CSS transforms.
231    RenderLayer* layer = renderer ? renderer->enclosingLayer() : 0;
232    while (layer && layer->isAllowedToQueryCompositingState()) {
233        // We can stop at compositing layers, to match the backing resolution.
234        // FIXME: should we be computing the transform to the nearest composited layer,
235        // or the nearest composited layer that does not paint into its ancestor?
236        // I think this is the nearest composited ancestor since we will inherit its
237        // transforms in the composited layer tree.
238        if (layer->compositingState() != NotComposited)
239            break;
240
241        if (TransformationMatrix* layerTransform = layer->transform())
242            absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
243
244        layer = layer->parent();
245    }
246
247    absoluteTransform.scale(deviceScaleFactor);
248}
249
250void SVGRenderingContext::renderSubtree(GraphicsContext* context, RenderObject* item, const AffineTransform& subtreeContentTransformation)
251{
252    ASSERT(item);
253    ASSERT(context);
254
255    PaintInfo info(context, PaintInfo::infiniteRect(), PaintPhaseForeground, PaintBehaviorNormal);
256
257    AffineTransform& contentTransformation = currentContentTransformation();
258    AffineTransform savedContentTransformation = contentTransformation;
259    contentTransformation = subtreeContentTransformation * contentTransformation;
260
261    ASSERT(!item->needsLayout());
262    item->paint(info, IntPoint());
263
264    contentTransformation = savedContentTransformation;
265}
266
267FloatRect SVGRenderingContext::clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect)
268{
269    const FloatSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
270    return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
271}
272
273void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
274{
275    AffineTransform::DecomposedType decomposition;
276    transform.decompose(decomposition);
277    decomposition.angle = 0;
278    transform.recompose(decomposition);
279}
280
281bool SVGRenderingContext::bufferForeground(OwnPtr<ImageBuffer>& imageBuffer)
282{
283    ASSERT(m_paintInfo);
284    ASSERT(m_object->isSVGImage());
285    FloatRect boundingBox = m_object->objectBoundingBox();
286
287    // Invalidate an existing buffer if the scale is not correct.
288    if (imageBuffer) {
289        AffineTransform transform = m_paintInfo->context->getCTM();
290        IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
291        IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
292        if (bufferSize != imageBuffer->size())
293            imageBuffer.clear();
294    }
295
296    // Create a new buffer and paint the foreground into it.
297    if (!imageBuffer) {
298        if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size())))) {
299            GraphicsContext* bufferedRenderingContext = imageBuffer->context();
300            bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
301            PaintInfo bufferedInfo(*m_paintInfo);
302            bufferedInfo.context = bufferedRenderingContext;
303            toRenderSVGImage(m_object)->paintForeground(bufferedInfo);
304        } else
305            return false;
306    }
307
308    m_paintInfo->context->drawImageBuffer(imageBuffer.get(), boundingBox);
309    return true;
310}
311
312}
313