1/*
2 * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
3 * Copyright (C) 2004, 2005, 2007, 2008, 2009 Rob Buis <buis@kde.org>
4 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
5 * Copyright (C) 2009 Google, Inc.
6 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB.  If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
22 */
23
24#include "config.h"
25
26#if ENABLE(SVG)
27#include "RenderSVGRoot.h"
28
29#include "Chrome.h"
30#include "ChromeClient.h"
31#include "Frame.h"
32#include "GraphicsContext.h"
33#include "HitTestResult.h"
34#include "LayoutRepainter.h"
35#include "Page.h"
36#include "RenderPart.h"
37#include "RenderSVGContainer.h"
38#include "RenderSVGResource.h"
39#include "RenderSVGResourceContainer.h"
40#include "RenderView.h"
41#include "SVGLength.h"
42#include "SVGRenderingContext.h"
43#include "SVGResources.h"
44#include "SVGResourcesCache.h"
45#include "SVGSVGElement.h"
46#include "SVGStyledElement.h"
47#include "SVGViewSpec.h"
48#include "TransformState.h"
49#include <wtf/StackStats.h>
50
51#if ENABLE(FILTERS)
52#include "RenderSVGResourceFilter.h"
53#endif
54
55using namespace std;
56
57namespace WebCore {
58
59RenderSVGRoot::RenderSVGRoot(SVGStyledElement* node)
60    : RenderReplaced(node)
61    , m_objectBoundingBoxValid(false)
62    , m_isLayoutSizeChanged(false)
63    , m_needsBoundariesOrTransformUpdate(true)
64    , m_hasSVGShadow(false)
65{
66}
67
68RenderSVGRoot::~RenderSVGRoot()
69{
70}
71
72void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
73{
74    // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
75    // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
76    // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
77    // If either of these are not specified, a value of '100%' must be assumed. Note: the ‘width’ and ‘height’ attributes are not
78    // the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height,
79    // and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion
80    // of the viewport that is actually covered by image data.
81    SVGSVGElement* svg = toSVGSVGElement(node());
82    ASSERT(svg);
83    Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties);
84    Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
85
86    // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
87    // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
88    // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
89    // - The aspect ratio is calculated by dividing a width by a height.
90    // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
91    //   px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
92    //   resolving both values to user units.
93    if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
94        if (intrinsicWidthAttribute.isFixed())
95            intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0));
96        if (intrinsicHeightAttribute.isFixed())
97            intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0));
98        if (!intrinsicSize.isEmpty())
99            intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
100        return;
101    }
102
103    // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
104    //   aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
105    //   fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
106    //   calculated and is considered unspecified.
107    intrinsicSize = svg->viewBox().size();
108    if (!intrinsicSize.isEmpty()) {
109        // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
110        intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
111        intrinsicSize = FloatSize();
112        return;
113    }
114
115    // If our intrinsic size is in percentage units, return those to the caller through the intrinsicSize. Notify the caller
116    // about the special situation, by setting isPercentageIntrinsicSize=true, so it knows how to interpret the return values.
117    if (intrinsicWidthAttribute.isPercent() && intrinsicHeightAttribute.isPercent()) {
118        isPercentageIntrinsicSize = true;
119        intrinsicSize = FloatSize(intrinsicWidthAttribute.percent(), intrinsicHeightAttribute.percent());
120    }
121}
122
123bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
124{
125    if (!node())
126        return false;
127
128    Frame* frame = node()->document()->frame();
129    if (!frame)
130        return false;
131
132    // Test whether we're embedded through an img.
133    if (!frame->page())
134        return false;
135
136    ChromeClient* chromeClient = frame->page()->chrome().client();
137    if (!chromeClient || !chromeClient->isSVGImageChromeClient())
138        return false;
139
140    return true;
141}
142
143bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
144{
145    if (!node())
146        return false;
147
148    Frame* frame = node()->document()->frame();
149    if (!frame)
150        return false;
151
152    // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
153    // but we only negotiate if we're in an SVG document.
154    if (!frame->ownerRenderer())
155        return false;
156    return frame->document()->isSVGDocument();
157}
158
159static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize, RenderView* renderView)
160{
161    return static_cast<LayoutUnit>(valueForLength(length, maxSize, renderView) * (length.isFixed() ? scale : 1));
162}
163
164LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
165{
166    SVGSVGElement* svg = toSVGSVGElement(node());
167    ASSERT(svg);
168
169    // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
170    if (!m_containerSize.isEmpty())
171        return m_containerSize.width();
172
173    if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
174        return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
175
176    if (svg->widthAttributeEstablishesViewport())
177        return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth(), view());
178
179    // SVG embedded through object/embed/iframe.
180    if (isEmbeddedThroughFrameContainingSVGDocument())
181        return document()->frame()->ownerRenderer()->availableLogicalWidth();
182
183    // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
184    return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
185}
186
187LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
188{
189    SVGSVGElement* svg = toSVGSVGElement(node());
190    ASSERT(svg);
191
192    // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
193    if (!m_containerSize.isEmpty())
194        return m_containerSize.height();
195
196    if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
197        return RenderReplaced::computeReplacedLogicalHeight();
198
199    if (svg->heightAttributeEstablishesViewport()) {
200        Length height = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
201        if (height.isPercent()) {
202            RenderBlock* cb = containingBlock();
203            ASSERT(cb);
204            while (cb->isAnonymous()) {
205                cb = cb->containingBlock();
206                cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
207            }
208        } else
209            RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
210
211        return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding), view());
212    }
213
214    // SVG embedded through object/embed/iframe.
215    if (isEmbeddedThroughFrameContainingSVGDocument())
216        return document()->frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
217
218    // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
219    return RenderReplaced::computeReplacedLogicalHeight();
220}
221
222void RenderSVGRoot::layout()
223{
224    StackStats::LayoutCheckPoint layoutCheckPoint;
225    ASSERT(needsLayout());
226
227    m_resourcesNeedingToInvalidateClients.clear();
228
229    // Arbitrary affine transforms are incompatible with LayoutState.
230    LayoutStateDisabler layoutStateDisabler(view());
231
232    bool needsLayout = selfNeedsLayout();
233    LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
234
235    LayoutSize oldSize = size();
236    updateLogicalWidth();
237    updateLogicalHeight();
238    buildLocalToBorderBoxTransform();
239
240    SVGSVGElement* svg = toSVGSVGElement(node());
241    ASSERT(svg);
242    m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
243    SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
244
245    if (!m_resourcesNeedingToInvalidateClients.isEmpty()) {
246        // Invalidate resource clients, which may mark some nodes for layout.
247        HashSet<RenderSVGResourceContainer*>::iterator end = m_resourcesNeedingToInvalidateClients.end();
248        for (HashSet<RenderSVGResourceContainer*>::iterator it = m_resourcesNeedingToInvalidateClients.begin(); it != end; ++it)
249            (*it)->removeAllClientsFromCache();
250
251        m_isLayoutSizeChanged = false;
252        SVGRenderSupport::layoutChildren(this, false);
253    }
254
255    // At this point LayoutRepainter already grabbed the old bounds,
256    // recalculate them now so repaintAfterLayout() uses the new bounds.
257    if (m_needsBoundariesOrTransformUpdate) {
258        updateCachedBoundaries();
259        m_needsBoundariesOrTransformUpdate = false;
260    }
261
262    updateLayerTransform();
263
264    repainter.repaintAfterLayout();
265
266    setNeedsLayout(false);
267}
268
269void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
270{
271    // An empty viewport disables rendering.
272    if (pixelSnappedBorderBoxRect().isEmpty())
273        return;
274
275    // Don't paint, if the context explicitly disabled it.
276    if (paintInfo.context->paintingDisabled())
277        return;
278
279    // An empty viewBox also disables rendering.
280    // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
281    SVGSVGElement* svg = toSVGSVGElement(node());
282    ASSERT(svg);
283    if (svg->hasEmptyViewBox())
284        return;
285
286    Page* page = 0;
287    if (Frame* frame = this->frame())
288        page = frame->page();
289
290    // Don't paint if we don't have kids, except if we have filters we should paint those.
291    if (!firstChild()) {
292        SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
293        if (!resources || !resources->filter()) {
294            if (page && paintInfo.phase == PaintPhaseForeground)
295                page->addRelevantUnpaintedObject(this, visualOverflowRect());
296            return;
297        }
298    }
299
300    if (page && paintInfo.phase == PaintPhaseForeground)
301        page->addRelevantRepaintedObject(this, visualOverflowRect());
302
303    // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
304    PaintInfo childPaintInfo(paintInfo);
305    childPaintInfo.context->save();
306
307    // Apply initial viewport clip - not affected by overflow handling
308    childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset, paintInfo.renderRegion)));
309
310    // Convert from container offsets (html renderers) to a relative transform (svg renderers).
311    // Transform from our paint container's coordinate system to our local coords.
312    IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
313    childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
314
315    // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
316    // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
317    {
318        SVGRenderingContext renderingContext;
319        bool continueRendering = true;
320        if (childPaintInfo.phase == PaintPhaseForeground) {
321            renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
322            continueRendering = renderingContext.isRenderingPrepared();
323        }
324
325        if (continueRendering)
326            RenderBox::paint(childPaintInfo, LayoutPoint());
327    }
328
329    childPaintInfo.context->restore();
330}
331
332void RenderSVGRoot::willBeDestroyed()
333{
334    RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
335
336    SVGResourcesCache::clientDestroyed(this);
337    RenderReplaced::willBeDestroyed();
338}
339
340void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
341{
342    if (diff == StyleDifferenceLayout)
343        setNeedsBoundariesUpdate();
344    RenderReplaced::styleWillChange(diff, newStyle);
345}
346
347void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
348{
349    RenderReplaced::styleDidChange(diff, oldStyle);
350    SVGResourcesCache::clientStyleChanged(this, diff, style());
351}
352
353void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
354{
355    RenderReplaced::addChild(child, beforeChild);
356    SVGResourcesCache::clientWasAddedToTree(child, child->style());
357}
358
359void RenderSVGRoot::removeChild(RenderObject* child)
360{
361    SVGResourcesCache::clientWillBeRemovedFromTree(child);
362    RenderReplaced::removeChild(child);
363}
364
365// RenderBox methods will expect coordinates w/o any transforms in coordinates
366// relative to our borderBox origin.  This method gives us exactly that.
367void RenderSVGRoot::buildLocalToBorderBoxTransform()
368{
369    SVGSVGElement* svg = toSVGSVGElement(node());
370    ASSERT(svg);
371    float scale = style()->effectiveZoom();
372    FloatPoint translate = svg->currentTranslate();
373    LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
374    m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
375    if (borderAndPadding.isEmpty() && scale == 1 && translate == FloatPoint::zero())
376        return;
377    m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
378}
379
380const AffineTransform& RenderSVGRoot::localToParentTransform() const
381{
382    // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
383    m_localToParentTransform = m_localToBorderBoxTransform;
384    if (x())
385        m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
386    if (y())
387        m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
388    return m_localToParentTransform;
389}
390
391LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
392{
393    return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
394}
395
396void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
397{
398    // Apply our local transforms (except for x/y translation), then our shadow,
399    // and then call RenderBox's method to handle all the normal CSS Box model bits
400    repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
401
402    const SVGRenderStyle* svgStyle = style()->svgStyle();
403    if (const ShadowData* shadow = svgStyle->shadow())
404        shadow->adjustRectForShadow(repaintRect);
405
406    // Apply initial viewport clip - not affected by overflow settings
407    repaintRect.intersect(pixelSnappedBorderBoxRect());
408
409    LayoutRect rect = enclosingIntRect(repaintRect);
410    RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
411    repaintRect = rect;
412}
413
414// This method expects local CSS box coordinates.
415// Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
416// to convert from SVG viewport coordinates to local CSS box coordinates.
417void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
418{
419    ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
420    ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
421
422    RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
423}
424
425const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
426{
427    return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
428}
429
430void RenderSVGRoot::updateCachedBoundaries()
431{
432    SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBoxExcludingShadow);
433    SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBoxExcludingShadow);
434    m_repaintBoundingBoxExcludingShadow.inflate(borderAndPaddingWidth());
435
436    m_repaintBoundingBox = m_repaintBoundingBoxExcludingShadow;
437    SVGRenderSupport::intersectRepaintRectWithShadows(this, m_repaintBoundingBox);
438}
439
440bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
441{
442    LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
443    LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
444
445    // Only test SVG content if the point is in our content box.
446    // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
447    if (contentBoxRect().contains(pointInBorderBox)) {
448        FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
449
450        for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
451            // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
452            if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
453                updateHitTestResult(result, pointInBorderBox);
454                if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
455                    return true;
456            }
457        }
458    }
459
460    // If we didn't early exit above, we've just hit the container <svg> element. Unlike SVG 1.1, 2nd Edition allows container elements to be hit.
461    if (hitTestAction == HitTestBlockBackground && visibleToHitTesting()) {
462        // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
463        // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
464        // to be able to detect hits on the background of a <div> element. If we'd return true here in the 'Foreground' phase, we are not able
465        // to detect these hits anymore.
466        LayoutRect boundsRect(accumulatedOffset + location(), size());
467        if (locationInContainer.intersects(boundsRect)) {
468            updateHitTestResult(result, pointInBorderBox);
469            if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
470                return true;
471        }
472    }
473
474    return false;
475}
476
477bool RenderSVGRoot::hasRelativeDimensions() const
478{
479    SVGSVGElement* svg = toSVGSVGElement(node());
480    ASSERT(svg);
481
482    return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent() || svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
483}
484
485bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const
486{
487    SVGSVGElement* svg = toSVGSVGElement(node());
488    ASSERT(svg);
489    return svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
490}
491
492bool RenderSVGRoot::hasRelativeLogicalHeight() const
493{
494    SVGSVGElement* svg = toSVGSVGElement(node());
495    ASSERT(svg);
496
497    return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent();
498}
499
500void RenderSVGRoot::addResourceForClientInvalidation(RenderSVGResourceContainer* resource)
501{
502    RenderObject* svgRoot = resource->parent();
503    while (svgRoot && !svgRoot->isSVGRoot())
504        svgRoot = svgRoot->parent();
505    if (!svgRoot)
506        return;
507    toRenderSVGRoot(svgRoot)->m_resourcesNeedingToInvalidateClients.add(resource);
508}
509
510}
511
512#endif // ENABLE(SVG)
513