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#include "RenderSVGResourceClipper.h"
25
26#include "ElementIterator.h"
27#include "Frame.h"
28#include "FrameView.h"
29#include "HitTestRequest.h"
30#include "HitTestResult.h"
31#include "IntRect.h"
32#include "RenderObject.h"
33#include "RenderStyle.h"
34#include "RenderView.h"
35#include "SVGNames.h"
36#include "SVGRenderingContext.h"
37#include "SVGResources.h"
38#include "SVGResourcesCache.h"
39#include "SVGUseElement.h"
40
41namespace WebCore {
42
43RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
44
45RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement& element, PassRef<RenderStyle> style)
46    : RenderSVGResourceContainer(element, WTF::move(style))
47{
48}
49
50RenderSVGResourceClipper::~RenderSVGResourceClipper()
51{
52}
53
54void RenderSVGResourceClipper::removeAllClientsFromCache(bool markForInvalidation)
55{
56    m_clipBoundaries = FloatRect();
57    m_clipper.clear();
58
59    markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
60}
61
62void RenderSVGResourceClipper::removeClientFromCache(RenderElement& client, bool markForInvalidation)
63{
64    m_clipper.remove(&client);
65
66    markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);
67}
68
69bool RenderSVGResourceClipper::applyResource(RenderElement& renderer, const RenderStyle&, GraphicsContext*& context, unsigned short resourceMode)
70{
71    ASSERT(context);
72    ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
73
74    return applyClippingToContext(renderer, renderer.objectBoundingBox(), renderer.repaintRectInLocalCoordinates(), context);
75}
76
77bool RenderSVGResourceClipper::pathOnlyClipping(GraphicsContext* context, const AffineTransform& animatedLocalTransform, const FloatRect& objectBoundingBox)
78{
79    // If the current clip-path gets clipped itself, we have to fallback to masking.
80    if (!style().svgStyle().clipperResource().isEmpty())
81        return false;
82    WindRule clipRule = RULE_NONZERO;
83    Path clipPath = Path();
84
85    // If clip-path only contains one visible shape or path, we can use path-based clipping. Invisible
86    // shapes don't affect the clipping and can be ignored. If clip-path contains more than one
87    // visible shape, the additive clipping may not work, caused by the clipRule. EvenOdd
88    // as well as NonZero can cause self-clipping of the elements.
89    // See also http://www.w3.org/TR/SVG/painting.html#FillRuleProperty
90    for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) {
91        RenderObject* renderer = childNode->renderer();
92        if (!renderer)
93            continue;
94        // Only shapes or paths are supported for direct clipping. We need to fallback to masking for texts.
95        if (renderer->isSVGText())
96            return false;
97        if (!childNode->isSVGElement() || !toSVGElement(childNode)->isSVGGraphicsElement())
98            continue;
99        SVGGraphicsElement* styled = toSVGGraphicsElement(childNode);
100        const RenderStyle& style = renderer->style();
101        if (style.display() == NONE || style.visibility() != VISIBLE)
102             continue;
103        const SVGRenderStyle& svgStyle = style.svgStyle();
104        // Current shape in clip-path gets clipped too. Fallback to masking.
105        if (!svgStyle.clipperResource().isEmpty())
106            return false;
107        // Fallback to masking, if there is more than one clipping path.
108        if (clipPath.isEmpty()) {
109            styled->toClipPath(clipPath);
110            clipRule = svgStyle.clipRule();
111        } else
112            return false;
113    }
114    // Only one visible shape/path was found. Directly continue clipping and transform the content to userspace if necessary.
115    if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
116        AffineTransform transform;
117        transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
118        transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
119        clipPath.transform(transform);
120    }
121
122    // Transform path by animatedLocalTransform.
123    clipPath.transform(animatedLocalTransform);
124
125    // The SVG specification wants us to clip everything, if clip-path doesn't have a child.
126    if (clipPath.isEmpty())
127        clipPath.addRect(FloatRect());
128    context->clipPath(clipPath, clipRule);
129    return true;
130}
131
132bool RenderSVGResourceClipper::applyClippingToContext(RenderElement& renderer, const FloatRect& objectBoundingBox,
133                                                      const FloatRect& repaintRect, GraphicsContext* context)
134{
135    bool missingClipperData = !m_clipper.contains(&renderer);
136    if (missingClipperData)
137        m_clipper.set(&renderer, std::make_unique<ClipperData>());
138
139    bool shouldCreateClipData = false;
140    AffineTransform animatedLocalTransform = clipPathElement().animatedLocalTransform();
141    ClipperData* clipperData = m_clipper.get(&renderer);
142    if (!clipperData->clipMaskImage) {
143        if (pathOnlyClipping(context, animatedLocalTransform, objectBoundingBox))
144            return true;
145        shouldCreateClipData = true;
146    }
147
148    AffineTransform absoluteTransform;
149    SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(renderer, absoluteTransform);
150
151    if (shouldCreateClipData && !repaintRect.isEmpty()) {
152        if (!SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, clipperData->clipMaskImage, ColorSpaceDeviceRGB, Unaccelerated))
153            return false;
154
155        GraphicsContext* maskContext = clipperData->clipMaskImage->context();
156        ASSERT(maskContext);
157
158        maskContext->concatCTM(animatedLocalTransform);
159
160        // clipPath can also be clipped by another clipPath.
161        SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(*this);
162        RenderSVGResourceClipper* clipper;
163        bool succeeded;
164        if (resources && (clipper = resources->clipper())) {
165            GraphicsContextStateSaver stateSaver(*maskContext);
166
167            if (!clipper->applyClippingToContext(*this, objectBoundingBox, repaintRect, maskContext))
168                return false;
169
170            succeeded = drawContentIntoMaskImage(clipperData, objectBoundingBox);
171            // The context restore applies the clipping on non-CG platforms.
172        } else
173            succeeded = drawContentIntoMaskImage(clipperData, objectBoundingBox);
174
175        if (!succeeded)
176            clipperData->clipMaskImage.reset();
177    }
178
179    if (!clipperData->clipMaskImage)
180        return false;
181
182    SVGRenderingContext::clipToImageBuffer(context, absoluteTransform, repaintRect, clipperData->clipMaskImage, missingClipperData);
183    return true;
184}
185
186bool RenderSVGResourceClipper::drawContentIntoMaskImage(ClipperData* clipperData, const FloatRect& objectBoundingBox)
187{
188    ASSERT(clipperData);
189    ASSERT(clipperData->clipMaskImage);
190
191    GraphicsContext* maskContext = clipperData->clipMaskImage->context();
192    ASSERT(maskContext);
193
194    AffineTransform maskContentTransformation;
195    if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
196        maskContentTransformation.translate(objectBoundingBox.x(), objectBoundingBox.y());
197        maskContentTransformation.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
198        maskContext->concatCTM(maskContentTransformation);
199    }
200
201    // Switch to a paint behavior where all children of this <clipPath> will be rendered using special constraints:
202    // - fill-opacity/stroke-opacity/opacity set to 1
203    // - masker/filter not applied when rendering the children
204    // - fill is set to the initial fill paint server (solid, black)
205    // - stroke is set to the initial stroke paint server (none)
206    PaintBehavior oldBehavior = view().frameView().paintBehavior();
207    view().frameView().setPaintBehavior(oldBehavior | PaintBehaviorRenderingSVGMask);
208
209    // Draw all clipPath children into a global mask.
210    for (auto& child : childrenOfType<SVGElement>(clipPathElement())) {
211        auto renderer = child.renderer();
212        if (!renderer)
213            continue;
214        if (renderer->needsLayout()) {
215            view().frameView().setPaintBehavior(oldBehavior);
216            return false;
217        }
218        const RenderStyle& style = renderer->style();
219        if (style.display() == NONE || style.visibility() != VISIBLE)
220            continue;
221
222        WindRule newClipRule = style.svgStyle().clipRule();
223        bool isUseElement = child.hasTagName(SVGNames::useTag);
224        if (isUseElement) {
225            SVGUseElement& useElement = toSVGUseElement(child);
226            renderer = useElement.rendererClipChild();
227            if (!renderer)
228                continue;
229            if (!useElement.hasAttribute(SVGNames::clip_ruleAttr))
230                newClipRule = renderer->style().svgStyle().clipRule();
231        }
232
233        // Only shapes, paths and texts are allowed for clipping.
234        if (!renderer->isSVGShape() && !renderer->isSVGText())
235            continue;
236
237        maskContext->setFillRule(newClipRule);
238
239        // In the case of a <use> element, we obtained its renderere above, to retrieve its clipRule.
240        // We have to pass the <use> renderer itself to renderSubtreeToImageBuffer() to apply it's x/y/transform/etc. values when rendering.
241        // So if isUseElement is true, refetch the childNode->renderer(), as renderer got overriden above.
242        SVGRenderingContext::renderSubtreeToImageBuffer(clipperData->clipMaskImage.get(), isUseElement ? *child.renderer() : *renderer, maskContentTransformation);
243    }
244
245    view().frameView().setPaintBehavior(oldBehavior);
246    return true;
247}
248
249void RenderSVGResourceClipper::calculateClipContentRepaintRect()
250{
251    // This is a rough heuristic to appraise the clip size and doesn't consider clip on clip.
252    for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) {
253        RenderObject* renderer = childNode->renderer();
254        if (!childNode->isSVGElement() || !renderer)
255            continue;
256        if (!renderer->isSVGShape() && !renderer->isSVGText() && !childNode->hasTagName(SVGNames::useTag))
257            continue;
258        const RenderStyle& style = renderer->style();
259        if (style.display() == NONE || style.visibility() != VISIBLE)
260             continue;
261        m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
262    }
263    m_clipBoundaries = clipPathElement().animatedLocalTransform().mapRect(m_clipBoundaries);
264}
265
266bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
267{
268    FloatPoint point = nodeAtPoint;
269    if (!SVGRenderSupport::pointInClippingArea(*this, point))
270        return false;
271
272    if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
273        AffineTransform transform;
274        transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
275        transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
276        point = transform.inverse().mapPoint(point);
277    }
278
279    point = clipPathElement().animatedLocalTransform().inverse().mapPoint(point);
280
281    for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) {
282        RenderObject* renderer = childNode->renderer();
283        if (!childNode->isSVGElement() || !renderer)
284            continue;
285        if (!renderer->isSVGShape() && !renderer->isSVGText() && !childNode->hasTagName(SVGNames::useTag))
286            continue;
287        IntPoint hitPoint;
288        HitTestResult result(hitPoint);
289        if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent | HitTestRequest::DisallowShadowContent), result, point, HitTestForeground))
290            return true;
291    }
292
293    return false;
294}
295
296FloatRect RenderSVGResourceClipper::resourceBoundingBox(const RenderObject& object)
297{
298    // Resource was not layouted yet. Give back the boundingBox of the object.
299    if (selfNeedsLayout())
300        return object.objectBoundingBox();
301
302    if (m_clipBoundaries.isEmpty())
303        calculateClipContentRepaintRect();
304
305    if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
306        FloatRect objectBoundingBox = object.objectBoundingBox();
307        AffineTransform transform;
308        transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
309        transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
310        return transform.mapRect(m_clipBoundaries);
311    }
312
313    return m_clipBoundaries;
314}
315
316}
317