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 GraphicsContextStateSaver stateSaver(*maskContext);
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 return false;
195 }
196 }
197
198 drawContentIntoMaskImage(clipperData, objectBoundingBox);
199 }
200
201 if (!clipperData->clipMaskImage)
202 return false;
203
204 SVGImageBufferTools::clipToImageBuffer(context, absoluteTransform, clampedAbsoluteTargetRect, clipperData->clipMaskImage);
205 return true;
206 }
207
drawContentIntoMaskImage(ClipperData * clipperData,const FloatRect & objectBoundingBox)208 bool RenderSVGResourceClipper::drawContentIntoMaskImage(ClipperData* clipperData, const FloatRect& objectBoundingBox)
209 {
210 ASSERT(clipperData);
211 ASSERT(clipperData->clipMaskImage);
212
213 GraphicsContext* maskContext = clipperData->clipMaskImage->context();
214 ASSERT(maskContext);
215
216 AffineTransform maskContentTransformation;
217 SVGClipPathElement* clipPath = static_cast<SVGClipPathElement*>(node());
218 if (clipPath->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
219 maskContentTransformation.translate(objectBoundingBox.x(), objectBoundingBox.y());
220 maskContentTransformation.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
221 maskContext->concatCTM(maskContentTransformation);
222 }
223
224 // Draw all clipPath children into a global mask.
225 for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
226 RenderObject* renderer = childNode->renderer();
227 if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
228 continue;
229 RenderStyle* style = renderer->style();
230 if (!style || style->display() == NONE || style->visibility() != VISIBLE)
231 continue;
232
233 WindRule newClipRule = style->svgStyle()->clipRule();
234 bool isUseElement = renderer->isSVGShadowTreeRootContainer();
235 if (isUseElement) {
236 SVGUseElement* useElement = static_cast<SVGUseElement*>(childNode);
237 renderer = useElement->rendererClipChild();
238 if (!renderer)
239 continue;
240 if (!useElement->hasAttribute(SVGNames::clip_ruleAttr))
241 newClipRule = renderer->style()->svgStyle()->clipRule();
242 }
243
244 // Only shapes, paths and texts are allowed for clipping.
245 if (!renderer->isSVGPath() && !renderer->isSVGText())
246 continue;
247
248 // Save the old RenderStyle of the current object for restoring after drawing
249 // it to the MaskImage. The new intermediate RenderStyle needs to inherit from
250 // the old one.
251 RefPtr<RenderStyle> oldRenderStyle = renderer->style();
252 RefPtr<RenderStyle> newRenderStyle = RenderStyle::clone(oldRenderStyle.get());
253 SVGRenderStyle* svgStyle = newRenderStyle.get()->accessSVGStyle();
254 svgStyle->setFillPaint(SVGRenderStyle::initialFillPaintType(), SVGRenderStyle::initialFillPaintColor(), SVGRenderStyle::initialFillPaintUri());
255 svgStyle->setStrokePaint(SVGRenderStyle::initialStrokePaintType(), SVGRenderStyle::initialStrokePaintColor(), SVGRenderStyle::initialStrokePaintUri());
256 svgStyle->setFillRule(newClipRule);
257 newRenderStyle.get()->setOpacity(1.0f);
258 svgStyle->setFillOpacity(1.0f);
259 svgStyle->setStrokeOpacity(1.0f);
260 svgStyle->setFilterResource(String());
261 svgStyle->setMaskerResource(String());
262
263 // The setStyle() call results in a styleDidChange() call, which in turn invalidations the resources.
264 // As we're mutating the resource on purpose, block updates until we've resetted the style again.
265 m_invalidationBlocked = true;
266 renderer->setStyle(newRenderStyle.release());
267
268 // In the case of a <use> element, we obtained its renderere above, to retrieve its clipRule.
269 // We have to pass the <use> renderer itself to renderSubtreeToImageBuffer() to apply it's x/y/transform/etc. values when rendering.
270 // So if isUseElement is true, refetch the childNode->renderer(), as renderer got overriden above.
271 SVGImageBufferTools::renderSubtreeToImageBuffer(clipperData->clipMaskImage.get(), isUseElement ? childNode->renderer() : renderer, maskContentTransformation);
272
273 renderer->setStyle(oldRenderStyle.release());
274 m_invalidationBlocked = false;
275 }
276
277 return true;
278 }
279
calculateClipContentRepaintRect()280 void RenderSVGResourceClipper::calculateClipContentRepaintRect()
281 {
282 // This is a rough heuristic to appraise the clip size and doesn't consider clip on clip.
283 for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
284 RenderObject* renderer = childNode->renderer();
285 if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
286 continue;
287 if (!renderer->isSVGPath() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
288 continue;
289 RenderStyle* style = renderer->style();
290 if (!style || style->display() == NONE || style->visibility() != VISIBLE)
291 continue;
292 m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
293 }
294 }
295
hitTestClipContent(const FloatRect & objectBoundingBox,const FloatPoint & nodeAtPoint)296 bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
297 {
298 FloatPoint point = nodeAtPoint;
299 if (!SVGRenderSupport::pointInClippingArea(this, point))
300 return false;
301
302 if (static_cast<SVGClipPathElement*>(node())->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
303 AffineTransform transform;
304 transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
305 transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
306 point = transform.inverse().mapPoint(point);
307 }
308
309 for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
310 RenderObject* renderer = childNode->renderer();
311 if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyled() || !renderer)
312 continue;
313 if (!renderer->isSVGPath() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
314 continue;
315 IntPoint hitPoint;
316 HitTestResult result(hitPoint);
317 if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent), result, point, HitTestForeground))
318 return true;
319 }
320
321 return false;
322 }
323
resourceBoundingBox(RenderObject * object)324 FloatRect RenderSVGResourceClipper::resourceBoundingBox(RenderObject* object)
325 {
326 // Resource was not layouted yet. Give back the boundingBox of the object.
327 if (selfNeedsLayout())
328 return object->objectBoundingBox();
329
330 if (m_clipBoundaries.isEmpty())
331 calculateClipContentRepaintRect();
332
333 if (static_cast<SVGClipPathElement*>(node())->clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
334 FloatRect objectBoundingBox = object->objectBoundingBox();
335 AffineTransform transform;
336 transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
337 transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
338 return transform.mapRect(m_clipBoundaries);
339 }
340
341 return m_clipBoundaries;
342 }
343
344 }
345
346 #endif // ENABLE(SVG)
347