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