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