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>
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.
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.
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.
26 #include "RenderSVGResourceClipper.h"
28 #include "AffineTransform.h"
29 #include "FloatRect.h"
30 #include "GraphicsContext.h"
31 #include "HitTestRequest.h"
32 #include "HitTestResult.h"
33 #include "ImageBuffer.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"
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>
53 RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
55 RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement* node)
56 : RenderSVGResourceContainer(node)
57 , m_invalidationBlocked(false)
61 RenderSVGResourceClipper::~RenderSVGResourceClipper()
63 if (m_clipper.isEmpty())
66 deleteAllValues(m_clipper);
70 void RenderSVGResourceClipper::removeAllClientsFromCache(bool markForInvalidation)
72 if (m_invalidationBlocked)
75 m_clipBoundaries = FloatRect();
76 if (!m_clipper.isEmpty()) {
77 deleteAllValues(m_clipper);
81 markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
84 void RenderSVGResourceClipper::removeClientFromCache(RenderObject* client, bool markForInvalidation)
87 if (m_invalidationBlocked)
90 if (m_clipper.contains(client))
91 delete m_clipper.take(client);
93 markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);
96 bool RenderSVGResourceClipper::applyResource(RenderObject* object, RenderStyle*, GraphicsContext*& context, unsigned short resourceMode)
100 ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
102 return applyClippingToContext(object, object->objectBoundingBox(), object->repaintRectInLocalCoordinates(), context);
105 bool RenderSVGResourceClipper::pathOnlyClipping(GraphicsContext* context, const AffineTransform& animatedLocalTransform, const FloatRect& objectBoundingBox)
107 // If the current clip-path gets clipped itself, we have to fallback to masking.
108 if (!style()->svgStyle()->clipperResource().isEmpty())
110 WindRule clipRule = RULE_NONZERO;
111 Path clipPath = Path();
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();
122 // Only shapes or paths are supported for direct clipping. We need to fallback to masking for texts.
123 if (renderer->isSVGText())
125 if (!childNode->isSVGElement() || !static_cast<SVGElement*>(childNode)->isStyledTransformable())
127 SVGStyledTransformableElement* styled = static_cast<SVGStyledTransformableElement*>(childNode);
128 RenderStyle* style = renderer->style();
129 if (!style || style->display() == NONE || style->visibility() != VISIBLE)
131 const SVGRenderStyle* svgStyle = style->svgStyle();
132 // Current shape in clip-path gets clipped too. Fallback to masking.
133 if (!svgStyle->clipperResource().isEmpty())
135 // Fallback to masking, if there is more than one clipping path.
136 if (clipPath.isEmpty()) {
137 styled->toClipPath(clipPath);
138 clipRule = svgStyle->clipRule();
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);
150 // Transform path by animatedLocalTransform.
151 clipPath.transform(animatedLocalTransform);
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);
160 bool RenderSVGResourceClipper::applyClippingToContext(RenderObject* object, const FloatRect& objectBoundingBox,
161 const FloatRect& repaintRect, GraphicsContext* context)
163 if (!m_clipper.contains(object))
164 m_clipper.set(object, new ClipperData);
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))
172 shouldCreateClipData = true;
175 AffineTransform absoluteTransform;
176 SVGImageBufferTools::calculateTransformationToOutermostSVGCoordinateSystem(object, absoluteTransform);
178 FloatRect absoluteTargetRect = absoluteTransform.mapRect(repaintRect);
179 FloatRect clampedAbsoluteTargetRect = SVGImageBufferTools::clampedAbsoluteTargetRect(absoluteTargetRect);
181 if (shouldCreateClipData && !clampedAbsoluteTargetRect.isEmpty()) {
182 if (!SVGImageBufferTools::createImageBuffer(absoluteTargetRect, clampedAbsoluteTargetRect, clipperData->clipMaskImage, ColorSpaceDeviceRGB))
185 GraphicsContext* maskContext = clipperData->clipMaskImage->context();
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);
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))
202 drawContentIntoMaskImage(clipperData, objectBoundingBox);
205 if (!clipperData->clipMaskImage)
208 SVGImageBufferTools::clipToImageBuffer(context, absoluteTransform, clampedAbsoluteTargetRect, clipperData->clipMaskImage);
212 bool RenderSVGResourceClipper::drawContentIntoMaskImage(ClipperData* clipperData, const FloatRect& objectBoundingBox)
215 ASSERT(clipperData->clipMaskImage);
217 GraphicsContext* maskContext = clipperData->clipMaskImage->context();
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);
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)
233 RenderStyle* style = renderer->style();
234 if (!style || style->display() == NONE || style->visibility() != VISIBLE)
237 WindRule newClipRule = style->svgStyle()->clipRule();
238 bool isUseElement = renderer->isSVGShadowTreeRootContainer();
240 SVGUseElement* useElement = static_cast<SVGUseElement*>(childNode);
241 renderer = useElement->rendererClipChild();
244 if (!useElement->hasAttribute(SVGNames::clip_ruleAttr))
245 newClipRule = renderer->style()->svgStyle()->clipRule();
248 // Only shapes, paths and texts are allowed for clipping.
249 if (!renderer->isSVGShape() && !renderer->isSVGText())
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
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());
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());
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);
277 renderer->setStyle(oldRenderStyle.release());
278 m_invalidationBlocked = false;
284 void RenderSVGResourceClipper::calculateClipContentRepaintRect()
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)
291 if (!renderer->isSVGShape() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
293 RenderStyle* style = renderer->style();
294 if (!style || style->display() == NONE || style->visibility() != VISIBLE)
296 m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
298 m_clipBoundaries = static_cast<SVGClipPathElement*>(node())->animatedLocalTransform().mapRect(m_clipBoundaries);
301 bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
303 FloatPoint point = nodeAtPoint;
304 if (!SVGRenderSupport::pointInClippingArea(this, point))
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);
315 point = clipPathElement->animatedLocalTransform().inverse().mapPoint(point);
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)
321 if (!renderer->isSVGShape() && !renderer->isSVGText() && !renderer->isSVGShadowTreeRootContainer())
324 HitTestResult result(hitPoint);
325 if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent), result, point, HitTestForeground))
332 FloatRect RenderSVGResourceClipper::resourceBoundingBox(RenderObject* object)
334 // Resource was not layouted yet. Give back the boundingBox of the object.
335 if (selfNeedsLayout())
336 return object->objectBoundingBox();
338 if (m_clipBoundaries.isEmpty())
339 calculateClipContentRepaintRect();
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);
349 return m_clipBoundaries;
354 #endif // ENABLE(SVG)