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