tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / rendering / svg / RenderSVGResourceClipper.cpp
1 /*
2  * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
3  * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org>
4  * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
5  * Copyright (C) 2011 Dirk Schulze <krit@webkit.org>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public License
18  * along with this library; see the file COPYING.LIB.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #include "config.h"
24
25 #if ENABLE(SVG)
26 #include "RenderSVGResourceClipper.h"
27
28 #include "AffineTransform.h"
29 #include "FloatRect.h"
30 #include "GraphicsContext.h"
31 #include "HitTestRequest.h"
32 #include "HitTestResult.h"
33 #include "ImageBuffer.h"
34 #include "IntRect.h"
35 #include "RenderObject.h"
36 #include "RenderSVGResource.h"
37 #include "RenderStyle.h"
38 #include "SVGClipPathElement.h"
39 #include "SVGElement.h"
40 #include "SVGImageBufferTools.h"
41 #include "SVGNames.h"
42 #include "SVGRenderSupport.h"
43 #include "SVGResources.h"
44 #include "SVGResourcesCache.h"
45 #include "SVGStyledElement.h"
46 #include "SVGStyledTransformableElement.h"
47 #include "SVGUnitTypes.h"
48 #include "SVGUseElement.h"
49 #include <wtf/UnusedParam.h>
50
51 namespace WebCore {
52
53 RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
54
55 RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement* node)
56     : RenderSVGResourceContainer(node)
57     , m_invalidationBlocked(false)
58 {
59 }
60
61 RenderSVGResourceClipper::~RenderSVGResourceClipper()
62 {
63     if (m_clipper.isEmpty())
64         return;
65
66     deleteAllValues(m_clipper);
67     m_clipper.clear();
68 }
69
70 void RenderSVGResourceClipper::removeAllClientsFromCache(bool markForInvalidation)
71 {
72     if (m_invalidationBlocked)
73         return;
74
75     m_clipBoundaries = FloatRect();
76     if (!m_clipper.isEmpty()) {
77         deleteAllValues(m_clipper);
78         m_clipper.clear();
79     }
80
81     markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
82 }
83
84 void RenderSVGResourceClipper::removeClientFromCache(RenderObject* client, bool markForInvalidation)
85 {
86     ASSERT(client);
87     if (m_invalidationBlocked)
88         return;
89
90     if (m_clipper.contains(client))
91         delete m_clipper.take(client);
92
93     markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);
94 }
95
96 bool RenderSVGResourceClipper::applyResource(RenderObject* object, RenderStyle*, GraphicsContext*& context, unsigned short resourceMode)
97 {
98     ASSERT(object);
99     ASSERT(context);
100     ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
101
102     return applyClippingToContext(object, object->objectBoundingBox(), object->repaintRectInLocalCoordinates(), context);
103 }
104
105 bool RenderSVGResourceClipper::pathOnlyClipping(GraphicsContext* context, const AffineTransform& animatedLocalTransform, const FloatRect& objectBoundingBox)
106 {
107     // If the current clip-path gets clipped itself, we have to fallback to masking.
108     if (!style()->svgStyle()->clipperResource().isEmpty())
109         return false;
110     WindRule clipRule = RULE_NONZERO;
111     Path clipPath = Path();
112
113     // If clip-path only contains one visible shape or path, we can use path-based clipping. Invisible
114     // shapes don't affect the clipping and can be ignored. If clip-path contains more than one
115     // visible shape, the additive clipping may not work, caused by the clipRule. EvenOdd
116     // as well as NonZero can cause self-clipping of the elements.
117     // See also http://www.w3.org/TR/SVG/painting.html#FillRuleProperty
118     for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
119         RenderObject* renderer = childNode->renderer();
120         if (!renderer)
121             continue;
122         // Only shapes or paths are supported for direct clipping. We need to fallback to masking for texts.
123         if (renderer->isSVGText())
124             return false;
125         if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyledTransformable())
126             continue;
127         SVGStyledTransformableElement* styled = static_cast<SVGStyledTransformableElement*>(childNode);
128         RenderStyle* style = renderer->style();
129         if (!style || style->display() == NONE || style->visibility() != VISIBLE)
130              continue;
131         const SVGRenderStyle* svgStyle = style->svgStyle();
132         // Current shape in clip-path gets clipped too. Fallback to masking.
133         if (!svgStyle->clipperResource().isEmpty())
134             return false;
135         // Fallback to masking, if there is more than one clipping path.
136         if (clipPath.isEmpty()) {
137             styled->toClipPath(clipPath);
138             clipRule = svgStyle->clipRule();
139         } else
140             return false;
141     }
142     // Only one visible shape/path was found. Directly continue clipping and transform the content to userspace if necessary.
143     if (static_cast<SVGClipPathElement*>(node())->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
144         AffineTransform transform;
145         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
146         transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
147         clipPath.transform(transform);
148     }
149
150     // Transform path by animatedLocalTransform.
151     clipPath.transform(animatedLocalTransform);
152
153     // The SVG specification wants us to clip everything, if clip-path doesn't have a child.
154     if (clipPath.isEmpty())
155         clipPath.addRect(FloatRect());
156     context->clipPath(clipPath, clipRule);
157     return true;
158 }
159
160 bool RenderSVGResourceClipper::applyClippingToContext(RenderObject* object, const FloatRect& objectBoundingBox,
161                                                       const FloatRect& repaintRect, GraphicsContext* context)
162 {
163     if (!m_clipper.contains(object))
164         m_clipper.set(object, new ClipperData);
165
166     bool shouldCreateClipData = false;
167     AffineTransform animatedLocalTransform = static_cast<SVGClipPathElement*>(node())->animatedLocalTransform();
168     ClipperData* clipperData = m_clipper.get(object);
169     if (!clipperData->clipMaskImage) {
170         if (pathOnlyClipping(context, animatedLocalTransform, objectBoundingBox))
171             return true;
172         shouldCreateClipData = true;
173     }
174
175     AffineTransform absoluteTransform;
176     SVGImageBufferTools::calculateTransformationToOutermostSVGCoordinateSystem(object, absoluteTransform);
177
178     FloatRect absoluteTargetRect = absoluteTransform.mapRect(repaintRect);
179     FloatRect clampedAbsoluteTargetRect = SVGImageBufferTools::clampedAbsoluteTargetRect(absoluteTargetRect);
180
181     if (shouldCreateClipData && !clampedAbsoluteTargetRect.isEmpty()) {
182         if (!SVGImageBufferTools::createImageBuffer(absoluteTargetRect, clampedAbsoluteTargetRect, clipperData->clipMaskImage, ColorSpaceDeviceRGB))
183             return false;
184
185         GraphicsContext* maskContext = clipperData->clipMaskImage->context();
186         ASSERT(maskContext);
187
188         // The save/restore pair is needed for clipToImageBuffer - it doesn't work without it on non-Cg platforms.
189         GraphicsContextStateSaver stateSaver(*maskContext);
190         maskContext->translate(-clampedAbsoluteTargetRect.x(), -clampedAbsoluteTargetRect.y());
191         maskContext->concatCTM(animatedLocalTransform);
192         maskContext->concatCTM(absoluteTransform);
193
194         // clipPath can also be clipped by another clipPath.
195         if (SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this)) {
196             if (RenderSVGResourceClipper* clipper = resources->clipper()) {
197                 if (!clipper->applyClippingToContext(this, objectBoundingBox, repaintRect, maskContext))
198                     return false;
199             }
200         }
201
202         drawContentIntoMaskImage(clipperData, objectBoundingBox);
203     }
204
205     if (!clipperData->clipMaskImage)
206         return false;
207
208     SVGImageBufferTools::clipToImageBuffer(context, absoluteTransform, clampedAbsoluteTargetRect, clipperData->clipMaskImage);
209     return true;
210 }
211
212 bool RenderSVGResourceClipper::drawContentIntoMaskImage(ClipperData* clipperData, const FloatRect& objectBoundingBox)
213 {
214     ASSERT(clipperData);
215     ASSERT(clipperData->clipMaskImage);
216
217     GraphicsContext* maskContext = clipperData->clipMaskImage->context();
218     ASSERT(maskContext);
219
220     AffineTransform maskContentTransformation;
221     SVGClipPathElement* clipPath = static_cast<SVGClipPathElement*>(node());
222     if (clipPath->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
223         maskContentTransformation.translate(objectBoundingBox.x(), objectBoundingBox.y());
224         maskContentTransformation.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
225         maskContext->concatCTM(maskContentTransformation);
226     }
227
228     // Draw all clipPath children into a global mask.
229     for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
230         RenderObject* renderer = childNode->renderer();
231         if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
232             continue;
233         RenderStyle* style = renderer->style();
234         if (!style || style->display() == NONE || style->visibility() != VISIBLE)
235             continue;
236
237         WindRule newClipRule = style->svgStyle()->clipRule();
238         bool isUseElement = renderer->isSVGShadowTreeRootContainer();
239         if (isUseElement) {
240             SVGUseElement* useElement = static_cast<SVGUseElement*>(childNode);
241             renderer = useElement->rendererClipChild();
242             if (!renderer)
243                 continue;
244             if (!useElement->hasAttribute(SVGNames::clip_ruleAttr))
245                 newClipRule = renderer->style()->svgStyle()->clipRule();
246         }
247
248         // Only shapes, paths and texts are allowed for clipping.
249         if (!renderer->isSVGShape() && !renderer->isSVGText())
250             continue;
251
252         // Save the old RenderStyle of the current object for restoring after drawing
253         // it to the MaskImage. The new intermediate RenderStyle needs to inherit from
254         // the old one.
255         RefPtr<RenderStyle> oldRenderStyle = renderer->style();
256         RefPtr<RenderStyle> newRenderStyle = RenderStyle::clone(oldRenderStyle.get());
257         SVGRenderStyle* svgStyle = newRenderStyle.get()->accessSVGStyle();
258         svgStyle->setFillPaint(SVGRenderStyle::initialFillPaintType(), SVGRenderStyle::initialFillPaintColor(), SVGRenderStyle::initialFillPaintUri());
259         svgStyle->setStrokePaint(SVGRenderStyle::initialStrokePaintType(), SVGRenderStyle::initialStrokePaintColor(), SVGRenderStyle::initialStrokePaintUri());
260         svgStyle->setFillRule(newClipRule);
261         newRenderStyle.get()->setOpacity(1);
262         svgStyle->setFillOpacity(1);
263         svgStyle->setStrokeOpacity(1);
264         svgStyle->setFilterResource(String());
265         svgStyle->setMaskerResource(String());
266
267         // The setStyle() call results in a styleDidChange() call, which in turn invalidations the resources.
268         // As we're mutating the resource on purpose, block updates until we've resetted the style again.
269         m_invalidationBlocked = true;
270         renderer->setStyle(newRenderStyle.release());
271
272         // In the case of a <use> element, we obtained its renderere above, to retrieve its clipRule.
273         // We have to pass the <use> renderer itself to renderSubtreeToImageBuffer() to apply it's x/y/transform/etc. values when rendering.
274         // So if isUseElement is true, refetch the childNode->renderer(), as renderer got overriden above.
275         SVGImageBufferTools::renderSubtreeToImageBuffer(clipperData->clipMaskImage.get(), isUseElement ? childNode->renderer() : renderer, maskContentTransformation);
276
277         renderer->setStyle(oldRenderStyle.release());
278         m_invalidationBlocked = false;
279     }
280
281     return true;
282 }
283
284 void RenderSVGResourceClipper::calculateClipContentRepaintRect()
285 {
286     // This is a rough heuristic to appraise the clip size and doesn't consider clip on clip.
287     for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
288         RenderObject* renderer = childNode->renderer();
289         if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
290             continue;
291         if (!renderer->isSVGShape() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
292             continue;
293         RenderStyle* style = renderer->style();
294         if (!style || style->display() == NONE || style->visibility() != VISIBLE)
295              continue;
296         m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
297     }
298     m_clipBoundaries = static_cast<SVGClipPathElement*>(node())->animatedLocalTransform().mapRect(m_clipBoundaries);
299 }
300
301 bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
302 {
303     FloatPoint point = nodeAtPoint;
304     if (!SVGRenderSupport::pointInClippingArea(this, point))
305         return false;
306
307     SVGClipPathElement* clipPathElement = static_cast<SVGClipPathElement*>(node());
308     if (clipPathElement->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
309         AffineTransform transform;
310         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
311         transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
312         point = transform.inverse().mapPoint(point);
313     }
314
315     point = clipPathElement->animatedLocalTransform().inverse().mapPoint(point);
316
317     for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
318         RenderObject* renderer = childNode->renderer();
319         if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
320             continue;
321         if (!renderer->isSVGShape() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
322             continue;
323         IntPoint hitPoint;
324         HitTestResult result(hitPoint);
325         if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent), result, point, HitTestForeground))
326             return true;
327     }
328
329     return false;
330 }
331
332 FloatRect RenderSVGResourceClipper::resourceBoundingBox(RenderObject* object)
333 {
334     // Resource was not layouted yet. Give back the boundingBox of the object.
335     if (selfNeedsLayout())
336         return object->objectBoundingBox();
337     
338     if (m_clipBoundaries.isEmpty())
339         calculateClipContentRepaintRect();
340
341     if (static_cast<SVGClipPathElement*>(node())->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
342         FloatRect objectBoundingBox = object->objectBoundingBox();
343         AffineTransform transform;
344         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
345         transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
346         return transform.mapRect(m_clipBoundaries);
347     }
348
349     return m_clipBoundaries;
350 }
351
352 }
353
354 #endif // ENABLE(SVG)