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/LocalFrame.h"
     29 #include "core/rendering/HitTestResult.h"
     30 #include "core/rendering/LayoutRepainter.h"
     31 #include "core/rendering/RenderLayer.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/SVGRenderSupport.h"
     36 #include "core/rendering/svg/SVGRenderingContext.h"
     37 #include "core/rendering/svg/SVGResources.h"
     38 #include "core/rendering/svg/SVGResourcesCache.h"
     39 #include "core/svg/SVGElement.h"
     40 #include "core/svg/SVGSVGElement.h"
     41 #include "core/svg/graphics/SVGImage.h"
     42 #include "platform/LengthFunctions.h"
     43 #include "platform/graphics/GraphicsContext.h"
     44 
     45 using namespace std;
     46 
     47 namespace WebCore {
     48 
     49 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
     50     : RenderReplaced(node)
     51     , m_objectBoundingBoxValid(false)
     52     , m_isLayoutSizeChanged(false)
     53     , m_needsBoundariesOrTransformUpdate(true)
     54     , m_hasBoxDecorations(false)
     55 {
     56 }
     57 
     58 RenderSVGRoot::~RenderSVGRoot()
     59 {
     60 }
     61 
     62 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
     63 {
     64     // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
     65     // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
     66     // The intrinsic width and height of the viewport of SVG content must be determined from the width and height attributes.
     67     SVGSVGElement* svg = toSVGSVGElement(node());
     68     ASSERT(svg);
     69 
     70     // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an object
     71     // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
     72     // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
     73     // - The aspect ratio is calculated by dividing a width by a height.
     74     // - If the width and height of the rootmost svg element are both specified with unit identifiers (in, mm, cm, pt, pc,
     75     //   px, em, ex) or in user units, then the aspect ratio is calculated from the width and height attributes after
     76     //   resolving both values to user units.
     77     intrinsicSize.setWidth(floatValueForLength(svg->intrinsicWidth(), 0));
     78     intrinsicSize.setHeight(floatValueForLength(svg->intrinsicHeight(), 0));
     79 
     80     if (!intrinsicSize.isEmpty()) {
     81         intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
     82     } else {
     83         // - If either/both of the width and height of the rootmost svg element are in percentage units (or omitted), the
     84         //   aspect ratio is calculated from the width and height values of the viewBox specified for the current SVG document
     85         //   fragment. If the viewBox is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
     86         //   calculated and is considered unspecified.
     87         FloatSize viewBoxSize = svg->viewBox()->currentValue()->value().size();
     88         if (!viewBoxSize.isEmpty()) {
     89             // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
     90             intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
     91         }
     92     }
     93 }
     94 
     95 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
     96 {
     97     return SVGImage::isInSVGImage(toSVGSVGElement(node()));
     98 }
     99 
    100 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
    101 {
    102     if (!node())
    103         return false;
    104 
    105     LocalFrame* frame = node()->document().frame();
    106     if (!frame)
    107         return false;
    108 
    109     // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
    110     // but we only negotiate if we're in an SVG document inside a embedded object (object/embed).
    111     if (!frame->ownerRenderer() || !frame->ownerRenderer()->isEmbeddedObject())
    112         return false;
    113     return frame->document()->isSVGDocument();
    114 }
    115 
    116 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
    117 {
    118     return static_cast<LayoutUnit>(valueForLength(length, maxSize) * (length.isFixed() ? scale : 1));
    119 }
    120 
    121 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
    122 {
    123     SVGSVGElement* svg = toSVGSVGElement(node());
    124     ASSERT(svg);
    125 
    126     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
    127     if (!m_containerSize.isEmpty())
    128         return m_containerSize.width();
    129 
    130     if (isEmbeddedThroughFrameContainingSVGDocument())
    131         return containingBlock()->availableLogicalWidth();
    132 
    133     if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
    134         return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
    135 
    136     if (svg->hasIntrinsicWidth())
    137         return resolveLengthAttributeForSVG(svg->intrinsicWidth(), style()->effectiveZoom(), containingBlock()->availableLogicalWidth().toFloat());
    138 
    139     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
    140     return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
    141 }
    142 
    143 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
    144 {
    145     SVGSVGElement* svg = toSVGSVGElement(node());
    146     ASSERT(svg);
    147 
    148     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
    149     if (!m_containerSize.isEmpty())
    150         return m_containerSize.height();
    151 
    152     if (isEmbeddedThroughFrameContainingSVGDocument())
    153         return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
    154 
    155     if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
    156         return RenderReplaced::computeReplacedLogicalHeight();
    157 
    158     if (svg->hasIntrinsicHeight())
    159         return resolveLengthAttributeForSVG(svg->intrinsicHeight(), style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
    160 
    161     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
    162     return RenderReplaced::computeReplacedLogicalHeight();
    163 }
    164 
    165 void RenderSVGRoot::layout()
    166 {
    167     ASSERT(needsLayout());
    168 
    169     // Arbitrary affine transforms are incompatible with LayoutState.
    170     ForceHorriblySlowRectMapping slowRectMapping(*this);
    171 
    172     bool needsLayout = selfNeedsLayout();
    173     LayoutRepainter repainter(*this, checkForPaintInvalidationDuringLayout() && needsLayout);
    174 
    175     LayoutSize oldSize = size();
    176     updateLogicalWidth();
    177     updateLogicalHeight();
    178     buildLocalToBorderBoxTransform();
    179 
    180     SVGRenderSupport::layoutResourcesIfNeeded(this);
    181 
    182     SVGSVGElement* svg = toSVGSVGElement(node());
    183     ASSERT(svg);
    184     m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
    185     SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
    186 
    187     // At this point LayoutRepainter already grabbed the old bounds,
    188     // recalculate them now so repaintAfterLayout() uses the new bounds.
    189     if (m_needsBoundariesOrTransformUpdate) {
    190         updateCachedBoundaries();
    191         m_needsBoundariesOrTransformUpdate = false;
    192     }
    193 
    194     m_overflow.clear();
    195     addVisualEffectOverflow();
    196 
    197     if (!shouldApplyViewportClip()) {
    198         FloatRect contentRepaintRect = paintInvalidationRectInLocalCoordinates();
    199         contentRepaintRect = m_localToBorderBoxTransform.mapRect(contentRepaintRect);
    200         addVisualOverflow(enclosingLayoutRect(contentRepaintRect));
    201     }
    202 
    203     updateLayerTransformAfterLayout();
    204     m_hasBoxDecorations = isDocumentElement() ? calculateHasBoxDecorations() : hasBoxDecorations();
    205     invalidateBackgroundObscurationStatus();
    206 
    207     repainter.repaintAfterLayout();
    208     clearNeedsLayout();
    209 }
    210 
    211 bool RenderSVGRoot::shouldApplyViewportClip() const
    212 {
    213     // the outermost svg is clipped if auto, and svg document roots are always clipped
    214     // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
    215     // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
    216     return style()->overflowX() == OHIDDEN
    217         || style()->overflowX() == OAUTO
    218         || style()->overflowX() == OSCROLL
    219         || this->isDocumentElement();
    220 }
    221 
    222 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
    223 {
    224     // An empty viewport disables rendering.
    225     if (pixelSnappedBorderBoxRect().isEmpty())
    226         return;
    227 
    228     // Don't paint, if the context explicitly disabled it.
    229     if (paintInfo.context->paintingDisabled())
    230         return;
    231 
    232     // SVG outlines are painted during PaintPhaseForeground.
    233     if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline)
    234         return;
    235 
    236     // An empty viewBox also disables rendering.
    237     // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
    238     SVGSVGElement* svg = toSVGSVGElement(node());
    239     ASSERT(svg);
    240     if (svg->hasEmptyViewBox())
    241         return;
    242 
    243     // Don't paint if we don't have kids, except if we have filters we should paint those.
    244     if (!firstChild()) {
    245         SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
    246         if (!resources || !resources->filter())
    247             return;
    248     }
    249 
    250     // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
    251     PaintInfo childPaintInfo(paintInfo);
    252     childPaintInfo.context->save();
    253 
    254     // Apply initial viewport clip
    255     if (shouldApplyViewportClip())
    256         childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset)));
    257 
    258     // Convert from container offsets (html renderers) to a relative transform (svg renderers).
    259     // Transform from our paint container's coordinate system to our local coords.
    260     IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
    261     childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
    262 
    263     // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
    264     // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
    265     {
    266         SVGRenderingContext renderingContext;
    267         bool continueRendering = true;
    268         if (childPaintInfo.phase == PaintPhaseForeground) {
    269             renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
    270             continueRendering = renderingContext.isRenderingPrepared();
    271         }
    272 
    273         if (continueRendering)
    274             RenderBox::paint(childPaintInfo, LayoutPoint());
    275     }
    276 
    277     childPaintInfo.context->restore();
    278 }
    279 
    280 void RenderSVGRoot::willBeDestroyed()
    281 {
    282     RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
    283 
    284     SVGResourcesCache::clientDestroyed(this);
    285     RenderReplaced::willBeDestroyed();
    286 }
    287 
    288 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
    289 {
    290     if (diff.needsFullLayout())
    291         setNeedsBoundariesUpdate();
    292     if (diff.needsRepaint()) {
    293         // Box decorations may have appeared/disappeared - recompute status.
    294         m_hasBoxDecorations = calculateHasBoxDecorations();
    295     }
    296 
    297     RenderReplaced::styleDidChange(diff, oldStyle);
    298     SVGResourcesCache::clientStyleChanged(this, diff, style());
    299 }
    300 
    301 bool RenderSVGRoot::isChildAllowed(RenderObject* child, RenderStyle*) const
    302 {
    303     return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
    304 }
    305 
    306 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
    307 {
    308     RenderReplaced::addChild(child, beforeChild);
    309     SVGResourcesCache::clientWasAddedToTree(child, child->style());
    310 }
    311 
    312 void RenderSVGRoot::removeChild(RenderObject* child)
    313 {
    314     SVGResourcesCache::clientWillBeRemovedFromTree(child);
    315     RenderReplaced::removeChild(child);
    316 }
    317 
    318 void RenderSVGRoot::insertedIntoTree()
    319 {
    320     RenderReplaced::insertedIntoTree();
    321     SVGResourcesCache::clientWasAddedToTree(this, style());
    322 }
    323 
    324 void RenderSVGRoot::willBeRemovedFromTree()
    325 {
    326     SVGResourcesCache::clientWillBeRemovedFromTree(this);
    327     RenderReplaced::willBeRemovedFromTree();
    328 }
    329 
    330 // RenderBox methods will expect coordinates w/o any transforms in coordinates
    331 // relative to our borderBox origin.  This method gives us exactly that.
    332 void RenderSVGRoot::buildLocalToBorderBoxTransform()
    333 {
    334     SVGSVGElement* svg = toSVGSVGElement(node());
    335     ASSERT(svg);
    336     float scale = style()->effectiveZoom();
    337     FloatPoint translate = svg->currentTranslate();
    338     LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
    339     m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
    340     AffineTransform viewToBorderBoxTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
    341     if (viewToBorderBoxTransform.isIdentity())
    342         return;
    343     m_localToBorderBoxTransform = viewToBorderBoxTransform * m_localToBorderBoxTransform;
    344 }
    345 
    346 const AffineTransform& RenderSVGRoot::localToParentTransform() const
    347 {
    348     // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
    349     m_localToParentTransform = m_localToBorderBoxTransform;
    350     if (x())
    351         m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
    352     if (y())
    353         m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
    354     return m_localToParentTransform;
    355 }
    356 
    357 LayoutRect RenderSVGRoot::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const
    358 {
    359     // This is an open-coded aggregate of SVGRenderSupport::clippedOverflowRectForPaintInvalidation,
    360     // RenderSVGRoot::computeFloatRectForPaintInvalidation and RenderReplaced::clippedOverflowRectForPaintInvalidation.
    361     // The reason for this is to optimize/minimize the repaint rect when the box is not "decorated"
    362     // (does not have background/border/etc.)
    363 
    364     // Return early for any cases where we don't actually paint.
    365     if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
    366         return LayoutRect();
    367 
    368     // Compute the repaint rect of the content of the SVG in the border-box coordinate space.
    369     FloatRect contentRepaintRect = paintInvalidationRectInLocalCoordinates();
    370     contentRepaintRect = m_localToBorderBoxTransform.mapRect(contentRepaintRect);
    371 
    372     // Apply initial viewport clip, overflow:visible content is added to visualOverflow
    373     // but the most common case is that overflow is hidden, so always intersect.
    374     contentRepaintRect.intersect(pixelSnappedBorderBoxRect());
    375 
    376     LayoutRect repaintRect = enclosingLayoutRect(contentRepaintRect);
    377     // If the box is decorated or is overflowing, extend it to include the border-box and overflow.
    378     if (m_hasBoxDecorations || hasRenderOverflow()) {
    379         // The selectionRect can project outside of the overflowRect, so take their union
    380         // for repainting to avoid selection painting glitches.
    381         LayoutRect decoratedRepaintRect = unionRect(localSelectionRect(false), visualOverflowRect());
    382         repaintRect.unite(decoratedRepaintRect);
    383     }
    384 
    385     // Compute the repaint rect in the parent coordinate space.
    386     LayoutRect rect = enclosingIntRect(repaintRect);
    387     RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect);
    388     return rect;
    389 }
    390 
    391 void RenderSVGRoot::computeFloatRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, FloatRect& paintInvalidationRect, bool fixed) const
    392 {
    393     // Apply our local transforms (except for x/y translation), then our shadow,
    394     // and then call RenderBox's method to handle all the normal CSS Box model bits
    395     paintInvalidationRect = m_localToBorderBoxTransform.mapRect(paintInvalidationRect);
    396 
    397     // Apply initial viewport clip
    398     if (shouldApplyViewportClip())
    399         paintInvalidationRect.intersect(pixelSnappedBorderBoxRect());
    400 
    401     LayoutRect rect = enclosingIntRect(paintInvalidationRect);
    402     RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, fixed);
    403     paintInvalidationRect = rect;
    404 }
    405 
    406 // This method expects local CSS box coordinates.
    407 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
    408 // to convert from SVG viewport coordinates to local CSS box coordinates.
    409 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
    410 {
    411     ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
    412     // We used to have this ASSERT here, but we removed it when enabling layer squashing.
    413     // See http://crbug.com/364901
    414     // ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
    415 
    416     RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
    417 }
    418 
    419 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
    420 {
    421     return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
    422 }
    423 
    424 void RenderSVGRoot::updateCachedBoundaries()
    425 {
    426     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox);
    427     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
    428 }
    429 
    430 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
    431 {
    432     LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
    433     LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
    434 
    435     // Only test SVG content if the point is in our content box.
    436     // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
    437     if (contentBoxRect().contains(pointInBorderBox)) {
    438         FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
    439 
    440         for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
    441             // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
    442             if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
    443                 updateHitTestResult(result, pointInBorderBox);
    444                 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
    445                     return true;
    446             }
    447         }
    448     }
    449 
    450     // 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.
    451     if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && visibleToHitTestRequest(request)) {
    452         // Only return true here, if the last hit testing phase 'BlockBackground' (or 'ChildBlockBackground' - depending on context) is executed.
    453         // If we'd return true in the 'Foreground' phase, hit testing would stop immediately. For SVG only trees this doesn't matter.
    454         // Though when we have a <foreignObject> subtree we need to be able to detect hits on the background of a <div> element.
    455         // If we'd return true here in the 'Foreground' phase, we are not able to detect these hits anymore.
    456         LayoutRect boundsRect(accumulatedOffset + location(), size());
    457         if (locationInContainer.intersects(boundsRect)) {
    458             updateHitTestResult(result, pointInBorderBox);
    459             if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
    460                 return true;
    461         }
    462     }
    463 
    464     return false;
    465 }
    466 
    467 }
    468